stratum-node-config 0.1.0-alpha.4

Versioned stratum.toml schema, comment-preserving editor, semantic validator, change preview and public-config hash for Stratum nodes
Documentation
//! Field-specific rules applied after the type check. Each returns a
//! lowercase message on failure and never echoes secret values.

use std::net::{Ipv6Addr, SocketAddr};

use crate::recipient;
use crate::schema::MAX_BACKUP_RECIPIENTS;
use crate::value::Value;

/// Longest accepted `node.name`, in characters.
const MAX_NODE_NAME_CHARS: usize = 64;

pub(crate) fn node_name(value: &Value) -> Result<(), String> {
    let s = value.as_str().unwrap_or_default();
    if s.is_empty() {
        return Err("must not be empty".to_owned());
    }
    if s.chars().count() > MAX_NODE_NAME_CHARS {
        return Err(format!("must be at most {MAX_NODE_NAME_CHARS} characters"));
    }
    if s.chars().any(char::is_control) {
        return Err("must not contain control characters".to_owned());
    }
    Ok(())
}

pub(crate) fn canonical_origin(value: &Value) -> Result<(), String> {
    let s = value.as_str().unwrap_or_default();
    if s.is_empty() {
        return Ok(());
    }
    let Some(authority) = s.strip_prefix("https://") else {
        return Err("must start with \"https://\"".to_owned());
    };
    if authority.contains(['/', '?', '#']) {
        return Err("must be an origin with no path, query, fragment or trailing slash".to_owned());
    }
    if authority.contains('@') {
        return Err("must not contain user information".to_owned());
    }
    if authority
        .chars()
        .any(|c| c.is_whitespace() || c.is_control())
    {
        return Err("must not contain whitespace or control characters".to_owned());
    }
    let (host_ok, port) = if let Some(rest) = authority.strip_prefix('[') {
        let Some((host, after)) = rest.split_once(']') else {
            return Err("has an unterminated ipv6 literal".to_owned());
        };
        let port = match after {
            "" => None,
            p => match p.strip_prefix(':') {
                Some(p) => Some(p),
                None => return Err("has text after the ipv6 literal".to_owned()),
            },
        };
        // One spelling per address: the RFC 5952 text form, which is what
        // `Ipv6Addr`'s `Display` writes (lowercase, no leading zeros, the
        // longest run of two or more zero groups compressed).
        match host.parse::<Ipv6Addr>() {
            Ok(addr) if addr.to_string() == host => {}
            Ok(_) => {
                return Err(
                    "must write the ipv6 address in canonical lowercase form (rfc 5952)".to_owned(),
                )
            }
            Err(_) => return Err("must name a valid lowercase host".to_owned()),
        }
        (true, port)
    } else {
        let (host, port) = match authority.split_once(':') {
            Some((h, p)) => (h, Some(p)),
            None => (authority, None),
        };
        (is_dns_host(host), port)
    };
    if !host_ok {
        return Err("must name a valid lowercase host".to_owned());
    }
    if let Some(port) = port {
        let valid = !port.is_empty()
            && port.bytes().all(|b| b.is_ascii_digit())
            && !port.starts_with('0')
            && port.parse::<u16>().is_ok();
        if !valid {
            return Err("must have a port between 1 and 65535".to_owned());
        }
        if port == "443" {
            return Err("must omit the default port 443".to_owned());
        }
    }
    Ok(())
}

/// A lowercase DNS name or IPv4 literal: dot-separated labels of 1 to 63
/// characters from `a-z`, `0-9` and `-`, not starting or ending with `-`.
fn is_dns_host(host: &str) -> bool {
    !host.is_empty()
        && host.len() <= 253
        && host.split('.').all(|label| {
            !label.is_empty()
                && label.len() <= 63
                && !label.starts_with('-')
                && !label.ends_with('-')
                && label
                    .bytes()
                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
        })
}

/// Parses a listen address; shared with [`crate::Config`].
pub(crate) fn parse_loopback(s: &str) -> Result<SocketAddr, String> {
    let addr: SocketAddr = s
        .parse()
        .map_err(|_| "must be a socket address such as 127.0.0.1:7460 or [::1]:7460".to_owned())?;
    if !addr.ip().is_loopback() {
        return Err("must use a loopback ip address".to_owned());
    }
    Ok(addr)
}

pub(crate) fn loopback_socket_address(value: &Value) -> Result<(), String> {
    parse_loopback(value.as_str().unwrap_or_default()).map(|_| ())
}

pub(crate) fn absolute_path(value: &Value) -> Result<(), String> {
    let s = value.as_str().unwrap_or_default();
    let Some(rest) = s.strip_prefix('/') else {
        return Err("must be an absolute path starting with \"/\"".to_owned());
    };
    if rest.is_empty() {
        return Err("must not be the filesystem root".to_owned());
    }
    if s.chars().any(char::is_control) {
        return Err("must not contain control characters".to_owned());
    }
    if rest.ends_with('/') {
        return Err("must not end with \"/\"".to_owned());
    }
    for component in rest.split('/') {
        match component {
            "" => return Err("must not contain empty components".to_owned()),
            "." | ".." => return Err("must not contain \".\" or \"..\" components".to_owned()),
            _ => {}
        }
    }
    Ok(())
}

/// The cross-field rule between the two storage directories, checked only
/// when both are individually valid. Returns the message for `backup_dir`.
pub(crate) fn distinct_dirs(state_dir: &str, backup_dir: &str) -> Result<(), String> {
    let inside = |inner: &str, outer: &str| {
        inner
            .strip_prefix(outer)
            .is_some_and(|rest| rest.starts_with('/'))
    };
    if state_dir == backup_dir {
        Err("must differ from storage.state_dir".to_owned())
    } else if inside(backup_dir, state_dir) {
        Err("must not lie inside storage.state_dir".to_owned())
    } else if inside(state_dir, backup_dir) {
        Err("must not contain storage.state_dir".to_owned())
    } else {
        Ok(())
    }
}

/// At most [`MAX_BACKUP_RECIPIENTS`] entries, each an age post-quantum
/// hybrid recipient (ADR D14); see [`crate::recipient`] for exactly what is
/// checked. The count is checked first, so a list that is too long is
/// reported as such whatever its entries hold.
pub(crate) fn age_recipients(value: &Value) -> Result<(), String> {
    let list = value.as_string_list().unwrap_or_default();
    if list.len() > MAX_BACKUP_RECIPIENTS {
        return Err(format!(
            "must hold at most {MAX_BACKUP_RECIPIENTS} recipients, found {}",
            list.len()
        ));
    }
    for (i, r) in list.iter().enumerate() {
        recipient::check_post_quantum(r).map_err(|e| format!("entry {} {}", i + 1, e.message()))?;
    }
    Ok(())
}

pub(crate) fn secret_ref(value: &Value) -> Result<(), String> {
    let s = value.as_str().unwrap_or_default();
    if s.chars().any(|c| c.is_whitespace() || c.is_control()) {
        return Err("must not contain whitespace or control characters".to_owned());
    }
    Ok(())
}