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.",
465 apply_class: ApplyClass::Restart,
466 rule: Some(rules::absolute_path),
467 },
468 FieldDescriptor {
469 path: "storage.backup_dir",
470 value_type: ValueType::String,
471 default: StaticDefault::Str("/var/lib/stratum/backups"),
472 description: "Directory backups are written into, one subdirectory per backup. \
473 It must be an absolute, normalised POSIX path and must neither equal, contain \
474 nor lie inside storage.state_dir.",
475 apply_class: ApplyClass::Restart,
476 rule: Some(rules::absolute_path),
477 },
478 FieldDescriptor {
479 path: "backup.age_recipients",
480 value_type: ValueType::StringList,
481 default: StaticDefault::List(&[]),
482 description: "age public keys the keystore is encrypted to in each backup. Every \
483 entry must be a post-quantum hybrid age recipient (ML-KEM-768 with X25519, as \
484 written by age 0.13 and later), a lowercase Bech32 string beginning with age1pq1; \
485 classical age1 recipients are refused. The list holds at most 32 entries. While \
486 the list is empty, backups are refused.",
487 apply_class: ApplyClass::Live,
488 rule: Some(rules::age_recipients),
489 },
490 FieldDescriptor {
491 path: "secrets.pod_admin_key_ref",
492 value_type: ValueType::SecretRef,
493 default: StaticDefault::Str(""),
494 description: "Opaque reference to the pod administration key held by a custody \
495 service. This library never resolves it, it is left out of the public \
496 configuration and its hash, and it is redacted in change lists. Empty means \
497 no key is configured. It must not contain whitespace or control characters.",
498 apply_class: ApplyClass::Restart,
499 rule: Some(rules::secret_ref),
500 },
501 FieldDescriptor {
502 path: "federation.egress_enabled",
503 value_type: ValueType::Boolean,
504 default: StaticDefault::Bool(false),
505 description: "Whether the node may open outbound federation connections to other \
506 nodes. Off by default.",
507 apply_class: ApplyClass::Live,
508 rule: None,
509 },
510 FieldDescriptor {
511 path: "limits.max_body_bytes",
512 value_type: ValueType::Integer {
513 min: 1024,
514 max: 1_048_576,
515 },
516 default: StaticDefault::Int(262_144),
517 description: "Largest request body, in bytes, the administrative API accepts. \
518 Larger requests are refused before they are read in full.",
519 apply_class: ApplyClass::Restart,
520 rule: None,
521 },
522 FieldDescriptor {
523 path: "limits.max_outstanding_challenges",
524 value_type: ValueType::Integer { min: 1, max: 64 },
525 default: StaticDefault::Int(16),
526 description: "Largest number of unexpired bootstrap challenges held at once. A \
527 request for a new challenge beyond this limit is refused.",
528 apply_class: ApplyClass::Live,
529 rule: None,
530 },
531];
532
533#[cfg(test)]
534mod tests {
535 use super::*;
536
537 static COLOURS: FieldDescriptor = FieldDescriptor {
538 path: "test.colour",
539 value_type: ValueType::Enum {
540 variants: &["red", "green"],
541 },
542 default: StaticDefault::Str("red"),
543 description: "Test-only enum field.",
544 apply_class: ApplyClass::Live,
545 rule: None,
546 };
547
548 #[test]
549 fn enum_type_accepts_listed_variants_only() {
550 assert!(
551 COLOURS.validate(&Value::from("green")).is_ok(),
552 "listed variant"
553 );
554 let err = COLOURS
555 .validate(&Value::from("blue"))
556 .expect_err("unlisted variant must fail");
557 assert_eq!(err.kind(), ValidationErrorKind::InvalidValue, "kind");
558 assert_eq!(err.message(), r#"must be one of "red", "green""#, "message");
559 let err = COLOURS
560 .validate(&Value::Integer(1))
561 .expect_err("integer must fail");
562 assert_eq!(err.kind(), ValidationErrorKind::WrongType, "kind");
563 assert_eq!(err.path(), Some("test.colour"), "path");
564 }
565
566 #[test]
567 fn sections_are_unique_and_in_order() {
568 let sections: Vec<&str> = schema().sections().collect();
569 assert_eq!(
570 sections,
571 [
572 "node",
573 "listen",
574 "storage",
575 "backup",
576 "secrets",
577 "federation",
578 "limits"
579 ],
580 "section order"
581 );
582 }
583}