openbutler-protocol 0.0.2

The wire contract between the OpenButler daemon and its clients: frame encoding, action envelopes, and the shared state types.
Documentation
//! The audit record and its tamper-evident chain.
//!
//! The audit log answers "who did what, when, and did it succeed" and is
//! a *separate* system from the operational log (owner decision
//! 2026-11-30): its own file, append-only, never part of the 256 MiB
//! operational ring. Deletion is not a v1 operation — the file grows by
//! admin-action volume only (bytes per record, a handful of records per
//! day), and an archival/retention design is its own later decision.
//!
//! The chain is the evidence property: every record carries the hash of
//! the record before it (`prev`, genesis = 64 zeros) and a `hash` over
//! its own canonical body — SHA-256 of `prev`, a newline, and the record
//! as JSON with the `hash` field removed. `serde_json`'s default map is
//! key-sorted, so the body serialization is canonical. Editing or
//! removing a line in the middle breaks every `hash` after it; adding a
//! line at the end without knowing the tail's hash does not link.
//!
//! Sealing and verification live here (pure functions, no I/O) so the
//! writer daemon and any future independent verifier agree byte for byte.

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};

/// The audit record shape this crate writes and understands.
pub const AUDIT_SCHEMA: u32 = 1;

/// The chain head the first record links to.
pub const GENESIS: &str = "0000000000000000000000000000000000000000000000000000000000000000";

/// One audit record: who acted, what, how it ended, and the chain links.
/// Required fields have no serde default — a record cannot be built
/// without its evidence; `extra` and `target`/`code` may be empty but
/// present, so an old or foreign line still parses for diagnosis.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AuditRecord {
    /// The record shape number; [`AUDIT_SCHEMA`] for new records.
    pub schema: u32,
    /// The record's own id (`log-` registry ids — audit lines are logs
    /// of a different stream, same non-forgeable id shape).
    pub eventid: String,
    /// Full timestamp with timezone, RFC 3339.
    pub ts: String,
    /// The catalogued `audit.*` event name.
    pub event: String,
    /// Who acted: `local` (the host's own pipe), a device session id, or
    /// the attempted username on a denied login.
    pub actor: String,
    /// What was acted on — a provider name, a path, an action target;
    /// empty when nothing specific names it.
    pub target: String,
    /// `ok` | `denied` | `failed`.
    pub result: String,
    /// The refusal or error code (`FirstEventTimeout`-style), empty when
    /// the action ended clean.
    pub code: String,
    /// Which door asked: `pipe` (host identity) or `tcp` (a session).
    pub source: String,
    /// Structured detail; credential-shaped values are redacted before
    /// this map is written, exactly like the operational log.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extra: Option<Map<String, Value>>,
    /// The previous record's `hash` (64 hex; [`GENESIS`] first).
    pub prev: String,
    /// SHA-256 over `prev`, newline, and this record's canonical body
    /// (every field except `hash` itself).
    pub hash: String,
}

impl AuditRecord {
    /// Computes and stores this record's `hash` for the `prev` it
    /// carries. Call once, right before writing.
    pub fn seal(&mut self) {
        let prev = self.prev.clone();
        let body = serde_json::to_value(&*self).unwrap_or(Value::Null);
        self.hash = chain_hash(&prev, &body);
    }

    /// Whether this record links to `prev_hash` and its own hash is the
    /// one its body commits to.
    pub fn links_from(&self, prev_hash: &str) -> bool {
        if self.prev != prev_hash {
            return false;
        }
        let body = serde_json::to_value(self).unwrap_or(Value::Null);
        chain_hash(&self.prev, &body) == self.hash
    }
}

