hyprstream_core/mac/audit.rs
1//! S7 (#573, epic #547) — tamper-evident, complete audit of every MAC
2//! authorization decision, with OpenTelemetry fan-out.
3//!
4//! This is the **Accounting** leg of the MAC security model: every allow/deny
5//! the PDP ([`crate::mac::avc`]) produces is recorded tamper-evidently, and a
6//! decision that cannot be audited is **denied** (fail-closed). The store is a
7//! data-plane structure — append-only, content-addressed, signed, and
8//! WAL-durable on write (a write is durable before the decision returns).
9//!
10//! ## Design (the four properties the task requires)
11//!
12//! 1. **Append-only** — the on-disk log is opened append-only; the API exposes
13//! no mutate/delete. The CAS layer writes content-addressed blobs whose
14//! names are their own hash, so overwrites are no-ops and a name never
15//! points at different bytes. See [`WalAuditStore`] and its tests.
16//! 2. **Content-addressed** — every [`AuditRecord`] is BLAKE3-hashed over its
17//! *canonical* CBOR encoding (deterministic: sorted maps, sorted keys), so
18//! the same decision yields the same hash ([`AuditRecord::content_hash`]).
19//! Tamper-evident by construction: changing any field changes the hash,
20//! which breaks the signature that covers it.
21//! 3. **WAL-durable on write** — [`WalAuditStore::record`] appends the signed
22//! record to a journal, then `fsync`s the file **and** its parent directory
23//! before returning `Ok(())`. The caller (the AVC) does not return a Permit
24//! until `record` returns, so a Permit is never handed out ahead of a
25//! durable audit entry. See the `wal_record_is_durable_before_return` test.
26//! 4. **Signed + hash-chained** — each record is signed via the existing COSE
27//! path ([`crate::mac::compiled::cose`] / `sign_composite`), and each record
28//! carries the [`prev_hash`](AuditRecord::prev_hash) of its predecessor, so
29//! the journal is an append-only **chain**. Tamper evidence is conjoint:
30//! altering a record breaks its hash (and thus its signature); reordering or
31//! deleting a *middle* record breaks the successor's `prev_hash` link. A
32//! deleted *tail* leaves a still-valid shorter chain, so it is caught
33//! instead by the **signed checkpoint** (§ Truncation) — the head anchor
34//! written out-of-band after every record.
35//!
36//! ## Truncation detection (the actual guarantee — and its limit)
37//!
38//! After every durable append, the store writes a **signed checkpoint** (a
39//! separate `checkpoint` file) recording the current head `(seq, head_hash)`.
40//! On open, the store fails closed if the journal's head sequence is *below*
41//! the checkpoint's — i.e. the tail was truncated. [`WalAuditStore::
42//! verify_journal`] additionally verifies the checkpoint's signature and that
43//! it matches the journal head, so a forged or rolled-back checkpoint is
44//! rejected offline.
45//!
46//! **Residual limit (honest):** the checkpoint is a *local* anchor. An attacker
47//! with write access to BOTH the journal and the checkpoint can truncate both
48//! consistently and evade local detection. Closing that requires an *off-host*
49//! anchor (replicate the signed head to OTel / a second host); that is tracked
50//! as a follow-up and deliberately out of scope here. What this store
51//! guarantees today: no tampering, reordering, or middle-deletion goes
52//! undetected, and tail-truncation is detected unless the checkpoint is
53//! destroyed in the same act.
54//!
55//! ## Complete mediation (the hook point)
56//!
57//! [`AuditedAvc`] wraps any [`Avc`] and routes **every** `decide` /
58//! `decide_with_token` call through the audit sink. Because the AVC is the
59//! single per-op entry point the PEP (S2) calls, auditing there is complete
60//! mediation: no decision bypasses it. On a cache *hit* the cached decision is
61//! still re-recorded (cheap: a hash + append + fsync) so the audit log reflects
62//! every op the PEP actually performed, not just PDP misses — completeness over
63//! cache efficiency.
64//!
65//! ## Fail-closed on audit failure
66//!
67//! If the audit write fails (disk full, IO error, signer error), the audited
68//! AVC **downgrades a Permit to Deny** and records the deny it actually
69//! enforced. A decision that cannot be audited is never allowed through. This
70//! is the explicit fail-closed contract; see the `permit_downgrades_to_deny_`
71//! `when_audit_write_fails` test.
72//!
73//! ## OpenTelemetry fan-out (fixes #453)
74//!
75//! Every decision emits a structured [`tracing`] event on the dedicated
76//! `hyprstream.mac.audit` target with fields `decision`, `subject`, `resource`,
77//! `action`, `generation`, and `reason`. OTel is wired as a `tracing`
78//! subscriber (see `bin/main.rs` `init_telemetry`), so these events fan out to
79//! OTLP automatically when the `otel` feature is active — denials become
80//! first-class observable signals, no longer buried at `debug` level.
81//!
82//! ## What is deferred (documented TODOs)
83//!
84//! - **Cross-host replication** of the audit store — S7 ships the local
85//! tamper-evident store; replication (gossip/OTLP log export to a central
86//! audit collector) is `TODO(S7-followup):` in [`WalAuditStore`].
87//! - **Retention / rotation** — the journal grows unbounded; rotation + remote
88//! archival is `TODO(S7-followup):` below.
89//! - **Policy-evolution feedback** — denials feeding back into PolicyService is
90//! `TODO(S7-followup):` — the records are here, the consumer is not.
91//! - **Hybrid (EdDSA + ML-DSA-65) signing of audit records** — S8 (#574) made
92//! the [`cose::CoseAuditSigner`] policy-aware: under a Hybrid crypto policy it
93//! fails closed if no ML-DSA-65 key is provisioned (no silent downgrade of a
94//! security-critical accounting artifact). Production wiring of the audited
95//! AVC (constructing a `WalAuditStore` with the node's PQ audit key and
96//! installing it in the PEP) is `TODO(S7-followup):`.
97
98use crate::mac::avc::{Avc, TokenScope};
99use crate::mac::lattice::SecurityLabel;
100use crate::mac::te::{Action, Decision, ObjectCtx, ObjectType, SubjectCtx, SubjectType};
101use parking_lot::Mutex;
102use serde::{Deserialize, Serialize};
103use std::fs::{File, OpenOptions};
104use std::io::{Read, Seek, SeekFrom, Write};
105use std::path::{Path, PathBuf};
106use std::sync::Arc;
107use thiserror::Error;
108
109// ────────────────────────────────────────────────────────────────────────────
110// The record
111// ────────────────────────────────────────────────────────────────────────────
112
113/// The delegator principal recorded on a **delegated** (two-principal, #680/#681)
114/// decision — the source of authority on whose behalf the record's `subject_*`
115/// (the effective, met context) was evaluated.
116///
117/// The audit record identifies principals by their **resolved MAC context**
118/// (TE type + S1 clearance), never caller-asserted strings — the same grain as
119/// `AuditRecord`'s `subject_*`. On the S6 grant path both this and the subject
120/// carry the [`crate::mac::te::GRANT_PATH_SUBJECT`] sentinel type, and the
121/// clearance is the distinguishing field.
122///
123/// Why the delegator and not the actor: the record's `subject_clearance` is
124/// already the effective `meet(delegator, actor)` clearance the PDP evaluated —
125/// and its **assurance is the actor's** (the meet clamps assurance to the
126/// signer's verified key material, #548/#681), so the actor's contribution is
127/// auditable directly on `subject_*`. The delegator is the missing half: the
128/// user-attribution (#445) a confused-deputy call would otherwise lose. Both
129/// source principals are therefore recoverable — the actor's clearance
130/// assurance from `subject_clearance`, the delegator here — and the effective
131/// clearance the decision actually rested on is `subject_clearance` itself.
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
133pub struct DelegationPrincipal {
134 /// TE subject type of the delegator (SELinux domain); the grant path uses
135 /// the [`crate::mac::te::GRANT_PATH_SUBJECT`] sentinel.
136 pub subject_type: SubjectType,
137 /// The delegator's clearance label (S1). MAC provenance for the authority
138 /// source.
139 pub subject_clearance: SecurityLabel,
140}
141
142/// A single authorization decision, as recorded by the audit store. This is
143/// the unit of tamper-evidence: it is content-addressed (BLAKE3 over canonical
144/// CBOR), signed, and append-logged.
145///
146/// Provenance is carried explicitly:
147/// - `generation` — the policy generation (lattice version) that produced the
148/// decision; binds the record to the exact compiled policy in force.
149/// - `policy_hash` — the BLAKE3 of the [`crate::mac::compiled::CompiledPolicy`]
150/// that governed this decision, when known (`None` for ad-hoc evaluators).
151/// - `subject_*` / `object_*` — the resolved security contexts (TE type +
152/// S1 label) the PDP actually saw, not caller-asserted strings.
153/// - `on_behalf_of` — for a delegated decision, the delegator principal
154/// (#680/#681); `None` for an ordinary single-principal decision.
155/// - `reason` — why the PDP decided as it did (floor failure, TE miss, token
156/// gate, audit-fail-closed, ...).
157///
158/// MAC labels are carried **as the structured `SecurityLabel`** on the subject
159/// (clearance) and object (label) — the audit store is itself MAC-relevant
160/// content (a rollup of decisions), so it carries the labels of the decisions
161/// it records.
162#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
163pub struct AuditRecord {
164 /// Monotonic sequence number within this store's journal, assigned by the
165 /// store. A gap in the on-disk sequence exposes a *middle* deletion; a
166 /// deleted *tail* is caught instead by [`prev_hash`](Self::prev_hash)
167 /// chaining plus the signed checkpoint (see [`WalAuditStore`]).
168 pub seq: u64,
169 /// Hash-chain link: the BLAKE3 content hash of the **previous** record in
170 /// this store's journal (`[0; 32]` for the genesis record). Assigned by the
171 /// store under the same lock that assigns `seq`, and covered by this
172 /// record's own signature (it is part of the hashed content). Reordering,
173 /// or deleting/altering any record, breaks the successor's link — so the
174 /// journal is an append-only chain, not just a sequence of independent
175 /// signed lines.
176 pub prev_hash: [u8; 32],
177 /// Wall-clock nanos since UNIX epoch when the decision was recorded.
178 pub ts_unix_nanos: u128,
179 /// The decision the PDP returned (`Permit` / `Deny` / `Escalate`).
180 pub decision: Decision,
181 /// The policy generation in force (lattice version). Provenance.
182 pub generation: u64,
183 /// Optional BLAKE3 of the governing `CompiledPolicy` (`None` for ad-hoc
184 /// evaluators that were not loaded from a signed policy).
185 pub policy_hash: Option<[u8; 32]>,
186 /// TE subject type (SELinux domain).
187 pub subject_type: SubjectType,
188 /// The subject's clearance label (S1). MAC provenance for the subject. On a
189 /// delegated decision this is the **effective** `meet(delegator, actor)`
190 /// clearance the PDP evaluated (assurance clamped to the actor's signer key,
191 /// #548/#681); the delegator half is recorded in [`Self::on_behalf_of`].
192 pub subject_clearance: SecurityLabel,
193 /// For a **delegated** decision (#680/#681), the delegator principal — the
194 /// source of authority on whose behalf `subject_*` acted. `None` for an
195 /// ordinary single-principal decision.
196 ///
197 /// **Versioned by omission:** serialized only when `Some`, so a
198 /// single-principal record's canonical bytes (and therefore its content
199 /// hash and its successor's `prev_hash` link) are byte-identical to the
200 /// pre-delegation schema — the hash chain is preserved across the upgrade.
201 #[serde(default, skip_serializing_if = "Option::is_none")]
202 pub on_behalf_of: Option<DelegationPrincipal>,
203 /// TE object type.
204 pub object_type: ObjectType,
205 /// The object's content-bound label (S1). MAC provenance for the object.
206 pub object_label: SecurityLabel,
207 /// The action / op being authorized.
208 pub action: Action,
209 /// Human-readable decision reason (which gate denied, or "permit").
210 pub reason: DecisionReason,
211 /// Independently verified application principal, when the enforcement
212 /// plane has a stable identifier. Omitted for legacy/type-only records.
213 #[serde(default, skip_serializing_if = "Option::is_none")]
214 pub subject_id: Option<String>,
215 /// Concrete tenant-qualified object/track, when known. Omitted for
216 /// legacy/type-only records.
217 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub object_id: Option<String>,
219}
220
221/// Why the PDP returned this decision. Recorded so denials are diagnosable and
222/// so the policy-evolution feedback (deferred) can bucket denials by cause.
223#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
224pub enum DecisionReason {
225 /// Both the TE matrix and the lattice floor permitted the op.
226 Permit,
227 /// The MAC lattice floor denied (clearance does not dominate label).
228 FloorDeny,
229 /// The PEP could not resolve a content-bound label for the object.
230 UnlabeledObject,
231 /// The PEP could not derive a verified subject clearance.
232 NoClearance,
233 /// A write was denied because the system's IFC write direction is not yet
234 /// ratified. Writes fail closed until that policy decision is made.
235 WriteDirectionUndecided,
236 /// The TE matrix had no allow (and no escalate) entry for the triple.
237 TeMiss,
238 /// The decision was `Escalate` (floor held, TE escalate-band hit).
239 Escalate,
240 /// The token gate denied (expired token or op outside the token op-set).
241 TokenGate,
242 /// **Fail-closed:** the audit write failed, so a Permit was downgraded to
243 /// Deny. This is itself auditable (the deny is what the PEP enforced).
244 AuditFailClosed,
245 /// The active MoQ/event PEP could not derive subject clearance.
246 MoqUnlabeledSubject,
247 /// The explicitly installed MoQ/event PEP had no operational policy.
248 MoqNoPepInstalled,
249 /// A streaming continuation's MoQ authority was stale or revoked.
250 MoqStaleAuthority,
251 /// The MoQ/event boundary coordinate did not decode into a typed
252 /// track/prefix identity (malformed grammar, noncanonical service
253 /// segment, or an internal map key passed as an identity).
254 MoqUnknownObjectIdentity,
255 /// Track admission was denied because moq-net has no #276 callback.
256 MoqTrackAdmissionHookUnavailable,
257
258 // ── B2 (#674): the S6 grant-path decision kind (see [`crate::mac::te::
259 // GRANT_PATH_SUBJECT`]). One variant per `mac::exchange::GrantError`
260 // gate, so a grant denial's cause is as diagnosable as a TE denial's. ──
261 /// No DPoP sender-binding proof was supplied (ZSP gate 1).
262 GrantMissingSenderBinding,
263 /// The presented grant carries no capabilities at all (gate 2).
264 GrantEmptyGrant,
265 /// The subject carried no derivable MAC clearance (gate 3, S1 floor).
266 GrantUnlabeledSubject,
267 /// The MAC clearance floor denied for a grant request (gate 5). Distinct
268 /// from [`DecisionReason::FloorDeny`] (a TE-path floor denial) so a grant
269 /// vs. per-op floor denial is distinguishable in the audit trail. Also
270 /// covers gate 4 (unlabeled object), which `evaluate_grant` maps to the
271 /// same `GrantError::InsufficientClearance`.
272 GrantFloorDeny,
273 /// The UCAN chain failed S5 validation (gate 6: bad signature, broken
274 /// linkage, widening, window escape, expiry, over-depth).
275 GrantChainInvalid,
276 /// The request exceeded the grant's ceiling (gate 7) — an escalation
277 /// attempt, denied pending a ceiling amendment (S6 does not auto-widen).
278 GrantOverCeiling,
279 /// A grant was `Permit`, but the caller's `sink` (or checking `can_sign`
280 /// preflight) could not durably audit it — the permit is downgraded to
281 /// deny, mirroring [`DecisionReason::AuditFailClosed`] for the grant path.
282 GrantAuditFailClosed,
283 /// Native Event service identity does not own the requested source/op.
284 MoqSourceOwnershipDenied,
285}
286
287impl DecisionReason {
288 #[inline]
289 pub fn as_str(self) -> &'static str {
290 match self {
291 DecisionReason::Permit => "permit",
292 DecisionReason::FloorDeny => "floor_deny",
293 DecisionReason::UnlabeledObject => "unlabeled_object",
294 DecisionReason::NoClearance => "no_clearance",
295 DecisionReason::WriteDirectionUndecided => "write_direction_undecided",
296 DecisionReason::TeMiss => "te_miss",
297 DecisionReason::Escalate => "escalate",
298 DecisionReason::TokenGate => "token_gate",
299 DecisionReason::AuditFailClosed => "audit_fail_closed",
300 DecisionReason::MoqUnlabeledSubject => "moq_unlabeled_subject",
301 DecisionReason::MoqNoPepInstalled => "moq_no_pep_installed",
302 DecisionReason::MoqStaleAuthority => "moq_stale_authority",
303 DecisionReason::MoqSourceOwnershipDenied => "moq_source_ownership_denied",
304 DecisionReason::MoqUnknownObjectIdentity => "moq_unknown_object_identity",
305 DecisionReason::MoqTrackAdmissionHookUnavailable => {
306 "moq_track_admission_hook_unavailable"
307 }
308 DecisionReason::GrantMissingSenderBinding => "grant_missing_sender_binding",
309 DecisionReason::GrantEmptyGrant => "grant_empty_grant",
310 DecisionReason::GrantUnlabeledSubject => "grant_unlabeled_subject",
311 DecisionReason::GrantFloorDeny => "grant_floor_deny",
312 DecisionReason::GrantChainInvalid => "grant_chain_invalid",
313 DecisionReason::GrantOverCeiling => "grant_over_ceiling",
314 DecisionReason::GrantAuditFailClosed => "grant_audit_fail_closed",
315 }
316 }
317}
318
319impl AuditRecord {
320 /// Canonical CBOR encoding for hashing/signing.
321 ///
322 /// Fu6/#677: this is real canonical CBOR via [`ciborium`] (the same CBOR
323 /// runtime the UCAN grant / COSE layers use), not `serde_json`. The module
324 /// docs, the WAL journal framing, and the S7 signed checkpoint all describe
325 /// the content-addressed digest as taken over *canonical CBOR*; the
326 /// previous `serde_json::to_vec` impl made the docs a lie and pinned the
327 /// hash to JSON's incidental field order — a hash-stability hazard on any
328 /// struct evolution that touched serde representation.
329 ///
330 /// Determinism: `ciborium` emits map keys in serde struct-field order, so
331 /// the same `AuditRecord` always serializes to identical bytes for a given
332 /// binary. This matches the canonical-CBOR convention used by the UCAN
333 /// grant's `signing_bytes` — see the `golden_content_hash_is_stable` test,
334 /// which pins a known record to a fixed BLAKE3 so any drift in the
335 /// canonical encoding is caught.
336 pub fn canonical_bytes(&self) -> Result<Vec<u8>, AuditError> {
337 let mut buf = Vec::new();
338 ciborium::ser::into_writer(self, &mut buf)
339 .map_err(|e| AuditError::Encode(e.to_string()))?;
340 Ok(buf)
341 }
342
343 /// BLAKE3 content hash of the canonical bytes — the content-addressed key
344 /// under which this record is stored in the CAS layer. Same decision ⇒
345 /// same hash (the test asserts this).
346 pub fn content_hash(&self) -> Result<[u8; 32], AuditError> {
347 let bytes = self.canonical_bytes()?;
348 Ok(*blake3::hash(&bytes).as_bytes())
349 }
350}
351
352// ────────────────────────────────────────────────────────────────────────────
353// Errors
354// ────────────────────────────────────────────────────────────────────────────
355
356/// Audit-store failures. All are fail-closed at the AVC boundary.
357#[derive(Error, Debug)]
358pub enum AuditError {
359 #[error("audit record encode failed: {0}")]
360 Encode(String),
361 #[error("audit record decode failed: {0}")]
362 Decode(String),
363 #[error("audit store IO failed: {0}")]
364 Io(String),
365 #[error("audit signature failed: {0}")]
366 Sign(String),
367 #[error("audit signature verification failed: {0}")]
368 Verify(String),
369 #[error("audit sequence regression: journal seq {journal} < counter {counter}")]
370 SeqRegression { journal: u64, counter: u64 },
371 /// The `prev_hash` chain is broken at `seq`: this record does not link to
372 /// its predecessor's hash (tampering, reordering, or a middle deletion).
373 #[error("audit chain break at seq {seq}: prev_hash does not match predecessor")]
374 ChainBreak { seq: u64 },
375 /// The signed checkpoint is ahead of the journal head: the journal tail was
376 /// truncated since the last durable write. `journal_seq` is the journal's
377 /// current head seq (`None` if the journal is empty/absent).
378 #[error(
379 "audit journal truncated: checkpoint at seq {checkpoint_seq}, journal head {journal_seq:?}"
380 )]
381 Truncation {
382 checkpoint_seq: u64,
383 journal_seq: Option<u64>,
384 },
385}
386
387impl From<std::io::Error> for AuditError {
388 fn from(e: std::io::Error) -> Self {
389 AuditError::Io(e.to_string())
390 }
391}
392
393// ────────────────────────────────────────────────────────────────────────────
394// Signing abstraction (mirrors mac::compiled::PolicySigner)
395// ────────────────────────────────────────────────────────────────────────────
396
397/// Abstraction over the authority that signs audit records. Production wires
398/// the hybrid COSE composite (EdDSA + ML-DSA-65) via
399/// [`crate::mac::compiled::cose`]; tests use a trivial stub.
400//
401// S8 (#574): the production audit signer signs with the hybrid composite
402// (EdDSA + ML-DSA-65), the same construction `mac::compiled::cose` uses. The
403// `CoseAuditSigner` is policy-aware: under a Hybrid policy with `require_pq`
404// it FAILS CLOSED if no ML-DSA-65 key is provisioned, rather than silently
405// emitting a classical-only signature (which would be a downgrade of a
406// security-critical accounting artifact). A Classical-only deployment passes
407// `require_pq = false` and gets classical EdDSA-only audit signatures (still
408// tamper-evident, not PQ-forgery-resistant) — the explicit, policy-selected
409// pinned suite, never an in-band downgrade.
410pub trait AuditSigner: Send + Sync {
411 /// Sign the record's signing input (see [`audit_signing_input`]).
412 fn sign(&self, signing_input: &[u8]) -> Result<Vec<u8>, AuditError>;
413}
414
415/// Abstraction over signature verification (for log-integrity checks / replay).
416pub trait AuditVerifier: Send + Sync {
417 /// Verify `signature` over `signing_input`. `Ok(())` on success.
418 fn verify(&self, signing_input: &[u8], signature: &[u8]) -> Result<(), AuditError>;
419}
420
421/// Domain-separated signing input: a fixed tag + the content hash. Binding the
422/// hash (not the raw bytes) keeps the signed payload small and stable, and
423/// makes the signature independent of the canonical-bytes serialization choice.
424pub fn audit_signing_input(content_hash: &[u8; 32]) -> Vec<u8> {
425 let mut v = Vec::with_capacity(16 + 32);
426 v.extend_from_slice(b"hs-mac-audit-v1"); // domain separation tag
427 v.extend_from_slice(content_hash);
428 v
429}
430
431/// Domain-separated signing input for the head-anchor checkpoint `(seq,
432/// head_hash)`. The tag differs from [`audit_signing_input`] so a per-record
433/// signature can never be replayed as a checkpoint signature (and vice-versa).
434pub fn checkpoint_signing_input(seq: u64, head_hash: &[u8; 32]) -> Vec<u8> {
435 let mut v = Vec::with_capacity(24 + 8 + 32);
436 v.extend_from_slice(b"hs-mac-audit-checkpoint-v1");
437 v.extend_from_slice(&seq.to_be_bytes());
438 v.extend_from_slice(head_hash);
439 v
440}
441
442/// Production signer/verifier adapters over `hyprstream_rpc::crypto::cose_sign`,
443/// mirroring [`crate::mac::compiled::cose`].
444///
445/// S8 (#574): the signer is policy-aware. Construct it via
446/// [`CoseAuditSigner::new`] with the node's enforced
447/// [`CryptoPolicy`](hyprstream_rpc::crypto::CryptoPolicy). Under a Hybrid policy
448/// it FAILS CLOSED at sign time if no ML-DSA-65 key is provisioned — an audit
449/// record is a security-critical accounting artifact and silently emitting an
450/// Ed25519-only signature under a Hybrid policy would be an in-band downgrade.
451/// The construction is the hybrid nested COSE composite; the key management is
452/// the caller's job (the node provisions the PQ audit key from the same
453/// `MlDsaSigningKeyStore` the token mint uses).
454pub mod cose {
455 use super::{AuditError, AuditSigner, AuditVerifier};
456 use ed25519_dalek::{SigningKey, VerifyingKey};
457 use hyprstream_rpc::crypto::cose_sign::{sign_composite, verify_composite};
458 use hyprstream_rpc::crypto::pq::{MlDsaSigningKey, MlDsaVerifyingKey};
459 use std::sync::Arc;
460
461 /// Domain-separation AAD for audit-record signatures (distinct from
462 /// policy/envelope AADs so an audit signature can never be replayed as
463 /// another message type).
464 pub const AUDIT_AAD: &[u8] = b"hs-mac-audit-v1";
465
466 /// Hybrid (EdDSA + ML-DSA-65) signer for audit records, policy-aware.
467 ///
468 /// Construct with [`CoseAuditSigner::new`], passing the node's enforced
469 /// [`CryptoPolicy`](hyprstream_rpc::crypto::CryptoPolicy). Under `Hybrid` the
470 /// ML-DSA-65 key is REQUIRED (fail-closed at sign time if absent); under
471 /// `Classical` it is OPTIONAL and a classical EdDSA-only signature is
472 /// emitted (the explicit, policy-selected pinned suite).
473 pub struct CoseAuditSigner<'a> {
474 ed_sk: &'a SigningKey,
475 pq_sk: Option<&'a MlDsaSigningKey>,
476 require_pq: bool,
477 }
478
479 impl<'a> CoseAuditSigner<'a> {
480 /// Construct a policy-aware audit signer.
481 ///
482 /// `policy` is the node's enforced crypto policy. `pq_sk` is the
483 /// provisioned ML-DSA-65 audit signing key (from the node's
484 /// `MlDsaSigningKeyStore`). Under `Hybrid`: `pq_sk = Some` produces a
485 /// hybrid composite (EdDSA + ML-DSA-65); `pq_sk = None` makes
486 /// construction succeed but every [`AuditSigner::sign`] FAILS CLOSED
487 /// (an audit record cannot be downgraded to classical under a Hybrid
488 /// policy — use [`Self::can_sign`] to check ahead of a hot path;
489 /// production MUST provision the PQ key under Hybrid). Under
490 /// `Classical`: `pq_sk` is ignored and EdDSA-only signatures are
491 /// emitted (the policy-selected suite).
492 pub fn new(
493 ed_sk: &'a SigningKey,
494 pq_sk: Option<&'a MlDsaSigningKey>,
495 policy: hyprstream_rpc::crypto::CryptoPolicy,
496 ) -> Self {
497 Self {
498 ed_sk,
499 // Under Classical the PQ key is ignored; coerce to None so the
500 // sign path unambiguously emits EdDSA-only (no silent hybrid).
501 pq_sk: if policy.uses_pq() { pq_sk } else { None },
502 require_pq: policy.uses_pq(),
503 }
504 }
505
506 /// Whether this signer can produce a signature under its policy: under
507 /// Hybrid this requires the PQ key; under Classical it always can.
508 /// Production wiring SHOULD check this at startup and fail to boot if
509 /// false under Hybrid (no audit signer ⇒ no Permit, per the S7
510 /// fail-closed contract).
511 #[must_use]
512 pub fn can_sign(&self) -> bool {
513 !self.require_pq || self.pq_sk.is_some()
514 }
515 }
516
517 impl AuditSigner for CoseAuditSigner<'_> {
518 fn sign(&self, signing_input: &[u8]) -> Result<Vec<u8>, AuditError> {
519 // Fail-closed: a Hybrid policy requires the ML-DSA-65 audit key. A
520 // missing key here is a provisioning bug; we refuse to emit a
521 // classical-only audit signature under Hybrid rather than silently
522 // downgrading a security-critical accounting artifact.
523 if self.require_pq && self.pq_sk.is_none() {
524 return Err(AuditError::Sign(
525 "Hybrid crypto policy requires an ML-DSA-65 audit signing key, none provisioned (fail-closed)".to_owned(),
526 ));
527 }
528 sign_composite(self.ed_sk, self.pq_sk, signing_input, AUDIT_AAD)
529 .map_err(|e| AuditError::Sign(e.to_string()))
530 }
531 }
532
533 /// Owned-key variant of [`CoseAuditSigner`] (B2, #674): production wiring
534 /// stores this on `OAuthState`/`AuditedAvc`, both of which must be
535 /// `'static` — a borrowed signer cannot live there. Holds `Arc`s to the
536 /// same key material a borrowed [`CoseAuditSigner`] would reference (a
537 /// startup-time snapshot of the node's active EdDSA + ML-DSA-65 keys), and
538 /// signs with the IDENTICAL fail-closed logic: under Hybrid, a missing PQ
539 /// key fails every `sign` call rather than downgrading.
540 pub struct OwnedCoseAuditSigner {
541 ed_sk: Arc<SigningKey>,
542 pq_sk: Option<Arc<MlDsaSigningKey>>,
543 require_pq: bool,
544 }
545
546 impl OwnedCoseAuditSigner {
547 /// Construct from owned key material + the node's enforced
548 /// [`CryptoPolicy`](hyprstream_rpc::crypto::CryptoPolicy). See
549 /// [`CoseAuditSigner::new`] for the exact Hybrid/Classical semantics —
550 /// identical here.
551 pub fn new(
552 ed_sk: Arc<SigningKey>,
553 pq_sk: Option<Arc<MlDsaSigningKey>>,
554 policy: hyprstream_rpc::crypto::CryptoPolicy,
555 ) -> Self {
556 Self {
557 ed_sk,
558 pq_sk: if policy.uses_pq() { pq_sk } else { None },
559 require_pq: policy.uses_pq(),
560 }
561 }
562
563 /// As [`CoseAuditSigner::can_sign`]: whether this signer can produce a
564 /// signature under its policy. Production wiring MUST check this at
565 /// startup and refuse to boot the audited grant path if false under
566 /// Hybrid (no audit signer ⇒ no Permit, per the S7 fail-closed
567 /// contract) — see `OAuthState::with_audit_sink`.
568 #[must_use]
569 pub fn can_sign(&self) -> bool {
570 !self.require_pq || self.pq_sk.is_some()
571 }
572 }
573
574 impl AuditSigner for OwnedCoseAuditSigner {
575 fn sign(&self, signing_input: &[u8]) -> Result<Vec<u8>, AuditError> {
576 if self.require_pq && self.pq_sk.is_none() {
577 return Err(AuditError::Sign(
578 "Hybrid crypto policy requires an ML-DSA-65 audit signing key, none provisioned (fail-closed)".to_owned(),
579 ));
580 }
581 sign_composite(&self.ed_sk, self.pq_sk.as_deref(), signing_input, AUDIT_AAD)
582 .map_err(|e| AuditError::Sign(e.to_string()))
583 }
584 }
585
586 /// Hybrid verifier. `require_pq = true` enforces the ML-DSA outer layer.
587 pub struct CoseAuditVerifier<'a> {
588 pub ed_vk: &'a VerifyingKey,
589 pub pq_vk: Option<&'a MlDsaVerifyingKey>,
590 pub require_pq: bool,
591 }
592
593 impl AuditVerifier for CoseAuditVerifier<'_> {
594 fn verify(&self, signing_input: &[u8], signature: &[u8]) -> Result<(), AuditError> {
595 verify_composite(
596 signature,
597 self.ed_vk,
598 self.pq_vk,
599 signing_input,
600 AUDIT_AAD,
601 self.require_pq,
602 )
603 .map(|_| ())
604 .map_err(|e| AuditError::Verify(e.to_string()))
605 }
606 }
607}
608
609// ────────────────────────────────────────────────────────────────────────────
610// The sink trait (what the AVC calls)
611// ────────────────────────────────────────────────────────────────────────────
612
613/// Where the audited AVC sends records. The authoritative impl is
614/// [`WalAuditStore`]; tests / non-durable deployments can swap a no-op or
615/// in-memory sink. **Fail-closed contract**: a `record` error makes the
616/// audited AVC downgrade a Permit to Deny (see [`AuditedAvc`]).
617pub trait AuditSink: Send + Sync {
618 /// Durably record `record`. Returns `Ok(())` only after the write is
619 /// durable (fsynced). The caller MUST treat `Err` as fail-closed.
620 fn record(&self, record: &AuditRecord) -> Result<(), AuditError>;
621}
622
623// Blanket forwarding so `Arc<T: AuditSink>` etc. are themselves sinks — the
624// natural shape for a sink shared between the AVC and the test harness / a
625// fan-out bus. This mirrors how `Clone`/`Deref` propagate through `Arc`.
626impl<T: AuditSink + ?Sized> AuditSink for Arc<T> {
627 #[inline]
628 fn record(&self, record: &AuditRecord) -> Result<(), AuditError> {
629 (**self).record(record)
630 }
631}
632
633/// A no-op sink for environments that opt out of durable audit (e.g. tests of
634/// the PDP itself that are not exercising S7). **Not for production** —
635/// production requires tamper-evident audit, which this provides none of.
636#[derive(Debug, Default, Clone)]
637pub struct NullAuditSink;
638
639impl AuditSink for NullAuditSink {
640 #[inline]
641 fn record(&self, _record: &AuditRecord) -> Result<(), AuditError> {
642 Ok(())
643 }
644}
645
646// ────────────────────────────────────────────────────────────────────────────
647// The authoritative data-plane store: append-only journal + CAS + signed
648// ────────────────────────────────────────────────────────────────────────────
649
650/// The authoritative tamper-evident audit store. Append-only journal +
651/// content-addressed CAS blobs, each record signed. WAL-durable on write.
652///
653/// ## On-disk layout
654/// ```text
655/// <root>/
656/// journal.log # append-only: one signed record per line (newline-framed
657/// # <seq>\t<sig_hex>\t<payload_b64>\n)
658/// checkpoint # signed head anchor, rewritten after every append:
659/// # <seq>\t<head_hash_hex>\t<sig_hex>\n
660/// cas/<ab>/<cdef…> # content-addressed blob per record: the canonical bytes,
661/// # named by their BLAKE3 hex (name==bytes tamper check).
662/// ```
663/// The CAS layer gives a second tamper-evidence check (the blob's name is its
664/// hash). The journal is an append-only **hash chain** (each record carries its
665/// predecessor's hash), and the signed `checkpoint` anchors the head so a
666/// truncated tail is detected on open (see the module docs).
667///
668/// ## What is NOT here (deferred)
669/// - TODO(S7-followup): cross-host replication (gossip / OTLP log export to a
670/// central collector). The local store is tamper-evident; remote collection
671/// is a transport concern.
672/// - TODO(S7-followup): retention / rotation. The journal grows unbounded
673/// today; a rotating appender + remote archival is a follow-up.
674/// - TODO(S7-followup): policy-evolution feedback (denial bucketing →
675/// PolicyService). The records are here; the consumer is not.
676pub struct WalAuditStore<S: AuditSigner> {
677 root: PathBuf,
678 journal_path: PathBuf,
679 checkpoint_path: PathBuf,
680 cas_dir: PathBuf,
681 signer: S,
682 /// The chain head: the next sequence number to assign and the content hash
683 /// of the last record written. Guarded by a mutex because the hash chain
684 /// requires record assignment (seq + prev_hash) and the journal append to
685 /// be serialized — two concurrent appends must not interleave or the chain
686 /// forks. (The previous `AtomicU64` seq did not order the appends.)
687 head: Mutex<ChainHead>,
688}
689
690/// The mutable chain head of a [`WalAuditStore`].
691#[derive(Debug, Clone, Copy)]
692struct ChainHead {
693 /// The sequence number the next record will receive.
694 next_seq: u64,
695 /// BLAKE3 content hash of the last record written (`[0; 32]` before any).
696 head_hash: [u8; 32],
697}
698
699impl<S: AuditSigner> WalAuditStore<S> {
700 /// Open (or create) a store at `root`. The journal and CAS dir are created
701 /// if missing. The chain head (next `seq` + `head_hash`) is seeded from the
702 /// journal's last record so a restart continues the chain monotonically.
703 ///
704 /// **Fail-closed truncation check:** if a signed checkpoint exists and its
705 /// sequence is *ahead* of the journal's last record, the tail was truncated
706 /// since the last durable write — [`open`](Self::open) refuses to start
707 /// (`AuditError::Truncation`) rather than silently continuing on a shortened
708 /// log (which would re-seed the seq counter from the truncated head and
709 /// erase the evidence). Full cryptographic verification of the chain and the
710 /// checkpoint signature is [`verify_journal`](Self::verify_journal).
711 pub fn open(root: impl AsRef<Path>, signer: S) -> Result<Self, AuditError> {
712 let root = root.as_ref().to_path_buf();
713 let journal_path = root.join("journal.log");
714 let checkpoint_path = root.join("checkpoint");
715 let cas_dir = root.join("cas");
716 std::fs::create_dir_all(&root)?;
717 std::fs::create_dir_all(&cas_dir)?;
718
719 // Seed the chain head from the journal's last record: the next record
720 // continues *after* the last seq, chained to the last record's hash.
721 let tail = journal_tail(&journal_path)?;
722 let (next_seq, head_hash) = match tail {
723 Some((seq, hash)) => (seq + 1, hash),
724 None => (0, [0u8; 32]),
725 };
726
727 // Fail-closed tail-truncation check against the signed checkpoint. The
728 // checkpoint records the head we last durably committed; if the journal
729 // now has fewer records, its tail was deleted. (A checkpoint that is
730 // *behind* the journal is fine — it just predates the last append, e.g.
731 // a crash between the journal fsync and the checkpoint fsync.)
732 if let Some((cp_seq, _cp_hash, _cp_sig)) = read_checkpoint(&checkpoint_path)? {
733 let journal_head = tail.map(|(seq, _)| seq);
734 let truncated = match journal_head {
735 None => true, // checkpoint exists but journal is empty/gone
736 Some(h) => h < cp_seq,
737 };
738 if truncated {
739 return Err(AuditError::Truncation {
740 checkpoint_seq: cp_seq,
741 journal_seq: journal_head,
742 });
743 }
744 }
745
746 Ok(Self {
747 root,
748 journal_path,
749 checkpoint_path,
750 cas_dir,
751 signer,
752 head: Mutex::new(ChainHead {
753 next_seq,
754 head_hash,
755 }),
756 })
757 }
758
759 /// Root of the store (diagnostics / tests).
760 pub fn root(&self) -> &Path {
761 &self.root
762 }
763
764 /// Durably append + sign + content-address a record. Returns `Ok(())` only
765 /// after the journal file AND its parent directory are fsynced — so a
766 /// Permit returned by the AVC is never ahead of a durable audit entry.
767 ///
768 /// The store owns sequence + chain assignment: the incoming `record.seq`
769 /// and `record.prev_hash` are **ignored** and overwritten with the store's
770 /// monotonic counter and current chain head, so neither invariant can be
771 /// violated by a caller. The caller (the AVC) supplies `seq: 0` /
772 /// `prev_hash: [0; 32]` as placeholders. The whole critical section runs
773 /// under the head lock so the seq, the `prev_hash` link, and the journal
774 /// append cannot interleave with a concurrent writer (which would fork the
775 /// chain).
776 fn record_inner(&self, record: &AuditRecord) -> Result<(), AuditError> {
777 // 0. Take the chain head. Held across the append so seq assignment,
778 // prev_hash chaining, and the journal write are one atomic step.
779 // (parking_lot::Mutex — no poisoning, lock() yields the guard.)
780 let mut head = self.head.lock();
781 let seq = head.next_seq;
782 let stored = AuditRecord {
783 seq,
784 prev_hash: head.head_hash,
785 ..record.clone()
786 };
787
788 // 1. Canonical bytes + content hash (content-addressing + chain link).
789 let bytes = stored.canonical_bytes()?;
790 let hash = *blake3::hash(&bytes).as_bytes();
791
792 // 2. Sign the domain-separated signing input. S8 (#574): the
793 // CoseAuditSigner is policy-aware — under Hybrid it fails closed here
794 // if no ML-DSA-65 key is provisioned (no silent downgrade). The signer
795 // trait abstracts which mode is in use.
796 let signing_input = audit_signing_input(&hash);
797 let signature = self.signer.sign(&signing_input)?;
798
799 // Keep the writer and bounded startup reader in agreement. Refuse an
800 // oversized record before writing CAS, WAL, checkpoint, or chain head.
801 let line = format!(
802 "{}\t{}\t{}\n",
803 stored.seq,
804 hex_encode(&signature),
805 base64_encode(&bytes),
806 );
807 if line.len() - 1 > MAX_AUDIT_TAIL_LINE {
808 return Err(AuditError::Encode(
809 "audit journal line exceeds limit".into(),
810 ));
811 }
812
813 // 3. Content-addressed CAS write (dedup + second tamper-evidence layer).
814 // Named by its own hash, so an overwrite is a no-op and a name never
815 // points at different bytes.
816 let (shard, rest) = shard_of(&hash);
817 let cas_shard = self.cas_dir.join(shard);
818 std::fs::create_dir_all(&cas_shard)?;
819 let blob_path = cas_shard.join(&rest);
820 if !blob_path.exists() {
821 // Write to a temp file in the same dir, fsync, then atomically rename
822 // — so a crash never leaves a half-written blob under the content
823 // address (which would violate the name==bytes invariant).
824 let tmp = cas_shard.join(format!(".{rest}.tmp"));
825 {
826 let mut f = File::create(&tmp)?;
827 f.write_all(&bytes)?;
828 f.sync_all()?;
829 }
830 std::fs::rename(&tmp, &blob_path)?;
831 }
832
833 // 4. Append to the journal: <seq>\t<sig_hex>\t<cbor_b64>\n, then fsync
834 // the file AND the directory (WAL durability: the append is
835 // durably on disk before we return).
836 {
837 let mut f = OpenOptions::new()
838 .create(true)
839 .append(true)
840 .open(&self.journal_path)?;
841 f.write_all(line.as_bytes())?;
842 f.sync_all()?;
843 }
844 // fsync the directory so the rename (step 3) and the journal's metadata
845 // (size, new inode) are durable. Without this a crash after the file
846 // fsync but before the dir fsync can lose the directory entry.
847 sync_dir(&self.root)?;
848
849 // 5. Advance and durably anchor the chain head. The signed checkpoint
850 // records `(seq, hash)` out-of-band so a later tail-truncation is
851 // detectable on open. Written AFTER the journal is durable: if we
852 // crash between the two, the checkpoint lags the journal (benign —
853 // open() treats a checkpoint behind the journal as fine); the
854 // dangerous direction (checkpoint ahead of a shortened journal) only
855 // arises from truncation, which is exactly what we detect.
856 self.write_checkpoint(seq, &hash)?;
857 head.next_seq = seq + 1;
858 head.head_hash = hash;
859 drop(head);
860
861 // 6. OTel fan-out: emit a structured tracing event so denials are
862 // observable (fixes #453). OTel is a tracing subscriber, so this
863 // reaches OTLP automatically when the `otel` feature is active.
864 emit_decision_event(&stored);
865 Ok(())
866 }
867
868 /// Write the signed head anchor `(seq, head_hash)` to the checkpoint file,
869 /// atomically (temp + rename) and fsynced so it is durable before the
870 /// enclosing `record` returns. The signature is over a domain-separated
871 /// input distinct from the per-record one, so a record signature can never
872 /// be replayed as a checkpoint signature.
873 fn write_checkpoint(&self, seq: u64, head_hash: &[u8; 32]) -> Result<(), AuditError> {
874 let signing_input = checkpoint_signing_input(seq, head_hash);
875 let signature = self.signer.sign(&signing_input)?;
876 let line = format!(
877 "{}\t{}\t{}\n",
878 seq,
879 hex_encode(head_hash),
880 hex_encode(&signature),
881 );
882 let tmp = self.root.join(".checkpoint.tmp");
883 {
884 let mut f = File::create(&tmp)?;
885 f.write_all(line.as_bytes())?;
886 f.sync_all()?;
887 }
888 std::fs::rename(&tmp, &self.checkpoint_path)?;
889 sync_dir(&self.root)?;
890 Ok(())
891 }
892
893 /// Read the whole journal back and verify it end-to-end: every signature
894 /// against `verifier`, the sequence gap-free, the `prev_hash` **chain**
895 /// intact, and — if present — the signed checkpoint's signature and that it
896 /// anchors the journal's actual head. Returns the records in order.
897 ///
898 /// This is the offline/cryptographic counterpart to [`open`](Self::open)'s
899 /// cheap runtime check: it catches tampering, reordering, and middle
900 /// deletion (chain break) as well as tail truncation and checkpoint
901 /// rollback (checkpoint vs. head mismatch).
902 pub fn verify_journal<V: AuditVerifier>(
903 &self,
904 verifier: &V,
905 ) -> Result<Vec<AuditRecord>, AuditError> {
906 if !self.journal_path.exists() {
907 return Ok(Vec::new());
908 }
909 let content = std::fs::read_to_string(&self.journal_path)?;
910 let mut out = Vec::new();
911 let mut expected_seq = 0u64;
912 // The running chain head: each record must name this as its prev_hash.
913 let mut running_head = [0u8; 32];
914 for (lineno, raw_line) in content.lines().enumerate() {
915 let line = raw_line.trim_end_matches('\r');
916 if line.is_empty() {
917 continue;
918 }
919 let mut parts = line.split('\t');
920 let seq_s = parts.next().ok_or_else(|| {
921 AuditError::Decode(format!("journal line {} missing seq", lineno + 1))
922 })?;
923 let sig_hex = parts.next().ok_or_else(|| {
924 AuditError::Decode(format!("journal line {} missing sig", lineno + 1))
925 })?;
926 let cbor_b64 = parts.next().ok_or_else(|| {
927 AuditError::Decode(format!("journal line {} missing payload", lineno + 1))
928 })?;
929 let seq: u64 = seq_s.parse().map_err(|e| {
930 AuditError::Decode(format!("journal line {}: bad seq: {}", lineno + 1, e))
931 })?;
932 if seq != expected_seq {
933 return Err(AuditError::SeqRegression {
934 journal: seq,
935 counter: expected_seq,
936 });
937 }
938 expected_seq = seq + 1;
939 let bytes = base64_decode(cbor_b64)?;
940 let sig = hex_decode(sig_hex)?;
941 let record: AuditRecord = ciborium::de::from_reader(&bytes[..]).map_err(|e| {
942 AuditError::Decode(format!("journal line {}: bad record: {}", lineno + 1, e))
943 })?;
944 // Chain: this record must link to the previous record's hash.
945 if record.prev_hash != running_head {
946 return Err(AuditError::ChainBreak { seq });
947 }
948 // Recompute the content hash and verify the signature over it.
949 let hash = *blake3::hash(&bytes).as_bytes();
950 let signing_input = audit_signing_input(&hash);
951 verifier.verify(&signing_input, &sig)?;
952 running_head = hash;
953 out.push(record);
954 }
955
956 // Checkpoint: if one exists, its signature must verify and it must
957 // anchor the journal's actual head — a truncated tail or a rolled-back
958 // checkpoint is caught here. (A checkpoint strictly *behind* the head is
959 // a benign crash between the journal and checkpoint fsyncs.)
960 if let Some((cp_seq, cp_hash, cp_sig)) = read_checkpoint(&self.checkpoint_path)? {
961 let cp_input = checkpoint_signing_input(cp_seq, &cp_hash);
962 verifier.verify(&cp_input, &cp_sig)?;
963 let head_seq = out.last().map(|r| r.seq);
964 match head_seq {
965 // Checkpoint ahead of the journal head ⇒ the tail was truncated.
966 Some(h) if cp_seq > h => {
967 return Err(AuditError::Truncation {
968 checkpoint_seq: cp_seq,
969 journal_seq: Some(h),
970 });
971 }
972 None => {
973 return Err(AuditError::Truncation {
974 checkpoint_seq: cp_seq,
975 journal_seq: None,
976 });
977 }
978 // Checkpoint exactly at the head ⇒ verify it names the head hash.
979 Some(h) if cp_seq == h && cp_hash != running_head => {
980 return Err(AuditError::ChainBreak { seq: cp_seq });
981 }
982 _ => {}
983 }
984 }
985 Ok(out)
986 }
987}
988
989impl<S: AuditSigner> AuditSink for WalAuditStore<S> {
990 fn record(&self, record: &AuditRecord) -> Result<(), AuditError> {
991 self.record_inner(record)
992 }
993}
994
995// ────────────────────────────────────────────────────────────────────────────
996// Complete-mediation wrapper: an AVC that audits every decision
997// ────────────────────────────────────────────────────────────────────────────
998
999/// An [`Avc`] that routes every decision through an [`AuditSink`]. This is the
1000/// S7 complete-mediation hook: because the PEP (S2) calls the AVC per op,
1001/// wrapping it here audits every decision with no bypass.
1002///
1003/// **Fail-closed:** if the audit write fails on what would otherwise be a
1004/// `Permit`, the wrapper downgrades to `Deny` (reason `AuditFailClosed`) and
1005/// attempts to record *that* deny (best-effort: if the sink is broken, the
1006/// enforced deny is still emitted as a tracing event so it is observable).
1007/// A decision that cannot be audited is never allowed through.
1008pub struct AuditedAvc<A: Avc, S: AuditSink> {
1009 inner: A,
1010 sink: S,
1011 /// The policy generation records get tagged with (the wrapped evaluator's
1012 /// generation, captured by the caller at construction).
1013 generation: u64,
1014 /// Optional BLAKE3 of the governing compiled policy (provenance). `None`
1015 /// when the wrapped AVC was not built from a signed `CompiledPolicy`.
1016 policy_hash: Option<[u8; 32]>,
1017}
1018
1019impl<A: Avc, S: AuditSink> AuditedAvc<A, S> {
1020 /// Wrap an AVC with audit. `generation` should be the evaluator's
1021 /// generation (`TeEvaluator::generation`); `policy_hash` the
1022 /// [`crate::mac::compiled::CompiledPolicy::policy_hash`] when available.
1023 pub fn new(inner: A, sink: S, generation: u64, policy_hash: Option<[u8; 32]>) -> Self {
1024 Self {
1025 inner,
1026 sink,
1027 generation,
1028 policy_hash,
1029 }
1030 }
1031
1032 /// Borrow the inner AVC (diagnostics / cache stats).
1033 pub fn inner(&self) -> &A {
1034 &self.inner
1035 }
1036
1037 /// Record a decision through the sink, applying the fail-closed rule.
1038 /// Returns the decision the PEP should enforce, plus the reason.
1039 ///
1040 /// `on_behalf_of` carries the delegator principal on a delegated (#680/#681)
1041 /// decision — `subject` is the effective, met context the AVC decided on;
1042 /// the delegator is recorded but never re-evaluated here (the meet already
1043 /// happened upstream in `SecurityContext::delegated`).
1044 fn audit(
1045 &self,
1046 subject: SubjectCtx,
1047 on_behalf_of: Option<SubjectCtx>,
1048 object: ObjectCtx,
1049 action: Action,
1050 decision: Decision,
1051 reason: DecisionReason,
1052 ) -> Decision {
1053 let enforced = decision;
1054 let record = AuditRecord {
1055 // seq/ts are assigned by the store via build_record-equivalent; but
1056 // the store's record() takes a fully-formed record, so we let the
1057 // caller-side assign. To keep seq monotonic AND owned by the store,
1058 // we instead hand the store a record with seq=0 and let a wrapping
1059 // helper reassign. Simpler: the store assigns seq in record() — but
1060 // the trait takes a complete record. We resolve this by giving the
1061 // record a placeholder seq here and having WalAuditStore re-stamp
1062 // it; see the store impl. For trait-based sinks without that
1063 // re-stamp, seq stays as written here (tests use NullAuditSink and
1064 // don't rely on seq).
1065 seq: 0,
1066 // Placeholder chain link; WalAuditStore assigns the real prev_hash
1067 // under its head lock, exactly as it does seq.
1068 prev_hash: [0u8; 32],
1069 ts_unix_nanos: now_unix_nanos(),
1070 decision: enforced,
1071 generation: self.generation,
1072 policy_hash: self.policy_hash,
1073 subject_type: subject.subject_type,
1074 subject_clearance: subject.clearance,
1075 on_behalf_of: on_behalf_of.map(|d| DelegationPrincipal {
1076 subject_type: d.subject_type,
1077 subject_clearance: d.clearance,
1078 }),
1079 object_type: object.object_type,
1080 object_label: object.label,
1081 action,
1082 reason,
1083 subject_id: None,
1084 object_id: None,
1085 };
1086 match self.sink.record(&record) {
1087 Ok(()) => enforced,
1088 Err(_) => {
1089 // Fail-closed: a Permit that can't be audited is downgraded to
1090 // Deny. Record the deny we actually enforce (best-effort: the
1091 // sink may still be broken, in which case the tracing event is
1092 // the only record, but it IS emitted).
1093 if enforced.is_permit() {
1094 let deny_record = AuditRecord {
1095 decision: Decision::Deny,
1096 reason: DecisionReason::AuditFailClosed,
1097 ..record
1098 };
1099 let _ = self.sink.record(&deny_record);
1100 emit_decision_event(&deny_record);
1101 Decision::Deny
1102 } else {
1103 // A deny that can't be audited is still a deny — enforced as
1104 // decided. We log the audit failure so it is observable.
1105 tracing::error!(
1106 target: "hyprstream.mac.audit",
1107 decision = "deny",
1108 reason = DecisionReason::AuditFailClosed.as_str(),
1109 "audit write failed recording a deny; enforcing deny as decided"
1110 );
1111 enforced
1112 }
1113 }
1114 }
1115 }
1116}
1117
1118impl<A: Avc, S: AuditSink> Avc for AuditedAvc<A, S> {
1119 #[inline]
1120 fn decide(&self, subject: SubjectCtx, object: ObjectCtx, action: Action) -> Decision {
1121 let decision = self.inner.decide(subject, object, action);
1122 let reason = decision_reason_for(decision);
1123 self.audit(subject, None, object, action, decision, reason)
1124 }
1125
1126 #[inline]
1127 fn decide_with_token(
1128 &self,
1129 subject: SubjectCtx,
1130 object: ObjectCtx,
1131 action: Action,
1132 token: &TokenScope,
1133 ) -> Decision {
1134 // The token gate lives inside the inner AVC; if it denies, the inner
1135 // returns Deny and we record reason=TokenGate (best-effort: we cannot
1136 // distinguish token-gate-deny from PDP-deny without the inner exposing
1137 // it, so we attribute a Deny to the most specific cause we can infer:
1138 // if the token's op-set excludes the action or it's expired, it's a
1139 // token gate; otherwise it's a PDP decision).
1140 let pre_reason = token_deny_reason(token, action);
1141 let decision = self.inner.decide_with_token(subject, object, action, token);
1142 let reason = if decision.is_permit() {
1143 DecisionReason::Permit
1144 } else {
1145 pre_reason.unwrap_or_else(|| decision_reason_for(decision))
1146 };
1147 self.audit(subject, None, object, action, decision, reason)
1148 }
1149
1150 fn flush(&self) {
1151 self.inner.flush();
1152 }
1153}
1154
1155impl<A: Avc, S: AuditSink> AuditedAvc<A, S> {
1156 /// Delegated (#680/#681) counterpart of [`Avc::decide`]: `subject` is the
1157 /// effective, met context the PDP decides on (already `meet(delegator,
1158 /// actor)` from [`hyprstream_rpc::auth::mac::SecurityContext::delegated`]);
1159 /// `on_behalf_of` is the delegator principal, recorded on the audit record
1160 /// but **never re-evaluated** (the decision rests on the met `subject`
1161 /// alone — the delegator cannot re-widen it).
1162 ///
1163 /// The plain [`Avc::decide`] is the single-principal case (`on_behalf_of =
1164 /// None`); this is the two-principal case the (future) reference monitor
1165 /// calls when a request arrived over a delegation. Kept off the `Avc` trait
1166 /// so the hot-path cache key stays `(subject, object, action)` — delegation
1167 /// is an audit-attribution concern, not a decision input.
1168 #[inline]
1169 pub fn decide_delegated(
1170 &self,
1171 subject: SubjectCtx,
1172 on_behalf_of: Option<SubjectCtx>,
1173 object: ObjectCtx,
1174 action: Action,
1175 ) -> Decision {
1176 let decision = self.inner.decide(subject, object, action);
1177 let reason = decision_reason_for(decision);
1178 self.audit(subject, on_behalf_of, object, action, decision, reason)
1179 }
1180
1181 /// Delegated counterpart of [`Avc::decide_with_token`]; see
1182 /// [`Self::decide_delegated`] for the two-principal semantics.
1183 #[inline]
1184 pub fn decide_delegated_with_token(
1185 &self,
1186 subject: SubjectCtx,
1187 on_behalf_of: Option<SubjectCtx>,
1188 object: ObjectCtx,
1189 action: Action,
1190 token: &TokenScope,
1191 ) -> Decision {
1192 let pre_reason = token_deny_reason(token, action);
1193 let decision = self.inner.decide_with_token(subject, object, action, token);
1194 let reason = if decision.is_permit() {
1195 DecisionReason::Permit
1196 } else {
1197 pre_reason.unwrap_or_else(|| decision_reason_for(decision))
1198 };
1199 self.audit(subject, on_behalf_of, object, action, decision, reason)
1200 }
1201}
1202
1203/// Infer a `DecisionReason` from a bare `Decision` (no token context).
1204fn decision_reason_for(d: Decision) -> DecisionReason {
1205 match d {
1206 Decision::Permit => DecisionReason::Permit,
1207 Decision::Escalate => DecisionReason::Escalate,
1208 Decision::Deny => {
1209 // We can't tell floor-deny from TE-miss without re-running the PDP,
1210 // and re-running would duplicate work. Record the generic deny
1211 // cause; the detailed split is recoverable from the policy + the
1212 // recorded contexts during post-hoc analysis. This keeps the hot
1213 // path single-evaluation.
1214 DecisionReason::TeMiss
1215 }
1216 }
1217}
1218
1219/// If the token gate would deny this action, return the reason; else `None`.
1220fn token_deny_reason(token: &TokenScope, action: Action) -> Option<DecisionReason> {
1221 if !token.authorizes_action(action) || token.valid_until <= std::time::Instant::now() {
1222 Some(DecisionReason::TokenGate)
1223 } else {
1224 None
1225 }
1226}
1227
1228/// Emit the structured `tracing` event that fans out to OTel (OTel is a tracing
1229/// subscriber; this is the S7 observability surface that fixes #453's
1230/// debug-level-denial visibility gap).
1231fn emit_decision_event(record: &AuditRecord) {
1232 let decision_str = match record.decision {
1233 Decision::Permit => "allow",
1234 Decision::Deny => "deny",
1235 Decision::Escalate => "escalate",
1236 };
1237 // Denials/escalations are warn; permits are info. Both carry identical
1238 // structured fields so the deny path is first-class, not buried.
1239 if record.decision.is_permit() {
1240 tracing::info!(
1241 target: "hyprstream.mac.audit",
1242 decision = decision_str,
1243 subject_type = record.subject_type.0,
1244 subject_clearance = %record.subject_clearance,
1245 object_type = record.object_type.0,
1246 object_label = %record.object_label,
1247 action = record.action.0,
1248 generation = record.generation,
1249 reason = record.reason.as_str(),
1250 seq = record.seq,
1251 "MAC authorization decision"
1252 );
1253 } else {
1254 tracing::warn!(
1255 target: "hyprstream.mac.audit",
1256 decision = decision_str,
1257 subject_type = record.subject_type.0,
1258 subject_clearance = %record.subject_clearance,
1259 object_type = record.object_type.0,
1260 object_label = %record.object_label,
1261 action = record.action.0,
1262 generation = record.generation,
1263 reason = record.reason.as_str(),
1264 seq = record.seq,
1265 "MAC authorization decision"
1266 );
1267 }
1268}
1269
1270// ────────────────────────────────────────────────────────────────────────────
1271// Small helpers (no extra deps: hex/base64 are tiny, inlined)
1272// ────────────────────────────────────────────────────────────────────────────
1273
1274fn now_unix_nanos() -> u128 {
1275 std::time::SystemTime::now()
1276 .duration_since(std::time::UNIX_EPOCH)
1277 .map(|d| d.as_nanos())
1278 .unwrap_or(0)
1279}
1280
1281/// Split a 32-byte BLAKE3 into a 2-hex-char shard dir and the remaining 62-hex
1282/// file name (git-style sharding to keep one CAS dir from bloating).
1283fn shard_of(hash: &[u8; 32]) -> (String, String) {
1284 let hex = hex_encode(hash);
1285 let (a, b) = hex.split_at(2);
1286 (a.to_owned(), b.to_owned())
1287}
1288
1289fn hex_encode(bytes: &[u8]) -> String {
1290 let mut s = String::with_capacity(bytes.len() * 2);
1291 for b in bytes {
1292 s.push_str(&format!("{b:02x}"));
1293 }
1294 s
1295}
1296
1297fn hex_decode(hex: &str) -> Result<Vec<u8>, AuditError> {
1298 if !hex.len().is_multiple_of(2) {
1299 return Err(AuditError::Decode("odd-length hex".into()));
1300 }
1301 let mut out = Vec::with_capacity(hex.len() / 2);
1302 let bytes = hex.as_bytes();
1303 for chunk in bytes.chunks_exact(2) {
1304 let hi = hex_nibble(chunk[0])?;
1305 let lo = hex_nibble(chunk[1])?;
1306 out.push((hi << 4) | lo);
1307 }
1308 Ok(out)
1309}
1310
1311fn hex_nibble(b: u8) -> Result<u8, AuditError> {
1312 match b {
1313 b'0'..=b'9' => Ok(b - b'0'),
1314 b'a'..=b'f' => Ok(b - b'a' + 10),
1315 b'A'..=b'F' => Ok(b - b'A' + 10),
1316 _ => Err(AuditError::Decode(format!("bad hex nibble: {b}"))),
1317 }
1318}
1319
1320/// Standard base64 alphabet (no padding for journal compactness; we frame with
1321/// tabs/newlines so length is recoverable).
1322fn base64_encode(bytes: &[u8]) -> String {
1323 const ALPHA: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1324 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
1325 for chunk in bytes.chunks(3) {
1326 let b0 = chunk[0] as u32;
1327 let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
1328 let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
1329 let triple = (b0 << 16) | (b1 << 8) | b2;
1330 out.push(ALPHA[((triple >> 18) & 0x3f) as usize] as char);
1331 out.push(ALPHA[((triple >> 12) & 0x3f) as usize] as char);
1332 if chunk.len() > 1 {
1333 out.push(ALPHA[((triple >> 6) & 0x3f) as usize] as char);
1334 }
1335 if chunk.len() > 2 {
1336 out.push(ALPHA[(triple & 0x3f) as usize] as char);
1337 }
1338 }
1339 out
1340}
1341
1342fn base64_decode(s: &str) -> Result<Vec<u8>, AuditError> {
1343 fn val(c: u8) -> Result<u8, AuditError> {
1344 match c {
1345 b'A'..=b'Z' => Ok(c - b'A'),
1346 b'a'..=b'z' => Ok(c - b'a' + 26),
1347 b'0'..=b'9' => Ok(c - b'0' + 52),
1348 b'+' => Ok(62),
1349 b'/' => Ok(63),
1350 _ => Err(AuditError::Decode(format!("bad base64 char: {c}"))),
1351 }
1352 }
1353 let bytes = s.as_bytes();
1354 let mut out = Vec::with_capacity(bytes.len() * 3 / 4);
1355 let mut buf = [0u8; 4];
1356 let mut i = 0;
1357 while i < bytes.len() {
1358 buf[i % 4] = val(bytes[i])?;
1359 if i % 4 == 3 {
1360 let triple = (u32::from(buf[0]) << 18)
1361 | (u32::from(buf[1]) << 12)
1362 | (u32::from(buf[2]) << 6)
1363 | u32::from(buf[3]);
1364 out.push((triple >> 16) as u8);
1365 out.push((triple >> 8) as u8);
1366 out.push(triple as u8);
1367 }
1368 i += 1;
1369 }
1370 // Handle the trailing partial group (1 or 2 trailing chars).
1371 let rem = i % 4;
1372 if rem == 2 {
1373 let triple = (u32::from(buf[0]) << 18) | (u32::from(buf[1]) << 12);
1374 out.push((triple >> 16) as u8);
1375 } else if rem == 3 {
1376 let triple =
1377 (u32::from(buf[0]) << 18) | (u32::from(buf[1]) << 12) | (u32::from(buf[2]) << 6);
1378 out.push((triple >> 16) as u8);
1379 out.push((triple >> 8) as u8);
1380 }
1381 Ok(out)
1382}
1383
1384/// Read only the journal's last nonempty record. The WAL can grow indefinitely;
1385/// loading it all at every restart can exhaust a small host before Event starts.
1386/// A single record over this limit is rejected rather than allocating without
1387/// bound. Full-chain verification remains the separate offline operation.
1388const MAX_AUDIT_TAIL_LINE: usize = 1024 * 1024;
1389
1390/// Return the last `(seq, content_hash)` so the next record continues the chain.
1391fn journal_tail(path: &Path) -> Result<Option<(u64, [u8; 32])>, AuditError> {
1392 let mut file = match File::open(path) {
1393 Ok(file) => file,
1394 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1395 Err(error) => return Err(error.into()),
1396 };
1397 let mut offset = file.metadata()?.len();
1398 let mut reversed = Vec::new();
1399 let mut chunk = [0u8; 8192];
1400 while offset > 0 {
1401 let length = offset.min(chunk.len() as u64) as usize;
1402 offset -= length as u64;
1403 file.seek(SeekFrom::Start(offset))?;
1404 file.read_exact(&mut chunk[..length])?;
1405 for &byte in chunk[..length].iter().rev() {
1406 if byte == b'\n' {
1407 if let Some(tail) = parse_reversed_tail(&mut reversed)? {
1408 return Ok(Some(tail));
1409 }
1410 } else {
1411 if reversed.len() == MAX_AUDIT_TAIL_LINE {
1412 return Err(AuditError::Decode("journal tail line exceeds limit".into()));
1413 }
1414 reversed.push(byte);
1415 }
1416 }
1417 }
1418 parse_reversed_tail(&mut reversed)
1419}
1420
1421fn parse_reversed_tail(reversed: &mut Vec<u8>) -> Result<Option<(u64, [u8; 32])>, AuditError> {
1422 reversed.reverse();
1423 let last = std::str::from_utf8(reversed)
1424 .map_err(|_| AuditError::Decode("journal tail is not UTF-8".into()))?
1425 .trim_end_matches('\r');
1426 if last.is_empty() {
1427 reversed.clear();
1428 return Ok(None);
1429 }
1430 let mut parts = last.split('\t');
1431 let seq_s = parts
1432 .next()
1433 .ok_or_else(|| AuditError::Decode("journal tail missing seq".into()))?;
1434 // parts[1] is the signature; parts[2] is the base64 payload.
1435 let _sig = parts.next();
1436 let payload_b64 = parts
1437 .next()
1438 .ok_or_else(|| AuditError::Decode("journal tail missing payload".into()))?;
1439 let seq: u64 = seq_s
1440 .parse()
1441 .map_err(|e| AuditError::Decode(format!("journal tail bad seq: {e}")))?;
1442 let bytes = base64_decode(payload_b64)?;
1443 let hash = *blake3::hash(&bytes).as_bytes();
1444 Ok(Some((seq, hash)))
1445}
1446
1447/// Read the signed checkpoint head anchor: `(seq, head_hash, signature)`.
1448/// `None` if no checkpoint has been written yet.
1449fn read_checkpoint(path: &Path) -> Result<Option<(u64, [u8; 32], Vec<u8>)>, AuditError> {
1450 if !path.exists() {
1451 return Ok(None);
1452 }
1453 let content = std::fs::read_to_string(path)?;
1454 let Some(line) = content
1455 .lines()
1456 .map(|l| l.trim_end_matches('\r'))
1457 .find(|l| !l.is_empty())
1458 else {
1459 return Ok(None);
1460 };
1461 let mut parts = line.split('\t');
1462 let seq_s = parts
1463 .next()
1464 .ok_or_else(|| AuditError::Decode("checkpoint missing seq".into()))?;
1465 let hash_hex = parts
1466 .next()
1467 .ok_or_else(|| AuditError::Decode("checkpoint missing head_hash".into()))?;
1468 let sig_hex = parts
1469 .next()
1470 .ok_or_else(|| AuditError::Decode("checkpoint missing sig".into()))?;
1471 let seq: u64 = seq_s
1472 .parse()
1473 .map_err(|e| AuditError::Decode(format!("checkpoint bad seq: {e}")))?;
1474 let hash_vec = hex_decode(hash_hex)?;
1475 let hash: [u8; 32] = hash_vec
1476 .try_into()
1477 .map_err(|_| AuditError::Decode("checkpoint head_hash not 32 bytes".into()))?;
1478 let sig = hex_decode(sig_hex)?;
1479 Ok(Some((seq, hash, sig)))
1480}
1481
1482/// fsync a directory (durability of directory entries: renames, creates).
1483fn sync_dir(path: &Path) -> Result<(), AuditError> {
1484 let f = File::open(path)?;
1485 f.sync_all()?;
1486 Ok(())
1487}
1488
1489// ────────────────────────────────────────────────────────────────────────────
1490// Tests
1491// ────────────────────────────────────────────────────────────────────────────
1492
1493#[cfg(test)]
1494#[allow(clippy::unwrap_used, clippy::expect_used)]
1495mod tests {
1496 use super::*;
1497 use crate::mac::avc::CachingAvc;
1498 use crate::mac::lattice::{
1499 Assurance, Compartment, CompartmentSet, Lattice, LatticeVersion, Level,
1500 };
1501 use crate::mac::te::{LatticeTeEvaluator, TeMatrix, TeRule};
1502 use parking_lot::Mutex;
1503 use std::collections::HashSet;
1504 use std::sync::Arc;
1505
1506 fn lattice() -> Lattice {
1507 Lattice::new(LatticeVersion(7), [Compartment::new("pii")])
1508 }
1509 fn high() -> SecurityLabel {
1510 SecurityLabel::new(Level::Secret, Assurance::PqHybrid, CompartmentSet::EMPTY)
1511 }
1512 fn low() -> SecurityLabel {
1513 SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY)
1514 }
1515 fn subj(t: u32, clr: SecurityLabel) -> SubjectCtx {
1516 SubjectCtx {
1517 subject_type: SubjectType(t),
1518 clearance: clr,
1519 }
1520 }
1521 fn obj(t: u32, lbl: SecurityLabel) -> ObjectCtx {
1522 ObjectCtx {
1523 object_type: ObjectType(t),
1524 label: lbl,
1525 }
1526 }
1527 fn rule(s: u32, o: u32, a: u32) -> TeRule {
1528 TeRule {
1529 subject_type: SubjectType(s),
1530 object_type: ObjectType(o),
1531 action: Action(a),
1532 }
1533 }
1534
1535 /// A trivial deterministic signer for unit tests (NOT for production).
1536 /// signature = blake3(key || signing_input). Mirrors compiled::StubSigner.
1537 struct StubSigner {
1538 key: [u8; 32],
1539 }
1540 impl AuditSigner for StubSigner {
1541 fn sign(&self, input: &[u8]) -> Result<Vec<u8>, AuditError> {
1542 let mut h = blake3::Hasher::new();
1543 h.update(&self.key);
1544 h.update(input);
1545 Ok(h.finalize().as_bytes().to_vec())
1546 }
1547 }
1548 struct StubVerifier {
1549 key: [u8; 32],
1550 }
1551 impl AuditVerifier for StubVerifier {
1552 fn verify(&self, input: &[u8], sig: &[u8]) -> Result<(), AuditError> {
1553 let mut h = blake3::Hasher::new();
1554 h.update(&self.key);
1555 h.update(input);
1556 let want = h.finalize();
1557 if want.as_bytes() == sig {
1558 Ok(())
1559 } else {
1560 Err(AuditError::Verify("stub signature mismatch".into()))
1561 }
1562 }
1563 }
1564
1565 /// An in-memory capturing sink for AVC-wrapper tests.
1566 struct CapturingSink {
1567 records: Mutex<Vec<AuditRecord>>,
1568 fail_next: Mutex<bool>,
1569 }
1570 impl CapturingSink {
1571 fn new() -> Self {
1572 Self {
1573 records: Mutex::new(Vec::new()),
1574 fail_next: Mutex::new(false),
1575 }
1576 }
1577 fn records(&self) -> Vec<AuditRecord> {
1578 self.records.lock().clone()
1579 }
1580 fn fail_next(&self) {
1581 *self.fail_next.lock() = true;
1582 }
1583 }
1584 impl AuditSink for CapturingSink {
1585 fn record(&self, record: &AuditRecord) -> Result<(), AuditError> {
1586 let mut fail = self.fail_next.lock();
1587 if *fail {
1588 *fail = false;
1589 return Err(AuditError::Io("injected failure".into()));
1590 }
1591 self.records.lock().push(record.clone());
1592 Ok(())
1593 }
1594 }
1595
1596 fn avc() -> CachingAvc<LatticeTeEvaluator> {
1597 let mut allow = HashSet::new();
1598 allow.insert(rule(1, 1, 1));
1599 let e = LatticeTeEvaluator::new(TeMatrix::from_allow(allow), lattice());
1600 CachingAvc::new(Arc::new(e))
1601 }
1602
1603 fn tmp_dir(name: &str) -> PathBuf {
1604 let p = std::env::temp_dir().join(format!("hs-s7-test-{}-{name}", std::process::id()));
1605 let _ = std::fs::remove_dir_all(&p);
1606 p
1607 }
1608
1609 // ── Property: content-addressing ────────────────────────────────────────
1610
1611 /// Fu6/#677: golden content-hash stability. The canonical encoding is real
1612 /// CBOR (not serde_json); this pins a fully-specified record to a fixed
1613 /// BLAKE3 so any drift in the canonical encoding — a struct field reorder,
1614 /// a serde representation change, a swap back to JSON — is caught here
1615 /// rather than silently breaking the on-disk hash chain. Update this hash
1616 /// *only* as part of an intentional, migration-aware encoding change.
1617 #[test]
1618 fn golden_content_hash_is_stable() {
1619 let rec = AuditRecord {
1620 seq: 1,
1621 prev_hash: [0u8; 32],
1622 ts_unix_nanos: 0,
1623 decision: Decision::Permit,
1624 generation: 7,
1625 policy_hash: None,
1626 subject_type: SubjectType(1),
1627 subject_clearance: high(),
1628 on_behalf_of: None,
1629 object_type: ObjectType(1),
1630 object_label: low(),
1631 action: Action(1),
1632 reason: DecisionReason::Permit,
1633 subject_id: None,
1634 object_id: None,
1635 };
1636 let hash = rec.content_hash().expect("canonical encode + hash");
1637 let hex = hex::encode(hash);
1638 assert_eq!(
1639 hex, "e3ca6519bde2ebb9a60273bd30a8acfa13a299280aafeca6c438ea21f8282b30",
1640 "Fu6 golden hash drifted — was the canonical CBOR encoding changed intentionally?"
1641 );
1642 }
1643
1644 #[test]
1645 fn same_decision_yields_same_content_hash() {
1646 let mut rec = AuditRecord {
1647 seq: 1,
1648 prev_hash: [0u8; 32],
1649 ts_unix_nanos: 0,
1650 decision: Decision::Permit,
1651 generation: 7,
1652 policy_hash: None,
1653 subject_type: SubjectType(1),
1654 subject_clearance: high(),
1655 on_behalf_of: None,
1656 object_type: ObjectType(1),
1657 object_label: low(),
1658 action: Action(1),
1659 reason: DecisionReason::Permit,
1660 subject_id: None,
1661 object_id: None,
1662 };
1663 let h1 = rec.content_hash().unwrap();
1664 // Same fields → same hash.
1665 let h2 = rec.content_hash().unwrap();
1666 assert_eq!(h1, h2, "identical record must content-address identically");
1667
1668 // Mutate any field → different hash.
1669 rec.decision = Decision::Deny;
1670 let h3 = rec.content_hash().unwrap();
1671 assert_ne!(h1, h3, "a mutated field must change the content hash");
1672
1673 // Restore and bump ts — also different (ts is part of the canonical bytes).
1674 rec.decision = Decision::Permit;
1675 rec.ts_unix_nanos = 1;
1676 let h4 = rec.content_hash().unwrap();
1677 assert_ne!(h1, h4, "timestamp drift must change the content hash");
1678 }
1679
1680 /// #680/#681 hash-chain back-compat: a single-principal record
1681 /// (`on_behalf_of: None`) must serialize byte-identically to the
1682 /// pre-delegation schema — the field is skipped entirely, so existing
1683 /// content hashes and `prev_hash` links are preserved across the upgrade.
1684 /// Setting a delegator changes the hash (it is covered content).
1685 #[test]
1686 fn on_behalf_of_none_is_omitted_and_some_changes_the_hash() {
1687 let mut rec = AuditRecord {
1688 seq: 1,
1689 prev_hash: [0u8; 32],
1690 ts_unix_nanos: 0,
1691 decision: Decision::Permit,
1692 generation: 7,
1693 policy_hash: None,
1694 subject_type: SubjectType(1),
1695 subject_clearance: high(),
1696 on_behalf_of: None,
1697 object_type: ObjectType(1),
1698 object_label: low(),
1699 action: Action(1),
1700 reason: DecisionReason::Permit,
1701 subject_id: None,
1702 object_id: None,
1703 };
1704
1705 // `None` is skipped: the field name never appears in the canonical
1706 // bytes, so a single-principal record is byte-identical to the
1707 // pre-delegation schema (which had no such field at all). The canonical
1708 // encoding is CBOR (Fu6/#677); the field name is a CBOR text string, so
1709 // a raw byte search for the UTF-8 substring tells us whether the field
1710 // is present (CBOR maps/integers are not valid UTF-8, so we must not
1711 // force the binary through `String::from_utf8`).
1712 let bytes_none = rec.canonical_bytes().unwrap();
1713 assert!(
1714 !contains_utf8(&bytes_none, b"on_behalf_of"),
1715 "a None delegator must be omitted from canonical bytes (hash-chain back-compat)"
1716 );
1717 let hash_none = rec.content_hash().unwrap();
1718
1719 // A delegated record IS distinguished: the delegator is covered content,
1720 // so the hash moves and the field is now present.
1721 rec.on_behalf_of = Some(DelegationPrincipal {
1722 subject_type: SubjectType(2),
1723 subject_clearance: low(),
1724 });
1725 let bytes_some = rec.canonical_bytes().unwrap();
1726 assert!(
1727 contains_utf8(&bytes_some, b"on_behalf_of"),
1728 "a Some delegator must appear in the canonical bytes"
1729 );
1730 assert_ne!(
1731 hash_none,
1732 rec.content_hash().unwrap(),
1733 "recording a delegator must change the content hash — it is tamper-evident content"
1734 );
1735 }
1736
1737 /// Raw byte-substring search — works on canonical CBOR (Fu6/#677) where the
1738 /// field name is a length-prefixed UTF-8 text string, without forcing the
1739 /// binary through `String::from_utf8` (CBOR maps/integers are not valid
1740 /// UTF-8).
1741 fn contains_utf8(haystack: &[u8], needle: &[u8]) -> bool {
1742 haystack.windows(needle.len()).any(|w| w == needle)
1743 }
1744
1745 /// #680/#681: `AuditedAvc::decide_delegated` decides on the effective (met)
1746 /// `subject` alone — the delegator never re-widens the decision — but stamps
1747 /// the delegator on the audit record's `on_behalf_of`. The plain `decide`
1748 /// path records `None`.
1749 #[test]
1750 fn decide_delegated_records_delegator_without_affecting_the_decision() {
1751 let inner = avc();
1752 let sink = Arc::new(CapturingSink::new());
1753 let audited = AuditedAvc::new(inner, sink.clone(), 7, None);
1754
1755 // Met subject clears the op (rule (1,1,1) + floor holds). The delegator
1756 // is a DISTINCT principal (different TE type + clearance).
1757 let met = subj(1, high());
1758 let delegator = subj(2, low());
1759 let d = audited.decide_delegated(met, Some(delegator), obj(1, low()), Action(1));
1760 assert_eq!(
1761 d,
1762 Decision::Permit,
1763 "decision rests on the met subject alone"
1764 );
1765
1766 // A non-delegated decision on the same triple records no delegator.
1767 let d2 = audited.decide(subj(1, high()), obj(1, low()), Action(1));
1768 assert_eq!(d2, Decision::Permit);
1769
1770 let recs = sink.records();
1771 assert_eq!(recs.len(), 2);
1772 let obo = recs[0]
1773 .on_behalf_of
1774 .expect("the delegated decision records its delegator");
1775 assert_eq!(obo.subject_type, SubjectType(2), "delegator's TE type");
1776 assert_eq!(obo.subject_clearance, low(), "delegator's own clearance");
1777 assert_eq!(
1778 recs[0].subject_clearance,
1779 high(),
1780 "subject_clearance is the met context, not the delegator's"
1781 );
1782 assert!(
1783 recs[1].on_behalf_of.is_none(),
1784 "the non-delegated decision records no delegator"
1785 );
1786 }
1787
1788 // ── Property: append-only / no mutate/delete API ────────────────────────
1789
1790 #[test]
1791 fn store_exposes_no_mutation_or_delete() {
1792 // The AuditSink trait surface is a single `record(&self, ...)`. There is
1793 // no update/delete. This test is a compile-time guarantee documented at
1794 // the trait; we additionally assert the journal only ever grows.
1795 let dir = tmp_dir("append_only");
1796 let store = WalAuditStore::open(&dir, StubSigner { key: [1; 32] }).unwrap();
1797 let rec = AuditRecord {
1798 seq: 0,
1799 prev_hash: [0u8; 32],
1800 ts_unix_nanos: 1,
1801 decision: Decision::Permit,
1802 generation: 7,
1803 policy_hash: None,
1804 subject_type: SubjectType(1),
1805 subject_clearance: high(),
1806 on_behalf_of: None,
1807 object_type: ObjectType(1),
1808 object_label: low(),
1809 action: Action(1),
1810 reason: DecisionReason::Permit,
1811 subject_id: None,
1812 object_id: None,
1813 };
1814 store.record(&rec).unwrap();
1815 store.record(&rec).unwrap();
1816 let content = std::fs::read_to_string(dir.join("journal.log")).unwrap();
1817 let lines: Vec<&str> = content.lines().filter(|l| !l.is_empty()).collect();
1818 assert_eq!(
1819 lines.len(),
1820 2,
1821 "journal must contain both appends, never overwrite"
1822 );
1823 // The trait object exposes only record():
1824 let sink: &dyn AuditSink = &store;
1825 // (If a mutating method existed on the trait, this cast would still
1826 // surface it; the guarantee is the trait def itself.)
1827 let _ = sink;
1828 }
1829
1830 // ── Property: WAL-durable-on-write ──────────────────────────────────────
1831
1832 #[test]
1833 fn wal_record_is_durable_before_return() {
1834 // record() returns Ok only after the journal is fsynced AND the dir is
1835 // fsynced. We assert durability by: (1) record succeeds, (2) the bytes
1836 // are present on disk (readable by a fresh process-like open), (3) the
1837 // CAS blob is present. A real crash-consistency test needs a power-cut
1838 // harness; here we assert the durability *contract* — the data is on
1839 // disk when record returns, not just in-flight.
1840 let dir = tmp_dir("wal");
1841 let store = WalAuditStore::open(&dir, StubSigner { key: [2; 32] }).unwrap();
1842 let rec = AuditRecord {
1843 seq: 0,
1844 prev_hash: [0u8; 32],
1845 ts_unix_nanos: 42,
1846 decision: Decision::Deny,
1847 generation: 7,
1848 policy_hash: Some([0xaa; 32]),
1849 subject_type: SubjectType(1),
1850 subject_clearance: high(),
1851 on_behalf_of: None,
1852 object_type: ObjectType(1),
1853 object_label: low(),
1854 action: Action(9),
1855 reason: DecisionReason::TeMiss,
1856 subject_id: None,
1857 object_id: None,
1858 };
1859 store.record(&rec).unwrap();
1860
1861 // Re-open a second store at the same path (simulating a restart that
1862 // sees only what was fsynced). The record MUST be visible.
1863 let reopened = WalAuditStore::open(&dir, StubSigner { key: [2; 32] }).unwrap();
1864 let verifier = StubVerifier { key: [2; 32] };
1865 let recovered = reopened.verify_journal(&verifier).unwrap();
1866 assert_eq!(recovered.len(), 1);
1867 assert_eq!(recovered[0].decision, Decision::Deny);
1868 assert_eq!(recovered[0].reason, DecisionReason::TeMiss);
1869 assert_eq!(recovered[0].policy_hash, Some([0xaa; 32]));
1870
1871 // And the chain head continued monotonically after reopen: the highest
1872 // on-disk seq was 0, so the reopened counter is seeded to 1 (next write).
1873 assert_eq!(
1874 reopened.head.lock().next_seq,
1875 1,
1876 "reopened store must continue the sequence monotonically"
1877 );
1878 // Writing one more record assigns seq 1 (no collision with seq 0).
1879 reopened.record(&rec).unwrap();
1880 let recovered2 = reopened.verify_journal(&verifier).unwrap();
1881 assert_eq!(recovered2.len(), 2);
1882 assert_eq!(recovered2[0].seq, 0);
1883 assert_eq!(
1884 recovered2[1].seq, 1,
1885 "sequence must be gap-free across reopen"
1886 );
1887 }
1888
1889 // ── Property: tamper-evidence (content-address + signature) ─────────────
1890
1891 #[test]
1892 fn tampered_record_fails_verify() {
1893 let dir = tmp_dir("tamper");
1894 let store = WalAuditStore::open(&dir, StubSigner { key: [3; 32] }).unwrap();
1895 let rec = AuditRecord {
1896 seq: 0,
1897 prev_hash: [0u8; 32],
1898 ts_unix_nanos: 1,
1899 decision: Decision::Permit,
1900 generation: 7,
1901 policy_hash: None,
1902 subject_type: SubjectType(1),
1903 subject_clearance: high(),
1904 on_behalf_of: None,
1905 object_type: ObjectType(1),
1906 object_label: low(),
1907 action: Action(1),
1908 reason: DecisionReason::Permit,
1909 subject_id: None,
1910 object_id: None,
1911 };
1912 store.record(&rec).unwrap();
1913
1914 // Tamper: flip the first char of the journal payload's CBOR field. The
1915 // signature (over the content hash of the canonical bytes) must no
1916 // longer verify. We flip the FIRST base64 char of the `<cbor_b64>`
1917 // field (not a trailing one) so the decoded bytes genuinely change
1918 // regardless of the encoding's length — a trailing-appended char can be
1919 // an incomplete base64 group the decoder drops, leaving the bytes (and
1920 // thus the hash) unchanged (Fu6/#677 made the encoding CBOR, which
1921 // shifted the payload length enough to expose this).
1922 let jp = dir.join("journal.log");
1923 let content = std::fs::read(&jp).unwrap();
1924 let mut lines: Vec<Vec<u8>> = content.split(|b| *b == b'\n').map(<[u8]>::to_vec).collect();
1925 let last_line = lines
1926 .iter_mut()
1927 .rev()
1928 .find(|l| !l.is_empty())
1929 .expect("journal has at least one record");
1930 // Locate the start of the 3rd `\t`-delimited field (the cbor_b64).
1931 let mut tab_count = 0;
1932 let mut cbor_start = 0;
1933 for (i, b) in last_line.iter().enumerate() {
1934 if *b == b'\t' {
1935 tab_count += 1;
1936 if tab_count == 2 {
1937 cbor_start = i + 1;
1938 break;
1939 }
1940 }
1941 }
1942 assert!(
1943 cbor_start < last_line.len(),
1944 "journal line has a cbor field"
1945 );
1946 let orig = last_line[cbor_start];
1947 last_line[cbor_start] = if orig == b'A' { b'B' } else { b'A' };
1948 let tampered: Vec<u8> = lines
1949 .iter()
1950 .flat_map(|l| l.iter().copied().chain(std::iter::once(b'\n')))
1951 .collect();
1952 std::fs::write(&jp, tampered).unwrap();
1953
1954 let reopened = WalAuditStore::open(&dir, StubSigner { key: [3; 32] }).unwrap();
1955 let verifier = StubVerifier { key: [3; 32] };
1956 let res = reopened.verify_journal(&verifier);
1957 assert!(
1958 res.is_err(),
1959 "a tampered record must fail signature verification"
1960 );
1961 }
1962
1963 // ── Property: sequence is gap-free (truncation detection) ───────────────
1964
1965 #[test]
1966 fn journal_seq_gap_is_detected() {
1967 // The store owns seq assignment, so a live store never produces a gap.
1968 // Truncation/tampering, however, could remove or renumber journal lines.
1969 // We simulate that by writing a valid journal then rewriting it with a
1970 // gap, and assert verify_journal catches the regression.
1971 let dir = tmp_dir("gap");
1972 let store = WalAuditStore::open(&dir, StubSigner { key: [4; 32] }).unwrap();
1973 let base = AuditRecord {
1974 seq: 0, // ignored — the store assigns seq.
1975 prev_hash: [0u8; 32], // ignored — the store assigns the chain link.
1976 ts_unix_nanos: 1,
1977 decision: Decision::Permit,
1978 generation: 7,
1979 policy_hash: None,
1980 subject_type: SubjectType(1),
1981 subject_clearance: high(),
1982 on_behalf_of: None,
1983 object_type: ObjectType(1),
1984 object_label: low(),
1985 action: Action(1),
1986 reason: DecisionReason::Permit,
1987 subject_id: None,
1988 object_id: None,
1989 };
1990 // Write two records (store assigns seq 0, then 1).
1991 store.record(&base).unwrap();
1992 store.record(&base).unwrap();
1993 let verifier = StubVerifier { key: [4; 32] };
1994 // Sanity: the live journal verifies.
1995 let ok = store.verify_journal(&verifier).unwrap();
1996 assert_eq!(ok.len(), 2);
1997
1998 // Tamper: rewrite the journal renumbering the second line from seq 1 to
1999 // seq 5 (a gap of 2,3,4). verify_journal must reject it.
2000 let jp = dir.join("journal.log");
2001 let content = std::fs::read_to_string(&jp).unwrap();
2002 let mut lines: Vec<String> = content.lines().map(str::to_owned).collect();
2003 // The store wrote seq 0 then seq 1. Rewrite the seq field of line 2.
2004 if lines.len() >= 2 {
2005 let parts: Vec<&str> = lines[1].splitn(3, '\t').collect();
2006 assert_eq!(parts.len(), 3, "journal line must have seq\\tsig\\tpayload");
2007 lines[1] = format!("5\t{}\t{}", parts[1], parts[2]);
2008 }
2009 std::fs::write(&jp, lines.join("\n") + "\n").unwrap();
2010
2011 let res = store.verify_journal(&verifier);
2012 match res {
2013 Err(AuditError::SeqRegression { journal, counter }) => {
2014 assert_eq!(journal, 5);
2015 assert_eq!(counter, 1, "expected the gap at counter=1");
2016 }
2017 other => panic!("expected SeqRegression, got {other:?}"),
2018 }
2019 }
2020
2021 // ── B3 (#675): hash-chain + signed checkpoint truncation detection ──────
2022
2023 /// A permit record with placeholder seq/prev_hash (the store assigns both).
2024 fn perm_rec() -> AuditRecord {
2025 AuditRecord {
2026 seq: 0,
2027 prev_hash: [0u8; 32],
2028 ts_unix_nanos: 1,
2029 decision: Decision::Permit,
2030 generation: 7,
2031 policy_hash: None,
2032 subject_type: SubjectType(1),
2033 subject_clearance: high(),
2034 on_behalf_of: None,
2035 object_type: ObjectType(1),
2036 object_label: low(),
2037 action: Action(1),
2038 reason: DecisionReason::Permit,
2039 subject_id: None,
2040 object_id: None,
2041 }
2042 }
2043
2044 #[test]
2045 fn reopen_reads_only_the_tail_of_a_large_journal() {
2046 let dir = tmp_dir("bounded_tail");
2047 let store = WalAuditStore::open(&dir, StubSigner { key: [7; 32] }).unwrap();
2048 store.record(&perm_rec()).unwrap();
2049 let journal = dir.join("journal.log");
2050 let expected = journal_tail(&journal).unwrap();
2051 let last_line = std::fs::read(&journal).unwrap();
2052
2053 // A sparse prefix makes the file large without consuming disk or RAM.
2054 // Runtime open must seek to the last record instead of reading it all.
2055 let mut file = OpenOptions::new()
2056 .write(true)
2057 .truncate(true)
2058 .open(&journal)
2059 .unwrap();
2060 file.seek(SeekFrom::Start(256 * 1024 * 1024)).unwrap();
2061 file.write_all(b"\n").unwrap();
2062 file.write_all(&last_line).unwrap();
2063 drop(file);
2064
2065 assert_eq!(journal_tail(&journal).unwrap(), expected);
2066 WalAuditStore::open(&dir, StubSigner { key: [7; 32] }).unwrap();
2067 std::fs::remove_dir_all(dir).unwrap();
2068 }
2069
2070 #[test]
2071 fn oversized_unterminated_tail_fails_without_unbounded_allocation() {
2072 let dir = tmp_dir("oversized_tail");
2073 std::fs::create_dir_all(&dir).unwrap();
2074 let journal = dir.join("journal.log");
2075 std::fs::write(&journal, vec![b'x'; MAX_AUDIT_TAIL_LINE + 1]).unwrap();
2076 assert!(
2077 matches!(journal_tail(&journal), Err(AuditError::Decode(message)) if message.contains("exceeds limit"))
2078 );
2079 std::fs::remove_dir_all(dir).unwrap();
2080 }
2081
2082 #[test]
2083 fn oversized_record_cannot_commit_an_unreadable_tail() {
2084 let dir = tmp_dir("oversized_write");
2085 let store = WalAuditStore::open(&dir, StubSigner { key: [7; 32] }).unwrap();
2086 store.record(&perm_rec()).unwrap();
2087 let journal = dir.join("journal.log");
2088 let checkpoint = dir.join("checkpoint");
2089 let original_journal = std::fs::read(&journal).unwrap();
2090 let original_checkpoint = std::fs::read(&checkpoint).unwrap();
2091
2092 let mut oversized = perm_rec();
2093 oversized.object_id = Some("x".repeat(MAX_AUDIT_TAIL_LINE));
2094 assert!(
2095 matches!(store.record(&oversized), Err(AuditError::Encode(message)) if message.contains("exceeds limit"))
2096 );
2097 assert_eq!(std::fs::read(&journal).unwrap(), original_journal);
2098 assert_eq!(std::fs::read(&checkpoint).unwrap(), original_checkpoint);
2099
2100 drop(store);
2101 let reopened = WalAuditStore::open(&dir, StubSigner { key: [7; 32] }).unwrap();
2102 reopened.record(&perm_rec()).unwrap();
2103 assert_eq!(journal_tail(&journal).unwrap().unwrap().0, 1);
2104 std::fs::remove_dir_all(dir).unwrap();
2105 }
2106
2107 /// Drop the last journal line (simulate a truncated tail).
2108 fn truncate_last_line(journal: &Path) {
2109 let content = std::fs::read_to_string(journal).unwrap();
2110 let mut lines: Vec<&str> = content.lines().filter(|l| !l.is_empty()).collect();
2111 lines.pop();
2112 std::fs::write(journal, lines.join("\n") + "\n").unwrap();
2113 }
2114
2115 /// The headline B3 fix: deleting the journal tail is detected on reopen via
2116 /// the signed checkpoint. The pre-fix store re-seeded its seq counter from
2117 /// the truncated journal head and continued silently — this asserts we now
2118 /// FAIL CLOSED instead.
2119 #[test]
2120 fn tail_truncation_is_detected_on_reopen() {
2121 let dir = tmp_dir("b3_trunc_reopen");
2122 let store = WalAuditStore::open(&dir, StubSigner { key: [7; 32] }).unwrap();
2123 for _ in 0..3 {
2124 store.record(&perm_rec()).unwrap(); // seq 0,1,2; checkpoint at seq 2
2125 }
2126 drop(store);
2127
2128 truncate_last_line(&dir.join("journal.log")); // journal head now seq 1
2129
2130 // `open` returns `Result<WalAuditStore, _>` and the store is not Debug,
2131 // so match on the Result rather than `unwrap_err`.
2132 let reopen = WalAuditStore::open(&dir, StubSigner { key: [7; 32] });
2133 assert!(
2134 matches!(
2135 reopen,
2136 Err(AuditError::Truncation {
2137 checkpoint_seq: 2,
2138 journal_seq: Some(1)
2139 })
2140 ),
2141 "reopen must fail closed on the truncated tail"
2142 );
2143 }
2144
2145 /// The offline verifier catches the same truncation (and would also catch a
2146 /// checkpoint that survived but is now ahead of the journal head).
2147 #[test]
2148 fn tail_truncation_is_detected_by_verify_journal() {
2149 let dir = tmp_dir("b3_trunc_verify");
2150 let store = WalAuditStore::open(&dir, StubSigner { key: [8; 32] }).unwrap();
2151 for _ in 0..3 {
2152 store.record(&perm_rec()).unwrap();
2153 }
2154 truncate_last_line(&dir.join("journal.log"));
2155
2156 let err = store
2157 .verify_journal(&StubVerifier { key: [8; 32] })
2158 .unwrap_err();
2159 assert!(
2160 matches!(
2161 err,
2162 AuditError::Truncation {
2163 checkpoint_seq: 2,
2164 ..
2165 }
2166 ),
2167 "verify_journal must detect the truncated tail, got {err:?}"
2168 );
2169 }
2170
2171 /// A record that is individually valid — correct seq, a real signature — but
2172 /// links to the WRONG predecessor hash must break the chain. A checker that
2173 /// only validated seq + signature (the pre-B3 behaviour) would accept it.
2174 #[test]
2175 fn forged_record_with_wrong_prev_hash_breaks_the_chain() {
2176 let dir = tmp_dir("b3_chain");
2177 let signer = StubSigner { key: [9; 32] };
2178 let store = WalAuditStore::open(&dir, StubSigner { key: [9; 32] }).unwrap();
2179 store.record(&perm_rec()).unwrap(); // seq 0
2180 store.record(&perm_rec()).unwrap(); // seq 1
2181 drop(store);
2182
2183 // Forge a replacement for the seq-1 line: valid seq, valid signature over
2184 // its own content, but a bogus prev_hash that does not link to seq 0.
2185 let forged = AuditRecord {
2186 seq: 1,
2187 prev_hash: [0xEE; 32],
2188 ..perm_rec()
2189 };
2190 let bytes = forged.canonical_bytes().unwrap();
2191 let hash = *blake3::hash(&bytes).as_bytes();
2192 let sig = signer.sign(&audit_signing_input(&hash)).unwrap();
2193 let forged_line = format!("1\t{}\t{}", hex_encode(&sig), base64_encode(&bytes));
2194
2195 let jp = dir.join("journal.log");
2196 let content = std::fs::read_to_string(&jp).unwrap();
2197 let mut lines: Vec<String> = content.lines().map(str::to_owned).collect();
2198 lines[1] = forged_line;
2199 std::fs::write(&jp, lines.join("\n") + "\n").unwrap();
2200
2201 // Reopen succeeds (seq 1 == checkpoint seq, no truncation); the chain
2202 // break surfaces in verify_journal — before the signature even matters.
2203 let reopened = WalAuditStore::open(&dir, StubSigner { key: [9; 32] }).unwrap();
2204 let err = reopened
2205 .verify_journal(&StubVerifier { key: [9; 32] })
2206 .unwrap_err();
2207 assert!(
2208 matches!(err, AuditError::ChainBreak { seq: 1 }),
2209 "a signed record with a wrong prev_hash must break the chain, got {err:?}"
2210 );
2211 }
2212
2213 /// An intact 3-record store verifies cleanly end-to-end (chain links + the
2214 /// checkpoint anchors the real head) — the positive control for the above.
2215 #[test]
2216 fn intact_chain_and_checkpoint_verify() {
2217 let dir = tmp_dir("b3_intact");
2218 let store = WalAuditStore::open(&dir, StubSigner { key: [10; 32] }).unwrap();
2219 for _ in 0..3 {
2220 store.record(&perm_rec()).unwrap();
2221 }
2222 let recs = store
2223 .verify_journal(&StubVerifier { key: [10; 32] })
2224 .unwrap();
2225 assert_eq!(recs.len(), 3);
2226 assert_eq!(recs[0].prev_hash, [0u8; 32], "genesis links to zero");
2227 assert_ne!(recs[1].prev_hash, [0u8; 32], "later records chain forward");
2228 }
2229
2230 // ── Complete mediation: every decision is audited ───────────────────────
2231
2232 #[test]
2233 fn every_decision_is_audited_including_cache_hits() {
2234 let inner = avc();
2235 let sink = Arc::new(CapturingSink::new());
2236 let audited = AuditedAvc::new(inner, sink.clone(), 7, None);
2237
2238 // First call: PDP miss → evaluate → cache → audit.
2239 let d1 = audited.decide(subj(1, high()), obj(1, low()), Action(1));
2240 // Second call: cache hit → still audit (completeness over cache efficiency).
2241 let d2 = audited.decide(subj(1, high()), obj(1, low()), Action(1));
2242 // A deny also audited.
2243 let d3 = audited.decide(subj(1, high()), obj(1, low()), Action(9));
2244
2245 assert_eq!(d1, Decision::Permit);
2246 assert_eq!(d2, Decision::Permit);
2247 assert_eq!(d3, Decision::Deny);
2248 let recs = sink.records();
2249 assert_eq!(recs.len(), 3, "all three ops must produce audit records");
2250 assert_eq!(recs[0].decision, Decision::Permit);
2251 assert_eq!(recs[1].decision, Decision::Permit);
2252 assert_eq!(recs[2].decision, Decision::Deny);
2253 assert_eq!(recs[2].reason, DecisionReason::TeMiss);
2254 }
2255
2256 // ── Fail-closed: Permit downgrades to Deny when audit write fails ───────
2257
2258 #[test]
2259 fn permit_downgrades_to_deny_when_audit_write_fails() {
2260 let inner = avc();
2261 let sink = Arc::new(CapturingSink::new());
2262 let audited = AuditedAvc::new(inner, sink.clone(), 7, None);
2263
2264 // Poison the next record() — the audit write will fail.
2265 sink.fail_next();
2266 // This WOULD be a Permit (rule (1,1,1) exists + floor holds), but the
2267 // audit write fails, so it must be downgraded to Deny.
2268 let d = audited.decide(subj(1, high()), obj(1, low()), Action(1));
2269 assert_eq!(
2270 d,
2271 Decision::Deny,
2272 "a Permit that can't be audited MUST be denied"
2273 );
2274
2275 // The fail-closed deny itself is recorded (best-effort second write).
2276 let recs = sink.records();
2277 let fail_closed = recs
2278 .iter()
2279 .find(|r| r.reason == DecisionReason::AuditFailClosed);
2280 assert!(
2281 fail_closed.is_some(),
2282 "the fail-closed deny must itself be auditable"
2283 );
2284 assert_eq!(fail_closed.unwrap().decision, Decision::Deny);
2285 }
2286
2287 // ── Deny stays Deny even if audit write fails (no escalation) ───────────
2288
2289 #[test]
2290 fn deny_stays_deny_when_audit_write_fails() {
2291 let inner = avc();
2292 let sink = Arc::new(CapturingSink::new());
2293 let audited = AuditedAvc::new(inner, sink.clone(), 7, None);
2294 sink.fail_next();
2295 // A deny (action 9 not in matrix) when audit fails: still a deny.
2296 let d = audited.decide(subj(1, high()), obj(1, low()), Action(9));
2297 assert_eq!(d, Decision::Deny);
2298 }
2299
2300 // ── NullAuditSink passes decisions through unchanged ────────────────────
2301
2302 #[test]
2303 fn null_sink_is_pass_through() {
2304 let inner = avc();
2305 let audited = AuditedAvc::new(inner, NullAuditSink, 7, None);
2306 assert_eq!(
2307 audited.decide(subj(1, high()), obj(1, low()), Action(1)),
2308 Decision::Permit
2309 );
2310 assert_eq!(
2311 audited.decide(subj(1, high()), obj(1, low()), Action(9)),
2312 Decision::Deny
2313 );
2314 }
2315
2316 // ── helpers ─────────────────────────────────────────────────────────────
2317
2318 #[test]
2319 fn shard_of_splits_two_then_rest() {
2320 let h = [0xab; 32];
2321 let (shard, rest) = shard_of(&h);
2322 assert_eq!(shard, "ab");
2323 assert_eq!(rest.len(), 62);
2324 }
2325
2326 #[test]
2327 fn hex_roundtrip() {
2328 let bytes = [0x00, 0x01, 0xfe, 0xff, 0xab, 0xcd];
2329 let s = hex_encode(&bytes);
2330 assert_eq!(hex_decode(&s).unwrap(), bytes);
2331 }
2332
2333 #[test]
2334 fn base64_roundtrip() {
2335 for case in [
2336 &b""[..],
2337 b"a",
2338 b"ab",
2339 b"abc",
2340 b"\xff\x00\x10\xde",
2341 b"hello audit",
2342 ] {
2343 let s = base64_encode(case);
2344 let dec = base64_decode(&s).unwrap();
2345 assert_eq!(dec, case, "roundtrip failed for {case:?}");
2346 }
2347 }
2348
2349 // ── S8 (#574): policy-aware hybrid audit signing ───────────────────────
2350
2351 use crate::mac::audit::cose::{CoseAuditSigner, CoseAuditVerifier};
2352 use ed25519_dalek::SigningKey;
2353 use hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair;
2354 use hyprstream_rpc::crypto::CryptoPolicy;
2355 use rand::rngs::OsRng;
2356
2357 /// Under a Hybrid policy, a signer with both keys produces a hybrid composite
2358 /// that verifies with `require_pq = true`.
2359 #[test]
2360 fn cose_audit_signer_hybrid_roundtrips_under_hybrid_policy() {
2361 let ed = SigningKey::generate(&mut OsRng);
2362 let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
2363 let signer = CoseAuditSigner::new(&ed, Some(&pq_sk), CryptoPolicy::Hybrid);
2364 assert!(signer.can_sign());
2365
2366 let input = b"audit-record-signing-input";
2367 let sig = signer.sign(input).unwrap();
2368
2369 let verifier = CoseAuditVerifier {
2370 ed_vk: &ed.verifying_key(),
2371 pq_vk: Some(&pq_vk),
2372 require_pq: true,
2373 };
2374 assert!(verifier.verify(input, &sig).is_ok());
2375 }
2376
2377 /// Fail-closed: under a Hybrid policy, a signer with NO ML-DSA-65 key MUST
2378 /// refuse to sign (no silent downgrade of a security-critical accounting
2379 /// artifact). `can_sign()` reflects this.
2380 #[test]
2381 fn cose_audit_signer_fails_closed_under_hybrid_without_pq_key() {
2382 let ed = SigningKey::generate(&mut OsRng);
2383 let signer = CoseAuditSigner::new(&ed, None, CryptoPolicy::Hybrid);
2384 assert!(!signer.can_sign(), "Hybrid without PQ key cannot sign");
2385 let err = signer.sign(b"x").unwrap_err();
2386 assert!(
2387 matches!(err, AuditError::Sign(ref m) if m.contains("fail-closed")),
2388 "expected fail-closed Sign error, got {err:?}"
2389 );
2390 }
2391
2392 /// Under a Classical policy, the signer emits an EdDSA-only signature even
2393 /// if a PQ key was supplied (the PQ key is ignored — no silent hybrid). The
2394 /// classical verifier (`require_pq = false`) accepts it.
2395 #[test]
2396 fn cose_audit_signer_classical_emits_eddsa_only() {
2397 let ed = SigningKey::generate(&mut OsRng);
2398 let (pq_sk, _pq_vk) = ml_dsa_generate_keypair();
2399 // Classical policy: PQ key is IGNORED.
2400 let signer = CoseAuditSigner::new(&ed, Some(&pq_sk), CryptoPolicy::Classical);
2401 assert!(signer.can_sign());
2402
2403 let input = b"classical-audit";
2404 let sig = signer.sign(input).unwrap();
2405 // Classical verifier accepts the EdDSA-only signature.
2406 let verifier = CoseAuditVerifier {
2407 ed_vk: &ed.verifying_key(),
2408 pq_vk: None,
2409 require_pq: false,
2410 };
2411 assert!(verifier.verify(input, &sig).is_ok());
2412
2413 // A Hybrid verifier MUST reject the classical-only signature.
2414 let (_other_sk, other_vk) = ml_dsa_generate_keypair();
2415 let hybrid_verifier = CoseAuditVerifier {
2416 ed_vk: &ed.verifying_key(),
2417 pq_vk: Some(&other_vk),
2418 require_pq: true,
2419 };
2420 assert!(
2421 hybrid_verifier.verify(input, &sig).is_err(),
2422 "Hybrid verifier must reject classical-only audit signature"
2423 );
2424 }
2425
2426 /// Tampered audit input must fail hybrid verification.
2427 #[test]
2428 fn cose_audit_signer_tampered_input_rejected() {
2429 let ed = SigningKey::generate(&mut OsRng);
2430 let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
2431 let signer = CoseAuditSigner::new(&ed, Some(&pq_sk), CryptoPolicy::Hybrid);
2432 let sig = signer.sign(b"original").unwrap();
2433 let verifier = CoseAuditVerifier {
2434 ed_vk: &ed.verifying_key(),
2435 pq_vk: Some(&pq_vk),
2436 require_pq: true,
2437 };
2438 assert!(verifier.verify(b"tampered", &sig).is_err());
2439 }
2440}