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
//! Parsing and validating `stratum.toml` text.

use std::fmt;

use toml_edit::{DocumentMut, TableLike};

use crate::config::Config;
use crate::error::{ValidationError, ValidationErrorKind, ValidationErrors};
use crate::public::{PublicConfig, PublicHash};
use crate::rules;
use crate::schema::{schema, SCHEMA_VERSION};
use crate::value::Value;

/// The largest `stratum.toml` this crate accepts, in bytes: 256 KiB.
///
/// [`ConfigDocument::parse`] and [`preview`](crate::preview) refuse longer
/// text before parsing it, and `preview` also refuses an edit whose result
/// would be longer, before diffing or validating it. A real configuration is
/// a few kilobytes; the bound keeps parse, diff and validation work small for
/// an HTTP caller that sends an oversized body or change.
pub const MAX_DOCUMENT_BYTES: usize = 256 * 1024;

/// The top-level key carrying the schema version.
pub(crate) const SCHEMA_VERSION_KEY: &str = "schema_version";

/// A validated `stratum.toml` document: its exact text plus the effective
/// configuration with defaults filled in.
///
/// The only way to obtain one is [`ConfigDocument::parse`] (or
/// [`Preview::document`](crate::Preview::document)), so holding a
/// `ConfigDocument` proves the text passed every rule in the schema.
///
/// # Examples
///
/// ```
/// use stratum_node_config::{ConfigDocument, Value};
///
/// let doc = ConfigDocument::parse(
///     "schema_version = 1\n\n[node]\nname = \"alpha\"\n",
/// )?;
/// assert_eq!(doc.config().node_name(), "alpha");
/// // Omitted fields take their defaults.
/// assert_eq!(doc.value("limits.max_outstanding_challenges"), Some(&Value::Integer(16)));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct ConfigDocument {
    text: String,
    values: Vec<Value>,
    config: Config,
}

impl ConfigDocument {
    /// Parses and validates `stratum.toml` text.
    ///
    /// # Errors
    ///
    /// Returns every problem found, not just the first: a TOML syntax error
    /// (reported alone, since nothing else can be checked), a missing or
    /// unsupported `schema_version`, unknown keys and tables, values of the
    /// wrong type, integers out of range, values that break a field's rule,
    /// and cross-field conflicts. Text longer than [`MAX_DOCUMENT_BYTES`] is
    /// refused unparsed with a single [`ValidationErrorKind::TooLarge`] error.
    ///
    /// # Examples
    ///
    /// ```
    /// use stratum_node_config::{ConfigDocument, ValidationErrorKind};
    ///
    /// let text = "schema_version = 1\n[limits]\nmax_body_bytes = 1\ncolour = \"red\"\n";
    /// let errors = ConfigDocument::parse(text).err().ok_or("expected errors")?;
    /// let kinds: Vec<_> = errors.iter().map(|e| (e.path(), e.kind())).collect();
    /// assert_eq!(kinds, [
    ///     (Some("limits.colour"), ValidationErrorKind::UnknownKey),
    ///     (Some("limits.max_body_bytes"), ValidationErrorKind::OutOfRange),
    /// ]);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn parse(text: &str) -> Result<Self, ValidationErrors> {
        if text.len() > MAX_DOCUMENT_BYTES {
            return Err(ValidationErrors::one(ValidationError::new(
                ValidationErrorKind::TooLarge,
                None,
                format!("document is larger than the {MAX_DOCUMENT_BYTES}-byte limit"),
            )));
        }
        let doc = parse_toml(text).map_err(ValidationErrors::one)?;
        Self::from_toml(text.to_owned(), &doc)
    }

    /// Validates an already parsed document whose text is `text`.
    pub(crate) fn from_toml(text: String, doc: &DocumentMut) -> Result<Self, ValidationErrors> {
        let analysis = analyse(doc);
        if let Some(errors) = ValidationErrors::from_vec(analysis.errors) {
            return Err(errors);
        }
        // Every field has a value once analysis reports no error; collecting
        // into `Option` keeps a missing one from shifting later indices.
        let values: Vec<Value> = analysis
            .values
            .into_iter()
            .collect::<Option<_>>()
            .expect("analysis without errors yields a value for every field");
        let config = Config::from_values(&values).map_err(ValidationErrors::one)?;
        Ok(Self {
            text,
            values,
            config,
        })
    }

    /// Returns the exact document text, comments and layout included.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the effective value of a field, with its default filled in
    /// when the document omits it, or `None` for a path not in the schema.
    pub fn value(&self, path: &str) -> Option<&Value> {
        schema().index_of(path).and_then(|i| self.values.get(i))
    }

    /// Returns the typed view of the effective configuration.
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// Returns the effective configuration without its secret-reference
    /// fields, safe to show to anyone who may see the node's status.
    pub fn public_config(&self) -> PublicConfig {
        PublicConfig::from_effective(&self.values)
    }

    /// Returns the SHA-256 hash of the public configuration, as defined on
    /// [`PublicConfig::hash`].
    pub fn public_hash(&self) -> PublicHash {
        self.public_config().hash()
    }
}

/// Redacted: shows the typed configuration (whose secret reference is
/// itself redacted) and the public hash, never the raw text.
impl fmt::Debug for ConfigDocument {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ConfigDocument")
            .field("config", &self.config)
            .field("public_hash", &self.public_hash())
            .finish_non_exhaustive()
    }
}

