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_body_bytes: u32,
63    max_outstanding_challenges: u32,
64}
65
66impl Config {
67    /// Builds the typed view from effective values in schema order, one per
68    /// schema field. Fails only if a value does not match its field, which
69    /// validation rules out.
70    ///
71    /// # Panics
72    ///
73    /// Panics if `values` does not hold exactly one value per schema field,
74    /// which is a bug in the caller.
75    pub(crate) fn from_values(values: &[Value]) -> Result<Self, ValidationError> {
76        let v = Lookup::new(values).expect("expected one value per schema field");
77        let non_empty = |s: &str| (!s.is_empty()).then(|| s.to_owned());
78        let listen = v.str("listen.address")?;
79        Ok(Self {
80            node_name: v.str("node.name")?.to_owned(),
81            canonical_origin: non_empty(v.str("node.canonical_origin")?),
82            listen_address: rules::parse_loopback(listen).map_err(|msg| {
83                ValidationError::at(ValidationErrorKind::InvalidValue, "listen.address", msg)
84            })?,
85            state_dir: PathBuf::from(v.str("storage.state_dir")?),
86            backup_dir: PathBuf::from(v.str("storage.backup_dir")?),
87            age_recipients: v.list("backup.age_recipients")?.to_vec(),
88            pod_admin_key_ref: non_empty(v.str("secrets.pod_admin_key_ref")?).map(SecretRef),
89            federation_egress_enabled: v.bool("federation.egress_enabled")?,
90            max_body_bytes: v.u32("limits.max_body_bytes")?,
91            max_outstanding_challenges: v.u32("limits.max_outstanding_challenges")?,
92        })
93    }
94
95    /// Returns `node.name`.
96    pub fn node_name(&self) -> &str {
97        &self.node_name
98    }
99
100    /// Returns `node.canonical_origin`, or `None` while it is empty.
101    pub fn canonical_origin(&self) -> Option<&str> {
102        self.canonical_origin.as_deref()
103    }
104
105    /// Returns `listen.address`, which is always a loopback address.
106    pub fn listen_address(&self) -> SocketAddr {
107        self.listen_address
108    }
109
110    /// Returns `storage.state_dir`, an absolute normalised path.
111    pub fn state_dir(&self) -> &Path {
112        &self.state_dir
113    }
114
115    /// Returns `storage.backup_dir`, an absolute normalised path distinct from
116    /// and not nested with [`Config::state_dir`].
117    pub fn backup_dir(&self) -> &Path {
118        &self.backup_dir
119    }
120
121    /// Returns `backup.age_recipients`; each is a structurally valid age
122    /// post-quantum hybrid recipient beginning with `age1pq1`.
123    pub fn age_recipients(&self) -> &[String] {
124        &self.age_recipients
125    }
126
127    /// Returns `secrets.pod_admin_key_ref`, or `None` while it is empty.
128    pub fn pod_admin_key_ref(&self) -> Option<&SecretRef> {
129        self.pod_admin_key_ref.as_ref()
130    }
131
132    /// Returns `federation.egress_enabled`.
133    pub fn federation_egress_enabled(&self) -> bool {
134        self.federation_egress_enabled
135    }
136
137    /// Returns `limits.max_body_bytes`, in `1024..=1048576`.
138    pub fn max_body_bytes(&self) -> u32 {
139        self.max_body_bytes
140    }
141
142    /// Returns `limits.max_outstanding_challenges`, in `1..=64`.
143    pub fn max_outstanding_challenges(&self) -> u32 {
144        self.max_outstanding_challenges
145    }
146}
147
148/// Typed lookup of effective values by schema path.
149struct Lookup<'v>(&'v [Value]);
150
151impl<'v> Lookup<'v> {
152    /// Wraps `values`, or returns `None` unless it holds exactly one value
153    /// per schema field.
154    fn new(values: &'v [Value]) -> Option<Self> {
155        (values.len() == schema().table().len()).then_some(Self(values))
156    }
157
158    /// Looks up `path`. Only an unknown path fails: [`Lookup::new`] checked
159    /// that every schema field has a value.
160    fn get(&self, path: &'static str) -> Result<&'v Value, ValidationError> {
161        let index = schema().index_of(path).ok_or_else(|| {
162            ValidationError::at(
163                ValidationErrorKind::UnknownKey,
164                path,
165                "field is not in the schema",
166            )
167        })?;
168        Ok(&self.0[index])
169    }
170
171    fn mismatch(path: &'static str, expected: &str) -> ValidationError {
172        ValidationError::at(
173            ValidationErrorKind::WrongType,
174            path,
175            format!("expected {expected}"),
176        )
177    }
178
179    fn str(&self, path: &'static str) -> Result<&'v str, ValidationError> {
180        self.get(path)?
181            .as_str()
182            .ok_or_else(|| Self::mismatch(path, "a string"))
183    }
184
185    fn list(&self, path: &'static str) -> Result<&'v [String], ValidationError> {
186        self.get(path)?
187            .as_string_list()
188            .ok_or_else(|| Self::mismatch(path, "a list of strings"))
189    }
190
191    fn bool(&self, path: &'static str) -> Result<bool, ValidationError> {
192        self.get(path)?
193            .as_bool()
194            .ok_or_else(|| Self::mismatch(path, "a boolean"))
195    }
196
197    /// A non-integer is [`ValidationErrorKind::WrongType`]; an integer
198    /// outside `u32` is [`ValidationErrorKind::OutOfRange`].
199    fn u32(&self, path: &'static str) -> Result<u32, ValidationError> {
200        let i = self
201            .get(path)?
202            .as_integer()
203            .ok_or_else(|| Self::mismatch(path, "an integer"))?;
204        u32::try_from(i).map_err(|_| {
205            ValidationError::at(
206                ValidationErrorKind::OutOfRange,
207                path,
208                format!("must be between 0 and {}", u32::MAX),
209            )
210        })
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use crate::schema::FieldDescriptor;
218
219    /// The effective values of the default configuration, in schema order.
220    fn defaults() -> Vec<Value> {
221        schema()
222            .fields()
223            .map(FieldDescriptor::default_value)
224            .collect()
225    }
226
227    fn with(path: &str, value: Value) -> Vec<Value> {
228        let mut values = defaults();
229        let i = schema().index_of(path).expect("path in schema");
230        values[i] = value;
231        values
232    }
233
234    #[test]
235    fn integer_outside_u32_is_out_of_range() {
236        for n in [-1, i64::from(u32::MAX) + 1] {
237            let values = with("limits.max_body_bytes", Value::Integer(n));
238            let e = Lookup::new(&values)
239                .expect("full value list")
240                .u32("limits.max_body_bytes")
241                .expect_err("out of range");
242            assert_eq!(e.kind(), ValidationErrorKind::OutOfRange, "{n}");
243            assert_eq!(e.message(), "must be between 0 and 4294967295", "{n}");
244        }
245        let values = with("limits.max_body_bytes", Value::Integer(4_294_967_295));
246        assert_eq!(
247            Lookup::new(&values)
248                .expect("full value list")
249                .u32("limits.max_body_bytes"),
250            Ok(u32::MAX),
251            "upper bound"
252        );
253    }
254
255    #[test]
256    fn non_integer_is_wrong_type() {
257        let values = with("limits.max_body_bytes", Value::from("many"));
258        let e = Lookup::new(&values)
259            .expect("full value list")
260            .u32("limits.max_body_bytes")
261            .expect_err("wrong type");
262        assert_eq!(e.kind(), ValidationErrorKind::WrongType, "kind");
263        assert_eq!(e.message(), "expected an integer", "message");
264    }
265
266    #[test]
267    fn unknown_path_is_unknown_key() {
268        let values = defaults();
269        let e = Lookup::new(&values)
270            .expect("full value list")
271            .get("limits.nope")
272            .expect_err("unknown");
273        assert_eq!(e.kind(), ValidationErrorKind::UnknownKey, "kind");
274    }
275
276    #[test]
277    #[should_panic(expected = "expected one value per schema field")]
278    fn short_value_list_is_a_bug_not_an_unknown_key() {
279        let mut values = defaults();
280        values.pop();
281        let _ = Config::from_values(&values);
282    }
283
284    #[test]
285    fn defaults_build_a_config() {
286        let config = Config::from_values(&defaults()).expect("defaults are valid");
287        assert_eq!(config.max_body_bytes(), 262_144, "default");
288    }
289}