Skip to main content

stratum_node_config/
config.rs

1//! Typed accessors over a validated configuration.
2
3use std::fmt;
4use std::net::SocketAddr;
5use std::path::{Path, PathBuf};
6use std::time::Duration;
7
8use crate::error::{ValidationError, ValidationErrorKind};
9use crate::rules;
10use crate::schema::schema;
11use crate::value::Value;
12
13/// Seconds in one day, for [`Config::removal_grace`].
14const SECS_PER_DAY: u64 = 86_400;
15
16/// An opaque reference to a secret held by a custody service.
17///
18/// The reference names where a secret lives; it is not the secret, and this
19/// library never resolves it. `Debug` is redacted so the reference does not
20/// leak into logs by accident; read it explicitly with [`SecretRef::as_str`].
21#[derive(Clone, PartialEq, Eq, Hash)]
22pub struct SecretRef(String);
23
24impl SecretRef {
25    /// Returns the reference text, for handing to the custody service.
26    pub fn as_str(&self) -> &str {
27        &self.0
28    }
29}
30
31impl fmt::Debug for SecretRef {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        f.write_str("SecretRef(<redacted>)")
34    }
35}
36
37/// The effective configuration of a valid document, with one strongly typed
38/// getter per schema field.
39///
40/// Obtained from [`ConfigDocument::config`](crate::ConfigDocument::config).
41/// Every value has already passed validation, so the getters cannot fail.
42///
43/// # Examples
44///
45/// ```
46/// use stratum_node_config::{schema, ConfigDocument};
47///
48/// let doc = ConfigDocument::parse(&schema().seed_text())?;
49/// let config = doc.config();
50/// assert_eq!(config.listen_address().port(), 7460);
51/// assert!(config.listen_address().ip().is_loopback());
52/// assert_eq!(config.canonical_origin(), None);
53/// assert_eq!(config.max_body_bytes(), 262_144);
54/// # Ok::<(), Box<dyn std::error::Error>>(())
55/// ```
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Config {
58    node_name: String,
59    canonical_origin: Option<String>,
60    listen_address: SocketAddr,
61    state_dir: PathBuf,
62    backup_dir: PathBuf,
63    age_recipients: Vec<String>,
64    pod_admin_key_ref: Option<SecretRef>,
65    federation_egress_enabled: bool,
66    max_tenants: u32,
67    invitations_enabled: bool,
68    invitation_ttl_secs: u32,
69    removal_grace_days: u32,
70    max_body_bytes: u32,
71    max_outstanding_challenges: u32,
72    max_pod_body_bytes: u32,
73    admission_requests_per_minute: u32,
74    min_pod_free_bytes: u64,
75    pod_bytes_per_tenant: u64,
76}
77
78impl Config {
79    /// Builds the typed view from effective values in schema order, one per
80    /// schema field. Fails only if a value does not match its field, which
81    /// validation rules out.
82    ///
83    /// # Panics
84    ///
85    /// Panics if `values` does not hold exactly one value per schema field,
86    /// which is a bug in the caller.
87    pub(crate) fn from_values(values: &[Value]) -> Result<Self, ValidationError> {
88        let v = Lookup::new(values).expect("expected one value per schema field");
89        let non_empty = |s: &str| (!s.is_empty()).then(|| s.to_owned());
90        let listen = v.str("listen.address")?;
91        Ok(Self {
92            node_name: v.str("node.name")?.to_owned(),
93            canonical_origin: non_empty(v.str("node.canonical_origin")?),
94            listen_address: rules::parse_loopback(listen).map_err(|msg| {
95                ValidationError::at(ValidationErrorKind::InvalidValue, "listen.address", msg)
96            })?,
97            state_dir: PathBuf::from(v.str("storage.state_dir")?),
98            backup_dir: PathBuf::from(v.str("storage.backup_dir")?),
99            age_recipients: v.list("backup.age_recipients")?.to_vec(),
100            pod_admin_key_ref: non_empty(v.str("secrets.pod_admin_key_ref")?).map(SecretRef),
101            federation_egress_enabled: v.bool("federation.egress_enabled")?,
102            max_body_bytes: v.u32("limits.max_body_bytes")?,
103            max_tenants: v.u32("membership.max_tenants")?,
104            invitations_enabled: v.bool("membership.invitations_enabled")?,
105            invitation_ttl_secs: v.u32("membership.invitation_ttl_secs")?,
106            removal_grace_days: v.u32("membership.removal_grace_days")?,
107            max_outstanding_challenges: v.u32("limits.max_outstanding_challenges")?,
108            max_pod_body_bytes: v.u32("limits.max_pod_body_bytes")?,
109            admission_requests_per_minute: v.u32("limits.admission_requests_per_minute")?,
110            min_pod_free_bytes: v.u64("limits.min_pod_free_bytes")?,
111            pod_bytes_per_tenant: v.u64("limits.pod_bytes_per_tenant")?,
112        })
113    }
114
115    /// Returns `node.name`.
116    pub fn node_name(&self) -> &str {
117        &self.node_name
118    }
119
120    /// Returns `node.canonical_origin`, or `None` while it is empty.
121    pub fn canonical_origin(&self) -> Option<&str> {
122        self.canonical_origin.as_deref()
123    }
124
125    /// Returns `listen.address`, which is always a loopback address.
126    pub fn listen_address(&self) -> SocketAddr {
127        self.listen_address
128    }
129
130    /// Returns `storage.state_dir`, an absolute normalised path.
131    pub fn state_dir(&self) -> &Path {
132        &self.state_dir
133    }
134
135    /// Returns `storage.backup_dir`, an absolute normalised path distinct from
136    /// and not nested with [`Config::state_dir`].
137    pub fn backup_dir(&self) -> &Path {
138        &self.backup_dir
139    }
140
141    /// Returns `backup.age_recipients`; each is a structurally valid age
142    /// post-quantum hybrid recipient beginning with `age1pq1`.
143    pub fn age_recipients(&self) -> &[String] {
144        &self.age_recipients
145    }
146
147    /// Returns `secrets.pod_admin_key_ref`, or `None` while it is empty.
148    ///
149    /// The field is reserved: a Stratum node generates its pod
150    /// administration key itself and does not read this reference.
151    pub fn pod_admin_key_ref(&self) -> Option<&SecretRef> {
152        self.pod_admin_key_ref.as_ref()
153    }
154
155    /// Returns `federation.egress_enabled`.
156    pub fn federation_egress_enabled(&self) -> bool {
157        self.federation_egress_enabled
158    }
159
160    /// Returns `limits.max_body_bytes`, in `1024..=1048576`.
161    pub fn max_body_bytes(&self) -> u32 {
162        self.max_body_bytes
163    }
164
165    /// Returns `limits.max_outstanding_challenges`, in `1..=64`.
166    pub fn max_outstanding_challenges(&self) -> u32 {
167        self.max_outstanding_challenges
168    }
169
170    /// Returns `membership.max_tenants`, in `1..=10000`.
171    pub fn max_tenants(&self) -> u32 {
172        self.max_tenants
173    }
174
175    /// Returns `membership.invitations_enabled`.
176    pub fn invitations_enabled(&self) -> bool {
177        self.invitations_enabled
178    }
179
180    /// Returns `membership.invitation_ttl_secs`, in `60..=2592000`.
181    pub fn invitation_ttl_secs(&self) -> u32 {
182        self.invitation_ttl_secs
183    }
184
185    /// Returns `limits.max_pod_body_bytes`, in `1024..=1073741824`.
186    pub fn max_pod_body_bytes(&self) -> u32 {
187        self.max_pod_body_bytes
188    }
189
190    /// Returns `limits.admission_requests_per_minute`, in `1..=6000`.
191    pub fn admission_requests_per_minute(&self) -> u32 {
192        self.admission_requests_per_minute
193    }
194
195    /// Returns `limits.min_pod_free_bytes`; zero means the check is off.
196    pub fn min_pod_free_bytes(&self) -> u64 {
197        self.min_pod_free_bytes
198    }
199
200    /// Returns `membership.removal_grace_days`, in `0..=3650`.
201    ///
202    /// The node stores the earliest purge time when a member is removed or
203    /// cancelled, from the value in force then, and never allows less than
204    /// 120 seconds.
205    ///
206    /// # Examples
207    ///
208    /// ```
209    /// use stratum_node_config::{schema, ConfigDocument};
210    ///
211    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
212    /// let doc = ConfigDocument::parse(&schema().seed_text())?;
213    /// let config = doc.config();
214    /// assert_eq!(config.removal_grace_days(), 30);
215    /// assert_eq!(config.removal_grace().as_secs(), 30 * 86_400);
216    /// # Ok(())
217    /// # }
218    /// ```
219    pub fn removal_grace_days(&self) -> u32 {
220        self.removal_grace_days
221    }
222
223    /// Returns `membership.removal_grace_days` as a duration of whole days.
224    /// Zero days is a zero duration; the 120 second floor is the node's to
225    /// apply.
226    ///
227    /// # Examples
228    ///
229    /// ```
230    /// use stratum_node_config::{preview, schema, Change};
231    ///
232    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
233    /// let doc = preview(&schema().seed_text(), &[Change::new("membership.removal_grace_days", 0)])?
234    ///     .into_document()
235    ///     .ok_or("the edit is valid")?;
236    /// assert!(doc.config().removal_grace().is_zero());
237    /// # Ok(())
238    /// # }
239    /// ```
240    pub fn removal_grace(&self) -> Duration {
241        Duration::from_secs(u64::from(self.removal_grace_days) * SECS_PER_DAY)
242    }
243
244    /// Returns `limits.pod_bytes_per_tenant`; zero means no limit.
245    ///
246    /// # Examples
247    ///
248    /// ```
249    /// use stratum_node_config::{schema, ConfigDocument};
250    ///
251    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
252    /// let doc = ConfigDocument::parse(&schema().seed_text())?;
253    /// assert_eq!(doc.config().pod_bytes_per_tenant(), 10 * 1024 * 1024 * 1024);
254    /// # Ok(())
255    /// # }
256    /// ```
257    pub fn pod_bytes_per_tenant(&self) -> u64 {
258        self.pod_bytes_per_tenant
259    }
260
261    /// Returns `true` when a pod of `pod_bytes` bytes is over quota: the
262    /// limit is above zero and `pod_bytes` is strictly above it.
263    ///
264    /// This is the one definition of "over quota"; the controller decides
265    /// the flag it publishes with it.
266    ///
267    /// # Examples
268    ///
269    /// ```
270    /// use stratum_node_config::{preview, schema, Change};
271    ///
272    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
273    /// let limited = preview(&schema().seed_text(), &[Change::new("limits.pod_bytes_per_tenant", 100)])?
274    ///     .into_document()
275    ///     .ok_or("the edit is valid")?;
276    /// assert!(!limited.config().is_over_quota(100));
277    /// assert!(limited.config().is_over_quota(101));
278    ///
279    /// let unlimited = preview(&schema().seed_text(), &[Change::new("limits.pod_bytes_per_tenant", 0)])?
280    ///     .into_document()
281    ///     .ok_or("the edit is valid")?;
282    /// assert!(!unlimited.config().is_over_quota(u64::MAX));
283    /// # Ok(())
284    /// # }
285    /// ```
286    pub fn is_over_quota(&self, pod_bytes: u64) -> bool {
287        self.pod_bytes_per_tenant > 0 && pod_bytes > self.pod_bytes_per_tenant
288    }
289}
290
291/// Typed lookup of effective values by schema path.
292struct Lookup<'v>(&'v [Value]);
293
294impl<'v> Lookup<'v> {
295    /// Wraps `values`, or returns `None` unless it holds exactly one value
296    /// per schema field.
297    fn new(values: &'v [Value]) -> Option<Self> {
298        (values.len() == schema().table().len()).then_some(Self(values))
299    }
300
301    /// Looks up `path`. Only an unknown path fails: [`Lookup::new`] checked
302    /// that every schema field has a value.
303    fn get(&self, path: &'static str) -> Result<&'v Value, ValidationError> {
304        let index = schema().index_of(path).ok_or_else(|| {
305            ValidationError::at(
306                ValidationErrorKind::UnknownKey,
307                path,
308                "field is not in the schema",
309            )
310        })?;
311        Ok(&self.0[index])
312    }
313
314    fn mismatch(path: &'static str, expected: &str) -> ValidationError {
315        ValidationError::at(
316            ValidationErrorKind::WrongType,
317            path,
318            format!("expected {expected}"),
319        )
320    }
321
322    fn str(&self, path: &'static str) -> Result<&'v str, ValidationError> {
323        self.get(path)?
324            .as_str()
325            .ok_or_else(|| Self::mismatch(path, "a string"))
326    }
327
328    fn list(&self, path: &'static str) -> Result<&'v [String], ValidationError> {
329        self.get(path)?
330            .as_string_list()
331            .ok_or_else(|| Self::mismatch(path, "a list of strings"))
332    }
333
334    fn bool(&self, path: &'static str) -> Result<bool, ValidationError> {
335        self.get(path)?
336            .as_bool()
337            .ok_or_else(|| Self::mismatch(path, "a boolean"))
338    }
339
340    /// A non-integer is [`ValidationErrorKind::WrongType`]; a negative
341    /// integer is [`ValidationErrorKind::OutOfRange`].
342    fn u64(&self, path: &'static str) -> Result<u64, ValidationError> {
343        let i = self
344            .get(path)?
345            .as_integer()
346            .ok_or_else(|| Self::mismatch(path, "an integer"))?;
347        u64::try_from(i).map_err(|_| {
348            ValidationError::at(
349                ValidationErrorKind::OutOfRange,
350                path,
351                format!("must be between 0 and {}", i64::MAX),
352            )
353        })
354    }
355
356    /// A non-integer is [`ValidationErrorKind::WrongType`]; an integer
357    /// outside `u32` is [`ValidationErrorKind::OutOfRange`].
358    fn u32(&self, path: &'static str) -> Result<u32, ValidationError> {
359        let i = self
360            .get(path)?
361            .as_integer()
362            .ok_or_else(|| Self::mismatch(path, "an integer"))?;
363        u32::try_from(i).map_err(|_| {
364            ValidationError::at(
365                ValidationErrorKind::OutOfRange,
366                path,
367                format!("must be between 0 and {}", u32::MAX),
368            )
369        })
370    }
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376    use crate::schema::FieldDescriptor;
377
378    /// The effective values of the default configuration, in schema order.
379    fn defaults() -> Vec<Value> {
380        schema()
381            .fields()
382            .map(FieldDescriptor::default_value)
383            .collect()
384    }
385
386    fn with(path: &str, value: Value) -> Vec<Value> {
387        let mut values = defaults();
388        let i = schema().index_of(path).expect("path in schema");
389        values[i] = value;
390        values
391    }
392
393    #[test]
394    fn integer_outside_u32_is_out_of_range() {
395        for n in [-1, i64::from(u32::MAX) + 1] {
396            let values = with("limits.max_body_bytes", Value::Integer(n));
397            let e = Lookup::new(&values)
398                .expect("full value list")
399                .u32("limits.max_body_bytes")
400                .expect_err("out of range");
401            assert_eq!(e.kind(), ValidationErrorKind::OutOfRange, "{n}");
402            assert_eq!(e.message(), "must be between 0 and 4294967295", "{n}");
403        }
404        let values = with("limits.max_body_bytes", Value::Integer(4_294_967_295));
405        assert_eq!(
406            Lookup::new(&values)
407                .expect("full value list")
408                .u32("limits.max_body_bytes"),
409            Ok(u32::MAX),
410            "upper bound"
411        );
412    }
413
414    #[test]
415    fn non_integer_is_wrong_type() {
416        let values = with("limits.max_body_bytes", Value::from("many"));
417        let e = Lookup::new(&values)
418            .expect("full value list")
419            .u32("limits.max_body_bytes")
420            .expect_err("wrong type");
421        assert_eq!(e.kind(), ValidationErrorKind::WrongType, "kind");
422        assert_eq!(e.message(), "expected an integer", "message");
423    }
424
425    #[test]
426    fn unknown_path_is_unknown_key() {
427        let values = defaults();
428        let e = Lookup::new(&values)
429            .expect("full value list")
430            .get("limits.nope")
431            .expect_err("unknown");
432        assert_eq!(e.kind(), ValidationErrorKind::UnknownKey, "kind");
433    }
434
435    #[test]
436    #[should_panic(expected = "expected one value per schema field")]
437    fn short_value_list_is_a_bug_not_an_unknown_key() {
438        let mut values = defaults();
439        values.pop();
440        let _ = Config::from_values(&values);
441    }
442
443    #[test]
444    fn defaults_build_a_config() {
445        let config = Config::from_values(&defaults()).expect("defaults are valid");
446        assert_eq!(config.max_body_bytes(), 262_144, "default");
447    }
448}