stratum-node-config 0.1.0-alpha.3

Versioned stratum.toml schema, comment-preserving editor, semantic validator, change preview and public-config hash for Stratum nodes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Typed accessors over a validated configuration.

use std::fmt;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::time::Duration;

use crate::error::{ValidationError, ValidationErrorKind};
use crate::rules;
use crate::schema::schema;
use crate::value::Value;

/// Seconds in one day, for [`Config::removal_grace`].
const SECS_PER_DAY: u64 = 86_400;

/// An opaque reference to a secret held by a custody service.
///
/// The reference names where a secret lives; it is not the secret, and this
/// library never resolves it. `Debug` is redacted so the reference does not
/// leak into logs by accident; read it explicitly with [`SecretRef::as_str`].
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct SecretRef(String);

impl SecretRef {
    /// Returns the reference text, for handing to the custody service.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for SecretRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("SecretRef(<redacted>)")
    }
}

/// The effective configuration of a valid document, with one strongly typed
/// getter per schema field.
///
/// Obtained from [`ConfigDocument::config`](crate::ConfigDocument::config).
/// Every value has already passed validation, so the getters cannot fail.
///
/// # Examples
///
/// ```
/// use stratum_node_config::{schema, ConfigDocument};
///
/// let doc = ConfigDocument::parse(&schema().seed_text())?;
/// let config = doc.config();
/// assert_eq!(config.listen_address().port(), 7460);
/// assert!(config.listen_address().ip().is_loopback());
/// assert_eq!(config.canonical_origin(), None);
/// assert_eq!(config.max_body_bytes(), 262_144);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
    node_name: String,
    canonical_origin: Option<String>,
    listen_address: SocketAddr,
    state_dir: PathBuf,
    backup_dir: PathBuf,
    age_recipients: Vec<String>,
    pod_admin_key_ref: Option<SecretRef>,
    federation_egress_enabled: bool,
    max_tenants: u32,
    invitations_enabled: bool,
    invitation_ttl_secs: u32,
    removal_grace_days: u32,
    max_body_bytes: u32,
    max_outstanding_challenges: u32,
    max_pod_body_bytes: u32,
    admission_requests_per_minute: u32,
    min_pod_free_bytes: u64,
    pod_bytes_per_tenant: u64,
}

impl Config {
    /// Builds the typed view from effective values in schema order, one per
    /// schema field. Fails only if a value does not match its field, which
    /// validation rules out.
    ///
    /// # Panics
    ///
    /// Panics if `values` does not hold exactly one value per schema field,
    /// which is a bug in the caller.
    pub(crate) fn from_values(values: &[Value]) -> Result<Self, ValidationError> {
        let v = Lookup::new(values).expect("expected one value per schema field");
        let non_empty = |s: &str| (!s.is_empty()).then(|| s.to_owned());
        let listen = v.str("listen.address")?;
        Ok(Self {
            node_name: v.str("node.name")?.to_owned(),
            canonical_origin: non_empty(v.str("node.canonical_origin")?),
            listen_address: rules::parse_loopback(listen).map_err(|msg| {
                ValidationError::at(ValidationErrorKind::InvalidValue, "listen.address", msg)
            })?,
            state_dir: PathBuf::from(v.str("storage.state_dir")?),
            backup_dir: PathBuf::from(v.str("storage.backup_dir")?),
            age_recipients: v.list("backup.age_recipients")?.to_vec(),
            pod_admin_key_ref: non_empty(v.str("secrets.pod_admin_key_ref")?).map(SecretRef),
            federation_egress_enabled: v.bool("federation.egress_enabled")?,
            max_body_bytes: v.u32("limits.max_body_bytes")?,
            max_tenants: v.u32("membership.max_tenants")?,
            invitations_enabled: v.bool("membership.invitations_enabled")?,
            invitation_ttl_secs: v.u32("membership.invitation_ttl_secs")?,
            removal_grace_days: v.u32("membership.removal_grace_days")?,
            max_outstanding_challenges: v.u32("limits.max_outstanding_challenges")?,
            max_pod_body_bytes: v.u32("limits.max_pod_body_bytes")?,
            admission_requests_per_minute: v.u32("limits.admission_requests_per_minute")?,
            min_pod_free_bytes: v.u64("limits.min_pod_free_bytes")?,
            pod_bytes_per_tenant: v.u64("limits.pod_bytes_per_tenant")?,
        })
    }

    /// Returns `node.name`.
    pub fn node_name(&self) -> &str {
        &self.node_name
    }

    /// Returns `node.canonical_origin`, or `None` while it is empty.
    pub fn canonical_origin(&self) -> Option<&str> {
        self.canonical_origin.as_deref()
    }

    /// Returns `listen.address`, which is always a loopback address.
    pub fn listen_address(&self) -> SocketAddr {
        self.listen_address
    }

    /// Returns `storage.state_dir`, an absolute normalised path.
    pub fn state_dir(&self) -> &Path {
        &self.state_dir
    }

    /// Returns `storage.backup_dir`, an absolute normalised path distinct from
    /// and not nested with [`Config::state_dir`].
    pub fn backup_dir(&self) -> &Path {
        &self.backup_dir
    }

