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
//! The public view of the effective configuration and its hash.

use std::fmt;
use std::fmt::Write as _;

use serde::ser::{Serialize, SerializeMap, Serializer};
use sha2::{Digest, Sha256};

use crate::document::SCHEMA_VERSION_KEY;
use crate::schema::{schema, SCHEMA_VERSION};
use crate::value::Value;

/// The version of the public-configuration hash format.
///
/// It is mixed into every hash as the prefix line
/// `stratum.public-config.v1`, so a change to the encoding can never produce
/// a hash that collides with one made under an earlier format.
pub const PUBLIC_HASH_VERSION: u32 = 1;

/// The effective configuration with every secret-reference field removed.
///
/// Entries are held in byte order of their dotted paths. Serialises as a
/// JSON object whose first key is `schema_version`, followed by each dotted
/// path mapped to its value, so a client can recompute
/// [`PublicConfig::hash`] from the JSON alone.
///
/// # Examples
///
/// ```
/// use stratum_node_config::{schema, ConfigDocument, Value};
///
/// let doc = ConfigDocument::parse(&schema().seed_text())?;
/// let public = doc.public_config();
/// assert_eq!(public.get("listen.address"), Some(&Value::from("127.0.0.1:7460")));
/// assert_eq!(public.get("secrets.pod_admin_key_ref"), None);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublicConfig {
    entries: Vec<(&'static str, Value)>,
}

impl PublicConfig {
    /// Builds the public view from effective values in schema order.
    pub(crate) fn from_effective(values: &[Value]) -> Self {
        let mut entries: Vec<(&'static str, Value)> = schema()
            .fields()
            .zip(values)
            .filter(|(field, _)| !field.is_secret_ref())
            .map(|(field, value)| (field.path(), value.clone()))
            .collect();
        entries.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes()));
        Self { entries }
    }

    /// Returns the value at a dotted path, or `None` for secret-reference
    /// fields and paths not in the schema.
    pub fn get(&self, path: &str) -> Option<&Value> {
        self.entries
            .iter()
            .find(|(p, _)| *p == path)
            .map(|(_, v)| v)
    }

    /// Iterates over `(path, value)` pairs in byte order of the path.
    pub fn iter(&self) -> PublicIter<'_> {
        PublicIter {
            inner: self.entries.iter(),
        }
    }

    /// Returns the number of fields in the public view.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns `true` if the public view has no fields.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Returns the canonical TOML text the hash is computed over.
    ///
    /// The text is valid TOML. Its first line is
    /// `schema_version = <SCHEMA_VERSION>`. Every public field follows, one
    /// per line, as `<dotted.path> = <value>\n`, in byte order of the path.
    /// Values use a fixed encoding that does not depend on any TOML library:
    /// booleans are `true`/`false`; integers are decimal with a leading `-`
    /// when negative; strings are double-quoted with `"` and `\`
    /// backslash-escaped and every ASCII control character written as
    /// `\uXXXX` in upper-case hex, all other characters as literal UTF-8;
    /// lists are `[`, the encoded strings separated by `", "`, then `]`.
    /// Because no encoded value contains a raw newline and every string is
    /// delimited and escaped, distinct configurations give distinct texts.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_config::{schema, ConfigDocument};
    ///
    /// let doc = ConfigDocument::parse(&schema().seed_text())?;
    /// let text = doc.public_config().canonical_text();
    /// assert!(text.starts_with("schema_version = 1\nbackup.age_recipients = []\n"));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn canonical_text(&self) -> String {
        let mut out = format!("{SCHEMA_VERSION_KEY} = {SCHEMA_VERSION}\n");
        for (path, value) in &self.entries {
            out.push_str(path);
            out.push_str(" = ");
            value.write_canonical(&mut out);
            out.push('\n');
        }
        out
    }

    /// Returns the public-configuration hash.
    ///
    /// The hash is `SHA-256("stratum.public-config.v1\n" ‖ canonical_text)`,
    /// where the prefix carries [`PUBLIC_HASH_VERSION`] and `canonical_text`
    /// is [`PublicConfig::canonical_text`] encoded as UTF-8. Changing a
    /// secret reference never changes it; changing any other field's
    /// effective value, the schema version, or a default that a document
    /// relies on always does.
    pub fn hash(&self) -> PublicHash {
        let mut hasher = Sha256::new();
        hasher.update(format!("stratum.public-config.v{PUBLIC_HASH_VERSION}\n").as_bytes());
        hasher.update(self.canonical_text().as_bytes());
        PublicHash(hasher.finalize().into())
    }
}

impl Serialize for PublicConfig {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut map = serializer.serialize_map(Some(self.entries.len() + 1))?;
        map.serialize_entry(SCHEMA_VERSION_KEY, &SCHEMA_VERSION)?;
        for (path, value) in &self.entries {
            map.serialize_entry(path, value)?;
        }
        map.end()
    }
}

impl<'a> IntoIterator for &'a PublicConfig {
    type Item = (&'static str, &'a Value);
    type IntoIter = PublicIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Iterator over a [`PublicConfig`]'s `(path, value)` pairs, returned by
/// [`PublicConfig::iter`].
#[derive(Debug, Clone)]
pub struct PublicIter<'a> {
    inner: std::slice::Iter<'a, (&'static str, Value)>,
}

impl<'a> Iterator for PublicIter<'a> {
    type Item = (&'static str, &'a Value);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(p, v)| (*p, v))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl ExactSizeIterator for PublicIter<'_> {}

impl std::iter::FusedIterator for PublicIter<'_> {}

/// A SHA-256 public-configuration hash, from [`PublicConfig::hash`].
///
/// `Display` and `Serialize` give 64 lowercase hex digits.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PublicHash([u8; 32]);

impl PublicHash {
    /// Returns the raw 32 digest bytes.
    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// Returns the hash as 64 lowercase hex digits.
    pub fn to_hex(&self) -> String {
        let mut s = String::with_capacity(64);
        for b in self.0 {
            // Writing to a String cannot fail.
            let _ = write!(s, "{b:02x}");
        }
        s
    }
}

impl fmt::Display for PublicHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_hex())
    }
}

impl fmt::Debug for PublicHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "PublicHash({})", self.to_hex())
    }
}

impl Serialize for PublicHash {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.to_hex())
    }
}