/// The chain hash: SHA-256 of `prev`, one newline, and the record's
/// canonical JSON with `hash` removed. Key order comes from
/// `serde_json`'s sorted map, so two runs of the same record agree.
pub fn chain_hash(prev: &str, body: &Value) -> String {
    let mut stripped = body.clone();
    if let Some(object) = stripped.as_object_mut() {
        object.remove("hash");
    }
    let canonical = serde_json::to_string(&stripped).unwrap_or_default();
    let mut hasher = Sha256::new();
    hasher.update(prev.as_bytes());
    hasher.update(b"\n");
    hasher.update(canonical.as_bytes());
    hasher
        .finalize()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

/// Walks a chain from [`GENESIS`]: every record must link to the hash
/// before it. Returns the last hash (the tail to append after), or the
/// index of the first record that does not link.
pub fn walk_chain(records: &[AuditRecord]) -> Result<String, usize> {
    let mut prev = GENESIS.to_owned();
    for (index, record) in records.iter().enumerate() {
        if !record.links_from(&prev) {
            return Err(index);
        }
        prev = record.hash.clone();
    }
    Ok(prev)
}

/// Parses one audit line (tolerant: unparsable lines are skipped by the
/// caller, which keeps a truncated last write from hiding the rest).
pub fn parse_line(line: &str) -> Option<AuditRecord> {
    let trimmed = line.trim();
    if !trimmed.starts_with('{') {
        return None;
    }
    serde_json::from_str(trimmed).ok()
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use super::*;
    use serde_json::json;

    fn sample(prev: &str) -> AuditRecord {
        AuditRecord {
            schema: AUDIT_SCHEMA,
            eventid: "log-0123456789abcdef".to_owned(),
            ts: "2026-11-30T20:00:00.000Z".to_owned(),
            event: "audit.login".to_owned(),
            actor: "local".to_owned(),
            target: String::new(),
            result: "ok".to_owned(),
            code: String::new(),
            source: "pipe".to_owned(),
            extra: None,
            prev: prev.to_owned(),
            hash: String::new(),
        }
    }

    #[test]
    fn a_sealed_record_links_and_a_tampered_one_does_not() {
        let mut first = sample(GENESIS);
        first.seal();
        assert_eq!(first.hash.len(), 64, "hex digest");
        assert!(first.links_from(GENESIS));

        let mut second = sample(&first.hash);
        second.seal();
        assert!(second.links_from(&first.hash), "the chain advances");

        // The evidence property: edit a fact after the fact and the
        // body no longer hashes to the stored hash.
        let mut tampered = second.clone();
        tampered.result = "denied".to_owned();
        assert!(
            !tampered.links_from(&first.hash),
            "a changed record must not link"
        );
        // Re-linking against the wrong predecessor fails too.
        assert!(!second.links_from(GENESIS));
    }

    #[test]
    fn walk_accepts_a_chain_and_rejects_a_removed_link() {
        let mut first = sample(GENESIS);
        first.seal();
        let mut second = sample(&first.hash);
        second.seal();
        let mut third = sample(&second.hash);
        third.seal();

        let tail = walk_chain(&[first.clone(), second.clone(), third.clone()]).unwrap();
        assert_eq!(tail, third.hash);

        // Middle record removed: third now sits after first and must fail.
        let broken = walk_chain(&[first, third]).expect_err("a gap breaks the chain");
        assert_eq!(broken, 1, "the record that does not link");
    }

    #[test]
    fn a_line_round_trips_and_the_body_is_canonical() {
        let mut record = sample(GENESIS);
        record.extra = Some(Map::from_iter([("note".to_owned(), json!("backup"))]));
        record.seal();
        let line = serde_json::to_string(&record).unwrap();
        let back = parse_line(&line).expect("parses");
        assert_eq!(back, record);
        // Sealing the parsed copy again reproduces the same hash: the
        // body serialization does not depend on insertion order.
        let mut copy = back;
        copy.hash.clear();
        copy.seal();
        assert_eq!(copy.hash, record.hash);
    }

    #[test]
    fn the_audit_event_name_shape_holds() {
        for name in ["audit.login", "audit.backup_taken", "audit.pruned"] {
            assert!(
                crate::eventlog::is_valid_event_name(name),
                "{name} must be category.action"
            );
        }
        assert!(!crate::eventlog::is_valid_event_name("audit"));
    }
}