stratum-node-config 0.1.0-alpha.1

Versioned stratum.toml schema, comment-preserving editor, semantic validator, change preview and public-config hash for Stratum nodes
Documentation
//! Typed accessors over a validated configuration.

use std::fmt;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};

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

/// An opaque reference to a secret held by a custody service.
///
/// The reference names where a secret lives; it is not the secret, and this
/// library never resolves it. `Debug` is redacted so the reference does not
/// leak into logs by accident; read it explicitly with [`SecretRef::as_str`].
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct SecretRef(String);

impl SecretRef {
    /// Returns the reference text, for handing to the custody service.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for SecretRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("SecretRef(<redacted>)")
    }
}

/// The effective configuration of a valid document, with one strongly typed
/// getter per schema field.
///
/// Obtained from [`ConfigDocument::config`](crate::ConfigDocument::config).
/// Every value has already passed validation, so the getters cannot fail.
///
/// # Examples
///
/// ```
/// use stratum_node_config::{schema, ConfigDocument};
///
/// let doc = ConfigDocument::parse(&schema().seed_text())?;
/// let config = doc.config();
/// assert_eq!(config.listen_address().port(), 7460);
/// assert!(config.listen_address().ip().is_loopback());
/// assert_eq!(config.canonical_origin(), None);
/// assert_eq!(config.max_body_bytes(), 262_144);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
    node_name: String,
    canonical_origin: Option<String>,
    listen_address: SocketAddr,
    state_dir: PathBuf,
    backup_dir: PathBuf,
    age_recipients: Vec<String>,
    pod_admin_key_ref: Option<SecretRef>,
    federation_egress_enabled: bool,
    max_body_bytes: u32,
    max_outstanding_challenges: u32,
}

impl Config {
    /// Builds the typed view from effective values in schema order, one per
    /// schema field. Fails only if a value does not match its field, which
    /// validation rules out.
    ///
    /// # Panics
    ///
    /// Panics if `values` does not hold exactly one value per schema field,
    /// which is a bug in the caller.
    pub(crate) fn from_values(values: &[Value]) -> Result<Self, ValidationError> {
        let v = Lookup::new(values).expect("expected one value per schema field");
        let non_empty = |s: &str| (!s.is_empty()).then(|| s.to_owned());
        let listen = v.str("listen.address")?;
        Ok(Self {
            node_name: v.str("node.name")?.to_owned(),
            canonical_origin: non_empty(v.str("node.canonical_origin")?),
            listen_address: rules::parse_loopback(listen).map_err(|msg| {
                ValidationError::at(ValidationErrorKind::InvalidValue, "listen.address", msg)
            })?,
            state_dir: PathBuf::from(v.str("storage.state_dir")?),
            backup_dir: PathBuf::from(v.str("storage.backup_dir")?),
            age_recipients: v.list("backup.age_recipients")?.to_vec(),
            pod_admin_key_ref: non_empty(v.str("secrets.pod_admin_key_ref")?).map(SecretRef),
            federation_egress_enabled: v.bool("federation.egress_enabled")?,
            max_body_bytes: v.u32("limits.max_body_bytes")?,
            max_outstanding_challenges: v.u32("limits.max_outstanding_challenges")?,
        })
    }

    /// Returns `node.name`.
    pub fn node_name(&self) -> &str {
        &self.node_name
    }

    /// Returns `node.canonical_origin`, or `None` while it is empty.
    pub fn canonical_origin(&self) -> Option<&str> {
        self.canonical_origin.as_deref()
    }

    /// Returns `listen.address`, which is always a loopback address.
    pub fn listen_address(&self) -> SocketAddr {
        self.listen_address
    }

    /// Returns `storage.state_dir`, an absolute normalised path.
    pub fn state_dir(&self) -> &Path {
        &self.state_dir
    }

    /// Returns `storage.backup_dir`, an absolute normalised path distinct from
    /// and not nested with [`Config::state_dir`].
    pub fn backup_dir(&self) -> &Path {
        &self.backup_dir
    }

    /// Returns `backup.age_recipients`; each is a structurally valid age
    /// post-quantum hybrid recipient beginning with `age1pq1`.
    pub fn age_recipients(&self) -> &[String] {
        &self.age_recipients
    }

    /// Returns `secrets.pod_admin_key_ref`, or `None` while it is empty.
    pub fn pod_admin_key_ref(&self) -> Option<&SecretRef> {
        self.pod_admin_key_ref.as_ref()
    }

    /// Returns `federation.egress_enabled`.
    pub fn federation_egress_enabled(&self) -> bool {
        self.federation_egress_enabled
    }

    /// Returns `limits.max_body_bytes`, in `1024..=1048576`.
    pub fn max_body_bytes(&self) -> u32 {
        self.max_body_bytes
    }