    /// Returns `backup.age_recipients`; each is a structurally valid age
    /// post-quantum hybrid recipient beginning with `age1pq1`.
    pub fn age_recipients(&self) -> &[String] {
        &self.age_recipients
    }

    /// Returns `secrets.pod_admin_key_ref`, or `None` while it is empty.
    ///
    /// The field is reserved: a Stratum node generates its pod
    /// administration key itself and does not read this reference.
    pub fn pod_admin_key_ref(&self) -> Option<&SecretRef> {
        self.pod_admin_key_ref.as_ref()
    }

    /// Returns `federation.egress_enabled`.
    pub fn federation_egress_enabled(&self) -> bool {
        self.federation_egress_enabled
    }

    /// Returns `limits.max_body_bytes`, in `1024..=1048576`.
    pub fn max_body_bytes(&self) -> u32 {
        self.max_body_bytes
    }

    /// Returns `limits.max_outstanding_challenges`, in `1..=64`.
    pub fn max_outstanding_challenges(&self) -> u32 {
        self.max_outstanding_challenges
    }

    /// Returns `membership.max_tenants`, in `1..=10000`.
    pub fn max_tenants(&self) -> u32 {
        self.max_tenants
    }

    /// Returns `membership.invitations_enabled`.
    pub fn invitations_enabled(&self) -> bool {
        self.invitations_enabled
    }

    /// Returns `membership.invitation_ttl_secs`, in `60..=2592000`.
    pub fn invitation_ttl_secs(&self) -> u32 {
        self.invitation_ttl_secs
    }

    /// Returns `limits.max_pod_body_bytes`, in `1024..=1073741824`.
    pub fn max_pod_body_bytes(&self) -> u32 {
        self.max_pod_body_bytes
    }

    /// Returns `limits.admission_requests_per_minute`, in `1..=6000`.
    pub fn admission_requests_per_minute(&self) -> u32 {
        self.admission_requests_per_minute
    }

    /// Returns `limits.min_pod_free_bytes`; zero means the check is off.
    pub fn min_pod_free_bytes(&self) -> u64 {
        self.min_pod_free_bytes
    }

    /// Returns `membership.removal_grace_days`, in `0..=3650`.
    ///
    /// The node stores the earliest purge time when a member is removed or
    /// cancelled, from the value in force then, and never allows less than
    /// 120 seconds.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_config::{schema, ConfigDocument};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let doc = ConfigDocument::parse(&schema().seed_text())?;
    /// let config = doc.config();
    /// assert_eq!(config.removal_grace_days(), 30);
    /// assert_eq!(config.removal_grace().as_secs(), 30 * 86_400);
    /// # Ok(())
    /// # }
    /// ```
    pub fn removal_grace_days(&self) -> u32 {
        self.removal_grace_days
    }

    /// Returns `membership.removal_grace_days` as a duration of whole days.
    /// Zero days is a zero duration; the 120 second floor is the node's to
    /// apply.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_config::{preview, schema, Change};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let doc = preview(&schema().seed_text(), &[Change::new("membership.removal_grace_days", 0)])?
    ///     .into_document()
    ///     .ok_or("the edit is valid")?;
    /// assert!(doc.config().removal_grace().is_zero());
    /// # Ok(())
    /// # }
    /// ```
    pub fn removal_grace(&self) -> Duration {
        Duration::from_secs(u64::from(self.removal_grace_days) * SECS_PER_DAY)
    }

    /// Returns `limits.pod_bytes_per_tenant`; zero means no limit.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_config::{schema, ConfigDocument};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let doc = ConfigDocument::parse(&schema().seed_text())?;
    /// assert_eq!(doc.config().pod_bytes_per_tenant(), 10 * 1024 * 1024 * 1024);
    /// # Ok(())
    /// # }
    /// ```
    pub fn pod_bytes_per_tenant(&self) -> u64 {
        self.pod_bytes_per_tenant
    }

    /// Returns `true` when a pod of `pod_bytes` bytes is over quota: the
    /// limit is above zero and `pod_bytes` is strictly above it.
    ///
    /// This is the one definition of "over quota"; the controller decides
    /// the flag it publishes with it.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_config::{preview, schema, Change};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let limited = preview(&schema().seed_text(), &[Change::new("limits.pod_bytes_per_tenant", 100)])?
    ///     .into_document()
    ///     .ok_or("the edit is valid")?;
    /// assert!(!limited.config().is_over_quota(100));
    /// assert!(limited.config().is_over_quota(101));
    ///
    /// let unlimited = preview(&schema().seed_text(), &[Change::new("limits.pod_bytes_per_tenant", 0)])?
    ///     .into_document()
    ///     .ok_or("the edit is valid")?;
    /// assert!(!unlimited.config().is_over_quota(u64::MAX));
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_over_quota(&self, pod_bytes: u64) -> bool {
        self.pod_bytes_per_tenant > 0 && pod_bytes > self.pod_bytes_per_tenant
    }
}

