Skip to main content

capy_core/
password_config.rs

1use crate::{AppError, Result};
2use serde::{Deserialize, Serialize};
3
4/// Automatic hardware/budget selection or an explicit worker count.
5#[derive(Clone, Debug, Default, PartialEq, Eq)]
6pub enum HashConcurrency {
7    /// Select from CPU parallelism and the memory budget.
8    #[default]
9    Auto,
10    /// Explicit concurrent blocking operations (1..=32), within the memory budget.
11    Fixed(usize),
12}
13impl Serialize for HashConcurrency {
14    fn serialize<S: serde::Serializer>(
15        &self,
16        serializer: S,
17    ) -> std::result::Result<S::Ok, S::Error> {
18        match self {
19            Self::Auto => serializer.serialize_str("auto"),
20            Self::Fixed(n) => n.serialize(serializer),
21        }
22    }
23}
24impl<'de> Deserialize<'de> for HashConcurrency {
25    fn deserialize<D: serde::Deserializer<'de>>(
26        deserializer: D,
27    ) -> std::result::Result<Self, D::Error> {
28        #[derive(Deserialize)]
29        #[serde(untagged)]
30        enum Value {
31            Name(String),
32            Count(usize),
33        }
34        match Value::deserialize(deserializer)? {
35            Value::Name(name) if name == "auto" => Ok(Self::Auto),
36            Value::Count(n) => Ok(Self::Fixed(n)),
37            _ => Err(serde::de::Error::custom(
38                "use auto or an integer concurrency",
39            )),
40        }
41    }
42}
43
44/// Per-application Argon2id admission and resource limits (`AUTH_PASSWORD_*`).
45#[derive(Clone, Debug, Deserialize, Serialize)]
46#[serde(default, deny_unknown_fields)]
47pub struct PasswordSettings {
48    /// `auto` (default) or 1..=32 workers. Cloned services share the same pool.
49    pub hash_concurrency: HashConcurrency,
50    /// Maximum wait for admission, milliseconds (1..=60000; default 5000).
51    pub hash_queue_timeout_ms: u64,
52    /// Maximum queued callers, excluding active workers (1..=4096; default 128).
53    pub hash_queue_capacity: usize,
54    /// Argon2 memory in KiB per operation (19456..=262144; default 19456).
55    pub memory_cost_kib: u32,
56    /// Argon2 passes (2..=10; default 2). Lanes remain one.
57    pub time_cost: u32,
58    /// Per-pool memory budget in KiB, including 1 MiB worker headroom (default 65536).
59    /// Tune against the container limit and other application allocations.
60    pub memory_budget_kib: u32,
61}
62impl Default for PasswordSettings {
63    fn default() -> Self {
64        Self {
65            hash_concurrency: HashConcurrency::default(),
66            hash_queue_timeout_ms: 5000,
67            hash_queue_capacity: 128,
68            memory_cost_kib: 19456,
69            time_cost: 2,
70            memory_budget_kib: 65536,
71        }
72    }
73}
74impl PasswordSettings {
75    /// Validate all bounds and resolve automatic concurrency. The default budget caps
76    /// memory even on hosts reporting hundreds of CPUs; it is not a process RSS limit.
77    pub fn concurrency(&self) -> Result<usize> {
78        let invalid = || {
79            AppError::Configuration("Invalid auth.password settings: use hash_concurrency = \"auto\" or 1..=32, hash_queue_timeout_ms 1..=60000, hash_queue_capacity 1..=4096, memory_cost_kib 19456..=262144, time_cost 2..=10, and memory_budget_kib <=1048576 covering (memory_cost_kib + 1024) per worker. Reduce concurrency or increase the budget within your container memory limit.".into())
80        };
81        if !(1..=60000).contains(&self.hash_queue_timeout_ms)
82            || !(1..=4096).contains(&self.hash_queue_capacity)
83            || !(19456..=262144).contains(&self.memory_cost_kib)
84            || !(2..=10).contains(&self.time_cost)
85            || self.memory_budget_kib > 1048576
86        {
87            return Err(invalid());
88        }
89        let memory_workers = (self.memory_budget_kib / (self.memory_cost_kib + 1024)) as usize;
90        if memory_workers == 0 {
91            return Err(invalid());
92        }
93        match &self.hash_concurrency {
94            HashConcurrency::Auto => Ok(std::thread::available_parallelism()
95                .map_or(1, usize::from)
96                .min(memory_workers)
97                .min(32)),
98            HashConcurrency::Fixed(n) if (1..=32).contains(n) && *n <= memory_workers => Ok(*n),
99            _ => Err(invalid()),
100        }
101    }
102}