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, active or suspended count against it; a cancelled or \
520 removed member does not. \
521 A redemption that would exceed it is refused and its invitation stays issued. \
522 Lowering it below the current count admits nobody new and removes nobody.",
523 apply_class: ApplyClass::Live,
524 rule: None,
525 },
526 FieldDescriptor {
527 path: "membership.invitations_enabled",
528 value_type: ValueType::Boolean,
529 default: StaticDefault::Bool(true),
530 description: "Whether the administrator may issue invitations and invitees may \
531 redeem them. Turning it off refuses both; existing members keep working.",
532 apply_class: ApplyClass::Live,
533 rule: None,
534 },
535 FieldDescriptor {
536 path: "membership.invitation_ttl_secs",
537 value_type: ValueType::Integer {
538 min: 60,
539 max: 2_592_000,
540 },
541 default: StaticDefault::Int(604_800),
542 description: "Lifetime, in seconds, of an invitation issued without an explicit \
543 expiry: 604800 is seven days. At least 60 and at most 2592000 (30 days).",
544 apply_class: ApplyClass::Live,
545 rule: None,
546 },
547 FieldDescriptor {
548 path: "membership.removal_grace_days",
549 value_type: ValueType::Integer { min: 0, max: 3650 },
550 default: StaticDefault::Int(30),
551 description: "Days after a member is removed or cancelled before `stratumd purge` may \
552 delete their pod data. The grace is fixed when the member is removed or \
553 cancelled, from the value configured then, so changing it later does not \
554 shorten a grace already given. Zero is allowed; the node never allows less \
555 than 120 seconds. Purge is always an explicit offline command: nothing deletes \
556 pod data when the grace ends. At most 3650.",
557 apply_class: ApplyClass::Live,
558 rule: None,
559 },
560 FieldDescriptor {
561 path: "limits.max_body_bytes",
562 value_type: ValueType::Integer {
563 min: 1024,
564 max: 1_048_576,
565 },
566 default: StaticDefault::Int(262_144),
567 description: "Largest request body, in bytes, the administrative API accepts. \
568 Larger requests are refused before they are read in full.",
569 apply_class: ApplyClass::Restart,
570 rule: None,
571 },
572 FieldDescriptor {
573 path: "limits.max_outstanding_challenges",
574 value_type: ValueType::Integer { min: 1, max: 64 },
575 default: StaticDefault::Int(16),
576 description: "Largest number of unexpired bootstrap challenges held at once. A \
577 request for a new challenge beyond this limit is refused.",
578 apply_class: ApplyClass::Live,
579 rule: None,
580 },
581 FieldDescriptor {
582 path: "limits.max_pod_body_bytes",
583 value_type: ValueType::Integer {
584 min: 1024,
585 max: 1_073_741_824,
586 },
587 default: StaticDefault::Int(16_777_216),
588 description: "Largest request body, in bytes, the gate accepts on a pod route: \
589 16777216 is 16 MiB. A larger body is refused with 413 before it is forwarded. \
590 At least 1024 and at most 1073741824 (1 GiB).",
591 apply_class: ApplyClass::Live,
592 rule: None,
593 },
594 FieldDescriptor {
595 path: "limits.admission_requests_per_minute",
596 value_type: ValueType::Integer { min: 1, max: 6000 },
597 default: StaticDefault::Int(30),
598 description: "Largest number of redemption requests the gate passes to the node \
599 per minute. Requests over the limit are refused with 429 and a Retry-After \
600 header.",
601 apply_class: ApplyClass::Live,
602 rule: None,
603 },
604 FieldDescriptor {
605 path: "limits.min_pod_free_bytes",
606 value_type: ValueType::Integer {
607 min: 0,
608 max: i64::MAX,
609 },
610 default: StaticDefault::Int(1_073_741_824),
611 description: "Free space, in bytes, below which the pod volume counts as low: \
612 1073741824 is 1 GiB. While it is low the gate refuses every pod write with 507 \
613 and reads continue. Zero turns the check off.",
614 apply_class: ApplyClass::Live,
615 rule: None,
616 },
617 FieldDescriptor {
618 path: "limits.pod_bytes_per_tenant",
619 value_type: ValueType::Integer {
620 min: 0,
621 max: i64::MAX,
622 },
623 default: StaticDefault::Int(10_737_418_240),
624 description: "Size limit, in bytes, of each tenant's pod: 10737418240 is 10 GiB. \
625 The node measures every pod periodically; a pod whose files total strictly \
626 more than this is over quota, and the gate then refuses PUT to it with 507 \
627 while GET, HEAD and DELETE continue. The limit is soft: writes that land \
628 between two measurements can overshoot it. Zero means no limit.",
629 apply_class: ApplyClass::Live,
630 rule: None,
631 },
632];
633
634#[cfg(test)]
635mod tests {
636 use super::*;
637
638 static COLOURS: FieldDescriptor = FieldDescriptor {
639 path: "test.colour",
640 value_type: ValueType::Enum {
641 variants: &["red", "green"],
642 },
643 default: StaticDefault::Str("red"),
644 description: "Test-only enum field.",
645 apply_class: ApplyClass::Live,
646 rule: None,
647 };
648
649 #[test]
650 fn enum_type_accepts_listed_variants_only() {
651 assert!(
652 COLOURS.validate(&Value::from("green")).is_ok(),
653 "listed variant"
654 );
655 let err = COLOURS
656 .validate(&Value::from("blue"))
657 .expect_err("unlisted variant must fail");
658 assert_eq!(err.kind(), ValidationErrorKind::InvalidValue, "kind");
659 assert_eq!(err.message(), r#"must be one of "red", "green""#, "message");
660 let err = COLOURS
661 .validate(&Value::Integer(1))
662 .expect_err("integer must fail");
663 assert_eq!(err.kind(), ValidationErrorKind::WrongType, "kind");
664 assert_eq!(err.path(), Some("test.colour"), "path");
665 }
666
667 #[test]
668 fn sections_are_unique_and_in_order() {
669 let sections: Vec<&str> = schema().sections().collect();
670 assert_eq!(
671 sections,
672 [
673 "node",
674 "listen",
675 "storage",
676 "backup",
677 "secrets",
678 "federation",
679 "membership",
680 "limits"
681 ],
682 "section order"
683 );
684 }
685}