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    /// The transaction or approval-event rows could not be read, so the
1086    /// cross-chain binding check did not run.
1087    NotChecked,
1088    /// A transaction row committed to an event tip that no longer exists —
1089    /// approval events were deleted from the end of the event chain, which the
1090    /// event chain walk alone cannot see.
1091    MissingEvent {
1092        transaction_seq: u64,
1093        event_tip: String,
1094    },
1095}
1096
1097/// Check the cross-chain binding: each `chain_version = 2` transaction row
1098/// signs the event-chain tip as of its insert, so a later deletion of trailing
1099/// approval events leaves a tip that can no longer be found.
1100///
1101/// This is what extends checkpoint anchoring to the event chain for free: the
1102/// checkpoints commit to the transaction tip, the transaction rows commit to
1103/// event tips. Events appended *after* the last transaction row are still
1104/// unanchored until the next row is written — the same bounded tail exposure
1105/// the transaction chain has between checkpoints.
1106pub fn verify_event_binding(tx_rows: &[ChainRow], event_rows: &[EventRow]) -> BindingOutcome {
1107    let known: std::collections::HashSet<&str> = event_rows
1108        .iter()
1109        .map(|row| row.chain_hash.as_str())
1110        .collect();
1111    let mut bindings_checked = 0u64;
1112    for row in tx_rows {
1113        let Some(tip) = row.event_tip.as_deref() else {
1114            continue;
1115        };
1116        if tip.is_empty() {
1117            continue;
1118        }
1119        if !known.contains(tip) {
1120            return BindingOutcome::MissingEvent {
1121                transaction_seq: row.seq,
1122                event_tip: tip.to_string(),
1123            };
1124        }
1125        bindings_checked += 1;
1126    }
1127    BindingOutcome::Consistent { bindings_checked }
1128}
1129
1130/// Everything `sysknife audit verify` checks, in one value.
1131///
1132/// Three independent questions, deliberately not collapsed into one enum:
1133/// is the authorisation record intact, is the approval record intact, and do
1134/// the two still agree. Collapsing them would let a clean transaction chain
1135/// mask a tampered approval trail in the summary line.
1136#[derive(Debug, Clone, PartialEq, Eq)]
1137pub struct AuditVerification {
1138    pub chain: VerifyOutcome,
1139    pub events: VerifyOutcome,
1140    pub binding: BindingOutcome,
1141    /// How many rows can name the account that acted, and why the rest cannot.
1142    ///
1143    /// Reported separately because `Intact` alone would be true and misleading: a
1144    /// host where every connection failed attribution produces a chain that
1145    /// verifies perfectly and answers "who acted" with nobody. The verdict is
1146    /// about tampering; this census is about how much the trail can tell you.
1147    ///
1148    /// `None` when the store could not be read at all, so no census was taken: a
1149    /// missing database, an unopenable one, an absent key. A readable but empty
1150    /// store is `Some`, with every count zero.
1151    ///
1152    /// Deliberately not a census of zero rows for the unreadable case: "nothing
1153    /// is known about attribution" and "the chain holds no rows" are different
1154    /// claims, and a zero that means the first reads as the second, which is the
1155    /// exact confusion this census exists to end.
1156    pub attribution: Option<AttributionCensus>,
1157}
1158
1159/// What one row's principal column can attest, given the encoding that signed it.
1160///
1161/// Four outcomes, because the remedies differ and an audit report that collapses
1162/// them tells the operator to do the wrong thing.
1163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1164enum RowStanding {
1165    /// A `chain_version = 3` row whose signed principal names an account.
1166    NamesAccount,
1167    /// A `chain_version = 3` row signing `none:unattributed`: the daemon tried
1168    /// to attribute the connection and could not.
1169    AttributionFailed,
1170    /// Nothing the signature covers. A v1 or v2 row, whose encoding had no
1171    /// principal field, or a v3 row with a blank column, which also verifies as
1172    /// `Broken` once the walk reaches it.
1173    NotRecorded,
1174    /// Nothing here that a signature vouches for. Three sources: the column is
1175    /// populated on an encoding that does not sign it, or the value is one this
1176    /// binary cannot read back as something the daemon could have written, or the
1177    /// row declares an encoding this build does not know, in which case the
1178    /// principal may be absent or held somewhere this build cannot see.
1179    ///
1180    /// This build never writes any of those, so the first two are evidence of an
1181    /// out-of-band write and the third of a newer daemon. None of them is evidence
1182    /// of who acted.
1183    Unattested,
1184}
1185
1186/// Which encoding, if any, signs the `caller_principal` column, and therefore
1187/// whether the column may be believed.
1188///
1189/// This is the load-bearing check in the census. [`ChainContent::canonical_bytes`]
1190/// pushes `caller_principal` into the signed bytes **only** in the v3 arm, so on a
1191/// v1 or v2 row that column is unsigned free space: anyone with write access to
1192/// the table can set it to `uid:0` and the chain still verifies `Intact`, because
1193/// there is no signature over it to break. Bucketing by the column instead of by
1194/// the encoding would let a plain `UPDATE` manufacture attribution, which is a
1195/// worse failure than the one this census was written to fix. Losing attribution
1196/// is a gap; inventing it is a lie.
1197fn standing(row: &ChainRow) -> RowStanding {
1198    // Empty treated as absent, and nothing trimmed, so this agrees with
1199    // `ChainRow::identity` exactly: it filters on `is_empty` and no more. An
1200    // earlier version trimmed first, which sent a whitespace-only v3 principal
1201    // into "written before the column existed" -- a row that in fact verifies
1202    // Intact and is an anomaly worth investigating. The schema stores `''` as
1203    // well as `NULL`, and `verify_chain` prints those two differently on purpose,
1204    // so both are reachable on real data.
1205    let stored = row.caller_principal.as_deref().filter(|p| !p.is_empty());
1206    match row.chain_version {
1207        CHAIN_VERSION_LEGACY | CHAIN_VERSION_V2 => match stored {
1208            None => RowStanding::NotRecorded,
1209            Some(_) => RowStanding::Unattested,
1210        },
1211        CHAIN_VERSION_V3 => match stored {
1212            None => RowStanding::NotRecorded,
1213            Some(p) => match crate::auth::CallerPrincipal::classify(p) {
1214                crate::auth::PrincipalClaim::Account => RowStanding::NamesAccount,
1215                crate::auth::PrincipalClaim::AttributionFailed => RowStanding::AttributionFailed,
1216                crate::auth::PrincipalClaim::Unrecognized => RowStanding::Unattested,
1217            },
1218        },
1219        // An encoding this binary does not know, which is any value outside 1..=3:
1220        // a newer daemon's, or a corrupt column. `verify_rows` already reports
1221        // `CannotVerify` for such a row, and the census must not claim an account
1222        // either, because this binary cannot say which fields that encoding signs
1223        // -- including whether it signs this column at all.
1224        _ => RowStanding::Unattested,
1225    }
1226}
1227
1228/// Attribution census over every transaction row read.
1229///
1230/// Counted over all rows, not only the ones that verified, so a chain that
1231/// breaks at row 5 still reports what the remaining rows *claim* about who
1232/// acted. Those claims are only as good as the chain verdict beside them: unless
1233/// it is `Intact`, treat every count here as unproven, and note that
1234/// [`Self::rows`] can then exceed the verdict's `rows_checked`. A row past the
1235/// break may be perfectly authentic -- a deleted or reordered row breaks the link
1236/// while leaving every later signature valid -- so the surplus is the part of the
1237/// trail this command cannot vouch for, not proof of forgery. [`Self::rows`]
1238/// exists so a reader can see that gap instead of inferring it.
1239///
1240/// One counter is not enough, because a row can name no account for reasons with
1241/// different remedies. `none:unattributed` says the daemon tried and failed on a
1242/// host that could have attributed the call, which is a configuration problem to
1243/// chase in the daemon log. A v1 or v2 row says the encoding had no principal
1244/// field when the row was signed, which is history and cannot be repaired:
1245/// backfilling it would rewrite the bytes the signature covers. An unattested
1246/// value says something wrote to the column that should not have.
1247///
1248/// Splitting them keeps the report honest on an upgraded database. A single
1249/// "unattributed" count of `0` over a chain of pre-v3 rows reads as "every
1250/// action is attributed" when in fact none of them is.
1251///
1252/// Fields are private and [`Self::of`] is the only constructor that reads rows, so
1253/// a census cannot state totals that contradict the rows it describes.
1254/// `from_counts_for_tests` is the one other way to build one, and it is
1255/// not for production. That is not hypothetical tidiness: in 0.3.0 the MCP report
1256/// built its own all-zero attribution count on the `cannot_verify` path, where a
1257/// real count had already been computed, and the MCP tool and `audit verify
1258/// --json` then published different numbers for one database.
1259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1260pub struct AttributionCensus {
1261    named: u64,
1262    attribution_failed: u64,
1263    not_recorded: u64,
1264    unattested: u64,
1265    rows: u64,
1266}
1267
1268impl AttributionCensus {
1269    /// Count the rows. The only way to obtain a census of real data.
1270    pub fn of(tx_rows: &[ChainRow]) -> Self {
1271        let mut census = Self {
1272            named: 0,
1273            attribution_failed: 0,
1274            not_recorded: 0,
1275            unattested: 0,
1276            rows: tx_rows.len() as u64,
1277        };
1278        for row in tx_rows {
1279            match standing(row) {
1280                RowStanding::NamesAccount => census.named += 1,
1281                RowStanding::AttributionFailed => census.attribution_failed += 1,
1282                RowStanding::NotRecorded => census.not_recorded += 1,
1283                RowStanding::Unattested => census.unattested += 1,
1284            }
1285        }
1286        census
1287    }
1288
1289    /// Rows whose signed principal names an account (`uid:` or `token:`).
1290    ///
1291    /// Names an *account*, which is not a person: see `SECURITY.md` on shared
1292    /// logins, `su`, uid reuse, and on `token:vsock` proving possession of a
1293    /// file.
1294    pub fn named(&self) -> u64 {
1295        self.named
1296    }
1297
1298    /// Rows signing `none:unattributed`, the daemon's admission that it could
1299    /// not name the caller.
1300    pub fn attribution_failed(&self) -> u64 {
1301        self.attribution_failed
1302    }
1303
1304    /// Rows with no principal the signature covers, normally written before the
1305    /// column existed.
1306    pub fn not_recorded(&self) -> u64 {
1307        self.not_recorded
1308    }
1309
1310    /// Rows carrying a principal no signature vouches for. Non-zero means
1311    /// investigate: nothing in SysKnife writes such a value.
1312    pub fn unattested(&self) -> u64 {
1313        self.unattested
1314    }
1315
1316    /// Rows censused.
1317    ///
1318    /// The four row outcomes partition the rows, and [`Self::of`]
1319    /// increments exactly one bucket per row, so this equals their sum. State the
1320    /// partition rather than the arithmetic: a fifth bucket keeps the partition
1321    /// true, and any sum written out by hand somewhere else would not survive it.
1322    pub fn rows(&self) -> u64 {
1323        self.rows
1324    }
1325
1326    /// Rows that name no account, for any reason. What an operator asking "can
1327    /// this trail tell me who acted" has to subtract.
1328    ///
1329    /// Subtraction rather than addition on purpose: a fifth *non-naming* bucket
1330    /// cannot make this number stale, whereas summing the reasons would need
1331    /// editing here too. A future bucket that does name an account would have to
1332    /// be added to `named` instead, which is why `named` is the one counter this
1333    /// subtracts.
1334    pub fn unnamed(&self) -> u64 {
1335        self.rows - self.named
1336    }
1337
1338    /// Build a census from counts, for rendering tests only.
1339    ///
1340    /// Behind the `test-support` feature rather than merely `#[doc(hidden)]`, which
1341    /// hides a function from documentation but not from callers. The CLI renderers
1342    /// live in another crate, where `cfg(test)` does not reach, and making them
1343    /// build signed `ChainRow` fixtures to assert on one line of prose would buy no
1344    /// safety; enabling the feature only as a dev-dependency keeps the door shut
1345    /// for production builds. [`Self::of`] is the constructor that reads rows.
1346    ///
1347    /// Panics if the counts overflow `u64`, rather than wrapping into a census
1348    /// whose `rows` is smaller than its buckets and whose [`Self::unnamed`] would
1349    /// then underflow.
1350    #[cfg(any(test, feature = "test-support"))]
1351    pub fn from_counts_for_tests(
1352        named: u64,
1353        attribution_failed: u64,
1354        not_recorded: u64,
1355        unattested: u64,
1356    ) -> Self {
1357        let rows = named
1358            .checked_add(attribution_failed)
1359            .and_then(|n| n.checked_add(not_recorded))
1360            .and_then(|n| n.checked_add(unattested))
1361            .expect("census counts must not overflow u64");
1362        Self {
1363            named,
1364            attribution_failed,
1365            not_recorded,
1366            unattested,
1367            rows,
1368        }
1369    }
1370}
1371
1372impl AuditVerification {
1373    /// Worst result across all three checks.
1374    ///
1375    /// A detected tamper (`1`) outranks an inability to check (`2`): if the
1376    /// chain is provably broken, reporting "could not verify" because some
1377    /// *other* check was inconclusive would understate what is known.
1378    pub fn exit_code(&self) -> i32 {
1379        let codes = [
1380            outcome_to_exit_code(&self.chain),
1381            outcome_to_exit_code(&self.events),
1382            binding_outcome_to_exit_code(&self.binding),
1383        ];
1384        if codes.contains(&1) {
1385            1
1386        } else if codes.contains(&2) {
1387            2
1388        } else {
1389            0
1390        }
1391    }
1392}
1393
1394/// Run all three checks with the daemon's key.
1395pub fn verify_all(
1396    key: &AuditKey,
1397    tx_rows: &[ChainRow],
1398    event_rows: &[EventRow],
1399) -> AuditVerification {
1400    AuditVerification {
1401        chain: verify_chain(key, tx_rows),
1402        events: verify_event_chain(key, event_rows),
1403        binding: verify_event_binding(tx_rows, event_rows),
1404        attribution: Some(AttributionCensus::of(tx_rows)),
1405    }
1406}
1407
1408/// Run all three checks with only the exported public key (the auditor path).
1409pub fn verify_all_with_pubkey(
1410    verifying_key_hex: &str,
1411    tx_rows: &[ChainRow],
1412    event_rows: &[EventRow],
1413) -> AuditVerification {
1414    AuditVerification {
1415        chain: verify_chain_with_pubkey(verifying_key_hex, tx_rows),
1416        events: verify_event_chain_with_pubkey(verifying_key_hex, event_rows),
1417        binding: verify_event_binding(tx_rows, event_rows),
1418        attribution: Some(AttributionCensus::of(tx_rows)),
1419    }
1420}
1421
1422/// Exit code for the binding check, on the same scale as
1423/// [`outcome_to_exit_code`]: a missing event is a detected tamper (`1`), while
1424/// a check that could not run is inconclusive (`2`).
1425pub fn binding_outcome_to_exit_code(outcome: &BindingOutcome) -> i32 {
1426    match outcome {
1427        BindingOutcome::Consistent { .. } => 0,
1428        BindingOutcome::NotChecked => 2,
1429        BindingOutcome::MissingEvent { .. } => 1,
1430    }
1431}
1432
1433// ── Signed checkpoints (external anchoring / tail-truncation detection) ──────
1434
1435/// A signed commitment to the chain tip at a point in time. Periodically
1436/// emitted and anchored to an independent, append-only sink (a separate
1437/// database, a WORM store, or an RFC 3161 timestamp) so that a later attempt to
1438/// rewrite or **truncate** the local chain is detectable: the anchored
1439/// `(seq, chain_tip)` can no longer be reproduced from the shortened chain.
1440///
1441/// This is the Certificate-Transparency "signed checkpoint" idiom. The
1442/// signature is Ed25519 over the canonical `(seq, chain_tip, created_at)`, so
1443/// an auditor verifies it with only the public key.
1444///
1445/// A `Checkpoint` value carries no validity guarantee on its own: validity is
1446/// established solely by [`verify_checkpoints`] under the public key. A
1447/// checkpoint loaded from a sink is untrusted input until verified.
1448#[derive(Debug, Clone, PartialEq, Eq)]
1449pub struct Checkpoint {
1450    /// `seq` of the chain tip this checkpoint commits to (the last row at
1451    /// emit time).
1452    pub seq: u64,
1453    /// `chain_hash` of the row at `seq` (the committed chain tip).
1454    pub chain_tip: String,
1455    /// RFC 3339 timestamp when the checkpoint was signed.
1456    pub created_at: String,
1457    /// Hex Ed25519 signature over `canonical(seq, chain_tip, created_at)`.
1458    pub signature: String,
1459}
1460
1461/// Canonical message signed into a checkpoint. Reuses the prefix-free field
1462/// framing so the encoding is unambiguous and stable across backends.
1463fn checkpoint_message(seq: u64, chain_tip: &str, created_at: &str) -> Vec<u8> {
1464    // Leading domain tag: separates checkpoint signatures from row signatures
1465    // (see `chain_message`) so the two contexts can never cross-verify.
1466    let mut buf = CHECKPOINT_DOMAIN.to_vec();
1467    push_field(&mut buf, "seq", &seq.to_string());
1468    push_field(&mut buf, "chain_tip", chain_tip);
1469    push_field(&mut buf, "created_at", created_at);
1470    buf
1471}
1472
1473impl AuditKey {
1474    /// Sign a checkpoint committing to `(seq, chain_tip)` at `created_at`.
1475    pub fn sign_checkpoint(&self, seq: u64, chain_tip: &str, created_at: &str) -> Checkpoint {
1476        let sig = self
1477            .signing
1478            .sign(&checkpoint_message(seq, chain_tip, created_at));
1479        Checkpoint {
1480            seq,
1481            chain_tip: chain_tip.to_string(),
1482            created_at: created_at.to_string(),
1483            signature: hex::encode(sig.to_bytes()),
1484        }
1485    }
1486}
1487
1488/// Result of checking anchored checkpoints against the current chain.
1489#[derive(Debug, Clone, PartialEq, Eq)]
1490pub enum CheckpointOutcome {
1491    /// Every checkpoint's signature is valid and its committed tip is still
1492    /// present in the chain at the committed `seq`.
1493    Consistent { checkpoints_checked: u64 },
1494    /// A checkpoint signature failed to verify under the public key.
1495    BadSignature { seq: u64 },
1496    /// A checkpoint commits to a `seq` no longer present in the chain — the
1497    /// chain has been **truncated** below a previously anchored tip.
1498    Truncated {
1499        checkpoint_seq: u64,
1500        current_max_seq: u64,
1501    },
1502    /// A checkpoint's committed `chain_tip` does not match the chain's
1503    /// `chain_hash` at that `seq` — the chain was **rewritten**.
1504    TipMismatch {
1505        seq: u64,
1506        anchored: String,
1507        actual: String,
1508    },
1509    /// Could not verify (e.g. malformed public key).
1510    CannotVerify { reason: String },
1511}
1512
1513/// Verify anchored `checkpoints` against `rows` (the current chain) with the
1514/// hex **public** key. Detects truncation (a checkpoint seq no longer in the
1515/// chain) and rewrite (tip mismatch at a checkpoint seq). `rows` must be in
1516/// seq order. This is the anti-root guarantee: a host attacker who shortens or
1517/// edits the local chain cannot reproduce a previously anchored signed tip.
1518pub fn verify_checkpoints(
1519    verifying_key_hex: &str,
1520    rows: &[ChainRow],
1521    checkpoints: &[Checkpoint],
1522) -> CheckpointOutcome {
1523    let vk = match parse_verifying_key(verifying_key_hex) {
1524        Some(vk) => vk,
1525        None => {
1526            return CheckpointOutcome::CannotVerify {
1527                reason: format!("invalid public key hex ({} chars)", verifying_key_hex.len()),
1528            };
1529        }
1530    };
1531    // `rows` is seq-sorted (ORDER BY seq ASC in the store; chain build order in
1532    // tests), so the tip seq is the last element and we can binary-search below.
1533    let current_max_seq = rows.last().map(|r| r.seq).unwrap_or(0);
1534    let mut checked = 0u64;
1535    for cp in checkpoints {
1536        let msg = checkpoint_message(cp.seq, &cp.chain_tip, &cp.created_at);
1537        if !signature_ok(&vk, &msg, &cp.signature) {
1538            return CheckpointOutcome::BadSignature { seq: cp.seq };
1539        }
1540        match rows.binary_search_by_key(&cp.seq, |r| r.seq) {
1541            Ok(idx) if rows[idx].chain_hash == cp.chain_tip => {}
1542            Ok(idx) => {
1543                return CheckpointOutcome::TipMismatch {
1544                    seq: cp.seq,
1545                    anchored: cp.chain_tip.clone(),
1546                    actual: rows[idx].chain_hash.clone(),
1547                };
1548            }
1549            Err(_) => {
1550                return CheckpointOutcome::Truncated {
1551                    checkpoint_seq: cp.seq,
1552                    current_max_seq,
1553                };
1554            }
1555        }
1556        checked += 1;
1557    }
1558    CheckpointOutcome::Consistent {
1559        checkpoints_checked: checked,
1560    }
1561}
1562
1563/// Process exit code for `sysknife audit checkpoint` verification, mirroring
1564/// [`outcome_to_exit_code`]: `0` consistent, `1` a detected tamper (bad
1565/// signature / truncation / rewrite), `2` cannot-verify (e.g. malformed public
1566/// key). The 1-vs-2 split matters for CI exactly as it does for chain verify.
1567pub fn checkpoint_outcome_to_exit_code(outcome: &CheckpointOutcome) -> i32 {
1568    match outcome {
1569        CheckpointOutcome::Consistent { .. } => 0,
1570        CheckpointOutcome::BadSignature { .. }
1571        | CheckpointOutcome::Truncated { .. }
1572        | CheckpointOutcome::TipMismatch { .. } => 1,
1573        CheckpointOutcome::CannotVerify { .. } => 2,
1574    }
1575}
1576
1577#[cfg(test)]
1578mod tests {
1579    use super::*;
1580
1581    fn fixed_key() -> AuditKey {
1582        AuditKey::from_bytes(vec![0x42; 32])
1583    }
1584
1585    fn sample_content<'a>(seq: u64, txid: &'a str) -> ChainContent<'a> {
1586        ChainContent {
1587            seq,
1588            key_id: CURRENT_KEY_ID,
1589            transaction_id: txid,
1590            request_id: "req-1",
1591            request_hash: "hash-abc",
1592            action_name: "UpdateSystem",
1593            risk_level: RiskLevel::High,
1594            summary: "Upgrade",
1595            approval_id: None,
1596            warnings_json: "[]",
1597            created_at: "2026-04-24T12:00:00Z",
1598            identity: ChainIdentity::V2 {
1599                caller_role: "Dev",
1600                event_tip: "",
1601            },
1602        }
1603    }
1604
1605    // ── chain_hash determinism + linkage ──────────────────────────────────
1606
1607    #[test]
1608    fn same_inputs_yield_same_hash() {
1609        let key = fixed_key();
1610        let h1 = key.chain_hash(&sample_content(1, "txa"), "");
1611        let h2 = key.chain_hash(&sample_content(1, "txa"), "");
1612        assert_eq!(h1, h2);
1613        assert_eq!(h1.len(), HASH_HEX_LEN);
1614    }
1615
1616    #[test]
1617    fn different_seq_yields_different_hash() {
1618        let key = fixed_key();
1619        let h1 = key.chain_hash(&sample_content(1, "txa"), "");
1620        let h2 = key.chain_hash(&sample_content(2, "txa"), "");
1621        assert_ne!(h1, h2);
1622    }
1623
1624    #[test]
1625    fn different_prev_hash_yields_different_hash() {
1626        let key = fixed_key();
1627        let h1 = key.chain_hash(&sample_content(1, "txa"), "");
1628        let h2 = key.chain_hash(&sample_content(1, "txa"), "deadbeef");
1629        assert_ne!(h1, h2);
1630    }
1631
1632    #[test]
1633    fn different_keys_yield_different_hashes() {
1634        let key1 = AuditKey::from_bytes(vec![0x01; 32]);
1635        let key2 = AuditKey::from_bytes(vec![0x02; 32]);
1636        let h1 = key1.chain_hash(&sample_content(1, "txa"), "");
1637        let h2 = key2.chain_hash(&sample_content(1, "txa"), "");
1638        assert_ne!(h1, h2);
1639    }
1640
1641    // ── canonical encoding stability ──────────────────────────────────────
1642
1643    #[test]
1644    fn canonical_bytes_have_stable_field_order() {
1645        let c = sample_content(1, "txa");
1646        let bytes = c.canonical_bytes();
1647        let s = String::from_utf8_lossy(&bytes);
1648        // Tags must appear in a fixed order.
1649        let order = [
1650            "seq",
1651            "key_id",
1652            "transaction_id",
1653            "request_id",
1654            "request_hash",
1655            "action_name",
1656            "risk_level",
1657            "summary",
1658            "approval_id",
1659            "warnings_json",
1660            "created_at",
1661        ];
1662        let mut last_idx = 0;
1663        for tag in order {
1664            let idx = s.find(tag).unwrap_or_else(|| panic!("missing {tag}"));
1665            assert!(idx >= last_idx, "{tag} out of order");
1666            last_idx = idx;
1667        }
1668    }
1669
1670    #[test]
1671    fn nul_bytes_in_field_value_are_escaped() {
1672        let mut c = sample_content(1, "txa");
1673        let summary = "before\0after";
1674        c.summary = summary;
1675        let bytes = c.canonical_bytes();
1676        // Raw NUL must NOT appear; escape sequence must.
1677        assert!(!bytes.contains(&0x00));
1678        assert!(String::from_utf8_lossy(&bytes).contains("before\\0after"));
1679    }
1680
1681    /// Backslash-NUL collision regression: an attacker who could craft a
1682    /// row with `summary = "before\\0after"` (literal backslash + zero) must
1683    /// NOT produce the same canonical bytes as one with raw `\x00`. Without
1684    /// the `\\` → `\\\\` escape, the two collide and the attacker can
1685    /// substitute one for the other while the chain hash matches.
1686    #[test]
1687    fn literal_backslash_zero_does_not_collide_with_raw_nul_escape() {
1688        let mut a = sample_content(1, "txa");
1689        a.summary = "before\\0after"; // literal backslash + '0'
1690        let mut b = sample_content(1, "txa");
1691        b.summary = "before\0after"; // raw NUL
1692        assert_ne!(
1693            a.canonical_bytes(),
1694            b.canonical_bytes(),
1695            "backslash escape must run before NUL escape to prevent collision"
1696        );
1697    }
1698
1699    fn key_for_collision_test() -> AuditKey {
1700        AuditKey::from_bytes(vec![0xab; 32])
1701    }
1702
1703    #[test]
1704    fn literal_backslash_zero_chain_hash_differs_from_raw_nul() {
1705        let key = key_for_collision_test();
1706        let mut a = sample_content(1, "txa");
1707        a.summary = "before\\0after";
1708        let mut b = sample_content(1, "txa");
1709        b.summary = "before\0after";
1710        assert_ne!(
1711            key.chain_hash(&a, ""),
1712            key.chain_hash(&b, ""),
1713            "chain signature must distinguish escape from raw byte"
1714        );
1715    }
1716
1717    // ── verify_chain ──────────────────────────────────────────────────────
1718
1719    /// Materialise the stored row that `content` would produce, so a test
1720    /// never hand-copies field-by-field and accidentally signs one thing while
1721    /// storing another.
1722    fn row_for(content: &ChainContent<'_>, prev: &str, chain_hash: String) -> ChainRow {
1723        let (chain_version, caller_role, event_tip, caller_principal) = match content.identity {
1724            ChainIdentity::LegacyV1 => (CHAIN_VERSION_LEGACY, None, None, None),
1725            ChainIdentity::V2 {
1726                caller_role,
1727                event_tip,
1728            } => (
1729                CHAIN_VERSION_V2,
1730                Some(caller_role.to_string()),
1731                Some(event_tip.to_string()),
1732                None,
1733            ),
1734            ChainIdentity::V3 {
1735                caller_role,
1736                event_tip,
1737                caller_principal,
1738            } => (
1739                CHAIN_VERSION_V3,
1740                Some(caller_role.to_string()),
1741                Some(event_tip.to_string()),
1742                Some(caller_principal.to_string()),
1743            ),
1744        };
1745        ChainRow {
1746            seq: content.seq,
1747            key_id: content.key_id.to_string(),
1748            transaction_id: content.transaction_id.to_string(),
1749            request_id: content.request_id.to_string(),
1750            request_hash: content.request_hash.to_string(),
1751            action_name: content.action_name.to_string(),
1752            risk_level: content.risk_level,
1753            summary: content.summary.to_string(),
1754            approval_id: content.approval_id.map(str::to_string),
1755            warnings_json: content.warnings_json.to_string(),
1756            created_at: content.created_at.to_string(),
1757            prev_chain_hash: prev.to_string(),
1758            chain_hash,
1759            chain_version,
1760            caller_role,
1761            event_tip,
1762            caller_principal,
1763        }
1764    }
1765
1766    fn build_chain(key: &AuditKey, count: usize) -> Vec<ChainRow> {
1767        let mut rows = Vec::with_capacity(count);
1768        let mut prev = String::new();
1769        for i in 0..count {
1770            let seq = (i + 1) as u64;
1771            let txid = format!("tx{i}");
1772            let content = sample_content(seq, &txid);
1773            let hash = key.chain_hash(&content, &prev);
1774            rows.push(row_for(&content, &prev, hash.clone()));
1775            prev = hash;
1776        }
1777        rows
1778    }
1779
1780    // ── caller identity in the signed content ─────────────────────────────
1781
1782    #[test]
1783    fn caller_role_is_covered_by_the_row_signature() {
1784        // The whole point of the v2 encoding: two rows identical except for
1785        // who asked must not share a signature, or the chain cannot answer
1786        // "which role requested this".
1787        let key = fixed_key();
1788        let mut dev = sample_content(1, "txa");
1789        dev.identity = ChainIdentity::V2 {
1790            caller_role: "Dev",
1791            event_tip: "",
1792        };
1793        let mut boot = sample_content(1, "txa");
1794        boot.identity = ChainIdentity::V2 {
1795            caller_role: "Boot",
1796            event_tip: "",
1797        };
1798        assert_ne!(key.chain_hash(&dev, ""), key.chain_hash(&boot, ""));
1799    }
1800
1801    #[test]
1802    fn event_tip_is_covered_by_the_row_signature() {
1803        let key = fixed_key();
1804        let mut empty = sample_content(1, "txa");
1805        empty.identity = ChainIdentity::V2 {
1806            caller_role: "Dev",
1807            event_tip: "",
1808        };
1809        let mut bound = sample_content(1, "txa");
1810        bound.identity = ChainIdentity::V2 {
1811            caller_role: "Dev",
1812            event_tip: "abc123",
1813        };
1814        assert_ne!(key.chain_hash(&empty, ""), key.chain_hash(&bound, ""));
1815    }
1816
1817    #[test]
1818    fn a_legacy_row_written_before_the_migration_still_verifies() {
1819        // The migration contract. A chain written by v0.2.12 or earlier has no
1820        // caller_role column; re-encoding those rows with an empty identity
1821        // would report every historical row as Broken, i.e. an upgrade would
1822        // look exactly like a compromise.
1823        let key = fixed_key();
1824        let mut content = sample_content(1, "tx-legacy");
1825        content.identity = ChainIdentity::LegacyV1;
1826        let hash = key.chain_hash(&content, "");
1827        let row = row_for(&content, "", hash);
1828        assert_eq!(row.chain_version, CHAIN_VERSION_LEGACY);
1829        assert_eq!(row.caller_role, None);
1830        assert_eq!(
1831            verify_chain(&key, &[row]),
1832            VerifyOutcome::Intact { rows_checked: 1 }
1833        );
1834    }
1835
1836    // ── v3: the row names the account, not just the role ──────────────────
1837
1838    /// The point of the encoding: two callers who share a role must produce
1839    /// distinguishable signed records. If the principal were unsigned, or merely
1840    /// stored, this would pass while proving nothing.
1841    #[test]
1842    fn two_admins_are_distinguishable_in_the_signed_record() {
1843        let key = fixed_key();
1844        let mut alice = sample_content(1, "tx-alice");
1845        alice.identity = ChainIdentity::V3 {
1846            caller_role: "admin",
1847            event_tip: "",
1848            caller_principal: "uid:1000",
1849        };
1850        let mut bob = sample_content(1, "tx-alice");
1851        bob.identity = ChainIdentity::V3 {
1852            caller_role: "admin",
1853            event_tip: "",
1854            caller_principal: "uid:1001",
1855        };
1856
1857        assert_ne!(
1858            key.chain_hash(&alice, ""),
1859            key.chain_hash(&bob, ""),
1860            "identical rows differing only in principal must sign differently, \
1861             otherwise the chain still cannot answer which account acted"
1862        );
1863    }
1864
1865    /// Rewriting the stored principal must break verification. A field that can
1866    /// be edited after the fact records nothing an auditor can rely on.
1867    #[test]
1868    fn editing_the_stored_principal_breaks_the_row() {
1869        let key = fixed_key();
1870        let mut content = sample_content(1, "tx1");
1871        content.identity = ChainIdentity::V3 {
1872            caller_role: "admin",
1873            event_tip: "",
1874            caller_principal: "uid:1000",
1875        };
1876        let hash = key.chain_hash(&content, "");
1877        let mut row = row_for(&content, "", hash);
1878        row.caller_principal = Some("uid:0".to_string());
1879
1880        assert!(
1881            matches!(verify_chain(&key, &[row]), VerifyOutcome::Broken { .. }),
1882            "a principal swapped to root must not verify"
1883        );
1884    }
1885
1886    /// Downgrade is the other direction of the same attack: strip the principal
1887    /// and claim the row was written under v2, hiding which account acted. The
1888    /// v3 message signed a different byte string, so it cannot verify as v2.
1889    #[test]
1890    fn downgrading_a_v3_row_to_v2_to_hide_the_account_breaks_it() {
1891        let key = fixed_key();
1892        let mut content = sample_content(1, "tx1");
1893        content.identity = ChainIdentity::V3 {
1894            caller_role: "admin",
1895            event_tip: "",
1896            caller_principal: "uid:1000",
1897        };
1898        let hash = key.chain_hash(&content, "");
1899        let mut row = row_for(&content, "", hash);
1900        row.chain_version = CHAIN_VERSION_V2;
1901        row.caller_principal = None;
1902
1903        assert!(
1904            matches!(verify_chain(&key, &[row]), VerifyOutcome::Broken { .. }),
1905            "a v3 row relabelled as v2 must not verify"
1906        );
1907    }
1908
1909    /// A v3 row with no principal is self-contradictory, and so is one whose
1910    /// principal is blank: both claim an encoding that names an account while
1911    /// naming none. Treated as a break, not as "cannot verify", because the row
1912    /// contradicts itself rather than being written by a newer binary.
1913    #[test]
1914    fn a_v3_row_without_a_usable_principal_is_broken() {
1915        let key = fixed_key();
1916        let mut content = sample_content(1, "tx1");
1917        content.identity = ChainIdentity::V3 {
1918            caller_role: "admin",
1919            event_tip: "",
1920            caller_principal: "uid:1000",
1921        };
1922        let hash = key.chain_hash(&content, "");
1923
1924        for absent in [None, Some(String::new())] {
1925            let mut row = row_for(&content, "", hash.clone());
1926            row.caller_principal = absent.clone();
1927            assert!(
1928                matches!(verify_chain(&key, &[row]), VerifyOutcome::Broken { .. }),
1929                "a v3 row with principal {absent:?} must be reported as broken"
1930            );
1931        }
1932    }
1933
1934    /// A row *signed with* a blank principal must be rejected, and this is the
1935    /// only test that can prove the guard exists.
1936    ///
1937    /// The sibling test that blanks a stored principal proves something weaker:
1938    /// that row was signed with `uid:1000`, so it fails on signature mismatch
1939    /// whether or not `identity()` filters empties. Here the signature is
1940    /// perfectly valid for the blank principal, so the row verifies unless the
1941    /// filter refuses it. Without the guard a daemon could sign rows that name
1942    /// nobody and every one of them would report as intact.
1943    #[test]
1944    fn a_row_signed_with_a_blank_principal_is_rejected_even_though_it_signs() {
1945        let key = fixed_key();
1946        let mut content = sample_content(1, "tx-blank");
1947        content.identity = ChainIdentity::V3 {
1948            caller_role: "admin",
1949            event_tip: "",
1950            caller_principal: "",
1951        };
1952        let hash = key.chain_hash(&content, "");
1953        // Derived from the very content that was signed, so every other field
1954        // matches by construction. Building it by hand is how the first version
1955        // of this test came to pass for the wrong reason: a mismatched seq made
1956        // the row fail on signature, guard or no guard.
1957        let row = row_for(&content, "", hash);
1958        assert_eq!(
1959            row.caller_principal.as_deref(),
1960            Some(""),
1961            "fixture must store the blank principal it signed"
1962        );
1963        assert_eq!(row.chain_version, CHAIN_VERSION_V3);
1964        assert!(
1965            matches!(verify_chain(&key, &[row]), VerifyOutcome::Broken { .. }),
1966            "a v3 row naming nobody must be broken, not accepted"
1967        );
1968    }
1969
1970    /// An attribution failure is a legitimate, verifiable identity: the daemon
1971    /// admits it could not name the caller, signs that admission, and the chain
1972    /// stays intact. If this ever reports Broken, every honest row on a host
1973    /// where `SO_PEERCRED` fails becomes a false tamper report.
1974    #[test]
1975    fn a_row_recording_an_attribution_failure_verifies() {
1976        let key = fixed_key();
1977        let principal = crate::auth::CallerPrincipal::Unattributed.as_signed_str();
1978        let mut content = sample_content(1, "tx-unattributed");
1979        content.identity = ChainIdentity::V3 {
1980            caller_role: "observer",
1981            event_tip: "",
1982            caller_principal: &principal,
1983        };
1984        let hash = key.chain_hash(&content, "");
1985        let row = row_for(&content, "", hash);
1986
1987        assert_eq!(
1988            verify_chain(&key, &[row]),
1989            VerifyOutcome::Intact { rows_checked: 1 }
1990        );
1991    }
1992
1993    /// The realistic database after two upgrades: legacy rows, v2 rows, then v3
1994    /// rows, all in one chain. Every generation has to keep verifying, which is
1995    /// the whole reason the encoding is selected per row.
1996    #[test]
1997    fn a_chain_spanning_all_three_encodings_verifies() {
1998        let key = fixed_key();
1999        let mut rows = Vec::new();
2000        let mut prev = String::new();
2001        for (i, identity) in [
2002            ChainIdentity::LegacyV1,
2003            ChainIdentity::V2 {
2004                caller_role: "dev",
2005                event_tip: "",
2006            },
2007            ChainIdentity::V3 {
2008                caller_role: "admin",
2009                event_tip: "",
2010                caller_principal: "uid:1000",
2011            },
2012            ChainIdentity::V3 {
2013                caller_role: "admin",
2014                event_tip: "",
2015                caller_principal: "token:vsock",
2016            },
2017        ]
2018        .into_iter()
2019        .enumerate()
2020        {
2021            let txid = format!("tx{i}");
2022            let mut content = sample_content((i + 1) as u64, &txid);
2023            content.identity = identity;
2024            let hash = key.chain_hash(&content, &prev);
2025            rows.push(row_for(&content, &prev, hash.clone()));
2026            prev = hash;
2027        }
2028
2029        assert_eq!(
2030            verify_chain(&key, &rows),
2031            VerifyOutcome::Intact { rows_checked: 4 }
2032        );
2033    }
2034
2035    /// Build a chain from a list of identities, signing each row properly, so no
2036    /// test signs one thing and stores another.
2037    fn chain_of(key: &AuditKey, identities: Vec<ChainIdentity<'_>>) -> Vec<ChainRow> {
2038        let mut rows = Vec::new();
2039        let mut prev = String::new();
2040        for (i, identity) in identities.into_iter().enumerate() {
2041            let txid = format!("tx{i}");
2042            let mut content = sample_content((i + 1) as u64, &txid);
2043            content.identity = identity;
2044            let hash = key.chain_hash(&content, &prev);
2045            rows.push(row_for(&content, &prev, hash.clone()));
2046            prev = hash;
2047        }
2048        rows
2049    }
2050
2051    /// The census has to distinguish *why* a row names no account, because the
2052    /// reasons have different remedies: a `none:unattributed` row means
2053    /// `SO_PEERCRED` failed on a host that could have attributed it, while a v1
2054    /// or v2 row means the encoding had no principal field at the time it was
2055    /// signed. Reporting only the first understates an upgraded database.
2056    ///
2057    /// Every bucket gets a distinct count, so no permutation of the four can
2058    /// satisfy this assertion. The first version used 2/1/2 and still passed with
2059    /// the `named` and `not_recorded` arms swapped.
2060    #[test]
2061    fn the_census_separates_attribution_failures_from_encodings_without_the_field() {
2062        let key = fixed_key();
2063        let unattributed = crate::auth::CallerPrincipal::Unattributed.as_signed_str();
2064        let rows = chain_of(
2065            &key,
2066            vec![
2067                ChainIdentity::LegacyV1,
2068                ChainIdentity::V2 {
2069                    caller_role: "dev",
2070                    event_tip: "",
2071                },
2072                ChainIdentity::V3 {
2073                    caller_role: "admin",
2074                    event_tip: "",
2075                    caller_principal: "uid:1000",
2076                },
2077                ChainIdentity::V3 {
2078                    caller_role: "admin",
2079                    event_tip: "",
2080                    caller_principal: "uid:1001",
2081                },
2082                ChainIdentity::V3 {
2083                    caller_role: "admin",
2084                    event_tip: "",
2085                    caller_principal: "token:vsock",
2086                },
2087                ChainIdentity::V3 {
2088                    caller_role: "observer",
2089                    event_tip: "",
2090                    caller_principal: &unattributed,
2091                },
2092            ],
2093        );
2094
2095        let verification = verify_all(&key, &rows, &[]);
2096        assert_eq!(
2097            verification.chain,
2098            VerifyOutcome::Intact { rows_checked: 6 },
2099            "every encoding must keep verifying; the census is not a verdict"
2100        );
2101        let census = verification
2102            .attribution
2103            .expect("rows were read, so a census was taken");
2104        assert_eq!(census.named(), 3);
2105        assert_eq!(census.attribution_failed(), 1);
2106        assert_eq!(census.not_recorded(), 2);
2107        assert_eq!(census.unattested(), 0);
2108        assert_eq!(census.rows(), 6);
2109        assert_eq!(
2110            census.unnamed(),
2111            3,
2112            "three of the six rows cannot name an account, by either reason"
2113        );
2114    }
2115
2116    /// The forgery this census must not enable.
2117    ///
2118    /// `ChainContent::canonical_bytes` signs `caller_principal` only in the v3
2119    /// arm, so on a v1 or v2 row the column is unsigned free space. Anyone with write access
2120    /// to the table can set it, and no signature breaks. If the census bucketed
2121    /// by the column rather than by the encoding, a single `UPDATE` would turn
2122    /// "none of these rows names an account" into "every row names root", with an
2123    /// `Intact` verdict beside it. Losing attribution is a gap; inventing it is a
2124    /// lie, and this is the test that keeps the lie unavailable.
2125    #[test]
2126    fn a_principal_written_into_an_encoding_that_does_not_sign_it_is_never_an_account() {
2127        let key = fixed_key();
2128        let mut rows = chain_of(
2129            &key,
2130            vec![
2131                ChainIdentity::LegacyV1,
2132                ChainIdentity::V2 {
2133                    caller_role: "dev",
2134                    event_tip: "",
2135                },
2136            ],
2137        );
2138        // The out-of-band write. Not signed by either encoding, so the chain is
2139        // expected to stay Intact: the signature cannot see this.
2140        rows[0].caller_principal = Some("uid:0".to_string());
2141        rows[1].caller_principal = Some("uid:0".to_string());
2142
2143        let verification = verify_all(&key, &rows, &[]);
2144        assert_eq!(
2145            verification.chain,
2146            VerifyOutcome::Intact { rows_checked: 2 },
2147            "no signature covers that column on v1/v2, so tampering with it is \
2148             invisible to verification -- which is exactly why the census must \
2149             not believe it"
2150        );
2151        let census = verification.attribution.expect("rows were read");
2152        assert_eq!(
2153            census.named(),
2154            0,
2155            "an unsigned column must never be credited as an account"
2156        );
2157        assert_eq!(
2158            census.unattested(),
2159            2,
2160            "and it must be reported as unattested, because nothing in SysKnife \
2161             writes that column on those encodings"
2162        );
2163        assert_eq!(census.unnamed(), 2);
2164    }
2165
2166    /// A principal column that is present but empty must not be tallied as an
2167    /// account. The schema allows `''` as well as `NULL`, and `identity()`
2168    /// already reads the two the same way, so the census has to agree with it.
2169    #[test]
2170    fn a_blank_principal_column_is_counted_as_naming_nobody() {
2171        let key = fixed_key();
2172        let mut content = sample_content(1, "tx-blank-census");
2173        content.identity = ChainIdentity::V3 {
2174            caller_role: "admin",
2175            event_tip: "",
2176            caller_principal: "",
2177        };
2178        let hash = key.chain_hash(&content, "");
2179        let row = row_for(&content, "", hash);
2180        assert_eq!(row.caller_principal.as_deref(), Some(""));
2181
2182        let verification = verify_all(&key, &[row], &[]);
2183        let census = verification.attribution.expect("a row was read");
2184        assert_eq!(census.named(), 0);
2185        assert_eq!(census.not_recorded(), 1);
2186        assert_eq!(census.rows(), 1);
2187        assert!(
2188            matches!(verification.chain, VerifyOutcome::Broken { .. }),
2189            "and the row is still reported as broken once the walk reaches it, \
2190             so census and verdict agree"
2191        );
2192    }
2193
2194    /// Values that look like a principal but name nobody. None of these can be
2195    /// written by the daemon (`CallerPrincipal::as_signed_str` always renders
2196    /// `scheme:value` with a non-empty value), so each one is evidence of an
2197    /// out-of-band write. Counting them as accounts would be this commit's own
2198    /// defect one level down: `none:overflow` in particular is a plausible future
2199    /// spelling of a *failure*, and crediting it as an account would invert its
2200    /// meaning.
2201    #[test]
2202    fn a_principal_this_binary_cannot_read_is_counted_as_unattested_not_as_an_account() {
2203        let key = fixed_key();
2204        for forged in [
2205            "garbage",
2206            "uid:",
2207            "none:overflow",
2208            // Whitespace is signed content like any other, so this row verifies
2209            // Intact. It still names nobody, and it belongs in the bucket that
2210            // asks for an investigation rather than the one that explains
2211            // pre-0.3.0 history: nothing in SysKnife writes it.
2212            "  ",
2213            "UID:1000",
2214            // A known scheme with a value the daemon could not have rendered.
2215            "uid:notanumber",
2216            "uid:1000:extra",
2217            "token:not-vsock",
2218        ] {
2219            let mut content = sample_content(1, "tx-forged");
2220            content.identity = ChainIdentity::V3 {
2221                caller_role: "admin",
2222                event_tip: "",
2223                caller_principal: forged,
2224            };
2225            let hash = key.chain_hash(&content, "");
2226            let row = row_for(&content, "", hash);
2227            let census = verify_all(&key, &[row], &[])
2228                .attribution
2229                .expect("a row was read");
2230            assert_eq!(
2231                census.named(),
2232                0,
2233                "{forged:?} names no account and must not be counted as one"
2234            );
2235            assert_eq!(
2236                census.unnamed(),
2237                1,
2238                "{forged:?} must be counted among the rows naming nobody"
2239            );
2240            assert_eq!(
2241                census.unattested(),
2242                1,
2243                "{forged:?} is signed content the daemon never writes, so it is a \
2244                 finding to investigate, not history to explain away"
2245            );
2246            assert_eq!(
2247                census.not_recorded(),
2248                0,
2249                "{forged:?} is present, so it must not be reported as a row that \
2250                 predates the column"
2251            );
2252        }
2253    }
2254
2255    /// The case that made the single counter misleading: a database written
2256    /// entirely before the principal column existed reports zero attribution
2257    /// failures, which reads as "everything is attributed". Every row in it names
2258    /// nobody, so `unnamed` must account for all of them.
2259    #[test]
2260    fn a_chain_predating_the_principal_field_reports_no_row_as_attributed() {
2261        let key = fixed_key();
2262        let rows = chain_of(
2263            &key,
2264            vec![
2265                ChainIdentity::LegacyV1,
2266                ChainIdentity::V2 {
2267                    caller_role: "dev",
2268                    event_tip: "",
2269                },
2270            ],
2271        );
2272
2273        let verification = verify_all(&key, &rows, &[]);
2274        assert_eq!(
2275            verification.chain,
2276            VerifyOutcome::Intact { rows_checked: 2 },
2277            "legacy rows must keep verifying; the census is not a verdict"
2278        );
2279        let census = verification.attribution.expect("rows were read");
2280        assert_eq!(census.attribution_failed(), 0);
2281        assert_eq!(census.named(), 0);
2282        assert_eq!(census.not_recorded(), 2);
2283        assert_eq!(census.unnamed(), 2);
2284    }
2285
2286    /// The census spans every row read, while verification stops at the first
2287    /// break. That is deliberate, and it is also the reason the counts are claims
2288    /// rather than findings: on a broken chain the rows after the break were
2289    /// written by whoever broke it. `rows()` is what lets a reader see the gap
2290    /// between what was counted and what was checked.
2291    #[test]
2292    fn a_broken_chain_censuses_more_rows_than_it_verified() {
2293        let key = fixed_key();
2294        let mut rows = chain_of(
2295            &key,
2296            vec![
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                ChainIdentity::V3 {
2308                    caller_role: "admin",
2309                    event_tip: "",
2310                    caller_principal: "uid:1000",
2311                },
2312            ],
2313        );
2314        rows[1].summary = "tampered".to_string();
2315
2316        let verification = verify_all(&key, &rows, &[]);
2317        let rows_checked = match verification.chain {
2318            VerifyOutcome::Broken { rows_checked, .. } => rows_checked,
2319            ref other => panic!("expected a detected tamper, got {other:?}"),
2320        };
2321        let census = verification.attribution.expect("rows were read");
2322        assert_eq!(rows_checked, 1, "the walk stops at the first broken row");
2323        assert_eq!(
2324            census.rows(),
2325            3,
2326            "while the census still describes every row read"
2327        );
2328        assert!(
2329            census.rows() > rows_checked,
2330            "the report must be able to show that more was counted than checked"
2331        );
2332    }
2333
2334    /// The auditor path takes the same census as the keyholder path. It is the
2335    /// one an external reviewer runs, so a census wired only into `verify_all`
2336    /// would leave exactly that audience with nothing.
2337    #[test]
2338    fn the_pubkey_only_path_takes_the_same_census() {
2339        let key = fixed_key();
2340        let unattributed = crate::auth::CallerPrincipal::Unattributed.as_signed_str();
2341        let rows = chain_of(
2342            &key,
2343            vec![
2344                ChainIdentity::V3 {
2345                    caller_role: "admin",
2346                    event_tip: "",
2347                    caller_principal: "uid:1000",
2348                },
2349                ChainIdentity::V3 {
2350                    caller_role: "observer",
2351                    event_tip: "",
2352                    caller_principal: &unattributed,
2353                },
2354            ],
2355        );
2356
2357        let with_key = verify_all(&key, &rows, &[]).attribution;
2358        let with_pubkey = verify_all_with_pubkey(&key.verifying_key_hex(), &rows, &[]).attribution;
2359        assert_eq!(
2360            with_key, with_pubkey,
2361            "the auditor must see the same attribution numbers as the keyholder"
2362        );
2363        let census = with_pubkey.expect("rows were read");
2364        assert_eq!(census.named(), 1);
2365        assert_eq!(census.attribution_failed(), 1);
2366    }
2367
2368    /// Attribution must not move the exit code. `Intact` is a statement about
2369    /// tampering, and `SECURITY.md` leans on that separation: a host where every
2370    /// connection failed attribution still has an untampered chain, and turning
2371    /// that into a non-zero exit would train operators to ignore the real signal.
2372    #[test]
2373    fn a_chain_that_names_nobody_still_exits_zero() {
2374        let key = fixed_key();
2375        let unattributed = crate::auth::CallerPrincipal::Unattributed.as_signed_str();
2376        let rows = chain_of(
2377            &key,
2378            vec![
2379                ChainIdentity::LegacyV1,
2380                ChainIdentity::V3 {
2381                    caller_role: "observer",
2382                    event_tip: "",
2383                    caller_principal: &unattributed,
2384                },
2385            ],
2386        );
2387
2388        let verification = verify_all(&key, &rows, &[]);
2389        let census = verification.attribution.expect("rows were read");
2390        assert_eq!(census.unnamed(), 2, "not one row names an account");
2391        assert_eq!(
2392            verification.exit_code(),
2393            0,
2394            "yet nothing was tampered with, so the command must succeed"
2395        );
2396    }
2397
2398    /// A row from a future encoding is "cannot verify", never "broken": an older
2399    /// binary reading a newer chain has found no tampering, only work it cannot
2400    /// reproduce. The message must say the supported range so the operator knows
2401    /// the fix is a newer build.
2402    #[test]
2403    fn a_future_encoding_reports_cannot_verify_with_the_supported_range() {
2404        let key = fixed_key();
2405        let content = sample_content(1, "tx1");
2406        let hash = key.chain_hash(&content, "");
2407        let mut row = row_for(&content, "", hash);
2408        row.chain_version = CHAIN_VERSION_CURRENT + 1;
2409
2410        match verify_chain(&key, &[row]) {
2411            VerifyOutcome::CannotVerify { reason } => {
2412                assert!(
2413                    reason.contains(&format!("chain_version={}", CHAIN_VERSION_CURRENT + 1)),
2414                    "name the version found, got: {reason}"
2415                );
2416                assert!(
2417                    reason.contains(&CHAIN_VERSION_CURRENT.to_string()),
2418                    "and the newest version understood, got: {reason}"
2419                );
2420            }
2421            other => panic!("a future encoding must not be reported as tampering: {other:?}"),
2422        }
2423    }
2424
2425    /// A row encoded exactly as the v0.2.16 binary would have encoded it: the
2426    /// content is synthetic, the hash is what that release's v2 encoder produced
2427    /// over it. No in-memory test can prove this property, because every other
2428    /// test in this module signs and verifies inside one process, so both halves
2429    /// move together whenever a constant changes.
2430    ///
2431    /// Concretely, this catches the aliasing hazard the `ChainIdentity` docs warn
2432    /// about: `identity()` dispatches stored `chain_version` values against
2433    /// `CHAIN_VERSION_CURRENT`, and the v2 encoder used to *sign* that same
2434    /// constant. Bump it for a new encoding and both the dispatch and the message
2435    /// shift, so every v2 row on disk stops verifying while the whole unit suite
2436    /// stays green. Only a golden vector notices.
2437    #[test]
2438    fn a_row_written_by_the_previous_release_still_verifies() {
2439        const GOLDEN_V2_CHAIN_HASH: &str = "ba12cbe49a149387898bc30f1e8d409effa025ab8e440e6e72bedf060afc831e45d9be264d6b18b7e0ef2f2b3584dbc6953b535546cecbbdc3d7ac666cae4d0a";
2440
2441        let key = fixed_key();
2442        let row = ChainRow {
2443            seq: 7,
2444            key_id: CURRENT_KEY_ID.to_string(),
2445            transaction_id: "tx-golden".to_string(),
2446            request_id: "req-golden".to_string(),
2447            request_hash: "hash-golden".to_string(),
2448            action_name: "AptInstall".to_string(),
2449            risk_level: RiskLevel::Medium,
2450            summary: "install ripgrep".to_string(),
2451            approval_id: Some("appr-golden".to_string()),
2452            warnings_json: "[]".to_string(),
2453            created_at: "2026-07-29T00:00:00Z".to_string(),
2454            prev_chain_hash: String::new(),
2455            chain_hash: GOLDEN_V2_CHAIN_HASH.to_string(),
2456            chain_version: 2,
2457            caller_role: Some("admin".to_string()),
2458            event_tip: Some("eventtip-golden".to_string()),
2459            caller_principal: None,
2460        };
2461
2462        assert_eq!(
2463            verify_chain(&key, std::slice::from_ref(&row)),
2464            VerifyOutcome::Intact { rows_checked: 1 },
2465            "a v2 row on disk must verify under this binary; if this fails, the v2 \
2466             encoding or its version dispatch changed and existing audit logs are unreadable"
2467        );
2468
2469        // Without this half the frozen constant is decorative: a build that
2470        // skipped signature checking entirely would still pass the assertion
2471        // above. Flipping one nibble must be rejected.
2472        let mut tampered = row;
2473        let flipped = match GOLDEN_V2_CHAIN_HASH.strip_prefix('b') {
2474            Some(rest) => format!("a{rest}"),
2475            None => format!("b{}", &GOLDEN_V2_CHAIN_HASH[1..]),
2476        };
2477        tampered.chain_hash = flipped;
2478        assert!(
2479            matches!(
2480                verify_chain(&key, &[tampered]),
2481                VerifyOutcome::Broken { .. }
2482            ),
2483            "a golden row with one nibble changed must not verify"
2484        );
2485    }
2486
2487    /// The v1 encoding is still claimed verifiable, and until now was protected
2488    /// only by tests that sign and verify in one process. Frozen here for the
2489    /// same reason as v2.
2490    #[test]
2491    fn a_legacy_v1_row_on_disk_still_verifies() {
2492        const GOLDEN_V1_CHAIN_HASH: &str = "ce8b47c15414e989e099303b826fcd9985360b794220cefbbf9689d25f31fe173283687feb6d1dd265ae5aca94c8bcfb87ce33ba8c954fafdad18a59cd97c702";
2493
2494        let row = ChainRow {
2495            chain_version: 1,
2496            caller_role: None,
2497            event_tip: None,
2498            caller_principal: None,
2499            chain_hash: GOLDEN_V1_CHAIN_HASH.to_string(),
2500            ..golden_row_shape()
2501        };
2502        assert_eq!(
2503            verify_chain(&fixed_key(), &[row]),
2504            VerifyOutcome::Intact { rows_checked: 1 }
2505        );
2506    }
2507
2508    /// And v3, frozen now while the encoder that produces it is the one under
2509    /// review. When v4 arrives, v3 rows will be in exactly the position v2 rows
2510    /// were in before this change, and this is the test that will notice.
2511    #[test]
2512    fn a_v3_row_on_disk_still_verifies() {
2513        const GOLDEN_V3_CHAIN_HASH: &str = "3c0d05f6ccaf9e65ccb796d4ffe96eb31a2ea67e446217c5234af916dc959d0f2c0ee3d3e5b525aece791ee7d6507efb98dcdd79f0d74dde4273859aa9627d08";
2514
2515        let row = ChainRow {
2516            chain_version: 3,
2517            caller_role: Some("admin".to_string()),
2518            event_tip: Some("eventtip-golden".to_string()),
2519            caller_principal: Some("uid:1000".to_string()),
2520            chain_hash: GOLDEN_V3_CHAIN_HASH.to_string(),
2521            ..golden_row_shape()
2522        };
2523        assert_eq!(
2524            verify_chain(&fixed_key(), &[row]),
2525            VerifyOutcome::Intact { rows_checked: 1 }
2526        );
2527    }
2528
2529    /// The golden rows above all have an empty `prev_chain_hash`, an approval id,
2530    /// and content with no bytes the escape table touches. This one has the
2531    /// opposite of each: a non-empty predecessor, no approval id, and a summary
2532    /// carrying a backslash, `0x1F`, `0x1E`, and a NUL. A refactor of the escape
2533    /// table or of the `approval_id: None` mapping changes this hash and nothing
2534    /// else in the suite.
2535    #[test]
2536    fn the_escape_table_and_absent_approval_encoding_are_frozen() {
2537        const GOLDEN_V2_AWKWARD_CHAIN_HASH: &str = "e6face6fe2346fc0f6c5c1e5845255579c8f08738406b88b0a1f6dbdf8ff85090a4b80d95bd0927ef54b0a2c4810d52ebb4bbf76cb68c865a7748df26442aa05";
2538
2539        let key = fixed_key();
2540        let content = ChainContent {
2541            seq: 8,
2542            approval_id: None,
2543            summary: "back\\slash and \x1funit and \x1erecord and nul\0byte",
2544            identity: ChainIdentity::V2 {
2545                caller_role: "dev",
2546                event_tip: "",
2547            },
2548            ..golden_content_shape()
2549        };
2550        assert_eq!(
2551            key.chain_hash(&content, "ba12cbe4"),
2552            GOLDEN_V2_AWKWARD_CHAIN_HASH,
2553            "the canonical encoding of escapes, an absent approval id, or a \
2554             non-empty prev_chain_hash changed"
2555        );
2556    }
2557
2558    /// Shared literal content for the golden vectors. Spelled out rather than
2559    /// derived from `sample_content` so a future edit to that helper cannot move
2560    /// what the frozen hashes describe.
2561    fn golden_content_shape() -> ChainContent<'static> {
2562        ChainContent {
2563            seq: 7,
2564            key_id: CURRENT_KEY_ID,
2565            transaction_id: "tx-golden",
2566            request_id: "req-golden",
2567            request_hash: "hash-golden",
2568            action_name: "AptInstall",
2569            risk_level: RiskLevel::Medium,
2570            summary: "install ripgrep",
2571            approval_id: Some("appr-golden"),
2572            warnings_json: "[]",
2573            created_at: "2026-07-29T00:00:00Z",
2574            identity: ChainIdentity::LegacyV1,
2575        }
2576    }
2577
2578    /// The stored-row twin of `golden_content_shape`.
2579    fn golden_row_shape() -> ChainRow {
2580        ChainRow {
2581            seq: 7,
2582            key_id: CURRENT_KEY_ID.to_string(),
2583            transaction_id: "tx-golden".to_string(),
2584            request_id: "req-golden".to_string(),
2585            request_hash: "hash-golden".to_string(),
2586            action_name: "AptInstall".to_string(),
2587            risk_level: RiskLevel::Medium,
2588            summary: "install ripgrep".to_string(),
2589            approval_id: Some("appr-golden".to_string()),
2590            warnings_json: "[]".to_string(),
2591            created_at: "2026-07-29T00:00:00Z".to_string(),
2592            prev_chain_hash: String::new(),
2593            chain_hash: String::new(),
2594            chain_version: 1,
2595            caller_role: None,
2596            event_tip: None,
2597            caller_principal: None,
2598        }
2599    }
2600
2601    #[test]
2602    fn a_chain_that_spans_the_migration_verifies_end_to_end() {
2603        // The realistic upgrade shape: old rows, then new rows appended by the
2604        // upgraded daemon, in one chain.
2605        let key = fixed_key();
2606        let mut rows = Vec::new();
2607        let mut prev = String::new();
2608        for (i, identity) in [
2609            ChainIdentity::LegacyV1,
2610            ChainIdentity::LegacyV1,
2611            ChainIdentity::V2 {
2612                caller_role: "Dev",
2613                event_tip: "",
2614            },
2615            ChainIdentity::V2 {
2616                caller_role: "Boot",
2617                event_tip: "",
2618            },
2619        ]
2620        .into_iter()
2621        .enumerate()
2622        {
2623            let txid = format!("tx{i}");
2624            let mut content = sample_content((i + 1) as u64, &txid);
2625            content.identity = identity;
2626            let hash = key.chain_hash(&content, &prev);
2627            rows.push(row_for(&content, &prev, hash.clone()));
2628            prev = hash;
2629        }
2630        assert_eq!(
2631            verify_chain(&key, &rows),
2632            VerifyOutcome::Intact { rows_checked: 4 }
2633        );
2634    }
2635
2636    #[test]
2637    fn downgrading_a_v2_row_to_hide_the_caller_role_breaks_it() {
2638        // The attack the version column might invite: relabel a v2 row as
2639        // legacy and drop the identity columns, so verification re-encodes it
2640        // without caller_role. The stored signature was made over the v2
2641        // message, so it cannot verify against the shorter one.
2642        let key = fixed_key();
2643        let mut rows = build_chain(&key, 2);
2644        rows[1].chain_version = CHAIN_VERSION_LEGACY;
2645        rows[1].caller_role = None;
2646        rows[1].event_tip = None;
2647        match verify_chain(&key, &rows) {
2648            VerifyOutcome::Broken {
2649                first_broken_seq, ..
2650            } => assert_eq!(first_broken_seq, 2),
2651            other => panic!("expected Broken, got {other:?}"),
2652        }
2653    }
2654
2655    #[test]
2656    fn a_v2_row_with_a_nulled_caller_role_is_broken_not_merely_unverifiable() {
2657        // Nulling the column while leaving chain_version=2 is a
2658        // self-contradictory row, not an infrastructure problem. It must map
2659        // to exit code 1 (tamper detected), never 2 (could not check) — a CI
2660        // gate that treats 2 as "skip" would otherwise wave it through.
2661        let key = fixed_key();
2662        let mut rows = build_chain(&key, 1);
2663        rows[0].caller_role = None;
2664        let outcome = verify_chain(&key, &rows);
2665        assert!(matches!(outcome, VerifyOutcome::Broken { .. }));
2666        assert_eq!(outcome_to_exit_code(&outcome), 1);
2667    }
2668
2669    #[test]
2670    fn a_chain_version_this_binary_does_not_know_is_cannot_verify() {
2671        // An older binary reading a newer chain genuinely cannot reproduce the
2672        // message. That is exit 2, distinct from a detected break.
2673        let key = fixed_key();
2674        let mut rows = build_chain(&key, 1);
2675        rows[0].chain_version = CHAIN_VERSION_CURRENT + 1;
2676        let outcome = verify_chain(&key, &rows);
2677        assert!(matches!(outcome, VerifyOutcome::CannotVerify { .. }));
2678        assert_eq!(outcome_to_exit_code(&outcome), 2);
2679    }
2680
2681    // ── approval-event chain ──────────────────────────────────────────────
2682
2683    fn event_content<'a>(seq: u64, kind: AuditEventKind, txid: &'a str) -> EventContent<'a> {
2684        EventContent {
2685            seq,
2686            key_id: CURRENT_KEY_ID,
2687            kind,
2688            transaction_id: txid,
2689            receipt_digest: "digest-abc",
2690            created_at: "2026-04-24T12:00:00Z",
2691        }
2692    }
2693
2694    fn build_event_chain(key: &AuditKey, kinds: &[AuditEventKind]) -> Vec<EventRow> {
2695        let mut rows = Vec::with_capacity(kinds.len());
2696        let mut prev = String::new();
2697        for (i, kind) in kinds.iter().enumerate() {
2698            let seq = (i + 1) as u64;
2699            let txid = format!("tx{i}");
2700            let content = event_content(seq, *kind, &txid);
2701            let hash = key.event_hash(&content, &prev);
2702            rows.push(EventRow {
2703                seq,
2704                key_id: content.key_id.to_string(),
2705                kind: content.kind.as_str().to_string(),
2706                transaction_id: content.transaction_id.to_string(),
2707                receipt_digest: content.receipt_digest.to_string(),
2708                created_at: content.created_at.to_string(),
2709                prev_chain_hash: prev.clone(),
2710                chain_hash: hash.clone(),
2711            });
2712            prev = hash;
2713        }
2714        rows
2715    }
2716
2717    #[test]
2718    fn event_kind_spellings_are_stable() {
2719        // These strings are inside the signed message. Renaming one silently
2720        // invalidates every event already written.
2721        assert_eq!(AuditEventKind::ApprovalGranted.as_str(), "approval_granted");
2722        assert_eq!(
2723            AuditEventKind::ApprovalConsumed.as_str(),
2724            "approval_consumed"
2725        );
2726        assert_eq!(AuditEventKind::ApprovalRevoked.as_str(), "approval_revoked");
2727    }
2728
2729    #[test]
2730    fn intact_event_chain_verifies() {
2731        let key = fixed_key();
2732        let rows = build_event_chain(
2733            &key,
2734            &[
2735                AuditEventKind::ApprovalGranted,
2736                AuditEventKind::ApprovalConsumed,
2737            ],
2738        );
2739        assert_eq!(
2740            verify_event_chain(&key, &rows),
2741            VerifyOutcome::Intact { rows_checked: 2 }
2742        );
2743    }
2744
2745    #[test]
2746    fn deleting_an_approval_event_from_the_middle_breaks_the_event_chain() {
2747        // The finding this chain exists for: before it, deleting the record
2748        // that an approval happened left `audit verify` reporting Intact.
2749        let key = fixed_key();
2750        let mut rows = build_event_chain(
2751            &key,
2752            &[
2753                AuditEventKind::ApprovalGranted,
2754                AuditEventKind::ApprovalConsumed,
2755                AuditEventKind::ApprovalRevoked,
2756            ],
2757        );
2758        rows.remove(1);
2759        match verify_event_chain(&key, &rows) {
2760            VerifyOutcome::Broken {
2761                first_broken_seq, ..
2762            } => assert_eq!(first_broken_seq, 3),
2763            other => panic!("expected Broken, got {other:?}"),
2764        }
2765    }
2766
2767    #[test]
2768    fn relabelling_a_revocation_as_a_grant_breaks_the_event_chain() {
2769        let key = fixed_key();
2770        let mut rows = build_event_chain(&key, &[AuditEventKind::ApprovalRevoked]);
2771        rows[0].kind = AuditEventKind::ApprovalGranted.as_str().to_string();
2772        assert!(matches!(
2773            verify_event_chain(&key, &rows),
2774            VerifyOutcome::Broken { .. }
2775        ));
2776    }
2777
2778    #[test]
2779    fn an_unrecognised_event_kind_is_a_break_not_a_panic() {
2780        let key = fixed_key();
2781        let mut rows = build_event_chain(&key, &[AuditEventKind::ApprovalGranted]);
2782        rows[0].kind = "approval_unicorned".to_string();
2783        assert!(matches!(
2784            verify_event_chain(&key, &rows),
2785            VerifyOutcome::Broken { .. }
2786        ));
2787    }
2788
2789    #[test]
2790    fn a_row_signature_cannot_be_replayed_as_an_event_signature() {
2791        // Domain separation, checked functionally rather than by comparing the
2792        // tag constants: the tags test proves the bytes differ, this proves the
2793        // difference actually reaches the verifier.
2794        let key = fixed_key();
2795        let content = event_content(1, AuditEventKind::ApprovalGranted, "tx0");
2796        let event_sig = key.event_hash(&content, "");
2797        let row_sig = key.chain_hash(&sample_content(1, "tx0"), "");
2798        assert_ne!(event_sig, row_sig);
2799
2800        let mut rows = build_event_chain(&key, &[AuditEventKind::ApprovalGranted]);
2801        rows[0].chain_hash = row_sig;
2802        assert!(matches!(
2803            verify_event_chain(&key, &rows),
2804            VerifyOutcome::Broken { .. }
2805        ));
2806    }
2807
2808    // ── cross-chain binding ───────────────────────────────────────────────
2809
2810    #[test]
2811    fn deleting_the_last_approval_event_is_caught_by_the_transaction_binding() {
2812        // Truncating the *tail* of the event chain leaves a self-consistent
2813        // event chain — the walk alone cannot see it. It is caught because a
2814        // later transaction row signed the tip that no longer exists, and the
2815        // transaction chain is what checkpoints anchor.
2816        let key = fixed_key();
2817        let events = build_event_chain(
2818            &key,
2819            &[
2820                AuditEventKind::ApprovalGranted,
2821                AuditEventKind::ApprovalConsumed,
2822            ],
2823        );
2824        let mut content = sample_content(1, "tx-after");
2825        content.identity = ChainIdentity::V2 {
2826            caller_role: "Dev",
2827            event_tip: &events[1].chain_hash,
2828        };
2829        let hash = key.chain_hash(&content, "");
2830        let tx_rows = vec![row_for(&content, "", hash)];
2831
2832        assert_eq!(
2833            verify_event_binding(&tx_rows, &events),
2834            BindingOutcome::Consistent {
2835                bindings_checked: 1
2836            }
2837        );
2838
2839        let truncated = &events[..1];
2840        assert_eq!(
2841            verify_event_chain(&key, truncated),
2842            VerifyOutcome::Intact { rows_checked: 1 },
2843            "a truncated event chain still walks clean; the binding is the detector"
2844        );
2845        match verify_event_binding(&tx_rows, truncated) {
2846            BindingOutcome::MissingEvent {
2847                transaction_seq, ..
2848            } => assert_eq!(transaction_seq, 1),
2849            other => panic!("expected MissingEvent, got {other:?}"),
2850        }
2851    }
2852
2853    #[test]
2854    fn legacy_rows_carry_no_binding_to_check() {
2855        // Rows written before the migration never committed to an event tip.
2856        // They must not be counted as bindings, and must not fail the check.
2857        let key = fixed_key();
2858        let mut content = sample_content(1, "tx-legacy");
2859        content.identity = ChainIdentity::LegacyV1;
2860        let hash = key.chain_hash(&content, "");
2861        let rows = vec![row_for(&content, "", hash)];
2862        assert_eq!(
2863            verify_event_binding(&rows, &[]),
2864            BindingOutcome::Consistent {
2865                bindings_checked: 0
2866            }
2867        );
2868    }
2869
2870    #[test]
2871    fn a_detected_break_outranks_an_inconclusive_check_in_the_exit_code() {
2872        // If one check proves tampering and another merely cannot run, the
2873        // command must report the tamper. Reporting 2 ("could not verify")
2874        // would let a CI gate that treats 2 as a skip wave a broken chain
2875        // through.
2876        let verification = AuditVerification {
2877            chain: VerifyOutcome::Broken {
2878                rows_checked: 1,
2879                first_broken_seq: 2,
2880                first_broken_transaction_id: "tx".to_string(),
2881                expected: "e".to_string(),
2882                actual: "a".to_string(),
2883            },
2884            events: VerifyOutcome::CannotVerify {
2885                reason: "no key".to_string(),
2886            },
2887            binding: BindingOutcome::Consistent {
2888                bindings_checked: 0,
2889            },
2890            attribution: None,
2891        };
2892        assert_eq!(verification.exit_code(), 1);
2893    }
2894
2895    #[test]
2896    fn a_clean_transaction_chain_does_not_mask_a_broken_event_chain() {
2897        let verification = AuditVerification {
2898            chain: VerifyOutcome::Intact { rows_checked: 3 },
2899            events: VerifyOutcome::Intact { rows_checked: 1 },
2900            binding: BindingOutcome::MissingEvent {
2901                transaction_seq: 3,
2902                event_tip: "abc".to_string(),
2903            },
2904            attribution: None,
2905        };
2906        assert_eq!(verification.exit_code(), 1);
2907    }
2908
2909    #[test]
2910    fn all_three_clean_is_exit_zero() {
2911        let verification = AuditVerification {
2912            chain: VerifyOutcome::Intact { rows_checked: 3 },
2913            events: VerifyOutcome::Intact { rows_checked: 2 },
2914            binding: BindingOutcome::Consistent {
2915                bindings_checked: 1,
2916            },
2917            attribution: None,
2918        };
2919        assert_eq!(verification.exit_code(), 0);
2920    }
2921
2922    #[test]
2923    fn binding_exit_codes_split_clean_tampered_and_unchecked() {
2924        assert_eq!(
2925            binding_outcome_to_exit_code(&BindingOutcome::Consistent {
2926                bindings_checked: 0
2927            }),
2928            0
2929        );
2930        assert_eq!(
2931            binding_outcome_to_exit_code(&BindingOutcome::MissingEvent {
2932                transaction_seq: 7,
2933                event_tip: "abc".to_string()
2934            }),
2935            1
2936        );
2937        assert_eq!(binding_outcome_to_exit_code(&BindingOutcome::NotChecked), 2);
2938    }
2939
2940    #[test]
2941    fn intact_chain_verifies() {
2942        let key = fixed_key();
2943        let rows = build_chain(&key, 5);
2944        let outcome = verify_chain(&key, &rows);
2945        assert_eq!(outcome, VerifyOutcome::Intact { rows_checked: 5 });
2946        assert_eq!(outcome_to_exit_code(&outcome), 0);
2947    }
2948
2949    #[test]
2950    fn empty_chain_verifies() {
2951        let key = fixed_key();
2952        let outcome = verify_chain(&key, &[]);
2953        assert_eq!(outcome, VerifyOutcome::Intact { rows_checked: 0 });
2954    }
2955
2956    #[test]
2957    fn tampered_summary_breaks_chain_at_first_offending_row() {
2958        let key = fixed_key();
2959        let mut rows = build_chain(&key, 3);
2960        // Mutate summary on row 1 (seq=2). Hash mismatch should be detected.
2961        rows[1].summary = "TAMPERED".to_string();
2962        let outcome = verify_chain(&key, &rows);
2963        match outcome {
2964            VerifyOutcome::Broken {
2965                first_broken_seq, ..
2966            } => assert_eq!(first_broken_seq, 2),
2967            other => panic!("expected Broken, got {other:?}"),
2968        }
2969    }
2970
2971    #[test]
2972    fn deleted_middle_row_breaks_chain_via_prev_hash_mismatch() {
2973        let key = fixed_key();
2974        let mut rows = build_chain(&key, 4);
2975        // Remove row at seq=2 entirely. Row 3's prev_chain_hash now mismatches.
2976        rows.remove(1);
2977        let outcome = verify_chain(&key, &rows);
2978        match outcome {
2979            VerifyOutcome::Broken {
2980                first_broken_seq, ..
2981            } => assert_eq!(
2982                first_broken_seq, 3,
2983                "first broken row is the one whose prev_hash refers to deleted row"
2984            ),
2985            other => panic!("expected Broken, got {other:?}"),
2986        }
2987    }
2988
2989    #[test]
2990    fn inserted_forged_row_breaks_chain() {
2991        // Counterpart to `deleted_middle_row_…`. An attacker who managed to
2992        // insert a fabricated row between two genuine ones still cannot
2993        // produce a `chain_hash` that links the insertion back to the prior
2994        // row's hash, so verification must flag the forgery at the inserted
2995        // row (or at the immediately following genuine row whose
2996        // `prev_chain_hash` no longer matches its real predecessor).
2997        let key = fixed_key();
2998        let mut rows = build_chain(&key, 3);
2999
3000        // Splice in a new row between seq=1 and seq=2 with a fabricated hash.
3001        let forged = ChainRow {
3002            // Carries a principal on purpose: without one the row is rejected as
3003            // self-contradictory *before* any signature is checked, and this test
3004            // exists to prove the walk stops on a bad signature.
3005            caller_principal: Some("uid:1000".to_string()),
3006            seq: 2,
3007            key_id: CURRENT_KEY_ID.to_string(),
3008            transaction_id: "tx-forged".to_string(),
3009            request_id: "req-forged".to_string(),
3010            request_hash: "hash-forged".to_string(),
3011            action_name: "InstallFlatpak".to_string(),
3012            risk_level: RiskLevel::Medium,
3013            summary: "Forged row".to_string(),
3014            approval_id: None,
3015            warnings_json: "[]".to_string(),
3016            created_at: "2026-04-25T13:00:00Z".to_string(),
3017            // Plausible prev_chain_hash chosen to look intact at boundary.
3018            prev_chain_hash: rows[0].chain_hash.clone(),
3019            // Not a valid signature; verification must reject this.
3020            chain_hash: "0".repeat(HASH_HEX_LEN),
3021            chain_version: CHAIN_VERSION_CURRENT,
3022            caller_role: Some("Dev".to_string()),
3023            event_tip: Some(String::new()),
3024        };
3025
3026        // Renumber the genuine seq=2/3 rows so seq is still 1..=4.
3027        let mut rest: Vec<ChainRow> = rows.split_off(1);
3028        for r in rest.iter_mut() {
3029            r.seq += 1;
3030        }
3031        rows.push(forged);
3032        rows.extend(rest);
3033
3034        // The fixture is deterministic: the forged row sits at seq=2 with a
3035        // signature that cannot verify, so the walk must stop exactly there.
3036        // Accepting "2 or 3" let an off-by-one in `verify_rows` pass.
3037        let outcome = verify_chain(&key, &rows);
3038        match outcome {
3039            VerifyOutcome::Broken {
3040                first_broken_seq, ..
3041            } => assert_eq!(
3042                first_broken_seq, 2,
3043                "the verifier must flag the forged row itself, not a later one"
3044            ),
3045            other => panic!("expected Broken, got {other:?}"),
3046        }
3047    }
3048
3049    // ── Ed25519 public-key verification / non-repudiation ─────────────────
3050
3051    #[test]
3052    fn signature_verifies_under_exported_public_key() {
3053        // The auditor path: verify with only the public key.
3054        let key = fixed_key();
3055        let rows = build_chain(&key, 4);
3056        let outcome = verify_chain_with_pubkey(&key.verifying_key_hex(), &rows);
3057        assert_eq!(outcome, VerifyOutcome::Intact { rows_checked: 4 });
3058    }
3059
3060    #[test]
3061    fn foreign_public_key_cannot_validate_chain() {
3062        // Non-repudiation: a different keypair's public key neither validates
3063        // the chain nor (by construction) could forge it. This is the property
3064        // the old symmetric HMAC could not provide.
3065        let signer = AuditKey::from_bytes(vec![0x11; 32]);
3066        let rows = build_chain(&signer, 3);
3067        let other = AuditKey::from_bytes(vec![0x22; 32]);
3068        let outcome = verify_chain_with_pubkey(&other.verifying_key_hex(), &rows);
3069        assert!(matches!(
3070            outcome,
3071            VerifyOutcome::Broken {
3072                first_broken_seq: 1,
3073                ..
3074            }
3075        ));
3076    }
3077
3078    #[test]
3079    fn verifying_key_hex_is_a_32_byte_public_key() {
3080        let key = fixed_key();
3081        let vk_hex = key.verifying_key_hex();
3082        assert_eq!(
3083            vk_hex.len(),
3084            64,
3085            "32-byte ed25519 public key = 64 hex chars"
3086        );
3087        assert!(hex::decode(&vk_hex).is_ok());
3088    }
3089
3090    #[test]
3091    fn malformed_signature_hex_is_broken_not_panic() {
3092        let key = fixed_key();
3093        let mut rows = build_chain(&key, 2);
3094        rows[0].chain_hash = "not-valid-hex!!".to_string();
3095        let outcome = verify_chain(&key, &rows);
3096        assert!(matches!(
3097            outcome,
3098            VerifyOutcome::Broken {
3099                first_broken_seq: 1,
3100                ..
3101            }
3102        ));
3103    }
3104
3105    #[test]
3106    fn bad_public_key_hex_yields_cannot_verify() {
3107        let key = fixed_key();
3108        let rows = build_chain(&key, 1);
3109        let outcome = verify_chain_with_pubkey("zz", &rows);
3110        assert!(matches!(outcome, VerifyOutcome::CannotVerify { .. }));
3111    }
3112
3113    #[test]
3114    fn load_or_generate_writes_public_key_sidecar() {
3115        let dir = tempfile::tempdir().unwrap();
3116        let path = dir.path().join("audit-key");
3117        let key = AuditKey::load_or_generate(&path).unwrap();
3118        let pub_path = dir.path().join("audit-key.pub");
3119        assert!(pub_path.exists(), "public key sidecar must be written");
3120        let pub_hex = std::fs::read_to_string(&pub_path).unwrap();
3121        assert_eq!(pub_hex.trim(), key.verifying_key_hex());
3122    }
3123
3124    #[test]
3125    fn wrong_key_id_yields_cannot_verify() {
3126        let key = fixed_key();
3127        let mut rows = build_chain(&key, 2);
3128        rows[0].key_id = "v99".to_string();
3129        let outcome = verify_chain(&key, &rows);
3130        assert!(matches!(outcome, VerifyOutcome::CannotVerify { .. }));
3131        assert_eq!(outcome_to_exit_code(&outcome), 2);
3132    }
3133
3134    #[test]
3135    fn exit_code_for_each_outcome() {
3136        assert_eq!(
3137            outcome_to_exit_code(&VerifyOutcome::Intact { rows_checked: 0 }),
3138            0
3139        );
3140        assert_eq!(
3141            outcome_to_exit_code(&VerifyOutcome::Broken {
3142                rows_checked: 0,
3143                first_broken_seq: 1,
3144                first_broken_transaction_id: String::new(),
3145                expected: String::new(),
3146                actual: String::new(),
3147            }),
3148            1
3149        );
3150        assert_eq!(
3151            outcome_to_exit_code(&VerifyOutcome::CannotVerify {
3152                reason: String::new()
3153            }),
3154            2
3155        );
3156    }
3157
3158    // ── AuditKey file management ──────────────────────────────────────────
3159
3160    #[test]
3161    fn load_or_generate_creates_with_0600_mode() {
3162        use std::os::unix::fs::PermissionsExt;
3163        let dir = tempfile::tempdir().unwrap();
3164        let path = dir.path().join("audit-key");
3165        let _key = AuditKey::load_or_generate(&path).unwrap();
3166        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
3167        assert_eq!(mode, 0o600);
3168    }
3169
3170    #[test]
3171    fn load_or_generate_is_idempotent() {
3172        let dir = tempfile::tempdir().unwrap();
3173        let path = dir.path().join("audit-key");
3174        let key1_bytes = {
3175            let _ = AuditKey::load_or_generate(&path).unwrap();
3176            std::fs::read(&path).unwrap()
3177        };
3178        let _ = AuditKey::load_or_generate(&path).unwrap();
3179        let key2_bytes = std::fs::read(&path).unwrap();
3180        assert_eq!(key1_bytes, key2_bytes, "second load must not regenerate");
3181    }
3182
3183    #[test]
3184    fn rejects_world_readable_key_file() {
3185        use std::os::unix::fs::PermissionsExt;
3186        let dir = tempfile::tempdir().unwrap();
3187        let path = dir.path().join("audit-key");
3188        std::fs::write(&path, vec![0u8; 32]).unwrap();
3189        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
3190        let result = AuditKey::load_or_generate(&path);
3191        assert!(matches!(
3192            result,
3193            Err(AuditKeyError::UnsafePermissions { .. })
3194        ));
3195    }
3196
3197    #[test]
3198    fn rejects_short_key_file() {
3199        use std::os::unix::fs::PermissionsExt;
3200        let dir = tempfile::tempdir().unwrap();
3201        let path = dir.path().join("audit-key");
3202        std::fs::write(&path, vec![0u8; 8]).unwrap();
3203        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
3204        let result = AuditKey::load_or_generate(&path);
3205        assert!(matches!(result, Err(AuditKeyError::KeyTooShort { .. })));
3206    }
3207
3208    // ── Debug redaction (HI-17 secret hygiene) ────────────────────────────
3209
3210    /// `Debug` must never expose the Ed25519 private key material, neither raw bytes,
3211    /// nor their hex encoding. A derived `Debug` would dump the bytes the
3212    /// moment anyone wrote `tracing::debug!("{key:?}")`.
3213    #[test]
3214    fn debug_redacts_key_bytes_and_their_hex_encoding() {
3215        // Use a distinctive byte pattern so accidental leaks are obvious.
3216        let raw = (0u8..32).collect::<Vec<u8>>();
3217        let key = AuditKey::from_bytes(raw.clone());
3218        let dbg = format!("{key:?}");
3219
3220        assert!(
3221            dbg.contains("redacted"),
3222            "Debug output must contain the literal 'redacted' marker, got: {dbg}"
3223        );
3224
3225        // Hex encoding of the bytes must NOT appear, in either case.
3226        let hex_lower = hex::encode(&raw);
3227        let hex_upper = hex::encode_upper(&raw);
3228        assert!(
3229            !dbg.contains(&hex_lower),
3230            "Debug output leaks lowercase hex of key bytes: {dbg}"
3231        );
3232        assert!(
3233            !dbg.contains(&hex_upper),
3234            "Debug output leaks uppercase hex of key bytes: {dbg}"
3235        );
3236
3237        // Each individual byte's two-hex-char form must also be absent. This
3238        // catches the case where a future change splits the bytes across the
3239        // formatter and prints them piecewise.
3240        for b in &raw {
3241            let pair = format!("{b:02x}");
3242            // 1-byte values 0x00..0x0f render as "00".."0f" — too short to
3243            // assert against safely (collides with key_id "v1" etc.). Only
3244            // check 2-char forms that cannot incidentally match the rest of
3245            // the Debug output.
3246            if *b >= 0x10 && pair != "1e" && pair != "1f" {
3247                assert!(
3248                    !dbg.contains(&pair),
3249                    "Debug output leaks byte {b:#04x} as {pair:?}: {dbg}"
3250                );
3251            }
3252        }
3253    }
3254
3255    /// Operators triaging a chain break need to know which key generation
3256    /// produced a row. `key_id` is not secret and must remain visible.
3257    #[test]
3258    fn debug_preserves_key_id() {
3259        let key = AuditKey::from_bytes(vec![0xff; 32]);
3260        let dbg = format!("{key:?}");
3261        assert!(
3262            dbg.contains("key_id"),
3263            "Debug output must label the key_id field: {dbg}"
3264        );
3265        assert!(
3266            dbg.contains(CURRENT_KEY_ID),
3267            "Debug output must contain the key_id value {CURRENT_KEY_ID:?}: {dbg}"
3268        );
3269    }
3270
3271    // ── signed checkpoints (anti-truncation / anti-rewrite) ───────────────
3272
3273    #[test]
3274    fn checkpoint_consistent_with_intact_chain() {
3275        let key = fixed_key();
3276        let rows = build_chain(&key, 5);
3277        let cp = key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:00:00Z");
3278        let outcome = verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]);
3279        assert_eq!(
3280            outcome,
3281            CheckpointOutcome::Consistent {
3282                checkpoints_checked: 1
3283            }
3284        );
3285    }
3286
3287    #[test]
3288    fn checkpoint_detects_truncation() {
3289        let key = fixed_key();
3290        let full = build_chain(&key, 5);
3291        // Anchor a checkpoint at the tip (seq=5); later the chain is cut to 3.
3292        let cp = key.sign_checkpoint(5, &full[4].chain_hash, "2026-04-24T12:00:00Z");
3293        let truncated = &full[..3];
3294        let outcome = verify_checkpoints(&key.verifying_key_hex(), truncated, &[cp]);
3295        assert!(matches!(
3296            outcome,
3297            CheckpointOutcome::Truncated {
3298                checkpoint_seq: 5,
3299                current_max_seq: 3
3300            }
3301        ));
3302    }
3303
3304    #[test]
3305    fn checkpoint_detects_rewrite() {
3306        let key = fixed_key();
3307        let mut rows = build_chain(&key, 4);
3308        let cp = key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:00:00Z");
3309        // Rewrite the row at seq=3 after the checkpoint was anchored.
3310        rows[2].chain_hash = "0".repeat(HASH_HEX_LEN);
3311        let outcome = verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]);
3312        assert!(matches!(
3313            outcome,
3314            CheckpointOutcome::TipMismatch { seq: 3, .. }
3315        ));
3316    }
3317
3318    #[test]
3319    fn checkpoint_bad_signature_detected() {
3320        let key = fixed_key();
3321        let rows = build_chain(&key, 3);
3322        let mut cp = key.sign_checkpoint(2, &rows[1].chain_hash, "2026-04-24T12:00:00Z");
3323        cp.signature = "0".repeat(HASH_HEX_LEN); // not a valid signature
3324        let outcome = verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]);
3325        assert!(matches!(
3326            outcome,
3327            CheckpointOutcome::BadSignature { seq: 2 }
3328        ));
3329    }
3330
3331    #[test]
3332    fn checkpoint_foreign_key_rejected() {
3333        // A checkpoint signed by one key must not verify under another key.
3334        let signer = AuditKey::from_bytes(vec![0x11; 32]);
3335        let rows = build_chain(&signer, 3);
3336        let cp = signer.sign_checkpoint(2, &rows[1].chain_hash, "2026-04-24T12:00:00Z");
3337        let other = AuditKey::from_bytes(vec![0x22; 32]);
3338        let outcome = verify_checkpoints(&other.verifying_key_hex(), &rows, &[cp]);
3339        assert!(matches!(
3340            outcome,
3341            CheckpointOutcome::BadSignature { seq: 2 }
3342        ));
3343    }
3344
3345    #[test]
3346    fn pubkey_verify_detects_tampered_middle_row() {
3347        // The core auditor claim: with only the public key, a mutated field in
3348        // a non-first row is detected at that exact seq.
3349        let key = fixed_key();
3350        let mut rows = build_chain(&key, 4);
3351        rows[2].summary = "TAMPERED".to_string();
3352        let outcome = verify_chain_with_pubkey(&key.verifying_key_hex(), &rows);
3353        assert!(matches!(
3354            outcome,
3355            VerifyOutcome::Broken {
3356                first_broken_seq: 3,
3357                ..
3358            }
3359        ));
3360    }
3361
3362    #[test]
3363    fn multiple_checkpoints_all_consistent() {
3364        let key = fixed_key();
3365        let rows = build_chain(&key, 5);
3366        let cps = vec![
3367            key.sign_checkpoint(2, &rows[1].chain_hash, "2026-04-24T12:00:00Z"),
3368            key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:05:00Z"),
3369            key.sign_checkpoint(5, &rows[4].chain_hash, "2026-04-24T12:10:00Z"),
3370        ];
3371        assert_eq!(
3372            verify_checkpoints(&key.verifying_key_hex(), &rows, &cps),
3373            CheckpointOutcome::Consistent {
3374                checkpoints_checked: 3
3375            }
3376        );
3377    }
3378
3379    #[test]
3380    fn middle_checkpoint_failure_is_reported() {
3381        // Earlier-consistent checkpoints must not mask a later failure.
3382        let key = fixed_key();
3383        let mut rows = build_chain(&key, 5);
3384        let cps = vec![
3385            key.sign_checkpoint(2, &rows[1].chain_hash, "2026-04-24T12:00:00Z"),
3386            key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:05:00Z"),
3387            key.sign_checkpoint(5, &rows[4].chain_hash, "2026-04-24T12:10:00Z"),
3388        ];
3389        rows[2].chain_hash = "0".repeat(HASH_HEX_LEN); // rewrite what cp #2 commits to
3390        assert!(matches!(
3391            verify_checkpoints(&key.verifying_key_hex(), &rows, &cps),
3392            CheckpointOutcome::TipMismatch { seq: 3, .. }
3393        ));
3394    }
3395
3396    #[test]
3397    fn checkpoint_created_at_is_signed() {
3398        // created_at is inside the signed message: backdating invalidates it.
3399        let key = fixed_key();
3400        let rows = build_chain(&key, 3);
3401        let mut cp = key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:00:00Z");
3402        cp.created_at = "2020-01-01T00:00:00Z".to_string();
3403        assert!(matches!(
3404            verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]),
3405            CheckpointOutcome::BadSignature { .. }
3406        ));
3407    }
3408
3409    #[test]
3410    fn checkpoint_seq_is_signed() {
3411        // seq is inside the signed message: moving it invalidates the signature.
3412        let key = fixed_key();
3413        let rows = build_chain(&key, 3);
3414        let mut cp = key.sign_checkpoint(3, &rows[2].chain_hash, "2026-04-24T12:00:00Z");
3415        cp.seq = 2;
3416        assert!(matches!(
3417            verify_checkpoints(&key.verifying_key_hex(), &rows, &[cp]),
3418            CheckpointOutcome::BadSignature { seq: 2 }
3419        ));
3420    }
3421
3422    #[test]
3423    fn checkpoint_detects_full_wipe() {
3424        // The whole chain deleted: the anchored tip cannot be reproduced.
3425        let key = fixed_key();
3426        let full = build_chain(&key, 3);
3427        let cp = key.sign_checkpoint(3, &full[2].chain_hash, "2026-04-24T12:00:00Z");
3428        assert!(matches!(
3429            verify_checkpoints(&key.verifying_key_hex(), &[], &[cp]),
3430            CheckpointOutcome::Truncated {
3431                checkpoint_seq: 3,
3432                current_max_seq: 0
3433            }
3434        ));
3435    }
3436
3437    #[test]
3438    fn domain_tags_are_distinct_and_prefix_free() {
3439        // Security invariant: row and checkpoint signatures can never
3440        // cross-verify because their signed messages start with distinct,
3441        // prefix-free domain tags.
3442        // Checked pairwise over the whole set rather than as a hand-written
3443        // list: adding a fourth tag to a hand-written list silently leaves the
3444        // new tag unchecked against the old ones.
3445        let tags: [(&str, &[u8]); 4] = [
3446            ("row", ROW_DOMAIN),
3447            ("checkpoint", CHECKPOINT_DOMAIN),
3448            ("approval", APPROVAL_DOMAIN),
3449            ("event", EVENT_DOMAIN),
3450        ];
3451        for (i, (name_a, a)) in tags.iter().enumerate() {
3452            for (name_b, b) in tags.iter().skip(i + 1) {
3453                assert_ne!(a, b, "{name_a} and {name_b} share a domain tag");
3454                assert!(!a.starts_with(b), "{name_a} is prefixed by {name_b}");
3455                assert!(!b.starts_with(a), "{name_b} is prefixed by {name_a}");
3456            }
3457        }
3458    }
3459
3460    #[test]
3461    fn approval_receipt_framing_is_injective() {
3462        // The signed receipt message must be injective in
3463        // (transaction_id, request_hash). Without `push_field` escaping, the
3464        // ambiguous pair below would collide because a raw 0x1F separator
3465        // cannot be distinguished from a 0x1F inside a field value.
3466        let key = fixed_key();
3467        let sep = "\u{1f}";
3468        let a = key.approval_receipt(&format!("tx{sep}b"), "c");
3469        let b = key.approval_receipt("tx", &format!("b{sep}c"));
3470        assert_ne!(a, b, "0x1F in a field must not alias distinct receipts");
3471
3472        // Sanity: the derivation is deterministic (Ed25519, same inputs).
3473        assert_eq!(
3474            key.approval_receipt("tx-1", "hash-1"),
3475            key.approval_receipt("tx-1", "hash-1"),
3476        );
3477        // And the commitment is exactly SHA-256 of the receipt.
3478        assert_eq!(
3479            key.approval_commitment("tx-1", "hash-1"),
3480            approval_receipt_digest(&key.approval_receipt("tx-1", "hash-1")),
3481        );
3482    }
3483}