stratum-node-config 0.1.0-alpha.2

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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
//! The schema table: the single source of every field's type, default,
//! description and apply class.

use std::fmt;
use std::iter::FusedIterator;

use serde::ser::{Serialize, SerializeStruct, Serializer};

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

/// The version of the `stratum.toml` schema this library implements.
///
/// A document must carry `schema_version = 1`; any other value is rejected.
pub const SCHEMA_VERSION: u32 = 1;

/// The largest number of entries `backup.age_recipients` may hold.
///
/// A Stratum node encrypts its keystore to every listed recipient in each
/// backup and refuses to write a backup to more than 32 of them, so a longer
/// list is rejected here, when the configuration is validated, rather than
/// at backup time. The field's [`FieldDescriptor::description`] states the
/// same limit.
///
/// # Examples
///
/// ```
/// use stratum_node_config::{schema, Value, MAX_BACKUP_RECIPIENTS};
///
/// let field = schema().field("backup.age_recipients").expect("field exists");
/// let too_many = vec!["age1pq1…".to_owned(); MAX_BACKUP_RECIPIENTS + 1];
/// let err = field.validate(&Value::from(too_many)).unwrap_err();
/// assert_eq!(err.message(), "must hold at most 32 recipients, found 33");
/// ```
pub const MAX_BACKUP_RECIPIENTS: usize = 32;

/// When a changed field takes effect.
///
/// The variants are ordered from least to most disruptive, so the strictest
/// class of a set of changes is their maximum.
///
/// # Examples
///
/// ```
/// use stratum_node_config::ApplyClass;
///
/// let classes = [ApplyClass::Live, ApplyClass::Redeploy, ApplyClass::Restart];
/// assert_eq!(classes.into_iter().max(), Some(ApplyClass::Redeploy));
/// assert_eq!(ApplyClass::Restart.to_string(), "restart");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ApplyClass {
    /// Takes effect in the running node without a restart.
    Live,
    /// Takes effect when the controller process restarts.
    Restart,
    /// Takes effect only after the deployment around the node is rebuilt,
    /// for example the tunnel or the public origin.
    Redeploy,
}

impl ApplyClass {
    /// Returns the lowercase name: `live`, `restart` or `redeploy`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Live => "live",
            Self::Restart => "restart",
            Self::Redeploy => "redeploy",
        }
    }
}

impl fmt::Display for ApplyClass {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The type of a schema field, including any range or variant set.
///
/// Serialises with a `kind` tag, for example
/// `{"kind": "integer", "min": 1, "max": 64}`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum ValueType {
    /// A UTF-8 string.
    String,
    /// An integer in `min..=max`.
    Integer {
        /// The smallest accepted value.
        min: i64,
        /// The largest accepted value.
        max: i64,
    },
    /// A boolean.
    Boolean,
    /// A string that must be one of a fixed set.
    Enum {
        /// The accepted strings.
        variants: &'static [&'static str],
    },
    /// A list of strings.
    StringList,
    /// An opaque reference to a secret held by a custody service.
    ///
    /// This library never resolves it. Secret-reference fields are excluded
    /// from the [`PublicConfig`](crate::PublicConfig) and its hash, and their
    /// values are redacted in change lists.
    SecretRef,
}

impl ValueType {
    fn name(self) -> &'static str {
        match self {
            Self::String | Self::Enum { .. } | Self::SecretRef => "a string",
            Self::Integer { .. } => "an integer",
            Self::Boolean => "a boolean",
            Self::StringList => "a list of strings",
        }
    }

    /// Checks that `value` has this type and lies within its range or set.
    fn check(self, value: &Value) -> Result<(), (ValidationErrorKind, String)> {
        let found = value.kind_name();
        let wrong = || {
            (
                ValidationErrorKind::WrongType,
                format!("expected {}, found {found}", self.name()),
            )
        };
        match (self, value) {
            (Self::String | Self::SecretRef, Value::String(_))
            | (Self::Boolean, Value::Boolean(_))
            | (Self::StringList, Value::StringList(_)) => Ok(()),
            (Self::Integer { min, max }, Value::Integer(i)) => {
                if (min..=max).contains(i) {
                    Ok(())
                } else {
                    Err((
                        ValidationErrorKind::OutOfRange,
                        format!("must be between {min} and {max}"),
                    ))
                }
            }
            (Self::Enum { variants }, Value::String(s)) => {
                if variants.contains(&s.as_str()) {
                    Ok(())
                } else {
                    let list: Vec<String> = variants.iter().map(|v| format!("\"{v}\"")).collect();
                    Err((
                        ValidationErrorKind::InvalidValue,
                        format!("must be one of {}", list.join(", ")),
                    ))
                }
            }
            _ => Err(wrong()),
        }
    }
}

