vouch-core 4.0.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
//! The trusted roots a verifier uses when the caller names none, read as the
//! Python reference `vouch.trusted_roots` reads them.
//!
//! The host reads the `VOUCH_TRUSTED_ROOTS` environment variable and the
//! saved list (`~/.vouch/trusted_roots`, with its own file-safety checks);
//! this module turns that text into roots. Each root is normalized with
//! [`crate::did_web::normalize_root`].

use serde_json::{json, Value};

use crate::error::{CoreError, Result};

/// The environment variable that names trusted roots.
pub const ENV_VAR: &str = "VOUCH_TRUSTED_ROOTS";

use crate::did_web::py_space;

/// Python's `str.splitlines` boundaries.
fn py_line_break(c: char) -> bool {
    matches!(
        c,
        '\n' | '\r'
            | '\u{0b}'
            | '\u{0c}'
            | '\u{1c}'
            | '\u{1d}'
            | '\u{1e}'
            | '\u{85}'
            | '\u{2028}'
            | '\u{2029}'
    )
}

fn py_splitlines(text: &str) -> Vec<&str> {
    let mut lines = Vec::new();
    let mut start = 0;
    let mut chars = text.char_indices().peekable();
    while let Some((i, c)) = chars.next() {
        if py_line_break(c) {
            lines.push(&text[start..i]);
            let mut end = i + c.len_utf8();
            if c == '\r' {
                if let Some(&(j, '\n')) = chars.peek() {
                    chars.next();
                    end = j + 1;
                }
            }
            start = end;
        }
    }
    if start < text.len() {
        lines.push(&text[start..]);
    }
    lines
}

/// The roots a saved list names: one per line, blank lines and lines
/// starting with '#' skipped, a line that is not a DID or domain ignored,
/// and each root kept once, in order.
pub fn roots_from_text(text: &str) -> Vec<String> {
    let mut roots: Vec<String> = Vec::new();
    for line in py_splitlines(text) {
        let entry = line.trim_matches(py_space);
        if entry.is_empty() || entry.starts_with('#') {
            continue;
        }
        if let Ok(root) = crate::did_web::normalize_root(entry) {
            if !roots.contains(&root) {
                roots.push(root);
            }
        }
    }
    roots
}

/// The roots `VOUCH_TRUSTED_ROOTS` names (commas separate roots, as do line
/// breaks).
pub fn roots_from_env(value: &str) -> Vec<String> {
    roots_from_text(&value.replace(',', "\n"))
}

/// The roots a verifier uses when the caller passes none:
/// `VOUCH_TRUSTED_ROOTS` when it is set (even to nothing), else the saved
/// list. None when neither names any root. `env` is the variable's value
/// (None: not set); `saved` the saved file's text (None: no usable file).
pub fn default_roots(env: Option<&str>, saved: Option<&str>) -> Option<Vec<String>> {
    let roots = match env {
        Some(v) => roots_from_env(v),
        None => saved.map(roots_from_text).unwrap_or_default(),
    };
    (!roots.is_empty()).then_some(roots)
}

/// [`default_roots`] as JSON: `{"env": text or null, "saved": text or null}`
/// to `{"roots": [...] or null}`.
pub fn default_roots_json(request: &Value) -> Result<Value> {
    let obj = request
        .as_object()
        .ok_or_else(|| CoreError::Json("the request must be a JSON object".into()))?;
    let text = |name: &str| match obj.get(name) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(s)) => Ok(Some(s.as_str())),
        Some(_) => Err(CoreError::Json(format!("{name} must be text or null"))),
    };
    Ok(json!({"roots": default_roots(text("env")?, text("saved")?)}))
}

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

    #[test]
    fn splits_like_python() {
        assert_eq!(py_splitlines("a\r\nb\rc\n"), vec!["a", "b", "c"]);
        assert_eq!(py_splitlines("a\u{2028}b"), vec!["a", "b"]);
        assert_eq!(py_splitlines(""), Vec::<&str>::new());
        assert_eq!(py_splitlines("\n"), vec![""]);
    }

    #[test]
    fn env_set_to_nothing_wins_over_saved() {
        assert_eq!(default_roots(Some(""), Some("example.com")), None);
        assert_eq!(
            default_roots(None, Some("example.com\n# note\nexample.com")),
            Some(vec!["did:web:example.com".to_string()])
        );
    }
}