/// Typed lookup of effective values by schema path.
struct Lookup<'v>(&'v [Value]);

impl<'v> Lookup<'v> {
    /// Wraps `values`, or returns `None` unless it holds exactly one value
    /// per schema field.
    fn new(values: &'v [Value]) -> Option<Self> {
        (values.len() == schema().table().len()).then_some(Self(values))
    }

    /// Looks up `path`. Only an unknown path fails: [`Lookup::new`] checked
    /// that every schema field has a value.
    fn get(&self, path: &'static str) -> Result<&'v Value, ValidationError> {
        let index = schema().index_of(path).ok_or_else(|| {
            ValidationError::at(
                ValidationErrorKind::UnknownKey,
                path,
                "field is not in the schema",
            )
        })?;
        Ok(&self.0[index])
    }

    fn mismatch(path: &'static str, expected: &str) -> ValidationError {
        ValidationError::at(
            ValidationErrorKind::WrongType,
            path,
            format!("expected {expected}"),
        )
    }

    fn str(&self, path: &'static str) -> Result<&'v str, ValidationError> {
        self.get(path)?
            .as_str()
            .ok_or_else(|| Self::mismatch(path, "a string"))
    }

    fn list(&self, path: &'static str) -> Result<&'v [String], ValidationError> {
        self.get(path)?
            .as_string_list()
            .ok_or_else(|| Self::mismatch(path, "a list of strings"))
    }

    fn bool(&self, path: &'static str) -> Result<bool, ValidationError> {
        self.get(path)?
            .as_bool()
            .ok_or_else(|| Self::mismatch(path, "a boolean"))
    }

    /// A non-integer is [`ValidationErrorKind::WrongType`]; a negative
    /// integer is [`ValidationErrorKind::OutOfRange`].
    fn u64(&self, path: &'static str) -> Result<u64, ValidationError> {
        let i = self
            .get(path)?
            .as_integer()
            .ok_or_else(|| Self::mismatch(path, "an integer"))?;
        u64::try_from(i).map_err(|_| {
            ValidationError::at(
                ValidationErrorKind::OutOfRange,
                path,
                format!("must be between 0 and {}", i64::MAX),
            )
        })
    }

    /// A non-integer is [`ValidationErrorKind::WrongType`]; an integer
    /// outside `u32` is [`ValidationErrorKind::OutOfRange`].
    fn u32(&self, path: &'static str) -> Result<u32, ValidationError> {
        let i = self
            .get(path)?
            .as_integer()
            .ok_or_else(|| Self::mismatch(path, "an integer"))?;
        u32::try_from(i).map_err(|_| {
            ValidationError::at(
                ValidationErrorKind::OutOfRange,
                path,
                format!("must be between 0 and {}", u32::MAX),
            )
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::FieldDescriptor;

    /// The effective values of the default configuration, in schema order.
    fn defaults() -> Vec<Value> {
        schema()
            .fields()
            .map(FieldDescriptor::default_value)
            .collect()
    }

    fn with(path: &str, value: Value) -> Vec<Value> {
        let mut values = defaults();
        let i = schema().index_of(path).expect("path in schema");
        values[i] = value;
        values
    }

    #[test]
    fn integer_outside_u32_is_out_of_range() {
        for n in [-1, i64::from(u32::MAX) + 1] {
            let values = with("limits.max_body_bytes", Value::Integer(n));
            let e = Lookup::new(&values)
                .expect("full value list")
                .u32("limits.max_body_bytes")
                .expect_err("out of range");
            assert_eq!(e.kind(), ValidationErrorKind::OutOfRange, "{n}");
            assert_eq!(e.message(), "must be between 0 and 4294967295", "{n}");
        }
        let values = with("limits.max_body_bytes", Value::Integer(4_294_967_295));
        assert_eq!(
            Lookup::new(&values)
                .expect("full value list")
                .u32("limits.max_body_bytes"),
            Ok(u32::MAX),
            "upper bound"
        );
    }

    #[test]
    fn non_integer_is_wrong_type() {
        let values = with("limits.max_body_bytes", Value::from("many"));
        let e = Lookup::new(&values)
            .expect("full value list")
            .u32("limits.max_body_bytes")
            .expect_err("wrong type");
        assert_eq!(e.kind(), ValidationErrorKind::WrongType, "kind");
        assert_eq!(e.message(), "expected an integer", "message");
    }

    #[test]
    fn unknown_path_is_unknown_key() {
        let values = defaults();
        let e = Lookup::new(&values)
            .expect("full value list")
            .get("limits.nope")
            .expect_err("unknown");
        assert_eq!(e.kind(), ValidationErrorKind::UnknownKey, "kind");
    }

    #[test]
    #[should_panic(expected = "expected one value per schema field")]
    fn short_value_list_is_a_bug_not_an_unknown_key() {
        let mut values = defaults();
        values.pop();
        let _ = Config::from_values(&values);
    }

    #[test]
    fn defaults_build_a_config() {
        let config = Config::from_values(&defaults()).expect("defaults are valid");
        assert_eq!(config.max_body_bytes(), 262_144, "default");
    }
}