/// A default as it can be written in a `static` table.
#[derive(Debug, Clone, Copy)]
enum StaticDefault {
    Str(&'static str),
    Int(i64),
    Bool(bool),
    List(&'static [&'static str]),
}

impl StaticDefault {
    fn to_value(self) -> Value {
        match self {
            Self::Str(s) => Value::from(s),
            Self::Int(i) => Value::Integer(i),
            Self::Bool(b) => Value::Boolean(b),
            Self::List(l) => Value::from(l),
        }
    }
}

/// A field-specific rule applied after the type check.
type Rule = fn(&Value) -> Result<(), String>;

/// One field of the schema: its path, type, default, description and apply
/// class.
///
/// Descriptors are obtained from [`Schema::fields`] or [`Schema::field`]; they
/// cannot be constructed outside this crate.
///
/// # Examples
///
/// ```
/// use stratum_node_config::{schema, ApplyClass, Value};
///
/// let field = schema().field("limits.max_body_bytes").ok_or("missing field")?;
/// assert_eq!(field.apply_class(), ApplyClass::Restart);
/// assert_eq!(field.default_value(), Value::Integer(262_144));
/// assert!(field.validate(&Value::Integer(10)).is_err());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct FieldDescriptor {
    path: &'static str,
    value_type: ValueType,
    default: StaticDefault,
    description: &'static str,
    apply_class: ApplyClass,
    rule: Option<Rule>,
}

impl FieldDescriptor {
    /// Returns the dotted path, such as `listen.address`.
    pub fn path(&self) -> &'static str {
        self.path
    }

    /// Returns the table the field lives in: the part of the path before the
    /// first dot.
    pub fn section(&self) -> &'static str {
        self.split().0
    }

    /// Returns the key within its table: the part of the path after the
    /// first dot.
    pub fn key(&self) -> &'static str {
        self.split().1
    }

    fn split(&self) -> (&'static str, &'static str) {
        self.path.split_once('.').unwrap_or((self.path, ""))
    }

    /// Returns the field's type.
    pub fn value_type(&self) -> ValueType {
        self.value_type
    }

    /// Returns the value the field takes when a document omits it.
    pub fn default_value(&self) -> Value {
        self.default.to_value()
    }

    /// Returns the one-paragraph, plain-text description.
    pub fn description(&self) -> &'static str {
        self.description
    }

    /// Returns when a change to this field takes effect.
    pub fn apply_class(&self) -> ApplyClass {
        self.apply_class
    }

    /// Returns `true` if the field holds a secret reference.
    pub fn is_secret_ref(&self) -> bool {
        matches!(self.value_type, ValueType::SecretRef)
    }

    /// Checks `value` against this field's type, range and rule.
    ///
    /// Cross-field rules, such as the state and backup directories having to
    /// differ, are only checked by [`ConfigDocument::parse`](crate::ConfigDocument::parse).
    ///
    /// # Errors
    ///
    /// Returns a [`ValidationError`] at this field's path when the value has
    /// the wrong type, is out of range, or breaks the field's rule.
    pub fn validate(&self, value: &Value) -> Result<(), ValidationError> {
        self.value_type
            .check(value)
            .map_err(|(kind, msg)| ValidationError::at(kind, self.path, msg))?;
        match self.rule {
            Some(rule) => rule(value).map_err(|msg| {
                ValidationError::at(ValidationErrorKind::InvalidValue, self.path, msg)
            }),
            None => Ok(()),
        }
    }
}

