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