/// Parses TOML, turning a syntax error into a [`ValidationError`].
///
/// The message is fixed text plus the line and column of the error. The
/// parser's own description is deliberately dropped: it can quote the
/// offending input, which may be a secret-reference value.
pub(crate) fn parse_toml(text: &str) -> Result<DocumentMut, ValidationError> {
    text.parse::<DocumentMut>().map_err(|e| {
        let message = match e.span() {
            Some(span) => {
                let (line, column) = line_column(text, span.start);
                format!("invalid toml at line {line}, column {column}")
            }
            None => "invalid toml".to_owned(),
        };
        ValidationError::new(ValidationErrorKind::Syntax, None, message)
    })
}

/// One-based line and column (in characters) of a byte offset.
fn line_column(text: &str, offset: usize) -> (usize, usize) {
    let before = text.get(..offset).unwrap_or(text);
    let line = before.matches('\n').count() + 1;
    let column = before.rsplit('\n').next().map_or(0, |l| l.chars().count()) + 1;
    (line, column)
}

/// The outcome of checking a syntactically valid document.
pub(crate) struct Analysis {
    /// Effective values in schema order: the document's value when it has
    /// the field's type (even if it breaks a rule), the default when the
    /// field is absent, and `None` when the document holds the wrong type.
    pub(crate) values: Vec<Option<Value>>,
    pub(crate) errors: Vec<ValidationError>,
}

/// Checks a parsed document against the schema, collecting every error.
pub(crate) fn analyse(doc: &DocumentMut) -> Analysis {
    let mut errors = Vec::new();
    check_schema_version(doc, &mut errors);
    check_unknown_keys(doc, &mut errors);

    let mut values = Vec::with_capacity(schema().table().len());
    for field in schema().fields() {
        let section = doc.get(field.section()).and_then(|i| i.as_table_like());
        let value = match section.and_then(|t| t.get(field.key())) {
            None => Some(field.default_value()),
            Some(item) => match Value::from_toml(item) {
                Ok(value) => {
                    if let Err(e) = field.validate(&value) {
                        errors.push(e);
                    }
                    Some(value)
                }
                Err(found) => {
                    errors.push(ValidationError::at(
                        ValidationErrorKind::WrongType,
                        field.path(),
                        format!("expected {}, found {found}", type_name(field)),
                    ));
                    None
                }
            },
        };
        values.push(value);
    }

    if let Some(e) = check_cross_field(&values, &errors) {
        errors.push(e);
    }
    Analysis { values, errors }
}

fn type_name(field: &crate::schema::FieldDescriptor) -> &'static str {
    field.default_value().kind_name()
}

fn check_schema_version(doc: &DocumentMut, errors: &mut Vec<ValidationError>) {
    let key = SCHEMA_VERSION_KEY;
    match doc.get(key) {
        None => errors.push(ValidationError::new(
            ValidationErrorKind::MissingSchemaVersion,
            Some(key),
            format!("missing; add schema_version = {SCHEMA_VERSION}"),
        )),
        Some(item) => match item.as_integer() {
            Some(v) if v == i64::from(SCHEMA_VERSION) => {}
            Some(v) => errors.push(ValidationError::at(
                ValidationErrorKind::UnsupportedSchemaVersion,
                key,
                format!("unsupported schema version {v}; this library supports {SCHEMA_VERSION}"),
            )),
            None => errors.push(ValidationError::at(
                ValidationErrorKind::WrongType,
                key,
                "expected an integer",
            )),
        },
    }
}

fn check_unknown_keys(doc: &DocumentMut, errors: &mut Vec<ValidationError>) {
    for (key, item) in doc.iter() {
        if key == SCHEMA_VERSION_KEY {
            continue;
        }
        if !schema().sections().any(|s| s == key) {
            errors.push(ValidationError::at(
                ValidationErrorKind::UnknownKey,
                key,
                "unknown key",
            ));
            continue;
        }
        let Some(table) = item.as_table_like() else {
            errors.push(ValidationError::at(
                ValidationErrorKind::WrongType,
                key,
                "expected a table",
            ));
            continue;
        };
        check_unknown_in_table(key, table, errors);
    }
}

fn check_unknown_in_table(section: &str, table: &dyn TableLike, errors: &mut Vec<ValidationError>) {
    for (key, _) in table.iter() {
        let path = format!("{section}.{key}");
        if schema().field(&path).is_none() {
            errors.push(ValidationError::at(
                ValidationErrorKind::UnknownKey,
                &path,
                "unknown key",
            ));
        }
    }
}

/// Applies cross-field rules to fields that are individually valid. A field
/// that already has an error is skipped so it is reported once.
fn check_cross_field(
    values: &[Option<Value>],
    errors: &[ValidationError],
) -> Option<ValidationError> {
    let clean = |path: &str| -> Option<&str> {
        if errors.iter().any(|e| e.path() == Some(path)) {
            return None;
        }
        schema()
            .index_of(path)
            .and_then(|i| values.get(i))
            .and_then(Option::as_ref)
            .and_then(Value::as_str)
    };
    let state = clean("storage.state_dir")?;
    let backup = clean("storage.backup_dir")?;
    rules::distinct_dirs(state, backup)
        .err()
        .map(|msg| ValidationError::at(ValidationErrorKind::Conflict, "storage.backup_dir", msg))
}

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

    #[test]
    fn line_column_counts_from_one() {
        assert_eq!(line_column("ab\ncd", 4), (2, 2), "second line");
        assert_eq!(line_column("ab", 0), (1, 1), "start");
    }
}