/// Shows the path, type, default and apply class; the description and rule
/// are elided.
impl fmt::Debug for FieldDescriptor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FieldDescriptor")
            .field("path", &self.path)
            .field("value_type", &self.value_type)
            .field("default", &self.default_value())
            .field("apply_class", &self.apply_class)
            .finish_non_exhaustive()
    }
}

impl Serialize for FieldDescriptor {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut s = serializer.serialize_struct("FieldDescriptor", 5)?;
        s.serialize_field("path", self.path)?;
        s.serialize_field("type", &self.value_type)?;
        s.serialize_field("default", &self.default_value())?;
        s.serialize_field("description", self.description)?;
        s.serialize_field("apply_class", &self.apply_class)?;
        s.end()
    }
}

/// The complete `stratum.toml` schema.
///
/// There is one schema per library version; obtain it with [`schema`]. It
/// serialises as `{"schema_version": 1, "fields": [...]}` for the HTTP schema
/// endpoint, and every other part of this crate (validation, the seed
/// document, the public view) is derived from the same table.
///
/// # Examples
///
/// ```
/// use stratum_node_config::schema;
///
/// for field in schema().fields() {
///     println!("{} ({}): {}", field.path(), field.apply_class(), field.description());
/// }
/// assert!(schema().field("listen.address").is_some());
/// ```
pub struct Schema {
    fields: &'static [FieldDescriptor],
}

impl Schema {
    /// Returns [`SCHEMA_VERSION`].
    pub fn version(&self) -> u32 {
        SCHEMA_VERSION
    }

    /// Iterates over every field in schema order.
    pub fn fields(&self) -> Fields {
        Fields {
            inner: self.fields.iter(),
        }
    }

    /// Looks a field up by its dotted path.
    pub fn field(&self, path: &str) -> Option<&'static FieldDescriptor> {
        self.fields.iter().find(|f| f.path == path)
    }

    /// Returns the schema-order index of a field.
    pub(crate) fn index_of(&self, path: &str) -> Option<usize> {
        self.fields.iter().position(|f| f.path == path)
    }

    /// Returns the schema's field table.
    pub(crate) fn table(&self) -> &'static [FieldDescriptor] {
        self.fields
    }

    /// Iterates over the section names in order of first appearance.
    pub(crate) fn sections(&self) -> impl Iterator<Item = &'static str> {
        let fields = self.fields;
        fields
            .iter()
            .enumerate()
            .filter(move |(i, f)| !fields[..*i].iter().any(|g| g.section() == f.section()))
            .map(|(_, f)| f.section())
    }
}

/// Shows the version and the field paths.
impl fmt::Debug for Schema {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let paths: Vec<&str> = self.fields.iter().map(|d| d.path).collect();
        f.debug_struct("Schema")
            .field("version", &SCHEMA_VERSION)
            .field("fields", &paths)
            .finish()
    }
}

impl Serialize for Schema {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut s = serializer.serialize_struct("Schema", 2)?;
        s.serialize_field("schema_version", &SCHEMA_VERSION)?;
        s.serialize_field("fields", self.fields)?;
        s.end()
    }
}

/// Iterator over the schema's [`FieldDescriptor`]s, returned by
/// [`Schema::fields`].
#[derive(Debug, Clone)]
pub struct Fields {
    inner: std::slice::Iter<'static, FieldDescriptor>,
}

impl Iterator for Fields {
    type Item = &'static FieldDescriptor;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl DoubleEndedIterator for Fields {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back()
    }
}

impl ExactSizeIterator for Fields {}

impl FusedIterator for Fields {}

/// Returns the `stratum.toml` schema.
pub fn schema() -> &'static Schema {
    &SCHEMA
}

static SCHEMA: Schema = Schema { fields: FIELDS };