    /// Returns `limits.max_outstanding_challenges`, in `1..=64`.
    pub fn max_outstanding_challenges(&self) -> u32 {
        self.max_outstanding_challenges
    }
}

/// Typed lookup of effective values by schema path.
struct Lookup<'v>(&'v [Value]);

impl<'v> Lookup<'v> {
    /// Wraps `values`, or returns `None` unless it holds exactly one value
    /// per schema field.
    fn new(values: &'v [Value]) -> Option<Self> {
        (values.len() == schema().table().len()).then_some(Self(values))
    }

    /// Looks up `path`. Only an unknown path fails: [`Lookup::new`] checked
    /// that every schema field has a value.
    fn get(&self, path: &'static str) -> Result<&'v Value, ValidationError> {
        let index = schema().index_of(path).ok_or_else(|| {
            ValidationError::at(
                ValidationErrorKind::UnknownKey,
                path,
                "field is not in the schema",
            )
        })?;
        Ok(&self.0[index])
    }

    fn mismatch(path: &'static str, expected: &str) -> ValidationError {
        ValidationError::at(
            ValidationErrorKind::WrongType,
            path,
            format!("expected {expected}"),
        )
    }

    fn str(&self, path: &'static str) -> Result<&'v str, ValidationError> {
        self.get(path)?
            .as_str()
            .ok_or_else(|| Self::mismatch(path, "a string"))
    }

    fn list(&self, path: &'static str) -> Result<&'v [String], ValidationError> {
        self.get(path)?
            .as_string_list()
            .ok_or_else(|| Self::mismatch(path, "a list of strings"))
    }

    fn bool(&self, path: &'static str) -> Result<bool, ValidationError> {
        self.get(path)?
            .as_bool()
            .ok_or_else(|| Self::mismatch(path, "a boolean"))
    }

    /// A non-integer is [`ValidationErrorKind::WrongType`]; an integer
    /// outside `u32` is [`ValidationErrorKind::OutOfRange`].
    fn u32(&self, path: &'static str) -> Result<u32, ValidationError> {
        let i = self
            .get(path)?
            .as_integer()
            .ok_or_else(|| Self::mismatch(path, "an integer"))?;
        u32::try_from(i).map_err(|_| {
            ValidationError::at(
                ValidationErrorKind::OutOfRange,
                path,
                format!("must be between 0 and {}", u32::MAX),
            )
        })
    }
}

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

    /// The effective values of the default configuration, in schema order.
    fn defaults() -> Vec<Value> {
        schema()
            .fields()
            .map(FieldDescriptor::default_value)
            .collect()
    }

    fn with(path: &str, value: Value) -> Vec<Value> {
        let mut values = defaults();
        let i = schema().index_of(path).expect("path in schema");
        values[i] = value;
        values
    }

    #[test]
    fn integer_outside_u32_is_out_of_range() {
        for n in [-1, i64::from(u32::MAX) + 1] {
            let values = with("limits.max_body_bytes", Value::Integer(n));
            let e = Lookup::new(&values)
                .expect("full value list")
                .u32("limits.max_body_bytes")
                .expect_err("out of range");
            assert_eq!(e.kind(), ValidationErrorKind::OutOfRange, "{n}");
            assert_eq!(e.message(), "must be between 0 and 4294967295", "{n}");
        }
        let values = with("limits.max_body_bytes", Value::Integer(4_294_967_295));
        assert_eq!(
            Lookup::new(&values)
                .expect("full value list")
                .u32("limits.max_body_bytes"),
            Ok(u32::MAX),
            "upper bound"
        );
    }

    #[test]
    fn non_integer_is_wrong_type() {
        let values = with("limits.max_body_bytes", Value::from("many"));
        let e = Lookup::new(&values)
            .expect("full value list")
            .u32("limits.max_body_bytes")
            .expect_err("wrong type");
        assert_eq!(e.kind(), ValidationErrorKind::WrongType, "kind");
        assert_eq!(e.message(), "expected an integer", "message");
    }

    #[test]
    fn unknown_path_is_unknown_key() {
        let values = defaults();
        let e = Lookup::new(&values)
            .expect("full value list")
            .get("limits.nope")
            .expect_err("unknown");
        assert_eq!(e.kind(), ValidationErrorKind::UnknownKey, "kind");
    }

    #[test]
    #[should_panic(expected = "expected one value per schema field")]
    fn short_value_list_is_a_bug_not_an_unknown_key() {
        let mut values = defaults();
        values.pop();
        let _ = Config::from_values(&values);
    }

    #[test]
    fn defaults_build_a_config() {
        let config = Config::from_values(&defaults()).expect("defaults are valid");
        assert_eq!(config.max_body_bytes(), 262_144, "default");
    }
}