Skip to main content

sysknife_daemon/
audit_chain.rs

1//! Forward Ed25519-signed hash chain for the audit log.
2//!
3//! Each `transactions` row stores `chain_hash` and `prev_chain_hash` columns.
4//! On insert, the daemon computes
5//!
6//! ```text
7//! chain_hash = ed25519_sign(ROW_DOMAIN || canonical(immutable_fields) || prev_chain_hash, signing_key)
8//! ```
9//!
10//! The `ROW_DOMAIN` prefix is **part of the signed message**, not decoration:
11//! it is what stops a row signature from ever verifying as a checkpoint or
12//! approval-receipt signature. An independent verifier that omits it will
13//! never reproduce a valid `chain_hash`.
14//!
15//! and stores both (the signature is hex-encoded; the first row in a chain has
16//! `prev_chain_hash = ""`). Ed25519 signatures are deterministic (RFC 8032), so
17//! the same content always produces the same `chain_hash`.
18//!
19//! Verification (`sysknife audit verify`) walks rows in `seq` order and checks
20//! each row's signature **with the public key**, reporting the first broken
21//! link. Because verification needs only the public key, an auditor or a
22//! central log aggregator can verify the chain **without holding the private
23//! key** — they cannot forge entries. This is the property a symmetric MAC
24//! (the previous HMAC-SHA256 design) could not provide: with an HMAC, the
25//! verifier and the forger are the same principal.
26//!
27//! ## Threat model
28//!
29//! - **Non-repudiation (asymmetric).** The daemon signs with the private key;
30//!   anyone with the exported public key (`<key>.pub`) can verify but not
31//!   forge. A compromise of the verifier does not enable forgery.
32//! - **Compromised host / root.** An attacker who reads the private key file
33//!   can forge *future* entries. Mitigation is to anchor signed checkpoints to
34//!   an append-only external sink (see `checkpoint_sink`) so that later
35//!   tampering with past entries becomes *detectable* and the tamper window is
36//!   bounded to "after compromise".
37//! - **Tail truncation** is undetectable by the chain walk alone: an attacker
38//!   who deletes the last K rows leaves a still-consistent chain. It is caught
39//!   by anchoring signed checkpoints to an independent append-only sink, since
40//!   a truncated chain can no longer reproduce a previously anchored
41//!   `(seq, chain_tip)` (see `verify_checkpoints` and `checkpoint_sink`). The
42//!   best-effort `audit_watermark` journald forward is a lighter complement.
43//! - **In-flight modification** between insert and read is mitigated by
44//!   computing the signature *before* INSERT and writing it in the same SQL
45//!   statement.
46//! - **Status mutations are not in the chain.** The mutable `status` field
47//!   is intentionally excluded — the chain protects the *authorisation
48//!   decision* (immutable fields captured at insert time), not the live
49//!   execution state. Status transitions ARE chained, separately: the
50//!   append-only `audit_events` table exists (created by migration v2 in
51//!   `transactions.rs`) and `verify_event_chain` / `verify_event_binding`
52//!   below verify it. This paragraph described that as future work long
53//!   after it shipped, which is worse than saying nothing — a reader would
54//!   conclude the capability is missing and either duplicate it or assume
55//!   status history is unprotected.
56//!
57//! ## Key management
58//!
59//! The Ed25519 private key (a 32-byte seed) lives in a file. By default the
60//! path is `<db_dir>/audit-key` (sibling of the SQLite database, or of
61//! whatever directory `sysknife_core::default_database_path` resolves to in
62//! production), and the env var `SYSKNIFE_AUDIT_KEY_PATH` overrides it for
63//! systemd unit drop-ins (typically `/etc/sysknife/audit-key`). The file is
64//! created with mode `0o600` on first daemon start if it does not exist;
65//! subsequent runs refuse to start if it is world-readable. The public key is
66//! written alongside as `<key>.pub` (hex) for auditors and aggregators.
67//!
68//! Future epochs (key rotation): each row already carries a `key_id`
69//! column. A planned rotation flow appends a checkpoint row signed with the
70//! outgoing key whose payload references both public-key fingerprints;
71//! verification walks the chain through epoch boundaries by looking up each
72//! row's `key_id` in a directory of retired public keys. For now, all rows use
73//! `key_id = "v1"` and rotation is manual (delete the chain, regenerate).
74
75use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
76use sha2::{Digest, Sha256};
77use std::path::{Path, PathBuf};
78use sysknife_types::RiskLevel;
79use zeroize::Zeroize;
80
81/// Stable identifier for the current key generation. Stored in every row.
82/// Tied to the schema, not the key bytes — rotation will introduce `"v2"` etc.
83pub const CURRENT_KEY_ID: &str = "v1";
84
85/// Hex-encoded length of an Ed25519 signature (64 raw bytes → 128 hex chars).
86pub const HASH_HEX_LEN: usize = 128;
87
88/// Domain-separation tags for Ed25519 signing contexts. They MUST stay distinct
89/// and prefix-free so a signature made in one context can never verify in any
90/// other. Enforced by the `domain_tags_are_distinct_and_prefix_free` test.
91const ROW_DOMAIN: &[u8] = b"sysknife-audit-row-v1\x1f";
92const CHECKPOINT_DOMAIN: &[u8] = b"sysknife-checkpoint-v1\x1f";
93const APPROVAL_DOMAIN: &[u8] = b"sysknife-approval-receipt-v1\x1f";
94const EVENT_DOMAIN: &[u8] = b"sysknife-audit-event-v1\x1f";
95
96/// Row encoding written before the caller-identity migration: no
97/// `caller_role`, no `event_tip`. Still verifiable — see [`ChainIdentity`].
98pub const CHAIN_VERSION_LEGACY: u32 = 1;
99/// Row encoding that added `caller_role` and `event_tip`.
100///
101/// This is a **stable literal, never an alias for the newest version**. The v2
102/// encoder signs this value, and `ChainRow::identity` dispatches stored rows
103/// against it. Point either at `CHAIN_VERSION_CURRENT` and the next encoding
104/// bump silently re-encodes every v2 row on disk, breaking audit logs while the
105/// unit suite stays green, because in-memory tests sign and verify under the
106/// same constant. `a_row_written_by_the_previous_release_still_verifies` is the
107/// golden vector that notices.
108pub const CHAIN_VERSION_V2: u32 = 2;
109/// Row encoding that added `caller_principal` on top of v2, so a row names the
110/// account that asked, not only its role class.
111///
112/// A stable literal for the same reason [`CHAIN_VERSION_V2`] is one: the v3
113/// encoder signs this value and `ChainRow::identity` dispatches stored v3 rows
114/// against it, so it must not move when a v4 encoding arrives.
115/// `a_v3_row_on_disk_still_verifies` is the golden vector that notices if it does.
116pub const CHAIN_VERSION_V3: u32 = 3;
117/// The encoding this binary *writes*. Always an alias for the newest versioned
118/// constant, never used to encode or dispatch a specific generation.
119///
120/// Kept distinct from the per-version literals because those two jobs pull in
121/// opposite directions: the writer must move with each new encoding, while every
122/// stored generation must keep being reproduced byte for byte forever.
123pub const CHAIN_VERSION_CURRENT: u32 = CHAIN_VERSION_V3;
124
125/// Loaded Ed25519 signing key + its identifier. Construct via
126/// [`AuditKey::load_or_generate`].
127///
128/// `Clone` is intentional: the audit-verify CLI needs to load the key once
129/// and share it between the SQLite read-only path and the Postgres pool.
130///
131/// `Debug` is implemented manually to redact the signing key. A derived
132/// `Debug` would dump the private key via any `tracing::debug!("{key:?}")`
133/// or `dbg!(key)` site, which would leak the audit secret into journald.
134/// We keep `key_id` visible because operators need to identify which key
135/// generation a record belongs to when triaging chain breaks.
136#[derive(Clone)]
137pub struct AuditKey {
138    key_id: String,
139    signing: SigningKey,
140}
141
142impl std::fmt::Debug for AuditKey {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        // Never render the private key. A derived `Debug` (or printing the
145        // signing key) would leak the audit secret into journald via any
146        // `tracing::debug!("{key:?}")`. `key_id` is not secret and is kept
147        // visible for triaging chain breaks.
148        f.debug_struct("AuditKey")
149            .field("key_id", &self.key_id)
150            .field("signing", &format_args!("<redacted signing key>"))
151            .finish()
152    }
153}
154
155// The `SigningKey` zeroizes its secret scalar on drop (ed25519-dalek `zeroize`
156// feature), so no manual `Drop` is needed to keep the private key out of
157// post-free memory.
158
159#[derive(Debug, thiserror::Error)]
160pub enum AuditKeyError {
161    #[error("io error reading audit key {path}: {source}")]
162    Io {
163        path: PathBuf,
164        #[source]
165        source: std::io::Error,
166    },
167    #[error(
168        "audit key file {path} has unsafe permissions {mode:#o}; \
169         tighten with `chmod 600 {path:?}` and restart"
170    )]
171    UnsafePermissions { path: PathBuf, mode: u32 },
172    #[error(
173        "audit key file {path} is too short ({len} bytes); \
174         expected at least 32 bytes of random material"
175    )]
176    KeyTooShort { path: PathBuf, len: usize },
177}
178
179impl AuditKey {
180    /// Load the audit key from `path`. If the file does not exist, generate a
181    /// 32-byte cryptographically random key and write it with mode `0o600`.
182    ///
183    /// On every load (including freshly generated), the file's permissions
184    /// are checked: any bit beyond `0o600` for owner-only access is rejected
185    /// — a world-readable audit key is a self-defeating audit chain.
186    pub fn load_or_generate(path: &Path) -> Result<Self, AuditKeyError> {
187        if !path.exists() {
188            generate_key_at(path)?;
189        }
190
191        let metadata = std::fs::metadata(path).map_err(|e| AuditKeyError::Io {
192            path: path.to_path_buf(),
193            source: e,
194        })?;
195
196        use std::os::unix::fs::PermissionsExt;
197        let mode = metadata.permissions().mode() & 0o777;
198        if mode & 0o077 != 0 {
199            // Group or world bits set — reject.
200            return Err(AuditKeyError::UnsafePermissions {
201                path: path.to_path_buf(),
202                mode,
203            });
204        }
205
206        let mut key_bytes = std::fs::read(path).map_err(|e| AuditKeyError::Io {
207            path: path.to_path_buf(),
208            source: e,
209        })?;
210        if key_bytes.len() < 32 {
211            return Err(AuditKeyError::KeyTooShort {
212                path: path.to_path_buf(),
213                len: key_bytes.len(),
214            });
215        }
216
217        let mut seed = [0u8; 32];
218        seed.copy_from_slice(&key_bytes[..32]);
219        let signing = SigningKey::from_bytes(&seed);
220        seed.zeroize();
221        key_bytes.zeroize();
222
223        Ok(Self {
224            key_id: CURRENT_KEY_ID.to_string(),
225            signing,
226        })
227    }
228
229    /// Construct a key from a 32-byte seed. For tests only — production builds
230    /// always go through [`Self::load_or_generate`] for the permission check.
231    #[cfg(test)]
232    pub fn from_bytes(bytes: Vec<u8>) -> Self {
233        let mut seed = [0u8; 32];
234        seed.copy_from_slice(&bytes[..32]);
235        let signing = SigningKey::from_bytes(&seed);
236        seed.zeroize();
237        Self {
238            key_id: CURRENT_KEY_ID.to_string(),
239            signing,
240        }
241    }
242
243    /// Stable identifier for this key generation.
244    pub fn key_id(&self) -> &str {
245        &self.key_id
246    }
247
248    /// Compute the chain signature for `content` linked to `prev_chain_hash`.
249    ///
250    /// Hex-encoded Ed25519 signature over `canonical(content) || prev_chain_hash`.
251    /// Deterministic (RFC 8032): identical inputs always yield the same value.
252    pub fn chain_hash(&self, content: &ChainContent, prev_chain_hash: &str) -> String {
253        let sig = self.signing.sign(&chain_message(content, prev_chain_hash));
254        hex::encode(sig.to_bytes())
255    }
256
257    /// The public verifying key for this audit key.
258    pub fn verifying_key(&self) -> VerifyingKey {
259        self.signing.verifying_key()
260    }
261
262    /// Hex-encoded 32-byte Ed25519 public key. Safe to publish; auditors use it
263    /// to verify the chain without the ability to forge entries.
264    pub fn verifying_key_hex(&self) -> String {
265        hex::encode(self.signing.verifying_key().to_bytes())
266    }
267
268    /// Derive the bearer receipt for one immutable preview. The signature is
269    /// deterministic, so a failed response delivery can be retried without
270    /// storing plaintext bearer credentials in the database.
271    pub fn approval_receipt(&self, transaction_id: &str, request_hash: &str) -> String {
272        // Frame both fields through `push_field` (the same escaping used for
273        // chain rows) so the signed message is injective in
274        // (transaction_id, request_hash). Raw concatenation with a bare 0x1F
275        // would alias distinct inputs if either field ever contained 0x1F;
276        // escaping removes that dependency on the callers' value shapes.
277        let mut message = APPROVAL_DOMAIN.to_vec();
278        push_field(&mut message, "txid", transaction_id);
279        push_field(&mut message, "reqhash", request_hash);
280        hex::encode(self.signing.sign(&message).to_bytes())
281    }
282
283    /// Chain-stored SHA-256 commitment to the deterministic approval receipt.
284    pub fn approval_commitment(&self, transaction_id: &str, request_hash: &str) -> String {
285        approval_receipt_digest(&self.approval_receipt(transaction_id, request_hash))
286    }
287}
288
289pub fn approval_receipt_digest(receipt: &str) -> String {
290    hex::encode(Sha256::digest(receipt.as_bytes()))
291}
292
293/// Message signed for a row: `ROW_DOMAIN || canonical(content) || prev_chain_hash`.
294///
295/// The leading domain tag separates row signatures from checkpoint signatures
296/// so a signature produced in one context can never verify in the other, even
297/// if the framed fields were ever to overlap.
298fn chain_message(content: &ChainContent, prev_chain_hash: &str) -> Vec<u8> {
299    let mut msg = ROW_DOMAIN.to_vec();
300    msg.extend_from_slice(&content.canonical_bytes());
301    msg.extend_from_slice(prev_chain_hash.as_bytes());
302    msg
303}
304
305/// Resolve the audit key file path: `$SYSKNIFE_AUDIT_KEY_PATH` if set,
306/// otherwise `<db_dir>/audit-key` (sibling of the database). This is the single
307/// definition of the key-location precedence documented in the module header;
308/// the CLI verify/checkpoint paths resolve through it so they always agree with
309/// the daemon on where the key lives.
310pub fn resolve_audit_key_path(db_path: &Path) -> PathBuf {
311    std::env::var("SYSKNIFE_AUDIT_KEY_PATH")
312        .map(PathBuf::from)
313        .unwrap_or_else(|_| {
314            db_path
315                .parent()
316                .unwrap_or_else(|| Path::new("."))
317                .join("audit-key")
318        })
319}
320
321/// Generate a 32-byte random key and write it to `path` with mode `0o600`.
322/// Parent directory is created with mode `0o700` if missing.
323fn generate_key_at(path: &Path) -> Result<(), AuditKeyError> {
324    use std::io::Write as _;
325    use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
326
327    if let Some(parent) = path.parent() {
328        if !parent.exists() {
329            std::fs::DirBuilder::new()
330                .recursive(true)
331                .mode(0o700)
332                .create(parent)
333                .map_err(|e| AuditKeyError::Io {
334                    path: parent.to_path_buf(),
335                    source: e,
336                })?;
337        }
338    }
339
340    let mut bytes = [0u8; 32];
341    fill_random(&mut bytes).map_err(|e| AuditKeyError::Io {
342        path: path.to_path_buf(),
343        source: e,
344    })?;
345
346    let mut f = std::fs::OpenOptions::new()
347        .write(true)
348        .create_new(true)
349        .mode(0o600)
350        .open(path)
351        .map_err(|e| AuditKeyError::Io {
352            path: path.to_path_buf(),
353            source: e,
354        })?;
355    f.write_all(&bytes).map_err(|e| AuditKeyError::Io {
356        path: path.to_path_buf(),
357        source: e,
358    })?;
359    f.sync_all().map_err(|e| AuditKeyError::Io {
360        path: path.to_path_buf(),
361        source: e,
362    })?;
363
364    // Write the public key alongside as `<key>.pub` (hex). Not secret: it lets
365    // an auditor or aggregator verify the chain without the private key.
366    let signing = SigningKey::from_bytes(&bytes);
367    let pub_hex = hex::encode(signing.verifying_key().to_bytes());
368    bytes.zeroize();
369    let mut pub_path = path.as_os_str().to_os_string();
370    pub_path.push(".pub");
371    std::fs::write(&pub_path, format!("{pub_hex}\n")).map_err(|e| AuditKeyError::Io {
372        path: PathBuf::from(pub_path),
373        source: e,
374    })?;
375    Ok(())
376}
377
378/// Fill `buf` with bytes from the kernel CSPRNG via `/dev/urandom`.
379fn fill_random(buf: &mut [u8]) -> std::io::Result<()> {
380    use std::io::Read as _;
381    let mut f = std::fs::File::open("/dev/urandom")?;
382    f.read_exact(buf)
383}
384
385/// Immutable fields hashed into the chain. Status is intentionally absent —
386/// see module docs.
387///
388/// # Security contract — chain-content immutability
389///
390/// Every field in this struct is captured **once** at INSERT time and baked
391/// into `chain_hash = ed25519_sign(canonical(self) || prev_chain_hash, key)`.
392/// After the row is written the hash is a one-time commitment: **no field
393/// in this struct may ever be mutated in place**.
394///
395/// `summary` is the field most likely to attract a future "let me just fix
396/// that typo" API. **Do not add an `update_summary` (or similar) function.**
397/// If a correction is genuinely needed, choose one of the two safe options:
398///
399/// 1. **Insert a corrective row** — a new transaction row that references the
400///    original `transaction_id` in its own `summary`, leaving the original
401///    row and its chain hash untouched.
402/// 2. **Extend the chain protocol** — introduce a dedicated amendment record
403///    type with its own chain link, so that both the original commitment and
404///    the correction are auditable.
405///
406/// Any other approach silently breaks chain integrity: `verify_chain` will
407/// flag the modified row as `Broken` because the stored signature will no
408/// longer verify against the row's content.
409///
410/// The canonical serialisation is stable across SQLite/Postgres backends.
411/// Each field is emitted as
412///
413/// ```text
414///     <tag-name> 0x1E <tag-value> 0x1F
415/// ```
416///
417/// where `0x1E` is the *tag/value* separator within a single field and `0x1F`
418/// is the *field* separator that terminates the field and introduces the
419/// next one. We use the ASCII C0 byte values RS (0x1E) and US (0x1F)
420/// because they are guaranteed not to appear in any normal text field, but
421/// **our role assignment is the inverse of the ASCII C0 convention**
422/// (where RS = "record separator" and US = "unit separator"). The names
423/// are kept in the source for byte-level traceability against the canonical
424/// buffer, not as a claim about ASCII semantics.
425///
426/// Inside a value, the four
427/// bytes `\\`, NUL, `RS`, `US` are escaped to `\\\\`, `\\0`, `\\1E`, `\\1F`
428/// respectively. The escape table is **prefix-free** (every escape starts
429/// with `\\`), so any value can be injected without ambiguity. See
430/// `push_field` for the implementation and tests for the round-trip.
431/// Which generation of the canonical row encoding a row was signed under.
432///
433/// # Why this is an enum and not two `Option` fields
434///
435/// Adding a field to [`ChainContent`] changes the signed message, so every row
436/// written before the change would re-encode differently and report as
437/// `Broken`. Chains already exist in the field, and "delete your audit log to
438/// upgrade" is not an acceptable migration for an audit log. The stored
439/// `chain_version` column therefore selects the encoding **per row**: legacy
440/// rows keep the exact bytes they were signed over, new rows carry the
441/// identity fields.
442///
443/// A downgrade is not a hiding place. Rewriting a `V2` row as `LegacyV1` (to
444/// erase `caller_role`) makes verification re-encode it without the identity
445/// fields, so the stored signature — made over the `V2` message — no longer
446/// verifies and the row reports as `Broken`.
447#[derive(Debug, Clone, Copy, PartialEq, Eq)]
448pub enum ChainIdentity<'a> {
449    /// `chain_version = 1`. Written before the identity migration.
450    LegacyV1,
451    /// `chain_version = 2`. Binds the row to the authenticated caller and to
452    /// the approval-event chain tip at insert time.
453    V2 {
454        /// Role the daemon resolved for the connection that requested this
455        /// action (`SO_PEERCRED` for Unix sockets, token for vsock). Signing it
456        /// lets an auditor answer which privilege tier asked; naming the account
457        /// is v3's `caller_principal`.
458        caller_role: &'a str,
459        /// `chain_hash` of the last [`EventRow`] at insert time, or `""` when
460        /// the event chain is empty. This is the cross-chain binding: because
461        /// checkpoints anchor the *transaction* chain tip, a committed
462        /// `event_tip` transitively anchors the event chain, so deleting
463        /// approval events below it becomes detectable.
464        event_tip: &'a str,
465    },
466    /// `chain_version = 3`. Everything v2 binds, plus the individual account.
467    ///
468    /// v2 answers "an Admin did this". On a host with two members of
469    /// `sysknife-admin` their signed records were indistinguishable, so the
470    /// trail could not answer the first question an investigation asks. v3
471    /// signs a principal as well.
472    V3 {
473        /// As v2.
474        caller_role: &'a str,
475        /// As v2.
476        event_tip: &'a str,
477        /// Scheme-prefixed identity of the caller, produced by
478        /// [`crate::auth::CallerPrincipal`]: `uid:1000` for a Unix-socket peer
479        /// whose credentials the kernel attested, `token:vsock` for a vsock
480        /// connection authenticated by the pre-shared token, and
481        /// `none:unattributed` when the daemon could establish neither.
482        ///
483        /// The scheme is signed along with the value on purpose. An auditor must
484        /// be able to tell a kernel-attested account from a shared secret that
485        /// any holder could have presented, and a bare string would erase that
486        /// difference.
487        caller_principal: &'a str,
488    },
489}
490
491impl ChainIdentity<'_> {
492    /// `chain_version` column value for this encoding.
493    pub fn version(&self) -> u32 {
494        match self {
495            Self::LegacyV1 => CHAIN_VERSION_LEGACY,
496            Self::V2 { .. } => CHAIN_VERSION_V2,
497            Self::V3 { .. } => CHAIN_VERSION_V3,
498        }
499    }
500}
501
502#[derive(Debug, Clone, PartialEq, Eq)]
503pub struct ChainContent<'a> {
504    pub seq: u64,
505    pub key_id: &'a str,
506    pub transaction_id: &'a str,
507    pub request_id: &'a str,
508    pub request_hash: &'a str,
509    pub action_name: &'a str,
510    pub risk_level: RiskLevel,
511    /// Human-readable description of the planned action.
512    ///
513    /// **Immutable after insert.** This field is included in the chain hash
514    /// (see [`ChainContent`] struct-level doc). It MUST NOT be updated after
515    /// the row is written — doing so silently invalidates `chain_hash` and
516    /// will be detected as `VerifyOutcome::Broken` by `sysknife audit verify`.
517    /// See the struct-level security contract for the only safe correction
518    /// strategies.
519    pub summary: &'a str,
520    /// Signed receipt commitment for daemon-created previews. Legacy/imported
521    /// rows may be `None`; serialised as empty for wire compatibility.
522    pub approval_id: Option<&'a str>,
523    /// JSON-canonical (sorted keys) array of warning strings.
524    pub warnings_json: &'a str,
525    pub created_at: &'a str,
526    /// Encoding generation. See [`ChainIdentity`] for why this is per-row.
527    pub identity: ChainIdentity<'a>,
528}
529
530impl<'a> ChainContent<'a> {
531    /// Stable canonical encoding of every field. Within each field the
532    /// `0x1E` byte separates tag from value, and `0x1F` terminates the field;
533    /// raw NUL becomes the two-byte escape `\0`.
534    pub fn canonical_bytes(&self) -> Vec<u8> {
535        let risk_level_str = match self.risk_level {
536            RiskLevel::Low => "low",
537            RiskLevel::Medium => "medium",
538            RiskLevel::High => "high",
539        };
540        let approval = self.approval_id.unwrap_or("");
541
542        let mut buf = Vec::with_capacity(512);
543        // Each field is `tag 0x1E value 0x1F`; tags make the canonical form
544        // self-describing for forensics.
545        push_field(&mut buf, "seq", &self.seq.to_string());
546        push_field(&mut buf, "key_id", self.key_id);
547        push_field(&mut buf, "transaction_id", self.transaction_id);
548        push_field(&mut buf, "request_id", self.request_id);
549        push_field(&mut buf, "request_hash", self.request_hash);
550        push_field(&mut buf, "action_name", self.action_name);
551        push_field(&mut buf, "risk_level", risk_level_str);
552        push_field(&mut buf, "summary", self.summary);
553        push_field(&mut buf, "approval_id", approval);
554        push_field(&mut buf, "warnings_json", self.warnings_json);
555        push_field(&mut buf, "created_at", self.created_at);
556        // Per-generation suffixes are *appended*, so a legacy row's bytes are
557        // unchanged and its signature still verifies. The `chain_version` tag
558        // leads each suffix, so no generation can alias another: two encodings
559        // differ in a signed field, not merely in field count.
560        //
561        // This is an exhaustive `match`, not a sequence of `if let`s, and that
562        // matters more than it looks. With `if let` chains, adding a variant and
563        // forgetting its arm compiles fine and silently encodes the new
564        // generation byte-identically to `LegacyV1` — signing an aliased message,
565        // which is exactly what the tag is supposed to prevent. As a `match`,
566        // the same omission is a compile error.
567        //
568        // Each arm spells its own fields out rather than sharing a helper. The
569        // duplication is deliberate: a frozen encoding must be able to stay
570        // frozen while a newer one changes.
571        match self.identity {
572            ChainIdentity::LegacyV1 => {}
573            ChainIdentity::V2 {
574                caller_role,
575                event_tip,
576            } => {
577                push_field(&mut buf, "chain_version", &CHAIN_VERSION_V2.to_string());
578                push_field(&mut buf, "caller_role", caller_role);
579                push_field(&mut buf, "event_tip", event_tip);
580            }
581            ChainIdentity::V3 {
582                caller_role,
583                event_tip,
584                caller_principal,
585            } => {
586                push_field(&mut buf, "chain_version", &CHAIN_VERSION_V3.to_string());
587                push_field(&mut buf, "caller_role", caller_role);
588                push_field(&mut buf, "event_tip", event_tip);
589                push_field(&mut buf, "caller_principal", caller_principal);
590            }
591        }
592        buf
593    }
594}
595
596/// Append `tag<RS>value<US>` to `buf`, escaping any byte that could otherwise
597/// alias one of the framing characters or another escape sequence.
598///
599/// The escape table is **prefix-free**: every escape starts with `\` (0x5C)
600/// followed by a tag that cannot itself be the start of a different escape.
601/// Concretely:
602///
603/// | Raw byte | Escape       |
604/// |---------:|--------------|
605/// | `\\`     | `\\\\`       |
606/// | `\x00`   | `\\0`        |
607/// | `\x1E`   | `\\1E`       |
608/// | `\x1F`   | `\\1F`       |
609///
610/// The `\\` escape MUST come first: without it, a field value containing the
611/// literal two-byte sequence `\` + `0` would canonicalise to the same bytes
612/// as a raw NUL and produce a chain-signature collision.
613fn push_field(buf: &mut Vec<u8>, tag: &str, value: &str) {
614    buf.extend_from_slice(tag.as_bytes());
615    buf.push(0x1E); // tag/value separator (ASCII RS byte, but used inversely — see ChainContent doc)
616    for b in value.bytes() {
617        match b {
618            b'\\' => buf.extend_from_slice(b"\\\\"),
619            0x00 => buf.extend_from_slice(b"\\0"),
620            0x1E => buf.extend_from_slice(b"\\1E"),
621            0x1F => buf.extend_from_slice(b"\\1F"),
622            other => buf.push(other),
623        }
624    }
625    buf.push(0x1F); // field terminator (ASCII US byte, but used inversely — see ChainContent doc)
626}
627
628/// Result of `verify_chain`.
629#[derive(Debug, Clone, PartialEq, Eq)]
630pub enum VerifyOutcome {
631    /// Chain is intact across all rows checked.
632    Intact { rows_checked: u64 },
633    /// One or more rows fail to chain. First broken row is reported.
634    Broken {
635        rows_checked: u64,
636        first_broken_seq: u64,
637        first_broken_transaction_id: String,
638        expected: String,
639        actual: String,
640    },
641    /// Verification could not be completed (missing key, unreachable storage,
642    /// retired key not on disk, etc.). Distinct from `Broken` — callers map
643    /// this to exit code 2.
644    CannotVerify { reason: String },
645}
646
647/// Process exit code for `sysknife audit verify`.
648///
649/// `0` intact, `1` broken, `2` cannot-verify. The split between 1 and 2
650/// matters: a CI pipeline expecting 0 or 1 must not silently pass on a
651/// missing key file.
652pub fn outcome_to_exit_code(outcome: &VerifyOutcome) -> i32 {
653    match outcome {
654        VerifyOutcome::Intact { .. } => 0,
655        VerifyOutcome::Broken { .. } => 1,
656        VerifyOutcome::CannotVerify { .. } => 2,
657    }
658}
659
660/// One row's worth of chain data, as fetched from the store.
661#[derive(Debug, Clone)]
662pub struct ChainRow {
663    pub seq: u64,
664    pub key_id: String,
665    pub transaction_id: String,
666    pub request_id: String,
667    pub request_hash: String,
668    pub action_name: String,
669    pub risk_level: RiskLevel,
670    pub summary: String,
671    pub approval_id: Option<String>,
672    pub warnings_json: String,
673    pub created_at: String,
674    pub prev_chain_hash: String,
675    pub chain_hash: String,
676    /// Which encoding this row was signed under. See [`ChainIdentity`].
677    pub chain_version: u32,
678    /// `NULL` for legacy rows; required for `chain_version` 2 and 3.
679    pub caller_role: Option<String>,
680    /// `NULL` for legacy rows; required for `chain_version` 2 and 3. May be the
681    /// empty string when the event chain was empty at insert time.
682    pub event_tip: Option<String>,
683    /// `NULL` for rows written before the principal migration (v1 and v2);
684    /// required for `chain_version = 3`. Scheme-prefixed, see
685    /// [`ChainIdentity::V3`].
686    pub caller_principal: Option<String>,
687}
688
689/// Why a stored row's columns do not describe a verifiable encoding.
690#[derive(Debug)]
691pub(crate) enum RowIdentityError {
692    /// The row claims an encoding this binary does not know how to reproduce.
693    /// Genuinely unverifiable, not evidence of tampering — an older binary
694    /// reading a newer chain lands here.
695    UnknownVersion(u32),
696    /// The row claims an identity encoding (2 or 3) but is missing one of its
697    /// columns. For v3 that includes a blank `caller_principal`, treated as
698    /// absent: a row naming nobody must not pass for one naming an account.
699    /// No message can be reconstructed, and the shape is self-contradictory,
700    /// so this counts as a detected break rather than an inability to check.
701    MissingField(&'static str),
702}
703
704impl ChainRow {
705    /// Recover the encoding this row was signed under, so a caller can rebuild
706    /// the exact message that produced `chain_hash`.
707    pub(crate) fn identity(&self) -> Result<ChainIdentity<'_>, RowIdentityError> {
708        match self.chain_version {
709            CHAIN_VERSION_LEGACY => Ok(ChainIdentity::LegacyV1),
710            CHAIN_VERSION_V2 => Ok(ChainIdentity::V2 {
711                caller_role: self
712                    .caller_role
713                    .as_deref()
714                    .ok_or(RowIdentityError::MissingField("caller_role"))?,
715                event_tip: self
716                    .event_tip
717                    .as_deref()
718                    .ok_or(RowIdentityError::MissingField("event_tip"))?,
719            }),
720            CHAIN_VERSION_V3 => Ok(ChainIdentity::V3 {
721                caller_role: self
722                    .caller_role
723                    .as_deref()
724                    .ok_or(RowIdentityError::MissingField("caller_role"))?,
725                event_tip: self
726                    .event_tip
727                    .as_deref()
728                    .ok_or(RowIdentityError::MissingField("event_tip"))?,
729                // An empty principal is treated as absent: a v3 row must name
730                // who asked, and "" names nobody. Accepting it would let a
731                // blank pass for an identity.
732                caller_principal: self
733                    .caller_principal
734                    .as_deref()
735                    .filter(|p| !p.is_empty())
736                    .ok_or(RowIdentityError::MissingField("caller_principal"))?,
737            }),
738            other => Err(RowIdentityError::UnknownVersion(other)),
739        }
740    }
741}
742
743/// Verify a chain using the daemon's key. Verification uses the **public** key
744/// (so it proves, but cannot forge) and also asserts every row was written
745/// under this key generation (`key_id`).
746pub fn verify_chain(key: &AuditKey, rows: &[ChainRow]) -> VerifyOutcome {
747    verify_rows(&key.verifying_key(), Some(key.key_id()), rows)
748}
749
750/// Verify a chain with only the hex-encoded Ed25519 **public** key. This is the
751/// auditor / aggregator path: it proves the chain without the private key and
752/// cannot be used to forge entries. `key_id` is not checked — the public key
753/// itself identifies the signer.
754pub fn verify_chain_with_pubkey(verifying_key_hex: &str, rows: &[ChainRow]) -> VerifyOutcome {
755    match parse_verifying_key(verifying_key_hex) {
756        Some(vk) => verify_rows(&vk, None, rows),
757        None => VerifyOutcome::CannotVerify {
758            reason: format!(
759                "invalid public key hex ({} chars); expected 64 hex chars of a \
760                 32-byte Ed25519 public key",
761                verifying_key_hex.len()
762            ),
763        },
764    }
765}
766
767fn parse_verifying_key(hex_str: &str) -> Option<VerifyingKey> {
768    let bytes = hex::decode(hex_str.trim()).ok()?;
769    let arr: [u8; 32] = bytes.try_into().ok()?;
770    VerifyingKey::from_bytes(&arr).ok()
771}
772
773/// Verify a stored hex signature over a row's message. Any malformed signature
774/// (bad hex, wrong length, invalid point) is a failed check, never a panic.
775fn signature_ok(vk: &VerifyingKey, msg: &[u8], sig_hex: &str) -> bool {
776    let Ok(bytes) = hex::decode(sig_hex) else {
777        return false;
778    };
779    let Ok(arr): Result<[u8; 64], _> = bytes.try_into() else {
780        return false;
781    };
782    vk.verify_strict(msg, &Signature::from_bytes(&arr)).is_ok()
783}
784
785/// Walk `rows` in seq order, verifying each row's signature with `vk` and its
786/// `prev_chain_hash` linkage. Returns the first break (or `Intact`). When
787/// `expect_key_id` is `Some`, every row must carry that `key_id`.
788fn verify_rows(vk: &VerifyingKey, expect_key_id: Option<&str>, rows: &[ChainRow]) -> VerifyOutcome {
789    let mut last_hash = String::new();
790    let mut rows_checked = 0u64;
791    for row in rows {
792        if let Some(kid) = expect_key_id {
793            if row.key_id != kid {
794                return VerifyOutcome::CannotVerify {
795                    reason: format!(
796                        "row seq={} uses key_id={:?} but only {:?} is loaded; \
797                         epoch keys not yet supported",
798                        row.seq, row.key_id, kid
799                    ),
800                };
801            }
802        }
803        if row.prev_chain_hash != last_hash {
804            return VerifyOutcome::Broken {
805                rows_checked,
806                first_broken_seq: row.seq,
807                first_broken_transaction_id: row.transaction_id.clone(),
808                expected: format!("prev_chain_hash={last_hash}"),
809                actual: format!("prev_chain_hash={}", row.prev_chain_hash),
810            };
811        }
812        let identity = match row.identity() {
813            Ok(identity) => identity,
814            Err(RowIdentityError::UnknownVersion(v)) => {
815                return VerifyOutcome::CannotVerify {
816                    reason: format!(
817                        "row seq={} declares chain_version={v}, which this binary cannot \
818                         reproduce (it understands {CHAIN_VERSION_LEGACY}..={CHAIN_VERSION_CURRENT}); \
819                         verify with a build at least as new as the one that wrote the chain",
820                        row.seq
821                    ),
822                };
823            }
824            Err(RowIdentityError::MissingField(field)) => {
825                // Report the version the row itself declares. Formatting
826                // CHAIN_VERSION_CURRENT here sent an operator investigating a
827                // v2 row to the wrong encoding, and got worse every time the
828                // newest version moved.
829                let stored = match field {
830                    "caller_role" => row.caller_role.as_deref(),
831                    "event_tip" => row.event_tip.as_deref(),
832                    "caller_principal" => row.caller_principal.as_deref(),
833                    _ => None,
834                };
835                return VerifyOutcome::Broken {
836                    rows_checked,
837                    first_broken_seq: row.seq,
838                    first_broken_transaction_id: row.transaction_id.clone(),
839                    expected: format!(
840                        "chain_version={} row carrying a non-empty {field}",
841                        row.chain_version
842                    ),
843                    // An empty column and an absent one send an operator to
844                    // different SQL, so they must not print the same way.
845                    actual: match stored {
846                        None => format!("{field}=NULL"),
847                        Some("") => format!("{field}='' (empty, not NULL)"),
848                        Some(other) => format!("{field}={other:?}"),
849                    },
850                };
851            }
852        };
853        let content = ChainContent {
854            seq: row.seq,
855            key_id: &row.key_id,
856            transaction_id: &row.transaction_id,
857            request_id: &row.request_id,
858            request_hash: &row.request_hash,
859            action_name: &row.action_name,
860            risk_level: row.risk_level,
861            summary: &row.summary,
862            approval_id: row.approval_id.as_deref(),
863            warnings_json: &row.warnings_json,
864            created_at: &row.created_at,
865            identity,
866        };
867        let msg = chain_message(&content, &row.prev_chain_hash);
868        if !signature_ok(vk, &msg, &row.chain_hash) {
869            return VerifyOutcome::Broken {
870                rows_checked,
871                first_broken_seq: row.seq,
872                first_broken_transaction_id: row.transaction_id.clone(),
873                expected: "valid ed25519 signature".to_string(),
874                actual: row.chain_hash.clone(),
875            };
876        }
877        last_hash = row.chain_hash.clone();
878        rows_checked += 1;
879    }
880    VerifyOutcome::Intact { rows_checked }
881}
882
883// ── Approval-event chain ─────────────────────────────────────────────────────
884
885/// A lifecycle event on an approval receipt.
886///
887/// The `transactions` chain commits to the *authorisation decision* at preview
888/// time. It says nothing about whether a human ever approved, whether that
889/// approval was spent, or whether it was retracted — those live in
890/// `transaction_approvals`, a plain mutable table. Deleting a row from it used
891/// to leave `sysknife audit verify` reporting `Intact`, so the record that an
892/// approval happened was the one part of the trail an attacker could erase
893/// without leaving a mark. These events are chained so that erasure breaks a
894/// signature.
895#[derive(Debug, Clone, Copy, PartialEq, Eq)]
896pub enum AuditEventKind {
897    /// A receipt was minted for a queued transaction.
898    ApprovalGranted,
899    /// A receipt was spent to move a transaction into `Running`.
900    ApprovalConsumed,
901    /// An undelivered receipt was retracted before it could be spent.
902    ApprovalRevoked,
903}
904
905impl AuditEventKind {
906    /// Stored and signed spelling. Stable on the wire — changing one of these
907    /// strings invalidates every event signature already written.
908    pub fn as_str(&self) -> &'static str {
909        match self {
910            Self::ApprovalGranted => "approval_granted",
911            Self::ApprovalConsumed => "approval_consumed",
912            Self::ApprovalRevoked => "approval_revoked",
913        }
914    }
915}
916
917/// Immutable content of one approval event, signed into the event chain.
918#[derive(Debug, Clone, PartialEq, Eq)]
919pub struct EventContent<'a> {
920    pub seq: u64,
921    pub key_id: &'a str,
922    pub kind: AuditEventKind,
923    pub transaction_id: &'a str,
924    /// The receipt digest the event concerns. Binds the event to the specific
925    /// receipt, so swapping in a different approval's digest breaks the
926    /// signature.
927    pub receipt_digest: &'a str,
928    pub created_at: &'a str,
929}
930
931impl EventContent<'_> {
932    /// Canonical encoding, using the same prefix-free field framing as
933    /// [`ChainContent::canonical_bytes`].
934    pub fn canonical_bytes(&self) -> Vec<u8> {
935        let mut buf = Vec::with_capacity(256);
936        push_field(&mut buf, "seq", &self.seq.to_string());
937        push_field(&mut buf, "key_id", self.key_id);
938        push_field(&mut buf, "kind", self.kind.as_str());
939        push_field(&mut buf, "transaction_id", self.transaction_id);
940        push_field(&mut buf, "receipt_digest", self.receipt_digest);
941        push_field(&mut buf, "created_at", self.created_at);
942        buf
943    }
944}
945
946fn event_message(content: &EventContent, prev_chain_hash: &str) -> Vec<u8> {
947    let mut msg = EVENT_DOMAIN.to_vec();
948    msg.extend_from_slice(&content.canonical_bytes());
949    msg.extend_from_slice(prev_chain_hash.as_bytes());
950    msg
951}
952
953impl AuditKey {
954    /// Compute the event-chain signature for `content` linked to
955    /// `prev_chain_hash`. Separate domain tag from rows and checkpoints, so an
956    /// event signature can never be replayed as a transaction row.
957    pub fn event_hash(&self, content: &EventContent, prev_chain_hash: &str) -> String {
958        hex::encode(
959            self.signing
960                .sign(&event_message(content, prev_chain_hash))
961                .to_bytes(),
962        )
963    }
964}
965
966/// One approval event as fetched from the store.
967#[derive(Debug, Clone, PartialEq, Eq)]
968pub struct EventRow {
969    pub seq: u64,
970    pub key_id: String,
971    /// Stored spelling of an [`AuditEventKind`]. Kept as a string so an
972    /// unrecognised value read from the database is a verification failure
973    /// rather than a deserialisation panic.
974    pub kind: String,
975    pub transaction_id: String,
976    pub receipt_digest: String,
977    pub created_at: String,
978    pub prev_chain_hash: String,
979    pub chain_hash: String,
980}
981
982/// Verify the approval-event chain with the daemon's key.
983pub fn verify_event_chain(key: &AuditKey, rows: &[EventRow]) -> VerifyOutcome {
984    verify_event_rows(&key.verifying_key(), Some(key.key_id()), rows)
985}
986
987/// Verify the approval-event chain with only the exported public key.
988pub fn verify_event_chain_with_pubkey(verifying_key_hex: &str, rows: &[EventRow]) -> VerifyOutcome {
989    match parse_verifying_key(verifying_key_hex) {
990        Some(vk) => verify_event_rows(&vk, None, rows),
991        None => VerifyOutcome::CannotVerify {
992            reason: format!(
993                "invalid public key hex ({} chars); expected 64 hex chars of a \
994                 32-byte Ed25519 public key",
995                verifying_key_hex.len()
996            ),
997        },
998    }
999}
1000
1001fn verify_event_rows(
1002    vk: &VerifyingKey,
1003    expect_key_id: Option<&str>,
1004    rows: &[EventRow],
1005) -> VerifyOutcome {
1006    let mut last_hash = String::new();
1007    let mut rows_checked = 0u64;
1008    for row in rows {
1009        if let Some(kid) = expect_key_id {
1010            if row.key_id != kid {
1011                return VerifyOutcome::CannotVerify {
1012                    reason: format!(
1013                        "event seq={} uses key_id={:?} but only {:?} is loaded; \
1014                         epoch keys not yet supported",
1015                        row.seq, row.key_id, kid
1016                    ),
1017                };
1018            }
1019        }
1020        if row.prev_chain_hash != last_hash {
1021            return VerifyOutcome::Broken {
1022                rows_checked,
1023                first_broken_seq: row.seq,
1024                first_broken_transaction_id: row.transaction_id.clone(),
1025                expected: format!("prev_chain_hash={last_hash}"),
1026                actual: format!("prev_chain_hash={}", row.prev_chain_hash),
1027            };
1028        }
1029        // An unknown `kind` cannot be re-encoded, so it can never reproduce a
1030        // valid signature. Report it as the break it is instead of guessing.
1031        let Some(kind) = parse_event_kind(&row.kind) else {
1032            return VerifyOutcome::Broken {
1033                rows_checked,
1034                first_broken_seq: row.seq,
1035                first_broken_transaction_id: row.transaction_id.clone(),
1036                expected: "a known event kind".to_string(),
1037                actual: format!("kind={:?}", row.kind),
1038            };
1039        };
1040        let content = EventContent {
1041            seq: row.seq,
1042            key_id: &row.key_id,
1043            kind,
1044            transaction_id: &row.transaction_id,
1045            receipt_digest: &row.receipt_digest,
1046            created_at: &row.created_at,
1047        };
1048        if !signature_ok(
1049            vk,
1050            &event_message(&content, &row.prev_chain_hash),
1051            &row.chain_hash,
1052        ) {
1053            return VerifyOutcome::Broken {
1054                rows_checked,
1055                first_broken_seq: row.seq,
1056                first_broken_transaction_id: row.transaction_id.clone(),
1057                expected: "valid ed25519 signature".to_string(),
1058                actual: row.chain_hash.clone(),
1059            };
1060        }
1061        last_hash = row.chain_hash.clone();
1062        rows_checked += 1;
1063    }
1064    VerifyOutcome::Intact { rows_checked }
1065}
1066
1067fn parse_event_kind(raw: &str) -> Option<AuditEventKind> {
1068    // Exhaustive by construction: the match below fails to compile if a
1069    // variant is added without a spelling here.
1070    [
1071        AuditEventKind::ApprovalGranted,
1072        AuditEventKind::ApprovalConsumed,
1073        AuditEventKind::ApprovalRevoked,
1074    ]
1075    .into_iter()
1076    .find(|kind| kind.as_str() == raw)
1077}
1078
1079/// Result of checking that the transaction chain's committed `event_tip`
1080/// values are still reproducible from the event chain.
1081#[derive(Debug, Clone, PartialEq, Eq)]
1082pub enum BindingOutcome {
1083    /// Every committed tip is present in the event chain.
1084    Consistent { bindings_checked: u64 },
1085    /// A transaction row committed to an event tip that no longer exists —
1086    /// approval events were deleted from the end of the event chain, which the
1087    /// event chain walk alone cannot see.
1088    MissingEvent {
1089        transaction_seq: u64,
1090        event_tip: String,
1091    },
1092}
1093
1094/// Check the cross-chain binding: each `chain_version = 2` transaction row
1095/// signs the event-chain tip as of its insert, so a later deletion of trailing
1096/// approval events leaves a tip that can no longer be found.
1097///
1098/// This is what extends checkpoint anchoring to the event chain for free: the
1099/// checkpoints commit to the transaction tip, the transaction rows commit to
1100/// event tips. Events appended *after* the last transaction row are still
1101/// unanchored until the next row is written — the same bounded tail exposure
1102/// the transaction chain has between checkpoints.
1103pub fn verify_event_binding(tx_rows: &[ChainRow], event_rows: &[EventRow]) -> BindingOutcome {
1104    let known: std::collections::HashSet<&str> = event_rows
1105        .iter()
1106        .map(|row| row.chain_hash.as_str())
1107        .collect();
1108    let mut bindings_checked = 0u64;
1109    for row in tx_rows {
1110        let Some(tip) = row.event_tip.as_deref() else {
1111            continue;
1112        };
1113        if tip.is_empty() {
1114            continue;
1115        }
1116        if !known.contains(tip) {
1117            return BindingOutcome::MissingEvent {
1118                transaction_seq: row.seq,
1119                event_tip: tip.to_string(),
1120            };
1121        }
1122        bindings_checked += 1;
1123    }
1124    BindingOutcome::Consistent { bindings_checked }
1125}
1126
1127/// Everything `sysknife audit verify` checks, in one value.
1128///
1129/// Three independent questions, deliberately not collapsed into one enum:
1130/// is the authorisation record intact, is the approval record intact, and do
1131/// the two still agree. Collapsing them would let a clean transaction chain
1132/// mask a tampered approval trail in the summary line.
1133#[derive(Debug, Clone, PartialEq, Eq)]
1134pub struct AuditVerification {
1135    pub chain: VerifyOutcome,
1136    pub events: VerifyOutcome,
1137    pub binding: BindingOutcome,
1138    /// How many rows can name the account that acted, and why the rest cannot.
1139    ///
1140    /// Reported separately because `Intact` alone would be true and misleading: a
1141    /// host where every connection failed attribution produces a chain that
1142    /// verifies perfectly and answers "who acted" with nobody. The verdict is
1143    /// about tampering; this census is about how much the trail can tell you.
1144    ///
1145    /// `None` when the store could not be read at all, so no census was taken: a
1146    /// missing database, an unopenable one, an absent key. A readable but empty
1147    /// store is `Some`, with every count zero.
1148    ///
1149    /// Deliberately not a census of zero rows for the unreadable case: "nothing
1150    /// is known about attribution" and "the chain holds no rows" are different
1151    /// claims, and a zero that means the first reads as the second, which is the
1152    /// exact confusion this census exists to end.
1153    pub attribution: Option<AttributionCensus>,
1154}
1155
1156/// What one row's principal column can attest, given the encoding that signed it.
1157///
1158/// Four outcomes, because the remedies differ and an audit report that collapses
1159/// them tells the operator to do the wrong thing.
1160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1161enum RowStanding {
1162    /// A `chain_version = 3` row whose signed principal names an account.
1163    NamesAccount,
1164    /// A `chain_version = 3` row signing `none:unattributed`: the daemon tried
1165    /// to attribute the connection and could not.
1166    AttributionFailed,
1167    /// Nothing the signature covers. A v1 or v2 row, whose encoding had no
1168    /// principal field, or a v3 row with a blank column, which also verifies as
1169    /// `Broken` once the walk reaches it.
1170    NotRecorded,
1171    /// Nothing here that a signature vouches for. Three sources: the column is
1172    /// populated on an encoding that does not sign it, or the value is one this
1173    /// binary cannot read back as something the daemon could have written, or the
1174    /// row declares an encoding this build does not know, in which case the
1175    /// principal may be absent or held somewhere this build cannot see.
1176    ///
1177    /// This build never writes any of those, so the first two are evidence of an
1178    /// out-of-band write and the third of a newer daemon. None of them is evidence
1179    /// of who acted.
1180    Unattested,
1181}
1182
1183/// Which encoding, if any, signs the `caller_principal` column, and therefore
1184/// whether the column may be believed.
1185///
1186/// This is the load-bearing check in the census. [`ChainContent::canonical_bytes`]
1187/// pushes `caller_principal` into the signed bytes **only** in the v3 arm, so on a
1188/// v1 or v2 row that column is unsigned free space: anyone with write access to
1189/// the table can set it to `uid:0` and the chain still verifies `Intact`, because
1190/// there is no signature over it to break. Bucketing by the column instead of by
1191/// the encoding would let a plain `UPDATE` manufacture attribution, which is a
1192/// worse failure than the one this census was written to fix. Losing attribution
1193/// is a gap; inventing it is a lie.
1194fn standing(row: &ChainRow) -> RowStanding {
1195    // Empty treated as absent, and nothing trimmed, so this agrees with
1196    // `ChainRow::identity` exactly: it filters on `is_empty` and no more. An
1197    // earlier version trimmed first, which sent a whitespace-only v3 principal
1198    // into "written before the column existed" -- a row that in fact verifies
1199    // Intact and is an anomaly worth investigating. The schema stores `''` as
1200    // well as `NULL`, and `verify_chain` prints those two differently on purpose,
1201    // so both are reachable on real data.
1202    let stored = row.caller_principal.as_deref().filter(|p| !p.is_empty());
1203    match row.chain_version {
1204        CHAIN_VERSION_LEGACY | CHAIN_VERSION_V2 => match stored {
1205            None => RowStanding::NotRecorded,
1206            Some(_) => RowStanding::Unattested,
1207        },
1208        CHAIN_VERSION_V3 => match stored {
1209            None => RowStanding::NotRecorded,
1210            Some(p) => match crate::auth::CallerPrincipal::classify(p) {
1211                crate::auth::PrincipalClaim::Account => RowStanding::NamesAccount,
1212                crate::auth::PrincipalClaim::AttributionFailed => RowStanding::AttributionFailed,
1213                crate::auth::PrincipalClaim::Unrecognized => RowStanding::Unattested,
1214            },
1215        },
1216        // An encoding this binary does not know, which is any value outside 1..=3:
1217        // a newer daemon's, or a corrupt column. `verify_rows` already reports
1218        // `CannotVerify` for such a row, and the census must not claim an account
1219        // either, because this binary cannot say which fields that encoding signs
1220        // -- including whether it signs this column at all.
1221        _ => RowStanding::Unattested,
1222    }
1223}
1224
1225/// Attribution census over every transaction row read.
1226///
1227/// Counted over all rows, not only the ones that verified, so a chain that
1228/// breaks at row 5 still reports what the remaining rows *claim* about who
1229/// acted. Those claims are only as good as the chain verdict beside them: unless
1230/// it is `Intact`, treat every count here as unproven, and note that
1231/// [`Self::rows`] can then exceed the verdict's `rows_checked`. A row past the
1232/// break may be perfectly authentic -- a deleted or reordered row breaks the link
1233/// while leaving every later signature valid -- so the surplus is the part of the
1234/// trail this command cannot vouch for, not proof of forgery. [`Self::rows`]
1235/// exists so a reader can see that gap instead of inferring it.
1236///
1237/// One counter is not enough, because a row can name no account for reasons with
1238/// different remedies. `none:unattributed` says the daemon tried and failed on a
1239/// host that could have attributed the call, which is a configuration problem to
1240/// chase in the daemon log. A v1 or v2 row says the encoding had no principal
1241/// field when the row was signed, which is history and cannot be repaired:
1242/// backfilling it would rewrite the bytes the signature covers. An unattested
1243/// value says something wrote to the column that should not have.
1244///
1245/// Splitting them keeps the report honest on an upgraded database. A single
1246/// "unattributed" count of `0` over a chain of pre-v3 rows reads as "every
1247/// action is attributed" when in fact none of them is.
1248///
1249/// Fields are private and [`Self::of`] is the only constructor that reads rows, so
1250/// a census cannot state totals that contradict the rows it describes.
1251/// `from_counts_for_tests` is the one other way to build one, and it is
1252/// not for production. That is not hypothetical tidiness: in 0.3.0 the MCP report
1253/// built its own all-zero attribution count on the `cannot_verify` path, where a
1254/// real count had already been computed, and the MCP tool and `audit verify
1255/// --json` then published different numbers for one database.
1256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1257pub struct AttributionCensus {
1258    named: u64,
1259    attribution_failed: u64,
1260    not_recorded: u64,
1261    unattested: u64,
1262    rows: u64,
1263}
1264
1265impl AttributionCensus {
1266    /// Count the rows. The only way to obtain a census of real data.
1267    pub fn of(tx_rows: &[ChainRow]) -> Self {
1268        let mut census = Self {
1269            named: 0,
1270            attribution_failed: 0,
1271            not_recorded: 0,
1272            unattested: 0,
1273            rows: tx_rows.len() as u64,
1274        };
1275        for row in tx_rows {
1276            match standing(row) {
1277                RowStanding::NamesAccount => census.named += 1,
1278                RowStanding::AttributionFailed => census.attribution_failed += 1,
1279                RowStanding::NotRecorded => census.not_recorded += 1,
1280                RowStanding::Unattested => census.unattested += 1,
1281            }
1282        }
1283        census
1284    }
1285
1286    /// Rows whose signed principal names an account (`uid:` or `token:`).
1287    ///
1288    /// Names an *account*, which is not a person: see `SECURITY.md` on shared
1289    /// logins, `su`, uid reuse, and on `token:vsock` proving possession of a
1290    /// file.
1291    pub fn named(&self) -> u64 {
1292        self.named
1293    }
1294
1295    /// Rows signing `none:unattributed`, the daemon's admission that it could
1296    /// not name the caller.
1297    pub fn attribution_failed(&self) -> u64 {
1298        self.attribution_failed
1299    }
1300
1301    /// Rows with no principal the signature covers, normally written before the
1302    /// column existed.
1303    pub fn not_recorded(&self) -> u64 {
1304        self.not_recorded
1305    }
1306
1307    /// Rows carrying a principal no signature vouches for. Non-zero means
1308    /// investigate: nothing in SysKnife writes such a value.
1309    pub fn unattested(&self) -> u64 {
1310        self.unattested
1311    }
1312
1313    /// Rows censused.
1314    ///
1315    /// The four row outcomes partition the rows, and [`Self::of`]
1316    /// increments exactly one bucket per row, so this equals their sum. State the
1317    /// partition rather than the arithmetic: a fifth bucket keeps the partition
1318    /// true, and any sum written out by hand somewhere else would not survive it.
1319    pub fn rows(&self) -> u64 {
1320        self.rows
1321    }
1322
1323    /// Rows that name no account, for any reason. What an operator asking "can
1324    /// this trail tell me who acted" has to subtract.
1325    ///
1326    /// Subtraction rather than addition on purpose: a fifth *non-naming* bucket
1327    /// cannot make this number stale, whereas summing the reasons would need
1328    /// editing here too. A future bucket that does name an account would have to
1329    /// be added to `named` instead, which is why `named` is the one counter this
1330    /// subtracts.
1331    pub fn unnamed(&self) -> u64 {
1332        self.rows - self.named
1333    }
1334
1335    /// Build a census from counts, for rendering tests only.
1336    ///
1337    /// Behind the `test-support` feature rather than merely `#[doc(hidden)]`, which
1338    /// hides a function from documentation but not from callers. The CLI renderers
1339    /// live in another crate, where `cfg(test)` does not reach, and making them
1340    /// build signed `ChainRow` fixtures to assert on one line of prose would buy no
1341    /// safety; enabling the feature only as a dev-dependency keeps the door shut
1342    /// for production builds. [`Self::of`] is the constructor that reads rows.
1343    ///
1344    /// Panics if the counts overflow `u64`, rather than wrapping into a census
1345    /// whose `rows` is smaller than its buckets and whose [`Self::unnamed`] would
1346    /// then underflow.
1347    #[cfg(any(test, feature = "test-support"))]
1348    pub fn from_counts_for_tests(
1349        named: u64,
1350        attribution_failed: u64,
1351        not_recorded: u64,
1352        unattested: u64,
1353    ) -> Self {
1354        let rows = named
1355            .checked_add(attribution_failed)
1356            .and_then(|n| n.checked_add(not_recorded))
1357            .and_then(|n| n.checked_add(unattested))
1358            .expect("census counts must not overflow u64");
1359        Self {
1360            named,
1361            attribution_failed,
1362            not_recorded,
1363            unattested,
1364            rows,
1365        }
1366    }
1367}
1368
1369impl AuditVerification {
1370    /// Worst result across all three checks.
1371    ///
1372    /// A detected tamper (`1`) outranks an inability to check (`2`): if the
1373    /// chain is provably broken, reporting "could not verify" because some
1374    /// *other* check was inconclusive would understate what is known.
1375    pub fn exit_code(&self) -> i32 {
1376        let codes = [
1377            outcome_to_exit_code(&self.chain),
1378            outcome_to_exit_code(&self.events),
1379            binding_outcome_to_exit_code(&self.binding),
1380        ];
1381        if codes.contains(&1) {
1382            1
1383        } else if codes.contains(&2) {
1384            2
1385        } else {
1386            0
1387        }
1388    }
1389}
1390
1391/// Run all three checks with the daemon's key.
1392pub fn verify_all(
1393    key: &AuditKey,
1394    tx_rows: &[ChainRow],
1395    event_rows: &[EventRow],
1396) -> AuditVerification {
1397    AuditVerification {
1398        chain: verify_chain(key, tx_rows),
1399        events: verify_event_chain(key, event_rows),
1400        binding: verify_event_binding(tx_rows, event_rows),
1401        attribution: Some(AttributionCensus::of(tx_rows)),
1402    }
1403}
1404
1405/// Run all three checks with only the exported public key (the auditor path).
1406pub fn verify_all_with_pubkey(
1407    verifying_key_hex: &str,
1408    tx_rows: &[ChainRow],
1409    event_rows: &[EventRow],
1410) -> AuditVerification {
1411    AuditVerification {
1412        chain: verify_chain_with_pubkey(verifying_key_hex, tx_rows),
1413        events: verify_event_chain_with_pubkey(verifying_key_hex, event_rows),
1414        binding: verify_event_binding(tx_rows, event_rows),
1415        attribution: Some(AttributionCensus::of(tx_rows)),
1416    }
1417}
1418
1419/// Exit code for the binding check, on the same scale as
1420/// [`outcome_to_exit_code`]: a missing event is a detected tamper (`1`).
1421pub fn binding_outcome_to_exit_code(outcome: &BindingOutcome) -> i32 {
1422    match outcome {
1423        BindingOutcome::Consistent { .. } => 0,
1424        BindingOutcome::MissingEvent { .. } => 1,
1425    }
1426}
1427
1428// ── Signed checkpoints (external anchoring / tail-truncation detection) ──────
1429
1430/// A signed commitment to the chain tip at a point in time. Periodically
1431/// emitted and anchored to an independent, append-only sink (a separate
1432/// database, a WORM store, or an RFC 3161 timestamp) so that a later attempt to
1433/// rewrite or **truncate** the local chain is detectable: the anchored
1434/// `(seq, chain_tip)` can no longer be reproduced from the shortened chain.
1435///
1436/// This is the Certificate-Transparency "signed checkpoint" idiom. The
1437/// signature is Ed25519 over the canonical `(seq, chain_tip, created_at)`, so
1438/// an auditor verifies it with only the public key.
1439///
1440/// A `Checkpoint` value carries no validity guarantee on its own: validity is
1441/// established solely by [`verify_checkpoints`] under the public key. A
1442/// checkpoint loaded from a sink is untrusted input until verified.
1443#[derive(Debug, Clone, PartialEq, Eq)]
1444pub struct Checkpoint {
1445    /// `seq` of the chain tip this checkpoint commits to (the last row at
1446    /// emit time).
1447    pub seq: u64,
1448    /// `chain_hash` of the row at `seq` (the committed chain tip).
1449    pub chain_tip: String,
1450    /// RFC 3339 timestamp when the checkpoint was signed.
1451    pub created_at: String,
1452    /// Hex Ed25519 signature over `canonical(seq, chain_tip, created_at)`.
1453    pub signature: String,
1454}
1455
1456/// Canonical message signed into a checkpoint. Reuses the prefix-free field
1457/// framing so the encoding is unambiguous and stable across backends.
1458fn checkpoint_message(seq: u64, chain_tip: &str, created_at: &str) -> Vec<u8> {
1459    // Leading domain tag: separates checkpoint signatures from row signatures
1460    // (see `chain_message`) so the two contexts can never cross-verify.
1461    let mut buf = CHECKPOINT_DOMAIN.to_vec();
1462    push_field(&mut buf, "seq", &seq.to_string());
1463    push_field(&mut buf, "chain_tip", chain_tip);
1464    push_field(&mut buf, "created_at", created_at);
1465    buf
1466}
1467
1468impl AuditKey {
1469    /// Sign a checkpoint committing to `(seq, chain_tip)` at `created_at`.
1470    pub fn sign_checkpoint(&self, seq: u64, chain_tip: &str, created_at: &str) -> Checkpoint {
1471        let sig = self
1472            .signing
1473            .sign(&checkpoint_message(seq, chain_tip, created_at));
1474        Checkpoint {
1475            seq,
1476            chain_tip: chain_tip.to_string(),
1477            created_at: created_at.to_string(),
1478            signature: hex::encode(sig.to_bytes()),
1479        }
1480    }
1481}
1482
1483/// Result of checking anchored checkpoints against the current chain.
1484#[derive(Debug, Clone, PartialEq, Eq)]
1485pub enum CheckpointOutcome {
1486    /// Every checkpoint's signature is valid and its committed tip is still
1487    /// present in the chain at the committed `seq`.
1488    Consistent { checkpoints_checked: u64 },
1489    /// A checkpoint signature failed to verify under the public key.
1490    BadSignature { seq: u64 },
1491    /// A checkpoint commits to a `seq` no longer present in the chain — the
1492    /// chain has been **truncated** below a previously anchored tip.
1493    Truncated {
1494        checkpoint_seq: u64,
1495        current_max_seq: u64,
1496    },
1497    /// A checkpoint's committed `chain_tip` does not match the chain's
1498    /// `chain_hash` at that `seq` — the chain was **rewritten**.
1499    TipMismatch {
1500        seq: u64,
1501        anchored: String,
1502        actual: String,
1503    },
1504    /// Could not verify (e.g. malformed public key).
1505    CannotVerify { reason: String },
1506}
1507
1508/// Verify anchored `checkpoints` against `rows` (the current chain) with the
1509/// hex **public** key. Detects truncation (a checkpoint seq no longer in the
1510/// chain) and rewrite (tip mismatch at a checkpoint seq). `rows` must be in
1511/// seq order. This is the anti-root guarantee: a host attacker who shortens or
1512/// edits the local chain cannot reproduce a previously anchored signed tip.
1513pub fn verify_checkpoints(
1514    verifying_key_hex: &str,
1515    rows: &[ChainRow],
1516    checkpoints: &[Checkpoint],
1517) -> CheckpointOutcome {
1518    let vk = match parse_verifying_key(verifying_key_hex) {
1519        Some(vk) => vk,
1520        None => {
1521            return CheckpointOutcome::CannotVerify {
1522                reason: format!("invalid public key hex ({} chars)", verifying_key_hex.len()),
1523            };
1524        }
1525    };
1526    // `rows` is seq-sorted (ORDER BY seq ASC in the store; chain build order in
1527    // tests), so the tip seq is the last element and we can binary-search below.
1528    let current_max_seq = rows.last().map(|r| r.seq).unwrap_or(0);
1529    let mut checked = 0u64;
1530    for cp in checkpoints {
1531        let msg = checkpoint_message(cp.seq, &cp.chain_tip, &cp.created_at);
1532        if !signature_ok(&vk, &msg, &cp.signature) {
1533            return CheckpointOutcome::BadSignature { seq: cp.seq };
1534        }
1535        match rows.binary_search_by_key(&cp.seq, |r| r.seq) {
1536            Ok(idx) if rows[idx].chain_hash == cp.chain_tip => {}
1537            Ok(idx) => {
1538                return CheckpointOutcome::TipMismatch {
1539                    seq: cp.seq,
1540                    anchored: cp.chain_tip.clone(),
1541                    actual: rows[idx].chain_hash.clone(),
1542                };
1543            }
1544            Err(_) => {
1545                return CheckpointOutcome::Truncated {
1546                    checkpoint_seq: cp.seq,
1547                    current_max_seq,
1548                };
1549            }
1550        }
1551        checked += 1;
1552    }
1553    CheckpointOutcome::Consistent {
1554        checkpoints_checked: checked,
1555    }
1556}
1557
1558/// Process exit code for `sysknife audit checkpoint` verification, mirroring
1559/// [`outcome_to_exit_code`]: `0` consistent, `1` a detected tamper (bad
1560/// signature / truncation / rewrite), `2` cannot-verify (e.g. malformed public
1561/// key). The 1-vs-2 split matters for CI exactly as it does for chain verify.
1562pub fn checkpoint_outcome_to_exit_code(outcome: &CheckpointOutcome) -> i32 {
1563    match outcome {
1564        CheckpointOutcome::Consistent { .. } => 0,
1565        CheckpointOutcome::BadSignature { .. }
1566        | CheckpointOutcome::Truncated { .. }
1567        | CheckpointOutcome::TipMismatch { .. } => 1,
1568        CheckpointOutcome::CannotVerify { .. } => 2,
1569    }
1570}
1571
1572#[cfg(test)]
1573mod tests {
1574    use super::*;
1575
1576    fn fixed_key() -> AuditKey {
1577        AuditKey::from_bytes(vec![0x42; 32])
1578    }
1579
1580    fn sample_content<'a>(seq: u64, txid: &'a str) -> ChainContent<'a> {
1581        ChainContent {
1582            seq,
1583            key_id: CURRENT_KEY_ID,
1584            transaction_id: txid,
1585            request_id: "req-1",
1586            request_hash: "hash-abc",
1587            action_name: "UpdateSystem",
1588            risk_level: RiskLevel::High,
1589            summary: "Upgrade",
1590            approval_id: None,
1591            warnings_json: "[]",
1592            created_at: "2026-04-24T12:00:00Z",
1593            identity: ChainIdentity::V2 {
1594                caller_role: "Dev",
1595                event_tip: "",
1596            },
1597        }
1598    }
1599
1600    // ── chain_hash determinism + linkage ──────────────────────────────────
1601
1602    #[test]
1603    fn same_inputs_yield_same_hash() {
1604        let key = fixed_key();
1605        let h1 = key.chain_hash(&sample_content(1, "txa"), "");
1606        let h2 = key.chain_hash(&sample_content(1, "txa"), "");
1607        assert_eq!(h1, h2);
1608        assert_eq!(h1.len(), HASH_HEX_LEN);
1609    }
1610
1611    #[test]
1612    fn different_seq_yields_different_hash() {
1613        let key = fixed_key();
1614        let h1 = key.chain_hash(&sample_content(1, "txa"), "");
1615        let h2 = key.chain_hash(&sample_content(2, "txa"), "");
1616        assert_ne!(h1, h2);
1617    }
1618
1619    #[test]
1620    fn different_prev_hash_yields_different_hash() {
1621        let key = fixed_key();
1622        let h1 = key.chain_hash(&sample_content(1, "txa"), "");
1623        let h2 = key.chain_hash(&sample_content(1, "txa"), "deadbeef");
1624        assert_ne!(h1, h2);
1625    }
1626
1627    #[test]
1628    fn different_keys_yield_different_hashes() {
1629        let key1 = AuditKey::from_bytes(vec![0x01; 32]);
1630        let key2 = AuditKey::from_bytes(vec![0x02; 32]);
1631        let h1 = key1.chain_hash(&sample_content(1, "txa"), "");
1632        let h2 = key2.chain_hash(&sample_content(1, "txa"), "");
1633        assert_ne!(h1, h2);
1634    }
1635
1636    // ── canonical encoding stability ──────────────────────────────────────
1637
1638    #[test]
1639    fn canonical_bytes_have_stable_field_order() {
1640        let c = sample_content(1, "txa");
1641        let bytes = c.canonical_bytes();
1642        let s = String::from_utf8_lossy(&bytes);
1643        // Tags must appear in a fixed order.
1644        let order = [
1645            "seq",
1646            "key_id",
1647            "transaction_id",
1648            "request_id",
1649            "request_hash",
1650            "action_name",
1651            "risk_level",
1652            "summary",
1653            "approval_id",
1654            "warnings_json",
1655            "created_at",
1656        ];
1657        let mut last_idx = 0;
1658        for tag in order {
1659            let idx = s.find(tag).unwrap_or_else(|| panic!("missing {tag}"));
1660            assert!(idx >= last_idx, "{tag} out of order");
1661            last_idx = idx;
1662        }
1663    }
1664
1665    #[test]
1666    fn nul_bytes_in_field_value_are_escaped() {
1667        let mut c = sample_content(1, "txa");
1668        let summary = "before\0after";
1669        c.summary = summary;
1670        let bytes = c.canonical_bytes();
1671        // Raw NUL must NOT appear; escape sequence must.
1672        assert!(!bytes.contains(&0x00));
1673        assert!(String::from_utf8_lossy(&bytes).contains("before\\0after"));
1674    }
1675
1676    /// Backslash-NUL collision regression: an attacker who could craft a
1677    /// row with `summary = "before\\0after"` (literal backslash + zero) must
1678    /// NOT produce the same canonical bytes as one with raw `\x00`. Without
1679    /// the `\\` → `\\\\` escape, the two collide and the attacker can
1680    /// substitute one for the other while the chain hash matches.
1681    #[test]
1682    fn literal_backslash_zero_does_not_collide_with_raw_nul_escape() {
1683        let mut a = sample_content(1, "txa");
1684        a.summary = "before\\0after"; // literal backslash + '0'
1685        let mut b = sample_content(1, "txa");
1686        b.summary = "before\0after"; // raw NUL
1687        assert_ne!(
1688            a.canonical_bytes(),
1689            b.canonical_bytes(),
1690            "backslash escape must run before NUL escape to prevent collision"
1691        );
1692    }
1693
1694    fn key_for_collision_test() -> AuditKey {
1695        AuditKey::from_bytes(vec![0xab; 32])
1696    }
1697
1698    #[test]
1699    fn literal_backslash_zero_chain_hash_differs_from_raw_nul() {
1700        let key = key_for_collision_test();
1701        let mut a = sample_content(1, "txa");
1702        a.summary = "before\\0after";
1703        let mut b = sample_content(1, "txa");
1704        b.summary = "before\0after";
1705        assert_ne!(
1706            key.chain_hash(&a, ""),
1707            key.chain_hash(&b, ""),
1708            "chain signature must distinguish escape from raw byte"
1709        );
1710    }
1711
1712    // ── verify_chain ──────────────────────────────────────────────────────
1713
1714    /// Materialise the stored row that `content` would produce, so a test
1715    /// never hand-copies field-by-field and accidentally signs one thing while
1716    /// storing another.
1717    fn row_for(content: &ChainContent<'_>, prev: &str, chain_hash: String) -> ChainRow {
1718        let (chain_version, caller_role, event_tip, caller_principal) = match content.identity {
1719            ChainIdentity::LegacyV1 => (CHAIN_VERSION_LEGACY, None, None, None),
1720            ChainIdentity::V2 {
1721                caller_role,
1722                event_tip,
1723            } => (
1724                CHAIN_VERSION_V2,
1725                Some(caller_role.to_string()),
1726                Some(event_tip.to_string()),
1727                None,
1728            ),
1729            ChainIdentity::V3 {
1730                caller_role,
1731                event_tip,
1732                caller_principal,
1733            } => (
1734                CHAIN_VERSION_V3,
1735                Some(caller_role.to_string()),
1736                Some(event_tip.to_string()),
1737                Some(caller_principal.to_string()),
1738            ),
1739        };
1740        ChainRow {
1741            seq: content.seq,
1742            key_id: content.key_id.to_string(),
1743            transaction_id: content.transaction_id.to_string(),
1744            request_id: content.request_id.to_string(),
1745            request_hash: content.request_hash.to_string(),
1746            action_name: content.action_name.to_string(),
1747            risk_level: content.risk_level,
1748            summary: content.summary.to_string(),
1749            approval_id: content.approval_id.map(str::to_string),
1750            warnings_json: content.warnings_json.to_string(),
1751            created_at: content.created_at.to_string(),
1752            prev_chain_hash: prev.to_string(),
1753            chain_hash,
1754            chain_version,
1755            caller_role,
1756            event_tip,
1757            caller_principal,
1758        }
1759    }
1760
1761    fn build_chain(key: &AuditKey, count: usize) -> Vec<ChainRow> {
1762        let mut rows = Vec::with_capacity(count);
1763        let mut prev = String::new();
1764        for i in 0..count {
1765            let seq = (i + 1) as u64;
1766            let txid = format!("tx{i}");
1767            let content = sample_content(seq, &txid);
1768            let hash = key.chain_hash(&content, &prev);
1769            rows.push(row_for(&content, &prev, hash.clone()));
1770            prev = hash;
1771        }
1772        rows
1773    }
1774
1775    // ── caller identity in the signed content ─────────────────────────────
1776
1777    #[test]
1778    fn caller_role_is_covered_by_the_row_signature() {
1779        // The whole point of the v2 encoding: two rows identical except for
1780        // who asked must not share a signature, or the chain cannot answer
1781        // "which role requested this".
1782        let key = fixed_key();
1783        let mut dev = sample_content(1, "txa");
1784        dev.identity = ChainIdentity::V2 {
1785            caller_role: "Dev",
1786            event_tip: "",
1787        };
1788        let mut boot = sample_content(1, "txa");
1789        boot.identity = ChainIdentity::V2 {
1790            caller_role: "Boot",
1791            event_tip: "",
1792        };
1793        assert_ne!(key.chain_hash(&dev, ""), key.chain_hash(&boot, ""));
1794    }
1795
1796    #[test]
1797    fn event_tip_is_covered_by_the_row_signature() {
1798        let key = fixed_key();
1799        let mut empty = sample_content(1, "txa");
1800        empty.identity = ChainIdentity::V2 {
1801            caller_role: "Dev",
1802            event_tip: "",
1803        };
1804        let mut bound = sample_content(1, "txa");
1805        bound.identity = ChainIdentity::V2 {
1806            caller_role: "Dev",
1807            event_tip: "abc123",
1808        };
1809        assert_ne!(key.chain_hash(&empty, ""), key.chain_hash(&bound, ""));
1810    }
1811
1812    #[test]
1813    fn a_legacy_row_written_before_the_migration_still_verifies() {
1814        // The migration contract. A chain written by v0.2.12 or earlier has no
1815        // caller_role column; re-encoding those rows with an empty identity
1816        // would report every historical row as Broken, i.e. an upgrade would
1817        // look exactly like a compromise.
1818        let key = fixed_key();
1819        let mut content = sample_content(1, "tx-legacy");
1820        content.identity = ChainIdentity::LegacyV1;
1821        let hash = key.chain_hash(&content, "");
1822        let row = row_for(&content, "", hash);
1823        assert_eq!(row.chain_version, CHAIN_VERSION_LEGACY);
1824        assert_eq!(row.caller_role, None);
1825        assert_eq!(
1826            verify_chain(&key, &[row]),
1827            VerifyOutcome::Intact { rows_checked: 1 }
1828        );
1829    }
1830
1831    // ── v3: the row names the account, not just the role ──────────────────
1832
1833    /// The point of the encoding: two callers who share a role must produce
1834    /// distinguishable signed records. If the principal were unsigned, or merely
1835    /// stored, this would pass while proving nothing.
1836    #[test]
1837    fn two_admins_are_distinguishable_in_the_signed_record() {
1838        let key = fixed_key();
1839        let mut alice = sample_content(1, "tx-alice");
1840        alice.identity = ChainIdentity::V3 {
1841            caller_role: "admin",
1842            event_tip: "",
1843            caller_principal: "uid:1000",
1844        };
1845        let mut bob = sample_content(1, "tx-alice");
1846        bob.identity = ChainIdentity::V3 {
1847            caller_role: "admin",
1848            event_tip: "",
1849            caller_principal: "uid:1001",
1850        };
1851
1852        assert_ne!(
1853            key.chain_hash(&alice, ""),
1854            key.chain_hash(&bob, ""),
1855            "identical rows differing only in principal must sign differently, \
1856             otherwise the chain still cannot answer which account acted"
1857        );
1858    }
1859
1860    /// Rewriting the stored principal must break verification. A field that can
1861    /// be edited after the fact records nothing an auditor can rely on.
1862    #[test]
1863    fn editing_the_stored_principal_breaks_the_row() {
1864        let key = fixed_key();
1865        let mut content = sample_content(1, "tx1");
1866        content.identity = ChainIdentity::V3 {
1867            caller_role: "admin",
1868            event_tip: "",
1869            caller_principal: "uid:1000",
1870        };
1871        let hash = key.chain_hash(&content, "");
1872        let mut row = row_for(&content, "", hash);
1873        row.caller_principal = Some("uid:0".to_string());
1874
1875        assert!(
1876            matches!(verify_chain(&key, &[row]), VerifyOutcome::Broken { .. }),
1877            "a principal swapped to root must not verify"
1878        );
1879    }
1880
1881    /// Downgrade is the other direction of the same attack: strip the principal
1882    /// and claim the row was written under v2, hiding which account acted. The
1883    /// v3 message signed a different byte string, so it cannot verify as v2.
1884    #[test]
1885    fn downgrading_a_v3_row_to_v2_to_hide_the_account_breaks_it() {
1886        let key = fixed_key();
1887        let mut content = sample_content(1, "tx1");
1888        content.identity = ChainIdentity::V3 {
1889            caller_role: "admin",
1890            event_tip: "",
1891            caller_principal: "uid:1000",
1892        };
1893        let hash = key.chain_hash(&content, "");
1894        let mut row = row_for(&content, "", hash);
1895        row.chain_version = CHAIN_VERSION_V2;
1896        row.caller_principal = None;
1897
1898        assert!(
1899            matches!(verify_chain(&key, &[row]), VerifyOutcome::Broken { .. }),
1900            "a v3 row relabelled as v2 must not verify"
1901        );
1902    }
1903
1904    /// A v3 row with no principal is self-contradictory, and so is one whose
1905    /// principal is blank: both claim an encoding that names an account while
1906    /// naming none. Treated as a break, not as "cannot verify", because the row
1907    /// contradicts itself rather than being written by a newer binary.
1908    #[test]
1909    fn a_v3_row_without_a_usable_principal_is_broken() {
1910        let key = fixed_key();
1911        let mut content = sample_content(1, "tx1");
1912        content.identity = ChainIdentity::V3 {
1913            caller_role: "admin",
1914            event_tip: "",
1915            caller_principal: "uid:1000",
1916        };
1917        let hash = key.chain_hash(&content, "");
1918
1919        for absent in [None, Some(String::new())] {
1920            let mut row = row_for(&content, "", hash.clone());
1921            row.caller_principal = absent.clone();
1922            assert!(
1923                matches!(verify_chain(&key, &[row]), VerifyOutcome::Broken { .. }),
1924                "a v3 row with principal {absent:?} must be reported as broken"
1925            );
1926        }
1927    }
1928
1929    /// A row *signed with* a blank principal must be rejected, and this is the
1930    /// only test that can prove the guard exists.
1931    ///
1932    /// The sibling test that blanks a stored principal proves something weaker:
1933    /// that row was signed with `uid:1000`, so it fails on signature mismatch
1934    /// whether or not `identity()` filters empties. Here the signature is
1935    /// perfectly valid for the blank principal, so the row verifies unless the
1936    /// filter refuses it. Without the guard a daemon could sign rows that name
1937    /// nobody and every one of them would report as intact.
1938    #[test]
1939    fn a_row_signed_with_a_blank_principal_is_rejected_even_though_it_signs() {
1940        let key = fixed_key();
1941        let mut content = sample_content(1, "tx-blank");
1942        content.identity = ChainIdentity::V3 {
1943            caller_role: "admin",
1944            event_tip: "",
1945            caller_principal: "",
1946        };
1947        let hash = key.chain_hash(&content, "");
1948        // Derived from the very content that was signed, so every other field
1949        // matches by construction. Building it by hand is how the first version
1950        // of this test came to pass for the wrong reason: a mismatched seq made
1951        // the row fail on signature, guard or no guard.
1952        let row = row_for(&content, "", hash);
1953        assert_eq!(
1954            row.caller_principal.as_deref(),
1955            Some(""),
1956            "fixture must store the blank principal it signed"
1957        );
1958        assert_eq!(row.chain_version, CHAIN_VERSION_V3);
1959        assert!(
1960            matches!(verify_chain(&key, &[row]), VerifyOutcome::Broken { .. }),
1961            "a v3 row naming nobody must be broken, not accepted"
1962        );
1963    }
1964
1965    /// An attribution failure is a legitimate, verifiable identity: the daemon
1966    /// admits it could not name the caller, signs that admission, and the chain
1967    /// stays intact. If this ever reports Broken, every honest row on a host
1968    /// where `SO_PEERCRED` fails becomes a false tamper report.
1969    #[test]
1970    fn a_row_recording_an_attribution_failure_verifies() {
1971        let key = fixed_key();
1972        let principal = crate::auth::CallerPrincipal::Unattributed.as_signed_str();
1973        let mut content = sample_content(1, "tx-unattributed");
1974        content.identity = ChainIdentity::V3 {
1975            caller_role: "observer",
1976            event_tip: "",
1977            caller_principal: &principal,
1978        };
1979        let hash = key.chain_hash(&content, "");
1980        let row = row_for(&content, "", hash);
1981
1982        assert_eq!(
1983            verify_chain(&key, &[row]),
1984            VerifyOutcome::Intact { rows_checked: 1 }
1985        );
1986    }
1987
1988    /// The realistic database after two upgrades: legacy rows, v2 rows, then v3
1989    /// rows, all in one chain. Every generation has to keep verifying, which is
1990    /// the whole reason the encoding is selected per row.
1991    #[test]
1992    fn a_chain_spanning_all_three_encodings_verifies() {
1993        let key = fixed_key();
1994        let mut rows = Vec::new();
1995        let mut prev = String::new();
1996        for (i, identity) in [
1997            ChainIdentity::LegacyV1,
1998            ChainIdentity::V2 {
1999                caller_role: "dev",
2000                event_tip: "",
2001            },
2002            ChainIdentity::V3 {
2003                caller_role: "admin",
2004                event_tip: "",
2005                caller_principal: "uid:1000",
2006            },
2007            ChainIdentity::V3 {
2008                caller_role: "admin",
2009                event_tip: "",
2010                caller_principal: "token:vsock",
2011            },
2012        ]
2013        .into_iter()
2014        .enumerate()
2015        {
2016            let txid = format!("tx{i}");
2017            let mut content = sample_content((i + 1) as u64, &txid);
2018            content.identity = identity;
2019            let hash = key.chain_hash(&content, &prev);
2020            rows.push(row_for(&content, &prev, hash.clone()));
2021            prev = hash;
2022        }
2023
2024        assert_eq!(
2025            verify_chain(&key, &rows),
2026            VerifyOutcome::Intact { rows_checked: 4 }
2027        );
2028    }
2029
2030    /// Build a chain from a list of identities, signing each row properly, so no
2031    /// test signs one thing and stores another.
2032    fn chain_of(key: &AuditKey, identities: Vec<ChainIdentity<'_>>) -> Vec<ChainRow> {
2033        let mut rows = Vec::new();
2034        let mut prev = String::new();
2035        for (i, identity) in identities.into_iter().enumerate() {
2036            let txid = format!("tx{i}");
2037            let mut content = sample_content((i + 1) as u64, &txid);
2038            content.identity = identity;
2039            let hash = key.chain_hash(&content, &prev);
2040            rows.push(row_for(&content, &prev, hash.clone()));
2041            prev = hash;
2042        }
2043        rows
2044    }
2045
2046    /// The census has to distinguish *why* a row names no account, because the
2047    /// reasons have different remedies: a `none:unattributed` row means
2048    /// `SO_PEERCRED` failed on a host that could have attributed it, while a v1
2049    /// or v2 row means the encoding had no principal field at the time it was
2050    /// signed. Reporting only the first understates an upgraded database.
2051    ///
2052    /// Every bucket gets a distinct count, so no permutation of the four can
2053    /// satisfy this assertion. The first version used 2/1/2 and still passed with
2054    /// the `named` and `not_recorded` arms swapped.
2055    #[test]
2056    fn the_census_separates_attribution_failures_from_encodings_without_the_field() {
2057        let key = fixed_key();
2058        let unattributed = crate::auth::CallerPrincipal::Unattributed.as_signed_str();
2059        let rows = chain_of(
2060            &key,
2061            vec![
2062                ChainIdentity::LegacyV1,
2063                ChainIdentity::V2 {
2064                    caller_role: "dev",
2065                    event_tip: "",
2066                },
2067                ChainIdentity::V3 {
2068                    caller_role: "admin",
2069                    event_tip: "",
2070                    caller_principal: "uid:1000",
2071                },
2072                ChainIdentity::V3 {
2073                    caller_role: "admin",
2074                    event_tip: "",
2075                    caller_principal: "uid:1001",
2076                },
2077                ChainIdentity::V3 {
2078                    caller_role: "admin",
2079                    event_tip: "",
2080                    caller_principal: "token:vsock",
2081                },
2082                ChainIdentity::V3 {
2083                    caller_role: "observer",
2084                    event_tip: "",
2085                    caller_principal: &unattributed,
2086                },
2087            ],
2088        );
2089
2090        let verification = verify_all(&key, &rows, &[]);
2091        assert_eq!(
2092            verification.chain,
2093            VerifyOutcome::Intact { rows_checked: 6 },
2094            "every encoding must keep verifying; the census is not a verdict"
2095        );
2096        let census = verification
2097            .attribution
2098            .expect("rows were read, so a census was taken");
2099        assert_eq!(census.named(), 3);
2100        assert_eq!(census.attribution_failed(), 1);
2101        assert_eq!(census.not_recorded(), 2);
2102        assert_eq!(census.unattested(), 0);
2103        assert_eq!(census.rows(), 6);
2104        assert_eq!(
2105            census.unnamed(),
2106            3,
2107            "three of the six rows cannot name an account, by either reason"
2108        );
2109    }
2110
2111    /// The forgery this census must not enable.
2112    ///
2113    /// `ChainContent::canonical_bytes` signs `caller_principal` only in the v3
2114    /// arm, so on a v1 or v2 row the column is unsigned free space. Anyone with write access
2115    /// to the table can set it, and no signature breaks. If the census bucketed
2116    /// by the column rather than by the encoding, a single `UPDATE` would turn
2117    /// "none of these rows names an account" into "every row names root", with an
2118    /// `Intact` verdict beside it. Losing attribution is a gap; inventing it is a
2119    /// lie, and this is the test that keeps the lie unavailable.
2120    #[test]
2121    fn a_principal_written_into_an_encoding_that_does_not_sign_it_is_never_an_account() {
2122        let key = fixed_key();
2123        let mut rows = chain_of(
2124            &key,
2125            vec![
2126                ChainIdentity::LegacyV1,
2127                ChainIdentity::V2 {
2128                    caller_role: "dev",
2129                    event_tip: "",
2130                },
2131            ],
2132        );
2133        // The out-of-band write. Not signed by either encoding, so the chain is
2134        // expected to stay Intact: the signature cannot see this.
2135        rows[0].caller_principal = Some("uid:0".to_string());
2136        rows[1].caller_principal = Some("uid:0".to_string());
2137
2138        let verification = verify_all(&key, &rows, &[]);
2139        assert_eq!(
2140            verification.chain,
2141            VerifyOutcome::Intact { rows_checked: 2 },
2142            "no signature covers that column on v1/v2, so tampering with it is \
2143             invisible to verification -- which is exactly why the census must \
2144             not believe it"
2145        );
2146        let census = verification.attribution.expect("rows were read");
2147        assert_eq!(
2148            census.named(),
2149            0,
2150            "an unsigned column must never be credited as an account"
2151        );
2152        assert_eq!(
2153            census.unattested(),
2154            2,
2155            "and it must be reported as unattested, because nothing in SysKnife \
2156             writes that column on those encodings"
2157        );
2158        assert_eq!(census.unnamed(), 2);
2159    }
2160
2161    /// A principal column that is present but empty must not be tallied as an
2162    /// account. The schema allows `''` as well as `NULL`, and `identity()`
2163    /// already reads the two the same way, so the census has to agree with it.
2164    #[test]
2165    fn a_blank_principal_column_is_counted_as_naming_nobody() {
2166        let key = fixed_key();
2167        let mut content = sample_content(1, "tx-blank-census");
2168        content.identity = ChainIdentity::V3 {
2169            caller_role: "admin",
2170            event_tip: "",
2171            caller_principal: "",
2172        };
2173        let hash = key.chain_hash(&content, "");
2174        let row = row_for(&content, "", hash);
2175        assert_eq!(row.caller_principal.as_deref(), Some(""));
2176
2177        let verification = verify_all(&key, &[row], &[]);
2178        let census = verification.attribution.expect("a row was read");
2179        assert_eq!(census.named(), 0);
2180        assert_eq!(census.not_recorded(), 1);
2181        assert_eq!(census.rows(), 1);
2182        assert!(
2183            matches!(verification.chain, VerifyOutcome::Broken { .. }),
2184            "and the row is still reported as broken once the walk reaches it, \
2185             so census and verdict agree"
2186        );
2187    }
2188
2189    /// Values that look like a principal but name nobody. None of these can be
2190    /// written by the daemon (`CallerPrincipal::as_signed_str` always renders
2191    /// `scheme:value` with a non-empty value), so each one is evidence of an
2192    /// out-of-band write. Counting them as accounts would be this commit's own
2193    /// defect one level down: `none:overflow` in particular is a plausible future
2194    /// spelling of a *failure*, and crediting it as an account would invert its
2195    /// meaning.
2196    #[test]
2197    fn a_principal_this_binary_cannot_read_is_counted_as_unattested_not_as_an_account() {
2198        let key = fixed_key();
2199        for forged in [
2200            "garbage",
2201            "uid:",
2202            "none:overflow",
2203            // Whitespace is signed content like any other, so this row verifies
2204            // Intact. It still names nobody, and it belongs in the bucket that
2205            // asks for an investigation rather than the one that explains
2206            // pre-0.3.0 history: nothing in SysKnife writes it.
2207            "  ",
2208            "UID:1000",
2209            // A known scheme with a value the daemon could not have rendered.
2210            "uid:notanumber",
2211            "uid:1000:extra",
2212            "token:not-vsock",
2213        ] {
2214            let mut content = sample_content(1, "tx-forged");
2215            content.identity = ChainIdentity::V3 {
2216                caller_role: "admin",
2217                event_tip: "",
2218                caller_principal: forged,
2219            };
2220            let hash = key.chain_hash(&content, "");
2221            let row = row_for(&content, "", hash);
2222            let census = verify_all(&key, &[row], &[])
2223                .attribution
2224                .expect("a row was read");
2225            assert_eq!(
2226                census.named(),
2227                0,
2228                "{forged:?} names no account and must not be counted as one"
2229            );
2230            assert_eq!(
2231                census.unnamed(),
2232                1,
2233                "{forged:?} must be counted among the rows naming nobody"
2234            );
2235            assert_eq!(
2236                census.unattested(),
2237                1,
2238                "{forged:?} is signed content the daemon never writes, so it is a \
2239                 finding to investigate, not history to explain away"
2240            );
2241            assert_eq!(
2242                census.not_recorded(),
2243                0,
2244                "{forged:?} is present, so it must not be reported as a row that \
2245                 predates the column"
2246            );
2247        }
2248    }
2249
2250    /// The case that made the single counter misleading: a database written
2251    /// entirely before the principal column existed reports zero attribution
2252    /// failures, which reads as "everything is attributed". Every row in it names
2253    /// nobody, so `unnamed` must account for all of them.
2254    #[test]
2255    fn a_chain_predating_the_principal_field_reports_no_row_as_attributed() {
2256        let key = fixed_key();
2257        let rows = chain_of(
2258            &key,
2259            vec![
2260                ChainIdentity::LegacyV1,
2261                ChainIdentity::V2 {
2262                    caller_role: "dev",
2263                    event_tip: "",
2264                },
2265            ],
2266        );
2267
2268        let verification = verify_all(&key, &rows, &[]);
2269        assert_eq!(
2270            verification.chain,
2271            VerifyOutcome::Intact { rows_checked: 2 },
2272            "legacy rows must keep verifying; the census is not a verdict"
2273        );
2274        let census = verification.attribution.expect("rows were read");
2275        assert_eq!(census.attribution_failed(), 0);
2276        assert_eq!(census.named(), 0);
2277        assert_eq!(census.not_recorded(), 2);
2278        assert_eq!(census.unnamed(), 2);
2279    }
2280
2281    /// The census spans every row read, while verification stops at the first
2282    /// break. That is deliberate, and it is also the reason the counts are claims
2283    /// rather than findings: on a broken chain the rows after the break were
2284    /// written by whoever broke it. `rows()` is what lets a reader see the gap
2285    /// between what was counted and what was checked.
2286    #[test]
2287    fn a_broken_chain_censuses_more_rows_than_it_verified() {
2288        let key = fixed_key();
2289        let mut rows = chain_of(
2290            &key,
2291            vec![
2292                ChainIdentity::V3 {
2293                    caller_role: "admin",
2294                    event_tip: "",
2295                    caller_principal: "uid:1000",
2296                },
2297                ChainIdentity::V3 {
2298                    caller_role: "admin",
2299                    event_tip: "",
2300                    caller_principal: "uid:1000",
2301                },
2302                ChainIdentity::V3 {
2303                    caller_role: "admin",
2304                    event_tip: "",
2305                    caller_principal: "uid:1000",
2306                },
2307            ],
2308        );
2309        rows[1].summary = "tampered".to_string();
2310
2311        let verification = verify_all(&key, &rows, &[]);
2312        let rows_checked = match verification.chain {
2313            VerifyOutcome::Broken { rows_checked, .. } => rows_checked,
2314            ref other => panic!("expected a detected tamper, got {other:?}"),
2315        };
2316        let census = verification.attribution.expect("rows were read");
2317        assert_eq!(rows_checked, 1, "the walk stops at the first broken row");
2318        assert_eq!(
2319            census.rows(),
2320            3,
2321            "while the census still describes every row read"
2322        );
2323        assert!(
2324            census.rows() > rows_checked,
2325            "the report must be able to show that more was counted than checked"
2326        );
2327    }
2328
2329    /// The auditor path takes the same census as the keyholder path. It is the
2330    /// one an external reviewer runs, so a census wired only into `verify_all`
2331    /// would leave exactly that audience with nothing.
2332    #[test]
2333    fn the_pubkey_only_path_takes_the_same_census() {
2334        let key = fixed_key();
2335        let unattributed = crate::auth::CallerPrincipal::Unattributed.as_signed_str();
2336        let rows = chain_of(
2337            &key,
2338            vec![
2339                ChainIdentity::V3 {
2340                    caller_role: "admin",
2341                    event_tip: "",
2342                    caller_principal: "uid:1000",
2343                },
2344                ChainIdentity::V3 {
2345                    caller_role: "observer",
2346                    event_tip: "",
2347                    caller_principal: &unattributed,
2348                },
2349            ],
2350        );
2351
2352        let with_key = verify_all(&key, &rows, &[]).attribution;
2353        let with_pubkey = verify_all_with_pubkey(&key.verifying_key_hex(), &rows, &[]).attribution;
2354        assert_eq!(
2355            with_key, with_pubkey,
2356            "the auditor must see the same attribution numbers as the keyholder"
2357        );
2358        let census = with_pubkey.expect("rows were read");
2359        assert_eq!(census.named(), 1);
2360        assert_eq!(census.attribution_failed(), 1);
2361    }
2362
2363    /// Attribution must not move the exit code. `Intact` is a statement about
2364    /// tampering, and `SECURITY.md` leans on that separation: a host where every
2365    /// connection failed attribution still has an untampered chain, and turning
2366    /// that into a non-zero exit would train operators to ignore the real signal.
2367    #[test]
2368    fn a_chain_that_names_nobody_still_exits_zero() {
2369        let key = fixed_key();
2370        let unattributed = crate::auth::CallerPrincipal::Unattributed.as_signed_str();
2371        let rows = chain_of(
2372            &key,
2373            vec![
2374                ChainIdentity::LegacyV1,
2375                ChainIdentity::V3 {
2376                    caller_role: "observer",
2377                    event_tip: "",
2378                    caller_principal: &unattributed,
2379                },
2380            ],
2381        );
2382
2383        let verification = verify_all(&key, &rows, &[]);
2384        let census = verification.attribution.expect("rows were read");
2385        assert_eq!(census.unnamed(), 2, "not one row names an account");
2386        assert_eq!(
2387            verification.exit_code(),
2388            0,
2389            "yet nothing was tampered with, so the command must succeed"
2390        );
2391    }
2392
2393    /// A row from a future encoding is "cannot verify", never "broken": an older
2394    /// binary reading a newer chain has found no tampering, only work it cannot
2395    /// reproduce. The message must say the supported range so the operator knows
2396    /// the fix is a newer build.
2397    #[test]
2398    fn a_future_encoding_reports_cannot_verify_with_the_supported_range() {
2399        let key = fixed_key();
2400        let content = sample_content(1, "tx1");
2401        let hash = key.chain_hash(&content, "");
2402        let mut row = row_for(&content, "", hash);
2403        row.chain_version = CHAIN_VERSION_CURRENT + 1;
2404
2405        match verify_chain(&key, &[row]) {
2406            VerifyOutcome::CannotVerify { reason } => {
2407                assert!(
2408                    reason.contains(&format!("chain_version={}", CHAIN_VERSION_CURRENT + 1)),
2409                    "name the version found, got: {reason}"
2410                );
2411                assert!(
2412                    reason.contains(&CHAIN_VERSION_CURRENT.to_string()),
2413                    "and the newest version understood, got: {reason}"
2414                );
2415            }
2416            other => panic!("a future encoding must not be reported as tampering: {other:?}"),
2417        }
2418    }
2419
2420    /// A row encoded exactly as the v0.2.16 binary would have encoded it: the
2421    /// content is synthetic, the hash is what that release's v2 encoder produced
2422    /// over it. No in-memory test can prove this property, because every other
2423    /// test in this module signs and verifies inside one process, so both halves
2424    /// move together whenever a constant changes.
2425    ///
2426    /// Concretely, this catches the aliasing hazard the `ChainIdentity` docs warn
2427    /// about: `identity()` dispatches stored `chain_version` values against
2428    /// `CHAIN_VERSION_CURRENT`, and the v2 encoder used to *sign* that same
2429    /// constant. Bump it for a new encoding and both the dispatch and the message
2430    /// shift, so every v2 row on disk stops verifying while the whole unit suite
2431    /// stays green. Only a golden vector notices.
2432    #[test]
2433    fn a_row_written_by_the_previous_release_still_verifies() {
2434        const GOLDEN_V2_CHAIN_HASH: &str = "ba12cbe49a149387898bc30f1e8d409effa025ab8e440e6e72bedf060afc831e45d9be264d6b18b7e0ef2f2b3584dbc6953b535546cecbbdc3d7ac666cae4d0a";
2435
2436        let key = fixed_key();
2437        let row = ChainRow {
2438            seq: 7,
2439            key_id: CURRENT_KEY_ID.to_string(),
2440            transaction_id: "tx-golden".to_string(),
2441            request_id: "req-golden".to_string(),
2442            request_hash: "hash-golden".to_string(),
2443            action_name: "AptInstall".to_string(),
2444            risk_level: RiskLevel::Medium,
2445            summary: "install ripgrep".to_string(),
2446            approval_id: Some("appr-golden".to_string()),
2447            warnings_json: "[]".to_string(),
2448            created_at: "2026-07-29T00:00:00Z".to_string(),
2449            prev_chain_hash: String::new(),
2450            chain_hash: GOLDEN_V2_CHAIN_HASH.to_string(),
2451            chain_version: 2,
2452            caller_role: Some("admin".to_string()),
2453            event_tip: Some("eventtip-golden".to_string()),
2454            caller_principal: None,
2455        };
2456
2457        assert_eq!(
2458            verify_chain(&key, std::slice::from_ref(&row)),
2459            VerifyOutcome::Intact { rows_checked: 1 },
2460            "a v2 row on disk must verify under this binary; if this fails, the v2 \
2461             encoding or its version dispatch changed and existing audit logs are unreadable"
2462        );
2463
2464        // Without this half the frozen constant is decorative: a build that
2465        // skipped signature checking entirely would still pass the assertion
2466        // above. Flipping one nibble must be rejected.
2467        let mut tampered = row;
2468        let flipped = match GOLDEN_V2_CHAIN_HASH.strip_prefix('b') {
2469            Some(rest) => format!("a{rest}"),
2470            None => format!("b{}", &GOLDEN_V2_CHAIN_HASH[1..]),
2471        };
2472        tampered.chain_hash = flipped;
2473        assert!(
2474            matches!(
2475                verify_chain(&key, &[tampered]),
2476                VerifyOutcome::Broken { .. }
2477            ),
2478            "a golden row with one nibble changed must not verify"
2479        );
2480    }
2481
2482    /// The v1 encoding is still claimed verifiable, and until now was protected
2483    /// only by tests that sign and verify in one process. Frozen here for the
2484    /// same reason as v2.
2485    #[test]
2486    fn a_legacy_v1_row_on_disk_still_verifies() {
2487        const GOLDEN_V1_CHAIN_HASH: &str = "ce8b47c15414e989e099303b826fcd9985360b794220cefbbf9689d25f31fe173283687feb6d1dd265ae5aca94c8bcfb87ce33ba8c954fafdad18a59cd97c702";
2488
2489        let row = ChainRow {
2490            chain_version: 1,
2491            caller_role: None,
2492            event_tip: None,
2493            caller_principal: None,
2494            chain_hash: GOLDEN_V1_CHAIN_HASH.to_string(),
2495            ..golden_row_shape()
2496        };
2497        assert_eq!(
2498            verify_chain(&fixed_key(), &[row]),
2499            VerifyOutcome::Intact { rows_checked: 1 }
2500        );
2501    }
2502
2503    /// And v3, frozen now while the encoder that produces it is the one under
2504    /// review. When v4 arrives, v3 rows will be in exactly the position v2 rows
2505    /// were in before this change, and this is the test that will notice.
2506    #[test]
2507    fn a_v3_row_on_disk_still_verifies() {
2508        const GOLDEN_V3_CHAIN_HASH: &str = "3c0d05f6ccaf9e65ccb796d4ffe96eb31a2ea67e446217c5234af916dc959d0f2c0ee3d3e5b525aece791ee7d6507efb98dcdd79f0d74dde4273859aa9627d08";
2509
2510        let row = ChainRow {
2511            chain_version: 3,
2512            caller_role: Some("admin".to_string()),
2513            event_tip: Some("eventtip-golden".to_string()),
2514            caller_principal: Some("uid:1000".to_string()),
2515            chain_hash: GOLDEN_V3_CHAIN_HASH.to_string(),
2516            ..golden_row_shape()
2517        };
2518        assert_eq!(
2519            verify_chain(&fixed_key(), &[row]),
2520            VerifyOutcome::Intact { rows_checked: 1 }
2521        );
2522    }
2523
2524    /// The golden rows above all have an empty `prev_chain_hash`, an approval id,
2525    /// and content with no bytes the escape table touches. This one has the
2526    /// opposite of each: a non-empty predecessor, no approval id, and a summary
2527    /// carrying a backslash, `0x1F`, `0x1E`, and a NUL. A refactor of the escape
2528    /// table or of the `approval_id: None` mapping changes this hash and nothing
2529    /// else in the suite.
2530    #[test]
2531    fn the_escape_table_and_absent_approval_encoding_are_frozen() {
2532        const GOLDEN_V2_AWKWARD_CHAIN_HASH: &str = "e6face6fe2346fc0f6c5c1e5845255579c8f08738406b88b0a1f6dbdf8ff85090a4b80d95bd0927ef54b0a2c4810d52ebb4bbf76cb68c865a7748df26442aa05";
2533
2534        let key = fixed_key();
2535        let content = ChainContent {
2536            seq: 8,
2537            approval_id: None,
2538            summary: "back\\slash and \x1funit and \x1erecord and nul\0byte",
2539            identity: ChainIdentity::V2 {
2540                caller_role: "dev",
2541                event_tip: "",
2542            },
2543            ..golden_content_shape()
2544        };
2545        assert_eq!(
2546            key.chain_hash(&content, "ba12cbe4"),
2547            GOLDEN_V2_AWKWARD_CHAIN_HASH,
2548            "the canonical encoding of escapes, an absent approval id, or a \
2549             non-empty prev_chain_hash changed"
2550        );
2551    }
2552
2553    /// Shared literal content for the golden vectors. Spelled out rather than
2554    /// derived from `sample_content` so a future edit to that helper cannot move
2555    /// what the frozen hashes describe.
2556    fn golden_content_shape() -> ChainContent<'static> {
2557        ChainContent {
2558            seq: 7,
2559            key_id: CURRENT_KEY_ID,
2560            transaction_id: "tx-golden",
2561            request_id: "req-golden",
2562            request_hash: "hash-golden",
2563            action_name: "AptInstall",
2564            risk_level: RiskLevel::Medium,
2565            summary: "install ripgrep",
2566            approval_id: Some("appr-golden"),
2567            warnings_json: "[]",
2568            created_at: "2026-07-29T00:00:00Z",
2569            identity: ChainIdentity::LegacyV1,
2570        }
2571    }
2572
2573    /// The stored-row twin of `golden_content_shape`.
2574    fn golden_row_shape() -> ChainRow {
2575        ChainRow {
2576            seq: 7,
2577            key_id: CURRENT_KEY_ID.to_string(),
2578            transaction_id: "tx-golden".to_string(),
2579            request_id: "req-golden".to_string(),
2580            request_hash: "hash-golden".to_string(),
2581            action_name: "AptInstall".to_string(),
2582            risk_level: RiskLevel::Medium,
2583            summary: "install ripgrep".to_string(),
2584            approval_id: Some("appr-golden".to_string()),
2585            warnings_json: "[]".to_string(),
2586            created_at: "2026-07-29T00:00:00Z".to_string(),
2587            prev_chain_hash: String::new(),
2588            chain_hash: String::new(),
2589            chain_version: 1,
2590            caller_role: None,
2591            event_tip: None,
2592            caller_principal: None,
2593        }
2594    }
2595
2596    #[test]
2597    fn a_chain_that_spans_the_migration_verifies_end_to_end() {
2598        // The realistic upgrade shape: old rows, then new rows appended by the
2599        // upgraded daemon, in one chain.
2600        let key = fixed_key();
2601        let mut rows = Vec::new();
2602        let mut prev = String::new();
2603        for (i, identity) in [
2604            ChainIdentity::LegacyV1,
2605            ChainIdentity::LegacyV1,
2606            ChainIdentity::V2 {
2607                caller_role: "Dev",
2608                event_tip: "",
2609            },
2610            ChainIdentity::V2 {
2611                caller_role: "Boot",
2612                event_tip: "",
2613            },
2614        ]
2615        .into_iter()
2616        .enumerate()
2617        {
2618            let txid = format!("tx{i}");
2619            let mut content = sample_content((i + 1) as u64, &txid);
2620            content.identity = identity;
2621            let hash = key.chain_hash(&content, &prev);
2622            rows.push(row_for(&content, &prev, hash.clone()));
2623            prev = hash;
2624        }
2625        assert_eq!(
2626            verify_chain(&key, &rows),
2627            VerifyOutcome::Intact { rows_checked: 4 }
2628        );
2629    }
2630
2631    #[test]
2632    fn downgrading_a_v2_row_to_hide_the_caller_role_breaks_it() {
2633        // The attack the version column might invite: relabel a v2 row as
2634        // legacy and drop the identity columns, so verification re-encodes it
2635        // without caller_role. The stored signature was made over the v2
2636        // message, so it cannot verify against the shorter one.
2637        let key = fixed_key();
2638        let mut rows = build_chain(&key, 2);
2639        rows[1].chain_version = CHAIN_VERSION_LEGACY;
2640        rows[1].caller_role = None;
2641        rows[1].event_tip = None;
2642        match verify_chain(&key, &rows) {
2643            VerifyOutcome::Broken {
2644                first_broken_seq, ..
2645            } => assert_eq!(first_broken_seq, 2),
2646            other => panic!("expected Broken, got {other:?}"),
2647        }
2648    }
2649
2650    #[test]
2651    fn a_v2_row_with_a_nulled_caller_role_is_broken_not_merely_unverifiable() {
2652        // Nulling the column while leaving chain_version=2 is a
2653        // self-contradictory row, not an infrastructure problem. It must map
2654        // to exit code 1 (tamper detected), never 2 (could not check) — a CI
2655        // gate that treats 2 as "skip" would otherwise wave it through.
2656        let key = fixed_key();
2657        let mut rows = build_chain(&key, 1);
2658        rows[0].caller_role = None;
2659        let outcome = verify_chain(&key, &rows);
2660        assert!(matches!(outcome, VerifyOutcome::Broken { .. }));
2661        assert_eq!(outcome_to_exit_code(&outcome), 1);
2662    }
2663
2664    #[test]
2665    fn a_chain_version_this_binary_does_not_know_is_cannot_verify() {
2666        // An older binary reading a newer chain genuinely cannot reproduce the
2667        // message. That is exit 2, distinct from a detected break.
2668        let key = fixed_key();
2669        let mut rows = build_chain(&key, 1);
2670        rows[0].chain_version = CHAIN_VERSION_CURRENT + 1;
2671        let outcome = verify_chain(&key, &rows);
2672        assert!(matches!(outcome, VerifyOutcome::CannotVerify { .. }));
2673        assert_eq!(outcome_to_exit_code(&outcome), 2);
2674    }
2675
2676    // ── approval-event chain ──────────────────────────────────────────────
2677
2678    fn event_content<'a>(seq: u64, kind: AuditEventKind, txid: &'a str) -> EventContent<'a> {
2679        EventContent {
2680            seq,
2681            key_id: CURRENT_KEY_ID,
2682            kind,
2683            transaction_id: txid,
2684            receipt_digest: "digest-abc",
2685            created_at: "2026-04-24T12:00:00Z",
2686        }
2687    }
2688
2689    fn build_event_chain(key: &AuditKey, kinds: &[AuditEventKind]) -> Vec<EventRow> {
2690        let mut rows = Vec::with_capacity(kinds.len());
2691        let mut prev = String::new();
2692        for (i, kind) in kinds.iter().enumerate() {
2693            let seq = (i + 1) as u64;
2694            let txid = format!("tx{i}");
2695            let content = event_content(seq, *kind, &txid);
2696            let hash = key.event_hash(&content, &prev);
2697            rows.push(EventRow {
2698                seq,
2699                key_id: content.key_id.to_string(),
2700                kind: content.kind.as_str().to_string(),
2701                transaction_id: content.transaction_id.to_string(),
2702                receipt_digest: content.receipt_digest.to_string(),
2703                created_at: content.created_at.to_string(),
2704                prev_chain_hash: prev.clone(),
2705                chain_hash: hash.clone(),
2706            });
2707            prev = hash;
2708        }
2709        rows
2710    }
2711
2712    #[test]
2713    fn event_kind_spellings_are_stable() {
2714        // These strings are inside the signed message. Renaming one silently
2715        // invalidates every event already written.
2716        assert_eq!(AuditEventKind::ApprovalGranted.as_str(), "approval_granted");
2717        assert_eq!(
2718            AuditEventKind::ApprovalConsumed.as_str(),
2719            "approval_consumed"
2720        );
2721        assert_eq!(AuditEventKind::ApprovalRevoked.as_str(), "approval_revoked");
2722    }
2723
2724    #[test]
2725    fn intact_event_chain_verifies() {
2726        let key = fixed_key();
2727        let rows = build_event_chain(
2728            &key,
2729            &[
2730                AuditEventKind::ApprovalGranted,
2731                AuditEventKind::ApprovalConsumed,
2732            ],
2733        );
2734        assert_eq!(
2735            verify_event_chain(&key, &rows),
2736            VerifyOutcome::Intact { rows_checked: 2 }
2737        );
2738    }
2739
2740    #[test]
2741    fn deleting_an_approval_event_from_the_middle_breaks_the_event_chain() {
2742        // The finding this chain exists for: before it, deleting the record
2743        // that an approval happened left `audit verify` reporting Intact.
2744        let key = fixed_key();
2745        let mut rows = build_event_chain(
2746            &key,
2747            &[
2748                AuditEventKind::ApprovalGranted,
2749                AuditEventKind::ApprovalConsumed,
2750                AuditEventKind::ApprovalRevoked,
2751            ],
2752        );
2753        rows.remove(1);
2754        match verify_event_chain(&key, &rows) {
2755            VerifyOutcome::Broken {
2756                first_broken_seq, ..
2757            } => assert_eq!(first_broken_seq, 3),
2758            other => panic!("expected Broken, got {other:?}"),
2759        }
2760    }
2761
2762    #[test]
2763    fn relabelling_a_revocation_as_a_grant_breaks_the_event_chain() {
2764        let key = fixed_key();
2765        let mut rows = build_event_chain(&key, &[AuditEventKind::ApprovalRevoked]);
2766        rows[0].kind = AuditEventKind::ApprovalGranted.as_str().to_string();
2767        assert!(matches!(
2768            verify_event_chain(&key, &rows),
2769            VerifyOutcome::Broken { .. }
2770        ));
2771    }
2772
2773    #[test]
2774    fn an_unrecognised_event_kind_is_a_break_not_a_panic() {
2775        let key = fixed_key();
2776        let mut rows = build_event_chain(&key, &[AuditEventKind::ApprovalGranted]);
2777        rows[0].kind = "approval_unicorned".to_string();
2778        assert!(matches!(
2779            verify_event_chain(&key, &rows),
2780            VerifyOutcome::Broken { .. }
2781        ));
2782    }
2783
2784    #[test]
2785    fn a_row_signature_cannot_be_replayed_as_an_event_signature() {
2786        // Domain separation, checked functionally rather than by comparing the
2787        // tag constants: the tags test proves the bytes differ, this proves the
2788        // difference actually reaches the verifier.
2789        let key = fixed_key();
2790        let content = event_content(1, AuditEventKind::ApprovalGranted, "tx0");
2791        let event_sig = key.event_hash(&content, "");
2792        let row_sig = key.chain_hash(&sample_content(1, "tx0"), "");
2793        assert_ne!(event_sig, row_sig);
2794
2795        let mut rows = build_event_chain(&key, &[AuditEventKind::ApprovalGranted]);
2796        rows[0].chain_hash = row_sig;
2797        assert!(matches!(
2798            verify_event_chain(&key, &rows),
2799            VerifyOutcome::Broken { .. }
2800        ));
2801    }
2802
2803    // ── cross-chain binding ───────────────────────────────────────────────
2804
2805    #[test]
2806    fn deleting_the_last_approval_event_is_caught_by_the_transaction_binding() {
2807        // Truncating the *tail* of the event chain leaves a self-consistent
2808        // event chain — the walk alone cannot see it. It is caught because a
2809        // later transaction row signed the tip that no longer exists, and the
2810        // transaction chain is what checkpoints anchor.
2811        let key = fixed_key();
2812        let events = build_event_chain(
2813            &key,
2814            &[
2815                AuditEventKind::ApprovalGranted,
2816                AuditEventKind::ApprovalConsumed,
2817            ],
2818        );
2819        let mut content = sample_content(1, "tx-after");
2820        content.identity = ChainIdentity::V2 {
2821            caller_role: "Dev",
2822            event_tip: &events[1].chain_hash,
2823        };
2824        let hash = key.chain_hash(&content, "");
2825        let tx_rows = vec![row_for(&content, "", hash)];
2826
2827        assert_eq!(
2828            verify_event_binding(&tx_rows, &events),
2829            BindingOutcome::Consistent {
2830                bindings_checked: 1
2831            }
2832        );
2833
2834        let truncated = &events[..1];
2835        assert_eq!(
2836            verify_event_chain(&key, truncated),
2837            VerifyOutcome::Intact { rows_checked: 1 },
2838            "a truncated event chain still walks clean; the binding is the detector"
2839        );
2840        match verify_event_binding(&tx_rows, truncated) {
2841            BindingOutcome::MissingEvent {
2842                transaction_seq, ..
2843            } => assert_eq!(transaction_seq, 1),
2844            other => panic!("expected MissingEvent, got {other:?}"),
2845        }
2846    }
2847
2848    #[test]
2849    fn legacy_rows_carry_no_binding_to_check() {
2850        // Rows written before the migration never committed to an event tip.
2851        // They must not be counted as bindings, and must not fail the check.
2852        let key = fixed_key();
2853        let mut content = sample_content(1, "tx-legacy");
2854        content.identity = ChainIdentity::LegacyV1;
2855        let hash = key.chain_hash(&content, "");
2856        let rows = vec![row_for(&content, "", hash)];
2857        assert_eq!(
2858            verify_event_binding(&rows, &[]),
2859            BindingOutcome::Consistent {
2860                bindings_checked: 0
2861            }
2862        );
2863    }
2864
2865    #[test]
2866    fn a_detected_break_outranks_an_inconclusive_check_in_the_exit_code() {
2867        // If one check proves tampering and another merely cannot run, the
2868        // command must report the tamper. Reporting 2 ("could not verify")
2869        // would let a CI gate that treats 2 as a skip wave a broken chain
2870        // through.
2871        let verification = AuditVerification {
2872            chain: VerifyOutcome::Broken {
2873                rows_checked: 1,
2874                first_broken_seq: 2,
2875                first_broken_transaction_id: "tx".to_string(),
2876                expected: "e".to_string(),
2877                actual: "a".to_string(),
2878            },
2879            events: VerifyOutcome::CannotVerify {
2880                reason: "no key".to_string(),
2881            },
2882            binding: BindingOutcome::Consistent {
2883                bindings_checked: 0,
2884            },
2885            attribution: None,
2886        };
2887        assert_eq!(verification.exit_code(), 1);
2888    }
2889
2890    #[test]
2891    fn a_clean_transaction_chain_does_not_mask_a_broken_event_chain() {
2892        let verification = AuditVerification {
2893            chain: VerifyOutcome::Intact { rows_checked: 3 },
2894            events: VerifyOutcome::Intact { rows_checked: 1 },
2895            binding: BindingOutcome::MissingEvent {
2896                transaction_seq: 3,
2897                event_tip: "abc".to_string(),
2898            },
2899            attribution: None,
2900        };
2901        assert_eq!(verification.exit_code(), 1);
2902    }
2903
2904    #[test]
2905    fn all_three_clean_is_exit_zero() {
2906        let verification = AuditVerification {
2907            chain: VerifyOutcome::Intact { rows_checked: 3 },
2908            events: VerifyOutcome::Intact { rows_checked: 2 },
2909            binding: BindingOutcome::Consistent {
2910                bindings_checked: 1,
2911            },
2912            attribution: None,
2913        };
2914        assert_eq!(verification.exit_code(), 0);
2915    }
2916
2917    #[test]
2918    fn binding_exit_codes_split_clean_from_tampered() {
2919        assert_eq!(
2920            binding_outcome_to_exit_code(&BindingOutcome::Consistent {
2921                bindings_checked: 0
2922            }),
2923            0
2924        );
2925        assert_eq!(
2926            binding_outcome_to_exit_code(&BindingOutcome::MissingEvent {
2927                transaction_seq: 7,
2928                event_tip: "abc".to_string()
2929            }),
2930            1
2931        );
2932    }
2933
2934    #[test]
2935    fn intact_chain_verifies() {
2936        let key = fixed_key();
2937        let rows = build_chain(&key, 5);
2938        let outcome = verify_chain(&key, &rows);
2939        assert_eq!(outcome, VerifyOutcome::Intact { rows_checked: 5 });
2940        assert_eq!(outcome_to_exit_code(&outcome), 0);
2941    }
2942
2943    #[test]
2944    fn empty_chain_verifies() {
2945        let key = fixed_key();
2946        let outcome = verify_chain(&key, &[]);
2947        assert_eq!(outcome, VerifyOutcome::Intact { rows_checked: 0 });
2948    }
2949
2950    #[test]
2951    fn tampered_summary_breaks_chain_at_first_offending_row() {
2952        let key = fixed_key();
2953        let mut rows = build_chain(&key, 3);
2954        // Mutate summary on row 1 (seq=2). Hash mismatch should be detected.
2955        rows[1].summary = "TAMPERED".to_string();
2956        let outcome = verify_chain(&key, &rows);
2957        match outcome {
2958            VerifyOutcome::Broken {
2959                first_broken_seq, ..
2960            } => assert_eq!(first_broken_seq, 2),
2961            other => panic!("expected Broken, got {other:?}"),
2962        }
2963    }
2964
2965    #[test]
2966    fn deleted_middle_row_breaks_chain_via_prev_hash_mismatch() {
2967        let key = fixed_key();
2968        let mut rows = build_chain(&key, 4);
2969        // Remove row at seq=2 entirely. Row 3's prev_chain_hash now mismatches.
2970        rows.remove(1);
2971        let outcome = verify_chain(&key, &rows);
2972        match outcome {
2973            VerifyOutcome::Broken {
2974                first_broken_seq, ..
2975            } => assert_eq!(
2976                first_broken_seq, 3,
2977                "first broken row is the one whose prev_hash refers to deleted row"
2978            ),
2979            other => panic!("expected Broken, got {other:?}"),
2980        }
2981    }
2982
2983    #[test]
2984    fn inserted_forged_row_breaks_chain() {
2985        // Counterpart to `deleted_middle_row_…`. An attacker who managed to
2986        // insert a fabricated row between two genuine ones still cannot
2987        // produce a `chain_hash` that links the insertion back to the prior
2988        // row's hash, so verification must flag the forgery at the inserted
2989        // row (or at the immediately following genuine row whose
2990        // `prev_chain_hash` no longer matches its real predecessor).
2991        let key = fixed_key();
2992        let mut rows = build_chain(&key, 3);
2993
2994        // Splice in a new row between seq=1 and seq=2 with a fabricated hash.
2995        let forged = ChainRow {
2996            // Carries a principal on purpose: without one the row is rejected as
2997            // self-contradictory *before* any signature is checked, and this test
2998            // exists to prove the walk stops on a bad signature.
2999            caller_principal: Some("uid:1000".to_string()),
3000            seq: 2,
3001            key_id: CURRENT_KEY_ID.to_string(),
3002            transaction_id: "tx-forged".to_string(),
3003            request_id: "req-forged".to_string(),
3004            request_hash: "hash-forged".to_string(),
3005            action_name: "InstallFlatpak".to_string(),
3006            risk_level: RiskLevel::Medium,
3007            summary: "Forged row".to_string(),
3008            approval_id: None,
3009            warnings_json: "[]".to_string(),
3010            created_at: "2026-04-25T13:00:00Z".to_string(),
3011            // Plausible prev_chain_hash chosen to look intact at boundary.
3012            prev_chain_hash: rows[0].chain_hash.clone(),
3013            // Not a valid signature; verification must reject this.
3014            chain_hash: "0".repeat(HASH_HEX_LEN),
3015            chain_version: CHAIN_VERSION_CURRENT,
3016            caller_role: Some("Dev".to_string()),
3017            event_tip: Some(String::new()),
3018        };
3019
3020        // Renumber the genuine seq=2/3 rows so seq is still 1..=4.
3021        let mut rest: Vec<ChainRow> = rows.split_off(1);
3022        for r in rest.iter_mut() {
3023            r.seq += 1;
3024        }
3025        rows.push(forged);
3026        rows.extend(rest);
3027
3028        // The fixture is deterministic: the forged row sits at seq=2 with a
3029        // signature that cannot verify, so the walk must stop exactly there.
3030        // Accepting "2 or 3" let an off-by-one in `verify_rows` pass.
3031        let outcome = verify_chain(&key, &rows);
3032        match outcome {
3033            VerifyOutcome::Broken {
3034                first_broken_seq, ..
3035            } => assert_eq!(
3036                first_broken_seq, 2,
3037                "the verifier must flag the forged row itself, not a later one"
3038            ),
3039            other => panic!("expected Broken, got {other:?}"),
3040        }
3041    }
3042
3043    // ── Ed25519 public-key verification / non-repudiation ─────────────────
3044
3045    #[test]
3046    fn signature_verifies_under_exported_public_key() {
3047        // The auditor path: verify with only the public key.
3048        let key = fixed_key();
3049        let rows = build_chain(&key, 4);
3050        let outcome = verify_chain_with_pubkey(&key.verifying_key_hex(), &rows);
3051        assert_eq!(outcome, VerifyOutcome::Intact { rows_checked: 4 });
3052    }
3053
3054    #[test]
3055    fn foreign_public_key_cannot_validate_chain() {
3056        // Non-repudiation: a different keypair's public key neither validates
3057        // the chain nor (by construction) could forge it. This is the property
3058        // the old symmetric HMAC could not provide.
3059        let signer = AuditKey::from_bytes(vec![0x11; 32]);
3060        let rows = build_chain(&signer, 3);
3061        let other = AuditKey::from_bytes(vec![0x22; 32]);
3062        let outcome = verify_chain_with_pubkey(&other.verifying_key_hex(), &rows);
3063        assert!(matches!(
3064            outcome,
3065            VerifyOutcome::Broken {
3066                first_broken_seq: 1,
3067                ..
3068            }
3069        ));
3070    }
3071
3072    #[test]
3073    fn verifying_key_hex_is_a_32_byte_public_key() {
3074        let key = fixed_key();
3075        let vk_hex = key.verifying_key_hex();
3076        assert_eq!(
3077            vk_hex.len(),
3078            64,
3079            "32-byte ed25519 public key = 64 hex chars"
3080        );
3081        assert!(hex::decode(&vk_hex).is_ok());
3082    }
3083
3084    #[test]
3085    fn malformed_signature_hex_is_broken_not_panic() {
3086        let key = fixed_key();
3087        let mut rows = build_chain(&key, 2);
3088        rows[0].chain_hash = "not-valid-hex!!".to_string();
3089        let outcome = verify_chain(&key, &rows);
3090        assert!(matches!(
3091            outcome,
3092            VerifyOutcome::Broken {
3093                first_broken_seq: 1,
3094                ..
3095            }
3096        ));
3097    }
3098
3099    #[test]
3100    fn bad_public_key_hex_yields_cannot_verify() {
3101        let key = fixed_key();
3102        let rows = build_chain(&key, 1);
3103        let outcome = verify_chain_with_pubkey("zz", &rows);
3104        assert!(matches!(outcome, VerifyOutcome::CannotVerify { .. }));
3105    }
3106
3107    #[test]
3108    fn load_or_generate_writes_public_key_sidecar() {
3109        let dir = tempfile::tempdir().unwrap();
3110        let path = dir.path().join("audit-key");
3111        let key = AuditKey::load_or_generate(&path).unwrap();
3112        let pub_path = dir.path().join("audit-key.pub");
3113        assert!(pub_path.exists(), "public key sidecar must be written");
3114        let pub_hex = std::fs::read_to_string(&pub_path).unwrap();
3115        assert_eq!(pub_hex.trim(), key.verifying_key_hex());
3116    }
3117
3118    #[test]
3119    fn wrong_key_id_yields_cannot_verify() {
3120        let key = fixed_key();
3121        let mut rows = build_chain(&key, 2);
3122        rows[0].key_id = "v99".to_string();
3123        let outcome = verify_chain(&key, &rows);
3124        assert!(matches!(outcome, VerifyOutcome::CannotVerify { .. }));
3125        assert_eq!(outcome_to_exit_code(&outcome), 2);
3126    }
3127
3128    #[test]
3129    fn exit_code_for_each_outcome() {
3130        assert_eq!(
3131            outcome_to_exit_code(&VerifyOutcome::Intact { rows_checked: 0 }),
3132            0
3133        );
3134        assert_eq!(
3135            outcome_to_exit_code(&VerifyOutcome::Broken {
3136                rows_checked: 0,
3137                first_broken_seq: 1,
3138                first_broken_transaction_id: String::new(),
3139                expected: String::new(),
3140                actual: String::new(),
3141            }),
3142            1
3143        );
3144        assert_eq!(
3145            outcome_to_exit_code(&VerifyOutcome::CannotVerify {
3146                reason: String::new()
3147            }),
3148            2
3149        );
3150    }
3151
3152    // ── AuditKey file management ──────────────────────────────────────────
3153
3154    #[test]
3155    fn load_or_generate_creates_with_0600_mode() {
3156        use std::os::unix::fs::PermissionsExt;
3157        let dir = tempfile::tempdir().unwrap();
3158        let path = dir.path().join("audit-key");
3159        let _key = AuditKey::load_or_generate(&path).unwrap();
3160        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
3161        assert_eq!(mode, 0o600);
3162    }
3163
3164    #[test]
3165    fn load_or_generate_is_idempotent() {
3166        let dir = tempfile::tempdir().unwrap();
3167        let path = dir.path().join("audit-key");
3168        let key1_bytes = {
3169            let _ = AuditKey::load_or_generate(&path).unwrap();
3170            std::fs::read(&path).unwrap()
3171        };
3172        let _ = AuditKey::load_or_generate(&path).unwrap();
3173        let key2_bytes = std::fs::read(&path).unwrap();
3174        assert_eq!(key1_bytes, key2_bytes, "second load must not regenerate");
3175    }
3176
3177    #[test]
3178    fn rejects_world_readable_key_file() {
3179        use std::os::unix::fs::PermissionsExt;
3180        let dir = tempfile::tempdir().unwrap();
3181        let path = dir.path().join("audit-key");
3182        std::fs::write(&path, vec![0u8; 32]).unwrap();
3183        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
3184        let result = AuditKey::load_or_generate(&path);
3185        assert!(matches!(
3186            result,
3187            Err(AuditKeyError::UnsafePermissions { .. })
3188        ));
3189    }
3190
3191    #[test]
3192    fn rejects_short_key_file() {
3193        use std::os::unix::fs::PermissionsExt;
3194        let dir = tempfile::tempdir().unwrap();
3195        let path = dir.path().join("audit-key");
3196        std::fs::write(&path, vec![0u8; 8]).unwrap();
3197        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
3198        let result = AuditKey::load_or_generate(&path);
3199        assert!(matches!(result, Err(AuditKeyError::KeyTooShort { .. })));
3200    }
3201
3202    // ── Debug redaction (HI-17 secret hygiene) ────────────────────────────
3203
3204    /// `Debug` must never expose the Ed25519 private key material, neither raw bytes,
3205    /// nor their hex encoding. A derived `Debug` would dump the bytes the
3206    /// moment anyone wrote `tracing::debug!("{key:?}")`.
3207    #[test]
3208    fn debug_redacts_key_bytes_and_their_hex_encoding() {
3209        // Use a distinctive byte pattern so accidental leaks are obvious.
3210        let raw = (0u8..32).collect::<Vec<u8>>();
3211        let key = AuditKey::from_bytes(raw.clone());
3212        let dbg = format!("{key:?}");
3213
3214        assert!(
3215            dbg.contains("redacted"),
3216            "Debug output must contain the literal 'redacted' marker, got: {dbg}"
3217        );
3218
3219        // Hex encoding of the bytes must NOT appear, in either case.
3220        let hex_lower = hex::encode(&raw);
3221        let hex_upper = hex::encode_upper(&raw);
3222        assert!(
3223            !dbg.contains(&hex_lower),
3224            "Debug output leaks lowercase hex of key bytes: {dbg}"
3225        );
3226        assert!(
3227            !dbg.contains(&hex_upper),
3228            "Debug output leaks uppercase hex of key bytes: {dbg}"
3229        );
3230
3231        // Each individual byte's two-hex-char form must also be absent. This
3232        // catches the case where a future change splits the bytes across the
3233        // formatter and prints them piecewise.
3234        for b in &raw {
3235            let pair = format!("{b:02x}");
3236            // 1-byte values 0x00..0x0f render as "00".."0f" — too short to
3237            // assert against safely (collides with key_id "v1" etc.). Only
3238            // check 2-char forms that cannot incidentally match the rest of
3239            // the Debug output.
3240            if *b >= 0x10 && pair != "1e" && pair != "1f" {
3241                assert!(
3242                    !dbg.contains(&pair),
3243                    "Debug output leaks byte {b:#04x} as {pair:?}: {dbg}"
3244                );
3245            }
3246        }
3247    }
3248
3249    /// Operators triaging a chain break need to know which key generation
3250    /// produced a row. `key_id` is not secret and must remain visible.
3251    #[test]
3252    fn debug_preserves_key_id() {
3253        let key = AuditKey::from_bytes(vec![0xff; 32]);
3254        let dbg = format!("{key:?}");
3255        assert!(
3256            dbg.contains("key_id"),
3257            "Debug output must label the key_id field: {dbg}"
3258        );
3259        assert!(
3260            dbg.contains(CURRENT_KEY_ID),
3261            "Debug output must contain the key_id value {CURRENT_KEY_ID:?}: {dbg}"
3262        );
3263    }
3264
3265    // ── signed checkpoints (anti-truncation / anti-rewrite) ───────────────
3266
3267    #[test]
3268    fn checkpoint_consistent_with_intact_chain() {
3269        let key = fixed_key();
3270        let rows = build_chain(&key, 5);
3271        let cp = key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:00:00Z");
3272        let outcome = verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]);
3273        assert_eq!(
3274            outcome,
3275            CheckpointOutcome::Consistent {
3276                checkpoints_checked: 1
3277            }
3278        );
3279    }
3280
3281    #[test]
3282    fn checkpoint_detects_truncation() {
3283        let key = fixed_key();
3284        let full = build_chain(&key, 5);
3285        // Anchor a checkpoint at the tip (seq=5); later the chain is cut to 3.
3286        let cp = key.sign_checkpoint(5, &full[4].chain_hash, "2026-04-24T12:00:00Z");
3287        let truncated = &full[..3];
3288        let outcome = verify_checkpoints(&key.verifying_key_hex(), truncated, &[cp]);
3289        assert!(matches!(
3290            outcome,
3291            CheckpointOutcome::Truncated {
3292                checkpoint_seq: 5,
3293                current_max_seq: 3
3294            }
3295        ));
3296    }
3297
3298    #[test]
3299    fn checkpoint_detects_rewrite() {
3300        let key = fixed_key();
3301        let mut rows = build_chain(&key, 4);
3302        let cp = key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:00:00Z");
3303        // Rewrite the row at seq=3 after the checkpoint was anchored.
3304        rows[2].chain_hash = "0".repeat(HASH_HEX_LEN);
3305        let outcome = verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]);
3306        assert!(matches!(
3307            outcome,
3308            CheckpointOutcome::TipMismatch { seq: 3, .. }
3309        ));
3310    }
3311
3312    #[test]
3313    fn checkpoint_bad_signature_detected() {
3314        let key = fixed_key();
3315        let rows = build_chain(&key, 3);
3316        let mut cp = key.sign_checkpoint(2, &rows[1].chain_hash, "2026-04-24T12:00:00Z");
3317        cp.signature = "0".repeat(HASH_HEX_LEN); // not a valid signature
3318        let outcome = verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]);
3319        assert!(matches!(
3320            outcome,
3321            CheckpointOutcome::BadSignature { seq: 2 }
3322        ));
3323    }
3324
3325    #[test]
3326    fn checkpoint_foreign_key_rejected() {
3327        // A checkpoint signed by one key must not verify under another key.
3328        let signer = AuditKey::from_bytes(vec![0x11; 32]);
3329        let rows = build_chain(&signer, 3);
3330        let cp = signer.sign_checkpoint(2, &rows[1].chain_hash, "2026-04-24T12:00:00Z");
3331        let other = AuditKey::from_bytes(vec![0x22; 32]);
3332        let outcome = verify_checkpoints(&other.verifying_key_hex(), &rows, &[cp]);
3333        assert!(matches!(
3334            outcome,
3335            CheckpointOutcome::BadSignature { seq: 2 }
3336        ));
3337    }
3338
3339    #[test]
3340    fn pubkey_verify_detects_tampered_middle_row() {
3341        // The core auditor claim: with only the public key, a mutated field in
3342        // a non-first row is detected at that exact seq.
3343        let key = fixed_key();
3344        let mut rows = build_chain(&key, 4);
3345        rows[2].summary = "TAMPERED".to_string();
3346        let outcome = verify_chain_with_pubkey(&key.verifying_key_hex(), &rows);
3347        assert!(matches!(
3348            outcome,
3349            VerifyOutcome::Broken {
3350                first_broken_seq: 3,
3351                ..
3352            }
3353        ));
3354    }
3355
3356    #[test]
3357    fn multiple_checkpoints_all_consistent() {
3358        let key = fixed_key();
3359        let rows = build_chain(&key, 5);
3360        let cps = vec![
3361            key.sign_checkpoint(2, &rows[1].chain_hash, "2026-04-24T12:00:00Z"),
3362            key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:05:00Z"),
3363            key.sign_checkpoint(5, &rows[4].chain_hash, "2026-04-24T12:10:00Z"),
3364        ];
3365        assert_eq!(
3366            verify_checkpoints(&key.verifying_key_hex(), &rows, &cps),
3367            CheckpointOutcome::Consistent {
3368                checkpoints_checked: 3
3369            }
3370        );
3371    }
3372
3373    #[test]
3374    fn middle_checkpoint_failure_is_reported() {
3375        // Earlier-consistent checkpoints must not mask a later failure.
3376        let key = fixed_key();
3377        let mut rows = build_chain(&key, 5);
3378        let cps = vec![
3379            key.sign_checkpoint(2, &rows[1].chain_hash, "2026-04-24T12:00:00Z"),
3380            key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:05:00Z"),
3381            key.sign_checkpoint(5, &rows[4].chain_hash, "2026-04-24T12:10:00Z"),
3382        ];
3383        rows[2].chain_hash = "0".repeat(HASH_HEX_LEN); // rewrite what cp #2 commits to
3384        assert!(matches!(
3385            verify_checkpoints(&key.verifying_key_hex(), &rows, &cps),
3386            CheckpointOutcome::TipMismatch { seq: 3, .. }
3387        ));
3388    }
3389
3390    #[test]
3391    fn checkpoint_created_at_is_signed() {
3392        // created_at is inside the signed message: backdating invalidates it.
3393        let key = fixed_key();
3394        let rows = build_chain(&key, 3);
3395        let mut cp = key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:00:00Z");
3396        cp.created_at = "2020-01-01T00:00:00Z".to_string();
3397        assert!(matches!(
3398            verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]),
3399            CheckpointOutcome::BadSignature { .. }
3400        ));
3401    }
3402
3403    #[test]
3404    fn checkpoint_seq_is_signed() {
3405        // seq is inside the signed message: moving it invalidates the signature.
3406        let key = fixed_key();
3407        let rows = build_chain(&key, 3);
3408        let mut cp = key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:00:00Z");
3409        cp.seq = 2;
3410        assert!(matches!(
3411            verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]),
3412            CheckpointOutcome::BadSignature { seq: 2 }
3413        ));
3414    }
3415
3416    #[test]
3417    fn checkpoint_detects_full_wipe() {
3418        // The whole chain deleted: the anchored tip cannot be reproduced.
3419        let key = fixed_key();
3420        let full = build_chain(&key, 3);
3421        let cp = key.sign_checkpoint(3, &full[2].chain_hash, "2026-04-24T12:00:00Z");
3422        assert!(matches!(
3423            verify_checkpoints(&key.verifying_key_hex(), &[], &[cp]),
3424            CheckpointOutcome::Truncated {
3425                checkpoint_seq: 3,
3426                current_max_seq: 0
3427            }
3428        ));
3429    }
3430
3431    #[test]
3432    fn domain_tags_are_distinct_and_prefix_free() {
3433        // Security invariant: row and checkpoint signatures can never
3434        // cross-verify because their signed messages start with distinct,
3435        // prefix-free domain tags.
3436        // Checked pairwise over the whole set rather than as a hand-written
3437        // list: adding a fourth tag to a hand-written list silently leaves the
3438        // new tag unchecked against the old ones.
3439        let tags: [(&str, &[u8]); 4] = [
3440            ("row", ROW_DOMAIN),
3441            ("checkpoint", CHECKPOINT_DOMAIN),
3442            ("approval", APPROVAL_DOMAIN),
3443            ("event", EVENT_DOMAIN),
3444        ];
3445        for (i, (name_a, a)) in tags.iter().enumerate() {
3446            for (name_b, b) in tags.iter().skip(i + 1) {
3447                assert_ne!(a, b, "{name_a} and {name_b} share a domain tag");
3448                assert!(!a.starts_with(b), "{name_a} is prefixed by {name_b}");
3449                assert!(!b.starts_with(a), "{name_b} is prefixed by {name_a}");
3450            }
3451        }
3452    }
3453
3454    #[test]
3455    fn approval_receipt_framing_is_injective() {
3456        // The signed receipt message must be injective in
3457        // (transaction_id, request_hash). Without `push_field` escaping, the
3458        // ambiguous pair below would collide because a raw 0x1F separator
3459        // cannot be distinguished from a 0x1F inside a field value.
3460        let key = fixed_key();
3461        let sep = "\u{1f}";
3462        let a = key.approval_receipt(&format!("tx{sep}b"), "c");
3463        let b = key.approval_receipt("tx", &format!("b{sep}c"));
3464        assert_ne!(a, b, "0x1F in a field must not alias distinct receipts");
3465
3466        // Sanity: the derivation is deterministic (Ed25519, same inputs).
3467        assert_eq!(
3468            key.approval_receipt("tx-1", "hash-1"),
3469            key.approval_receipt("tx-1", "hash-1"),
3470        );
3471        // And the commitment is exactly SHA-256 of the receipt.
3472        assert_eq!(
3473            key.approval_commitment("tx-1", "hash-1"),
3474            approval_receipt_digest(&key.approval_receipt("tx-1", "hash-1")),
3475        );
3476    }
3477}