static FIELDS: &[FieldDescriptor] = &[
    FieldDescriptor {
        path: "node.name",
        value_type: ValueType::String,
        default: StaticDefault::Str("stratum"),
        description: "Human-readable name of this node, shown on the setup page, in \
            status output and to members. It is a label only and carries no authority. \
            It must be 1 to 64 characters with no control characters.",
        apply_class: ApplyClass::Live,
        rule: Some(rules::node_name),
    },
    FieldDescriptor {
        path: "node.canonical_origin",
        value_type: ValueType::String,
        default: StaticDefault::Str(""),
        description: "Public HTTPS origin the node is reached at, such as \
            https://pod.example.org. Leave it empty until the public origin is set up. \
            When set it must be an https:// origin with a lowercase host, an optional \
            non-default port, and no path, query, fragment or trailing slash. An IPv6 host \
            is written in brackets in its canonical RFC 5952 form, such as [2001:db8::1].",
        apply_class: ApplyClass::Redeploy,
        rule: Some(rules::canonical_origin),
    },
    FieldDescriptor {
        path: "listen.address",
        value_type: ValueType::String,
        default: StaticDefault::Str("127.0.0.1:7460"),
        description: "Socket address the controller's administrative API and setup page \
            listen on, written as ip:port. The IP must be a loopback address \
            (127.0.0.0/8 or [::1]); the API is never exposed on another interface.",
        apply_class: ApplyClass::Restart,
        rule: Some(rules::loopback_socket_address),
    },
    FieldDescriptor {
        path: "storage.state_dir",
        value_type: ValueType::String,
        default: StaticDefault::Str("/var/lib/stratum/state"),
        description: "Directory holding the node's store, keystore and bootstrap token. \
            It must be an absolute, normalised POSIX path (starting with /, no trailing \
            slash, no empty, . or .. components) and must neither equal, contain nor lie \
            inside storage.backup_dir. The running state directory is given on the \
            daemon's command line, not read from this field.",
        apply_class: ApplyClass::Restart,
        rule: Some(rules::absolute_path),
    },
    FieldDescriptor {
        path: "storage.backup_dir",
        value_type: ValueType::String,
        default: StaticDefault::Str("/var/lib/stratum/backups"),
        description: "Directory backups are written into, one subdirectory per backup. \
            It must be an absolute, normalised POSIX path and must neither equal, contain \
            nor lie inside storage.state_dir.",
        apply_class: ApplyClass::Restart,
        rule: Some(rules::absolute_path),
    },
    FieldDescriptor {
        path: "backup.age_recipients",
        value_type: ValueType::StringList,
        default: StaticDefault::List(&[]),
        description: "age public keys the keystore is encrypted to in each backup. Every \
            entry must be a post-quantum hybrid age recipient (ML-KEM-768 with X25519, as \
            written by age 0.13 and later), a lowercase Bech32 string beginning with age1pq1; \
            classical age1 recipients are refused. The list holds at most 32 entries. While \
            the list is empty, backups are refused.",
        apply_class: ApplyClass::Live,
        rule: Some(rules::age_recipients),
    },
    FieldDescriptor {
        path: "secrets.pod_admin_key_ref",
        value_type: ValueType::SecretRef,
        default: StaticDefault::Str(""),
        description: "Reserved and not read: the node generates the pod administration \
            key itself. The field is kept so that existing documents stay valid. Like every \
            secret reference it is left out of the public configuration and its hash and is \
            redacted in change lists. It must not contain whitespace or control characters.",
        apply_class: ApplyClass::Restart,
        rule: Some(rules::secret_ref),
    },
    FieldDescriptor {
        path: "federation.egress_enabled",
        value_type: ValueType::Boolean,
        default: StaticDefault::Bool(false),
        description: "Whether the node may open outbound federation connections to other \
            nodes. Off by default.",
        apply_class: ApplyClass::Live,
        rule: None,
    },
    FieldDescriptor {
        path: "membership.max_tenants",
        value_type: ValueType::Integer {
            min: 1,
            max: 10_000,
        },
        default: StaticDefault::Int(8),
        description: "Largest number of tenants the node admits. Members that are \
            reserved, provisioned or active count against it; a cancelled member does not. \
            A redemption that would exceed it is refused and its invitation stays issued. \
            Lowering it below the current count admits nobody new and removes nobody.",
        apply_class: ApplyClass::Live,
        rule: None,
    },
    FieldDescriptor {
        path: "membership.invitations_enabled",
        value_type: ValueType::Boolean,
        default: StaticDefault::Bool(true),
        description: "Whether the administrator may issue invitations and invitees may \
            redeem them. Turning it off refuses both; existing members keep working.",
        apply_class: ApplyClass::Live,
        rule: None,
    },
    FieldDescriptor {
        path: "membership.invitation_ttl_secs",
        value_type: ValueType::Integer {
            min: 60,
            max: 2_592_000,
        },
        default: StaticDefault::Int(604_800),
        description: "Lifetime, in seconds, of an invitation issued without an explicit \
            expiry: 604800 is seven days. At least 60 and at most 2592000 (30 days).",
        apply_class: ApplyClass::Live,
        rule: None,
    },
    FieldDescriptor {
        path: "limits.max_body_bytes",
        value_type: ValueType::Integer {
            min: 1024,
            max: 1_048_576,
        },
        default: StaticDefault::Int(262_144),
        description: "Largest request body, in bytes, the administrative API accepts. \
            Larger requests are refused before they are read in full.",
        apply_class: ApplyClass::Restart,
        rule: None,
    },
    FieldDescriptor {
        path: "limits.max_outstanding_challenges",
        value_type: ValueType::Integer { min: 1, max: 64 },
        default: StaticDefault::Int(16),
        description: "Largest number of unexpired bootstrap challenges held at once. A \
            request for a new challenge beyond this limit is refused.",
        apply_class: ApplyClass::Live,
        rule: None,
    },
    FieldDescriptor {
        path: "limits.max_pod_body_bytes",
        value_type: ValueType::Integer {
            min: 1024,
            max: 1_073_741_824,
        },
        default: StaticDefault::Int(16_777_216),
        description: "Largest request body, in bytes, the gate accepts on a pod route: \
            16777216 is 16 MiB. A larger body is refused with 413 before it is forwarded. \
            At least 1024 and at most 1073741824 (1 GiB).",
        apply_class: ApplyClass::Live,
        rule: None,
    },
    FieldDescriptor {
        path: "limits.admission_requests_per_minute",
        value_type: ValueType::Integer { min: 1, max: 6000 },
        default: StaticDefault::Int(30),
        description: "Largest number of redemption requests the gate passes to the node \
            per minute. Requests over the limit are refused with 429 and a Retry-After \
            header.",
        apply_class: ApplyClass::Live,
        rule: None,
    },
    FieldDescriptor {
        path: "limits.min_pod_free_bytes",
        value_type: ValueType::Integer {
            min: 0,
            max: i64::MAX,
        },
        default: StaticDefault::Int(1_073_741_824),
        description: "Free space, in bytes, below which the pod volume counts as low: \
            1073741824 is 1 GiB. While it is low the gate refuses every pod write with 507 \
            and reads continue. Zero turns the check off.",
        apply_class: ApplyClass::Live,
        rule: None,
    },
];

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

    static COLOURS: FieldDescriptor = FieldDescriptor {
        path: "test.colour",
        value_type: ValueType::Enum {
            variants: &["red", "green"],
        },
        default: StaticDefault::Str("red"),
        description: "Test-only enum field.",
        apply_class: ApplyClass::Live,
        rule: None,
    };

    #[test]
    fn enum_type_accepts_listed_variants_only() {
        assert!(
            COLOURS.validate(&Value::from("green")).is_ok(),
            "listed variant"
        );
        let err = COLOURS
            .validate(&Value::from("blue"))
            .expect_err("unlisted variant must fail");
        assert_eq!(err.kind(), ValidationErrorKind::InvalidValue, "kind");
        assert_eq!(err.message(), r#"must be one of "red", "green""#, "message");
        let err = COLOURS
            .validate(&Value::Integer(1))
            .expect_err("integer must fail");
        assert_eq!(err.kind(), ValidationErrorKind::WrongType, "kind");
        assert_eq!(err.path(), Some("test.colour"), "path");
    }

    #[test]
    fn sections_are_unique_and_in_order() {
        let sections: Vec<&str> = schema().sections().collect();
        assert_eq!(
            sections,
            [
                "node",
                "listen",
                "storage",
                "backup",
                "secrets",
                "federation",
                "membership",
                "limits"
            ],
            "section order"
        );
    }
}