1use std::fmt;
5use std::iter::FusedIterator;
6
7use serde::ser::{Serialize, SerializeStruct, Serializer};
8
9use crate::error::{ValidationError, ValidationErrorKind};
10use crate::rules;
11use crate::value::Value;
12
13pub const SCHEMA_VERSION: u32 = 1;
17
18pub const MAX_BACKUP_RECIPIENTS: usize = 32;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize)]
53#[serde(rename_all = "lowercase")]
54#[non_exhaustive]
55pub enum ApplyClass {
56 Live,
58 Restart,
60 Redeploy,
63}
64
65impl ApplyClass {
66 pub fn as_str(self) -> &'static str {
68 match self {
69 Self::Live => "live",
70 Self::Restart => "restart",
71 Self::Redeploy => "redeploy",
72 }
73 }
74}
75
76impl fmt::Display for ApplyClass {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 f.write_str(self.as_str())
79 }
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
87#[serde(tag = "kind", rename_all = "snake_case")]
88#[non_exhaustive]
89pub enum ValueType {
90 String,
92 Integer {
94 min: i64,
96 max: i64,
98 },
99 Boolean,
101 Enum {
103 variants: &'static [&'static str],
105 },
106 StringList,
108 SecretRef,
114}
115
116impl ValueType {
117 fn name(self) -> &'static str {
118 match self {
119 Self::String | Self::Enum { .. } | Self::SecretRef => "a string",
120 Self::Integer { .. } => "an integer",
121 Self::Boolean => "a boolean",
122 Self::StringList => "a list of strings",
123 }
124 }
125
126 fn check(self, value: &Value) -> Result<(), (ValidationErrorKind, String)> {
128 let found = value.kind_name();
129 let wrong = || {
130 (
131 ValidationErrorKind::WrongType,
132 format!("expected {}, found {found}", self.name()),
133 )
134 };
135 match (self, value) {
136 (Self::String | Self::SecretRef, Value::String(_))
137 | (Self::Boolean, Value::Boolean(_))
138 | (Self::StringList, Value::StringList(_)) => Ok(()),
139 (Self::Integer { min, max }, Value::Integer(i)) => {
140 if (min..=max).contains(i) {
141 Ok(())
142 } else {
143 Err((
144 ValidationErrorKind::OutOfRange,
145 format!("must be between {min} and {max}"),
146 ))
147 }
148 }
149 (Self::Enum { variants }, Value::String(s)) => {
150 if variants.contains(&s.as_str()) {
151 Ok(())
152 } else {
153 let list: Vec<String> = variants.iter().map(|v| format!("\"{v}\"")).collect();
154 Err((
155 ValidationErrorKind::InvalidValue,
156 format!("must be one of {}", list.join(", ")),
157 ))
158 }
159 }
160 _ => Err(wrong()),
161 }
162 }
163}
164
165#[derive(Debug, Clone, Copy)]
167enum StaticDefault {
168 Str(&'static str),
169 Int(i64),
170 Bool(bool),
171 List(&'static [&'static str]),
172}
173
174impl StaticDefault {
175 fn to_value(self) -> Value {
176 match self {
177 Self::Str(s) => Value::from(s),
178 Self::Int(i) => Value::Integer(i),
179 Self::Bool(b) => Value::Boolean(b),
180 Self::List(l) => Value::from(l),
181 }
182 }
183}
184
185type Rule = fn(&Value) -> Result<(), String>;
187
188pub struct FieldDescriptor {
206 path: &'static str,
207 value_type: ValueType,
208 default: StaticDefault,
209 description: &'static str,
210 apply_class: ApplyClass,
211 rule: Option<Rule>,
212}
213
214impl FieldDescriptor {
215 pub fn path(&self) -> &'static str {
217 self.path
218 }
219
220 pub fn section(&self) -> &'static str {
223 self.split().0
224 }
225
226 pub fn key(&self) -> &'static str {
229 self.split().1
230 }
231
232 fn split(&self) -> (&'static str, &'static str) {
233 self.path.split_once('.').unwrap_or((self.path, ""))
234 }
235
236 pub fn value_type(&self) -> ValueType {
238 self.value_type
239 }
240
241 pub fn default_value(&self) -> Value {
243 self.default.to_value()
244 }
245
246 pub fn description(&self) -> &'static str {
248 self.description
249 }
250
251 pub fn apply_class(&self) -> ApplyClass {
253 self.apply_class
254 }
255
256 pub fn is_secret_ref(&self) -> bool {
258 matches!(self.value_type, ValueType::SecretRef)
259 }
260
261 pub fn validate(&self, value: &Value) -> Result<(), ValidationError> {
271 self.value_type
272 .check(value)
273 .map_err(|(kind, msg)| ValidationError::at(kind, self.path, msg))?;
274 match self.rule {
275 Some(rule) => rule(value).map_err(|msg| {
276 ValidationError::at(ValidationErrorKind::InvalidValue, self.path, msg)
277 }),
278 None => Ok(()),
279 }
280 }
281}
282
283impl fmt::Debug for FieldDescriptor {
286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 f.debug_struct("FieldDescriptor")
288 .field("path", &self.path)
289 .field("value_type", &self.value_type)
290 .field("default", &self.default_value())
291 .field("apply_class", &self.apply_class)
292 .finish_non_exhaustive()
293 }
294}
295
296impl Serialize for FieldDescriptor {
297 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
298 let mut s = serializer.serialize_struct("FieldDescriptor", 5)?;
299 s.serialize_field("path", self.path)?;
300 s.serialize_field("type", &self.value_type)?;
301 s.serialize_field("default", &self.default_value())?;
302 s.serialize_field("description", self.description)?;
303 s.serialize_field("apply_class", &self.apply_class)?;
304 s.end()
305 }
306}
307
308pub struct Schema {
326 fields: &'static [FieldDescriptor],
327}
328
329impl Schema {
330 pub fn version(&self) -> u32 {
332 SCHEMA_VERSION
333 }
334
335 pub fn fields(&self) -> Fields {
337 Fields {
338 inner: self.fields.iter(),
339 }
340 }
341
342 pub fn field(&self, path: &str) -> Option<&'static FieldDescriptor> {
344 self.fields.iter().find(|f| f.path == path)
345 }
346
347 pub(crate) fn index_of(&self, path: &str) -> Option<usize> {
349 self.fields.iter().position(|f| f.path == path)
350 }
351
352 pub(crate) fn table(&self) -> &'static [FieldDescriptor] {
354 self.fields
355 }
356
357 pub(crate) fn sections(&self) -> impl Iterator<Item = &'static str> {
359 let fields = self.fields;
360 fields
361 .iter()
362 .enumerate()
363 .filter(move |(i, f)| !fields[..*i].iter().any(|g| g.section() == f.section()))
364 .map(|(_, f)| f.section())
365 }
366}
367
368impl fmt::Debug for Schema {
370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371 let paths: Vec<&str> = self.fields.iter().map(|d| d.path).collect();
372 f.debug_struct("Schema")
373 .field("version", &SCHEMA_VERSION)
374 .field("fields", &paths)
375 .finish()
376 }
377}
378
379impl Serialize for Schema {
380 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
381 let mut s = serializer.serialize_struct("Schema", 2)?;
382 s.serialize_field("schema_version", &SCHEMA_VERSION)?;
383 s.serialize_field("fields", self.fields)?;
384 s.end()
385 }
386}
387
388#[derive(Debug, Clone)]
391pub struct Fields {
392 inner: std::slice::Iter<'static, FieldDescriptor>,
393}
394
395impl Iterator for Fields {
396 type Item = &'static FieldDescriptor;
397
398 fn next(&mut self) -> Option<Self::Item> {
399 self.inner.next()
400 }
401
402 fn size_hint(&self) -> (usize, Option<usize>) {
403 self.inner.size_hint()
404 }
405}
406
407impl DoubleEndedIterator for Fields {
408 fn next_back(&mut self) -> Option<Self::Item> {
409 self.inner.next_back()
410 }
411}
412
413impl ExactSizeIterator for Fields {}
414
415impl FusedIterator for Fields {}
416
417pub fn schema() -> &'static Schema {
419 &SCHEMA
420}
421
422static SCHEMA: Schema = Schema { fields: FIELDS };
423
424static FIELDS: &[FieldDescriptor] = &[
425 FieldDescriptor {
426 path: "node.name",
427 value_type: ValueType::String,
428 default: StaticDefault::Str("stratum"),
429 description: "Human-readable name of this node, shown on the setup page, in \
430 status output and to members. It is a label only and carries no authority. \
431 It must be 1 to 64 characters with no control characters.",
432 apply_class: ApplyClass::Live,
433 rule: Some(rules::node_name),
434 },
435 FieldDescriptor {
436 path: "node.canonical_origin",
437 value_type: ValueType::String,
438 default: StaticDefault::Str(""),
439 description: "Public HTTPS origin the node is reached at, such as \
440 https://pod.example.org. Leave it empty until the public origin is set up. \
441 When set it must be an https:// origin with a lowercase host, an optional \
442 non-default port, and no path, query, fragment or trailing slash. An IPv6 host \
443 is written in brackets in its canonical RFC 5952 form, such as [2001:db8::1].",
444 apply_class: ApplyClass::Redeploy,
445 rule: Some(rules::canonical_origin),
446 },
447 FieldDescriptor {
448 path: "listen.address",
449 value_type: ValueType::String,
450 default: StaticDefault::Str("127.0.0.1:7460"),
451 description: "Socket address the controller's administrative API and setup page \
452 listen on, written as ip:port. The IP must be a loopback address \
453 (127.0.0.0/8 or [::1]); the API is never exposed on another interface.",
454 apply_class: ApplyClass::Restart,
455 rule: Some(rules::loopback_socket_address),
456 },
457 FieldDescriptor {
458 path: "storage.state_dir",
459 value_type: ValueType::String,
460 default: StaticDefault::Str("/var/lib/stratum/state"),
461 description: "Directory holding the node's store, keystore and bootstrap token. \
462 It must be an absolute, normalised POSIX path (starting with /, no trailing \
463 slash, no empty, . or .. components) and must neither equal, contain nor lie \
464 inside storage.backup_dir. The running state directory is given on the \
465 daemon's command line, not read from this field.",
466 apply_class: ApplyClass::Restart,
467 rule: Some(rules::absolute_path),
468 },
469 FieldDescriptor {
470 path: "storage.backup_dir",
471 value_type: ValueType::String,
472 default: StaticDefault::Str("/var/lib/stratum/backups"),
473 description: "Directory backups are written into, one subdirectory per backup. \
474 It must be an absolute, normalised POSIX path and must neither equal, contain \
475 nor lie inside storage.state_dir.",
476 apply_class: ApplyClass::Restart,
477 rule: Some(rules::absolute_path),
478 },
479 FieldDescriptor {
480 path: "backup.age_recipients",
481 value_type: ValueType::StringList,
482 default: StaticDefault::List(&[]),
483 description: "age public keys the keystore is encrypted to in each backup. Every \
484 entry must be a post-quantum hybrid age recipient (ML-KEM-768 with X25519, as \
485 written by age 0.13 and later), a lowercase Bech32 string beginning with age1pq1; \
486 classical age1 recipients are refused. The list holds at most 32 entries. While \
487 the list is empty, backups are refused.",
488 apply_class: ApplyClass::Live,
489 rule: Some(rules::age_recipients),
490 },
491 FieldDescriptor {
492 path: "secrets.pod_admin_key_ref",
493 value_type: ValueType::SecretRef,
494 default: StaticDefault::Str(""),
495 description: "Reserved and not read: the node generates the pod administration \
496 key itself. The field is kept so that existing documents stay valid. Like every \
497 secret reference it is left out of the public configuration and its hash and is \
498 redacted in change lists. It must not contain whitespace or control characters.",
499 apply_class: ApplyClass::Restart,
500 rule: Some(rules::secret_ref),
501 },
502 FieldDescriptor {
503 path: "federation.egress_enabled",
504 value_type: ValueType::Boolean,
505 default: StaticDefault::Bool(false),
506 description: "Whether the node may open outbound federation connections to other \
507 nodes. Off by default.",
508 apply_class: ApplyClass::Live,
509 rule: None,
510 },
511 FieldDescriptor {
512 path: "membership.max_tenants",
513 value_type: ValueType::Integer {
514 min: 1,
515 max: 10_000,
516 },
517 default: StaticDefault::Int(8),
518 description: "Largest number of tenants the node admits. Members that are \
519 reserved, provisioned or active count against it; a cancelled member does not. \
520 A redemption that would exceed it is refused and its invitation stays issued. \
521 Lowering it below the current count admits nobody new and removes nobody.",
522 apply_class: ApplyClass::Live,
523 rule: None,
524 },
525 FieldDescriptor {
526 path: "membership.invitations_enabled",
527 value_type: ValueType::Boolean,
528 default: StaticDefault::Bool(true),
529 description: "Whether the administrator may issue invitations and invitees may \
530 redeem them. Turning it off refuses both; existing members keep working.",
531 apply_class: ApplyClass::Live,
532 rule: None,
533 },
534 FieldDescriptor {
535 path: "membership.invitation_ttl_secs",
536 value_type: ValueType::Integer {
537 min: 60,
538 max: 2_592_000,
539 },
540 default: StaticDefault::Int(604_800),
541 description: "Lifetime, in seconds, of an invitation issued without an explicit \
542 expiry: 604800 is seven days. At least 60 and at most 2592000 (30 days).",
543 apply_class: ApplyClass::Live,
544 rule: None,
545 },
546 FieldDescriptor {
547 path: "limits.max_body_bytes",
548 value_type: ValueType::Integer {
549 min: 1024,
550 max: 1_048_576,
551 },
552 default: StaticDefault::Int(262_144),
553 description: "Largest request body, in bytes, the administrative API accepts. \
554 Larger requests are refused before they are read in full.",
555 apply_class: ApplyClass::Restart,
556 rule: None,
557 },
558 FieldDescriptor {
559 path: "limits.max_outstanding_challenges",
560 value_type: ValueType::Integer { min: 1, max: 64 },
561 default: StaticDefault::Int(16),
562 description: "Largest number of unexpired bootstrap challenges held at once. A \
563 request for a new challenge beyond this limit is refused.",
564 apply_class: ApplyClass::Live,
565 rule: None,
566 },
567 FieldDescriptor {
568 path: "limits.max_pod_body_bytes",
569 value_type: ValueType::Integer {
570 min: 1024,
571 max: 1_073_741_824,
572 },
573 default: StaticDefault::Int(16_777_216),
574 description: "Largest request body, in bytes, the gate accepts on a pod route: \
575 16777216 is 16 MiB. A larger body is refused with 413 before it is forwarded. \
576 At least 1024 and at most 1073741824 (1 GiB).",
577 apply_class: ApplyClass::Live,
578 rule: None,
579 },
580 FieldDescriptor {
581 path: "limits.admission_requests_per_minute",
582 value_type: ValueType::Integer { min: 1, max: 6000 },
583 default: StaticDefault::Int(30),
584 description: "Largest number of redemption requests the gate passes to the node \
585 per minute. Requests over the limit are refused with 429 and a Retry-After \
586 header.",
587 apply_class: ApplyClass::Live,
588 rule: None,
589 },
590 FieldDescriptor {
591 path: "limits.min_pod_free_bytes",
592 value_type: ValueType::Integer {
593 min: 0,
594 max: i64::MAX,
595 },
596 default: StaticDefault::Int(1_073_741_824),
597 description: "Free space, in bytes, below which the pod volume counts as low: \
598 1073741824 is 1 GiB. While it is low the gate refuses every pod write with 507 \
599 and reads continue. Zero turns the check off.",
600 apply_class: ApplyClass::Live,
601 rule: None,
602 },
603];
604
605#[cfg(test)]
606mod tests {
607 use super::*;
608
609 static COLOURS: FieldDescriptor = FieldDescriptor {
610 path: "test.colour",
611 value_type: ValueType::Enum {
612 variants: &["red", "green"],
613 },
614 default: StaticDefault::Str("red"),
615 description: "Test-only enum field.",
616 apply_class: ApplyClass::Live,
617 rule: None,
618 };
619
620 #[test]
621 fn enum_type_accepts_listed_variants_only() {
622 assert!(
623 COLOURS.validate(&Value::from("green")).is_ok(),
624 "listed variant"
625 );
626 let err = COLOURS
627 .validate(&Value::from("blue"))
628 .expect_err("unlisted variant must fail");
629 assert_eq!(err.kind(), ValidationErrorKind::InvalidValue, "kind");
630 assert_eq!(err.message(), r#"must be one of "red", "green""#, "message");
631 let err = COLOURS
632 .validate(&Value::Integer(1))
633 .expect_err("integer must fail");
634 assert_eq!(err.kind(), ValidationErrorKind::WrongType, "kind");
635 assert_eq!(err.path(), Some("test.colour"), "path");
636 }
637
638 #[test]
639 fn sections_are_unique_and_in_order() {
640 let sections: Vec<&str> = schema().sections().collect();
641 assert_eq!(
642 sections,
643 [
644 "node",
645 "listen",
646 "storage",
647 "backup",
648 "secrets",
649 "federation",
650 "membership",
651 "limits"
652 ],
653 "section order"
654 );
655 }
656}