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;
pub const SCHEMA_VERSION: u32 = 1;
pub const MAX_BACKUP_RECIPIENTS: usize = 32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ApplyClass {
Live,
Restart,
Redeploy,
}
impl ApplyClass {
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())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum ValueType {
String,
Integer {
min: i64,
max: i64,
},
Boolean,
Enum {
variants: &'static [&'static str],
},
StringList,
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",
}
}
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()),
}
}
}
#[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),
}
}
}
type Rule = fn(&Value) -> Result<(), String>;
pub struct FieldDescriptor {
path: &'static str,
value_type: ValueType,
default: StaticDefault,
description: &'static str,
apply_class: ApplyClass,
rule: Option<Rule>,
}
impl FieldDescriptor {
pub fn path(&self) -> &'static str {
self.path
}
pub fn section(&self) -> &'static str {
self.split().0
}
pub fn key(&self) -> &'static str {
self.split().1
}
fn split(&self) -> (&'static str, &'static str) {
self.path.split_once('.').unwrap_or((self.path, ""))
}
pub fn value_type(&self) -> ValueType {
self.value_type
}
pub fn default_value(&self) -> Value {
self.default.to_value()
}
pub fn description(&self) -> &'static str {
self.description
}
pub fn apply_class(&self) -> ApplyClass {
self.apply_class
}
pub fn is_secret_ref(&self) -> bool {
matches!(self.value_type, ValueType::SecretRef)
}
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(()),
}
}
}
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()
}
}
pub struct Schema {
fields: &'static [FieldDescriptor],
}
impl Schema {
pub fn version(&self) -> u32 {
SCHEMA_VERSION
}
pub fn fields(&self) -> Fields {
Fields {
inner: self.fields.iter(),
}
}
pub fn field(&self, path: &str) -> Option<&'static FieldDescriptor> {
self.fields.iter().find(|f| f.path == path)
}
pub(crate) fn index_of(&self, path: &str) -> Option<usize> {
self.fields.iter().position(|f| f.path == path)
}
pub(crate) fn table(&self) -> &'static [FieldDescriptor] {
self.fields
}
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())
}
}
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()
}
}
#[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 {}
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, active or suspended count against it; a cancelled or \
removed 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: "membership.removal_grace_days",
value_type: ValueType::Integer { min: 0, max: 3650 },
default: StaticDefault::Int(30),
description: "Days after a member is removed or cancelled before `stratumd purge` may \
delete their pod data. The grace is fixed when the member is removed or \
cancelled, from the value configured then, so changing it later does not \
shorten a grace already given. Zero is allowed; the node never allows less \
than 120 seconds. Purge is always an explicit offline command: nothing deletes \
pod data when the grace ends. At most 3650.",
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,
},
FieldDescriptor {
path: "limits.pod_bytes_per_tenant",
value_type: ValueType::Integer {
min: 0,
max: i64::MAX,
},
default: StaticDefault::Int(10_737_418_240),
description: "Size limit, in bytes, of each tenant's pod: 10737418240 is 10 GiB. \
The node measures every pod periodically; a pod whose files total strictly \
more than this is over quota, and the gate then refuses PUT to it with 507 \
while GET, HEAD and DELETE continue. The limit is soft: writes that land \
between two measurements can overshoot it. Zero means no limit.",
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"
);
}
}