Skip to main content

reddb_server/runtime/
audit_log.rs

1//! Structured audit log for SOC 2 / HIPAA / ISO 27001 deploys.
2//!
3//! Replaces the previous free-form `record(action, principal, target,
4//! result, details)` API with a stable JSON-Lines schema keyed on
5//! `event_id`, `ts`, `principal`, `tenant`, `action`, `resource`,
6//! `outcome`, `detail`, `remote_addr`, and `correlation_id` so external
7//! tooling (Splunk, Datadog HEC, ELK, BigQuery, Athena) can ingest the
8//! file without per-deploy regex.
9//!
10//! Operational properties:
11//!   * **Async-write**: emit sites push onto a bounded `std::sync::mpsc`
12//!     channel; a dedicated thread owns the file handle and flushes on
13//!     a periodic timer (default 250 ms) or per-event when
14//!     `RED_AUDIT_FSYNC=every`. If the channel fills the emit site
15//!     falls back to a direct sync write — losing throughput is
16//!     preferable to dropping audit lines.
17//!   * **Rotation**: when the active file exceeds `RED_AUDIT_MAX_BYTES`
18//!     (default 64 MiB) the writer renames it to
19//!     `.audit.log.<ms>.zst`, zstd-compresses it, and starts a fresh
20//!     active file. The repo already pulls `zstd`; we don't add a gzip
21//!     dependency.
22//!   * **Hash chain (tamper-evidence)**: each event carries a
23//!     `prev_hash` field — the sha256 of the previous JSON line. An
24//!     auditor verifying the file recomputes the chain; a single edit
25//!     anywhere in the file breaks every subsequent hash. Does **not**
26//!     defend against an attacker with `root + write` (they could
27//!     rebuild the chain), but it does defend against accidental edits
28//!     and most insider tampering.
29//!   * **SIEM streaming**: when `RED_AUDIT_STREAM_URL` is set every
30//!     line is also POSTed to that URL fire-and-forget.
31//!
32//! Pre-1.0: the file format breaks from the previous shape. Old
33//! `.audit.log` files are NOT readable by the new query endpoint.
34//! That's an accepted regression — operators upgrading should rotate
35//! the file before the deploy.
36
37use std::io::{BufWriter, Write};
38use std::path::{Path, PathBuf};
39use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
40use std::sync::{mpsc, Arc, Mutex};
41use std::thread::{self, JoinHandle};
42use std::time::{Duration, Instant};
43
44use crate::crypto::{os_random, sha256};
45use crate::json::{Map, Value as JsonValue};
46use reddb_types::encoding::base64_encode;
47
48// ---------------------------------------------------------------------------
49// Schema
50// ---------------------------------------------------------------------------
51
52/// Auth pathway that produced the principal. Decoupled from
53/// `crate::auth::AuthSource` so we can record System / Anonymous /
54/// Session / ApiKey lanes that aren't surfaced by the runtime auth
55/// enum (which only covers Password / ClientCert / Oauth today).
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum AuditAuthSource {
58    ApiKey,
59    Session,
60    Password,
61    Oauth,
62    ClientCert,
63    Anonymous,
64    System,
65}
66
67impl AuditAuthSource {
68    pub fn as_str(self) -> &'static str {
69        match self {
70            Self::ApiKey => "api_key",
71            Self::Session => "session",
72            Self::Password => "password",
73            Self::Oauth => "oauth",
74            Self::ClientCert => "client_cert",
75            Self::Anonymous => "anonymous",
76            Self::System => "system",
77        }
78    }
79
80    pub fn parse(s: &str) -> Option<Self> {
81        Some(match s {
82            "api_key" => Self::ApiKey,
83            "session" => Self::Session,
84            "password" => Self::Password,
85            "oauth" => Self::Oauth,
86            "client_cert" => Self::ClientCert,
87            "anonymous" => Self::Anonymous,
88            "system" => Self::System,
89            _ => return None,
90        })
91    }
92}
93
94/// Outcome of the audited action.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum Outcome {
97    Success,
98    Denied,
99    Error,
100}
101
102impl Outcome {
103    pub fn as_str(self) -> &'static str {
104        match self {
105            Self::Success => "success",
106            Self::Denied => "denied",
107            Self::Error => "error",
108        }
109    }
110
111    pub fn parse(s: &str) -> Option<Self> {
112        Some(match s {
113            "success" | "ok" => Self::Success,
114            "denied" | "deny" => Self::Denied,
115            "error" | "err" => Self::Error,
116            _ => return None,
117        })
118    }
119}
120
121/// Structured audit event. Serialised as one JSONL row per call.
122#[derive(Debug, Clone)]
123pub struct AuditEvent {
124    pub ts: u128,
125    pub event_id: String,
126    pub principal: Option<String>,
127    pub source: AuditAuthSource,
128    pub tenant: Option<String>,
129    pub action: String,
130    pub resource: Option<String>,
131    pub outcome: Outcome,
132    pub detail: JsonValue,
133    pub remote_addr: Option<String>,
134    pub correlation_id: Option<String>,
135}
136
137impl AuditEvent {
138    /// Convenience builder. The caller fills the required fields and
139    /// chains the optional ones — keeps emit sites readable.
140    pub fn builder(action: impl Into<String>) -> AuditEventBuilder {
141        AuditEventBuilder {
142            inner: AuditEvent {
143                ts: crate::utils::now_unix_millis() as u128,
144                event_id: new_event_id(),
145                principal: None,
146                source: AuditAuthSource::System,
147                tenant: None,
148                action: action.into(),
149                resource: None,
150                outcome: Outcome::Success,
151                detail: JsonValue::Null,
152                remote_addr: None,
153                correlation_id: None,
154            },
155        }
156    }
157
158    /// Wrap a pre-structured-API call into the new schema. Used by the
159    /// back-compat `record(action, principal, target, result, details)`
160    /// path so existing emit sites keep compiling.
161    pub fn from_legacy(
162        action: &str,
163        principal: &str,
164        target: &str,
165        result: &str,
166        details: JsonValue,
167    ) -> Self {
168        let outcome = if result == "ok" {
169            Outcome::Success
170        } else if result.starts_with("err") {
171            Outcome::Error
172        } else if result.starts_with("denied") || result.starts_with("deny") {
173            Outcome::Denied
174        } else {
175            Outcome::Success
176        };
177        let mut detail = details;
178        if !result.is_empty() && result != "ok" {
179            // Preserve the human-readable result string for forensic
180            // continuity with pre-restructuring lines.
181            let mut obj = match detail {
182                JsonValue::Object(map) => map,
183                JsonValue::Null => Map::new(),
184                other => {
185                    let mut m = Map::new();
186                    m.insert("legacy".to_string(), other);
187                    m
188                }
189            };
190            obj.entry("result_text".to_string())
191                .or_insert(JsonValue::String(result.to_string()));
192            detail = JsonValue::Object(obj);
193        }
194        Self {
195            ts: crate::utils::now_unix_millis() as u128,
196            event_id: new_event_id(),
197            principal: if principal.is_empty() || principal == "system" {
198                None
199            } else {
200                Some(principal.to_string())
201            },
202            source: if principal == "system" {
203                AuditAuthSource::System
204            } else if principal.is_empty() {
205                AuditAuthSource::Anonymous
206            } else {
207                AuditAuthSource::Password
208            },
209            tenant: None,
210            action: action.to_string(),
211            resource: if target.is_empty() {
212                None
213            } else {
214                Some(target.to_string())
215            },
216            outcome,
217            detail,
218            remote_addr: None,
219            correlation_id: None,
220        }
221    }
222
223    /// Render to a single JSONL line, optionally seeded with a
224    /// `prev_hash` for the tamper-evident chain.
225    pub fn to_json_line(&self, prev_hash: Option<&str>) -> String {
226        let mut object = Map::new();
227        object.insert("ts".to_string(), JsonValue::Number(self.ts as f64));
228        object.insert(
229            "ts_iso".to_string(),
230            JsonValue::String(format_iso8601(self.ts as u64)),
231        );
232        object.insert(
233            "event_id".to_string(),
234            JsonValue::String(self.event_id.clone()),
235        );
236        if let Some(p) = &self.principal {
237            object.insert("principal".to_string(), JsonValue::String(p.clone()));
238        }
239        object.insert(
240            "source".to_string(),
241            JsonValue::String(self.source.as_str().to_string()),
242        );
243        if let Some(t) = &self.tenant {
244            object.insert("tenant".to_string(), JsonValue::String(t.clone()));
245        }
246        object.insert("action".to_string(), JsonValue::String(self.action.clone()));
247        if let Some(r) = &self.resource {
248            object.insert("resource".to_string(), JsonValue::String(r.clone()));
249        }
250        object.insert(
251            "outcome".to_string(),
252            JsonValue::String(self.outcome.as_str().to_string()),
253        );
254        if !matches!(self.detail, JsonValue::Null) {
255            object.insert("detail".to_string(), self.detail.clone());
256        }
257        if let Some(ip) = &self.remote_addr {
258            object.insert("remote_addr".to_string(), JsonValue::String(ip.clone()));
259        }
260        if let Some(cid) = &self.correlation_id {
261            object.insert("correlation_id".to_string(), JsonValue::String(cid.clone()));
262        }
263        if let Some(h) = prev_hash {
264            object.insert("prev_hash".to_string(), JsonValue::String(h.to_string()));
265        }
266        JsonValue::Object(object).to_string_compact()
267    }
268
269    /// Parse one JSONL line back into an `AuditEvent`. Returns `None`
270    /// for legacy lines (pre-restructuring) or malformed JSON; callers
271    /// in the query path use this to filter.
272    pub fn parse_line(line: &str) -> Option<Self> {
273        let v: JsonValue = crate::json::from_str(line).ok()?;
274        let action = v.get("action")?.as_str()?.to_string();
275        let outcome_s = v.get("outcome").and_then(|n| n.as_str()).unwrap_or("");
276        let outcome = Outcome::parse(outcome_s)?;
277        let ts = v.get("ts").and_then(|n| n.as_f64()).unwrap_or(0.0) as u128;
278        let event_id = v
279            .get("event_id")
280            .and_then(|n| n.as_str())
281            .unwrap_or("")
282            .to_string();
283        let source = v
284            .get("source")
285            .and_then(|n| n.as_str())
286            .and_then(AuditAuthSource::parse)
287            .unwrap_or(AuditAuthSource::System);
288        Some(Self {
289            ts,
290            event_id,
291            principal: v
292                .get("principal")
293                .and_then(|n| n.as_str())
294                .map(|s| s.to_string()),
295            source,
296            tenant: v
297                .get("tenant")
298                .and_then(|n| n.as_str())
299                .map(|s| s.to_string()),
300            action,
301            resource: v
302                .get("resource")
303                .and_then(|n| n.as_str())
304                .map(|s| s.to_string()),
305            outcome,
306            detail: v.get("detail").cloned().unwrap_or(JsonValue::Null),
307            remote_addr: v
308                .get("remote_addr")
309                .and_then(|n| n.as_str())
310                .map(|s| s.to_string()),
311            correlation_id: v
312                .get("correlation_id")
313                .and_then(|n| n.as_str())
314                .map(|s| s.to_string()),
315        })
316    }
317}
318
319/// Builder for `AuditEvent`. Generated by `AuditEvent::builder()`.
320pub struct AuditEventBuilder {
321    inner: AuditEvent,
322}
323
324impl AuditEventBuilder {
325    pub fn principal(mut self, principal: impl Into<String>) -> Self {
326        self.inner.principal = Some(principal.into());
327        self
328    }
329
330    pub fn principal_opt(mut self, principal: Option<String>) -> Self {
331        self.inner.principal = principal;
332        self
333    }
334
335    pub fn source(mut self, source: AuditAuthSource) -> Self {
336        self.inner.source = source;
337        self
338    }
339
340    pub fn tenant(mut self, tenant: impl Into<String>) -> Self {
341        self.inner.tenant = Some(tenant.into());
342        self
343    }
344
345    pub fn resource(mut self, resource: impl Into<String>) -> Self {
346        self.inner.resource = Some(resource.into());
347        self
348    }
349
350    pub fn outcome(mut self, outcome: Outcome) -> Self {
351        self.inner.outcome = outcome;
352        self
353    }
354
355    pub fn detail(mut self, detail: JsonValue) -> Self {
356        self.inner.detail = detail;
357        self
358    }
359
360    /// Add a single typed audit field to the detail object. Goes
361    /// through `AuditFieldEscaper` so caller-supplied bytes never
362    /// reach `format!` or string concatenation — see ADR 0010.
363    pub fn field(mut self, field: AuditField) -> Self {
364        let mut obj = match std::mem::replace(&mut self.inner.detail, JsonValue::Null) {
365            JsonValue::Object(map) => map,
366            JsonValue::Null => Map::new(),
367            other => {
368                // Preserve any preceding non-object detail under a
369                // reserved key rather than dropping it on the floor.
370                let mut m = Map::new();
371                m.insert("legacy_detail".to_string(), other);
372                m
373            }
374        };
375        obj.insert(field.name.to_string(), field.value.into_json_value());
376        self.inner.detail = JsonValue::Object(obj);
377        self
378    }
379
380    /// Bulk variant of [`Self::field`] for multi-field call sites.
381    pub fn fields(mut self, fields: impl IntoIterator<Item = AuditField>) -> Self {
382        for f in fields {
383            self = self.field(f);
384        }
385        self
386    }
387
388    pub fn remote_addr(mut self, addr: impl Into<String>) -> Self {
389        self.inner.remote_addr = Some(addr.into());
390        self
391    }
392
393    pub fn correlation_id(mut self, cid: impl Into<String>) -> Self {
394        self.inner.correlation_id = Some(cid.into());
395        self
396    }
397
398    pub fn build(self) -> AuditEvent {
399        self.inner
400    }
401}
402
403// ---------------------------------------------------------------------------
404// AuditFieldEscaper — typed-field guard (ADR 0010 / issue #177)
405// ---------------------------------------------------------------------------
406
407/// Typed value variants accepted by the audit-field guard. The
408/// serializer (`to_json_line`) owns the framing; an `AuditValue`
409/// cannot smuggle structural bytes past the canonical encoder
410/// (`crate::serde_json::Value::escape_string`, RFC 8259 §7) because
411/// the variant is consumed as a typed value, not as an interpolated
412/// string. Adversarial corpora (CRLF, NUL, quote, semicolon,
413/// JSON-in-JSON, control bytes 0x00..0x20) survive the boundary
414/// because the encoder emits `\u00XX` escapes for every byte below
415/// 0x20.
416#[derive(Debug, Clone)]
417pub enum AuditValue {
418    String(String),
419    /// Arbitrary bytes — base64-encoded on emit so non-UTF-8 payloads
420    /// (binary keys, raw frame bytes) never enter the JSON string
421    /// channel.
422    Bytes(Vec<u8>),
423    Number(i64),
424    Bool(bool),
425    Null,
426}
427
428impl AuditValue {
429    fn into_json_value(self) -> JsonValue {
430        match self {
431            AuditValue::String(s) => JsonValue::String(s),
432            AuditValue::Bytes(bytes) => JsonValue::String(base64_encode(&bytes)),
433            AuditValue::Number(n) => JsonValue::Number(n as f64),
434            AuditValue::Bool(b) => JsonValue::Bool(b),
435            AuditValue::Null => JsonValue::Null,
436        }
437    }
438}
439
440impl From<String> for AuditValue {
441    fn from(value: String) -> Self {
442        AuditValue::String(value)
443    }
444}
445
446impl From<&str> for AuditValue {
447    fn from(value: &str) -> Self {
448        AuditValue::String(value.to_string())
449    }
450}
451
452impl From<&String> for AuditValue {
453    fn from(value: &String) -> Self {
454        AuditValue::String(value.clone())
455    }
456}
457
458impl From<Vec<u8>> for AuditValue {
459    fn from(value: Vec<u8>) -> Self {
460        AuditValue::Bytes(value)
461    }
462}
463
464impl From<&[u8]> for AuditValue {
465    fn from(value: &[u8]) -> Self {
466        AuditValue::Bytes(value.to_vec())
467    }
468}
469
470impl From<i64> for AuditValue {
471    fn from(value: i64) -> Self {
472        AuditValue::Number(value)
473    }
474}
475
476impl From<u64> for AuditValue {
477    fn from(value: u64) -> Self {
478        // Saturate at i64::MAX rather than wrapping; audit fields
479        // are observability data, not arithmetic inputs.
480        AuditValue::Number(if value > i64::MAX as u64 {
481            i64::MAX
482        } else {
483            value as i64
484        })
485    }
486}
487
488impl From<u32> for AuditValue {
489    fn from(value: u32) -> Self {
490        AuditValue::Number(value as i64)
491    }
492}
493
494impl From<usize> for AuditValue {
495    fn from(value: usize) -> Self {
496        AuditValue::Number(if value > i64::MAX as usize {
497            i64::MAX
498        } else {
499            value as i64
500        })
501    }
502}
503
504impl From<bool> for AuditValue {
505    fn from(value: bool) -> Self {
506        AuditValue::Bool(value)
507    }
508}
509
510impl<T: Into<AuditValue>> From<Option<T>> for AuditValue {
511    fn from(value: Option<T>) -> Self {
512        match value {
513            Some(v) => v.into(),
514            None => AuditValue::Null,
515        }
516    }
517}
518
519/// A single typed audit field (key + typed value). Construction is
520/// gated by [`AuditFieldEscaper::field`] so the typed value cannot
521/// be bypassed — there is no `pub` constructor for the field that
522/// accepts a free-form string value.
523#[derive(Debug, Clone)]
524pub struct AuditField {
525    name: &'static str,
526    value: AuditValue,
527}
528
529impl AuditField {
530    pub fn name(&self) -> &'static str {
531        self.name
532    }
533    pub fn value(&self) -> &AuditValue {
534        &self.value
535    }
536}
537
538/// Typed-field guard for audit emission (ADR 0010).
539///
540/// The guard owns the boundary's escape contract: caller-supplied
541/// bytes always round-trip through a typed `AuditValue`, never
542/// through `format!`, never through string concatenation. The
543/// canonical JSON encoder is `crate::serde_json::Value::escape_string`
544/// (RFC 8259 §7 compliant after F-01 hotfix #181) which the
545/// `AuditEvent::to_json_line` serializer uses for every string slot.
546///
547/// The other two encoder paths in the codebase
548/// (`utils::json::JsonValue::write_json` and
549/// `presentation::query_result::write_json_string`) are correct after #181 but
550/// not the canonical owner of the audit boundary. Both are marked
551/// `#[deprecated]` on the audit path and remain in place for
552/// non-audit call sites pending follow-up retirement.
553pub struct AuditFieldEscaper;
554
555impl AuditFieldEscaper {
556    /// Construct a typed audit field. The `name` is `'static` so
557    /// the schema key set is fixed at compile time — only `value`
558    /// can carry attacker-influenced bytes, and `value` is a typed
559    /// enum, not a string sink.
560    pub fn field(name: &'static str, value: impl Into<AuditValue>) -> AuditField {
561        AuditField {
562            name,
563            value: value.into(),
564        }
565    }
566}
567
568// ---------------------------------------------------------------------------
569// Identifier
570// ---------------------------------------------------------------------------
571
572/// Crockford-base32 ULID-like ID: 10-char timestamp prefix + 16-char
573/// random suffix = 26 chars total. Ordered lexicographically by time.
574fn new_event_id() -> String {
575    const ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
576    let now_ms = crate::utils::now_unix_millis();
577    let mut rand_bytes = [0u8; 10];
578    let _ = os_random::fill_bytes(&mut rand_bytes);
579
580    let mut out = String::with_capacity(26);
581    // 48-bit timestamp -> 10 base32 chars (50 bits, top 2 are zero).
582    for i in (0..10).rev() {
583        let shift = (i as u32) * 5;
584        let idx = ((now_ms >> shift) & 0x1f) as usize;
585        out.push(ALPHABET[idx] as char);
586    }
587    // 80 random bits -> 16 base32 chars.
588    let mut acc: u128 = 0;
589    for &b in &rand_bytes {
590        acc = (acc << 8) | (b as u128);
591    }
592    for i in (0..16).rev() {
593        let shift = (i as u32) * 5;
594        let idx = ((acc >> shift) & 0x1f) as usize;
595        out.push(ALPHABET[idx] as char);
596    }
597    out
598}
599
600// ---------------------------------------------------------------------------
601// Fsync mode
602// ---------------------------------------------------------------------------
603
604#[derive(Debug, Clone, Copy, PartialEq, Eq)]
605enum FsyncMode {
606    /// Buffered, fsync only on rotation + shutdown.
607    Off,
608    /// fsync after every event. Safe for HIPAA strong-durability.
609    Every,
610    /// fsync every N ms (default 250) — compliance-appropriate
611    /// without tanking write throughput.
612    Periodic,
613}
614
615impl FsyncMode {
616    fn from_env() -> Self {
617        match std::env::var("RED_AUDIT_FSYNC")
618            .unwrap_or_default()
619            .to_ascii_lowercase()
620            .as_str()
621        {
622            "every" | "strong" | "on" => Self::Every,
623            "off" | "none" => Self::Off,
624            _ => Self::Periodic,
625        }
626    }
627}
628
629// ---------------------------------------------------------------------------
630// Channel message
631// ---------------------------------------------------------------------------
632
633#[allow(clippy::large_enum_variant)]
634enum WriterMsg {
635    Event(AuditEvent),
636    Flush(mpsc::Sender<()>),
637    Shutdown,
638}
639
640// ---------------------------------------------------------------------------
641// AuditLogger
642// ---------------------------------------------------------------------------
643
644#[derive(Debug)]
645pub struct AuditLogger {
646    path: PathBuf,
647    tx: Mutex<Option<mpsc::SyncSender<WriterMsg>>>,
648    /// Direct-write fallback mutex. Used when the writer thread isn't
649    /// running (in-memory tests) or the channel is full and the emit
650    /// site picks the sync path so the event can't be dropped.
651    fallback_lock: Mutex<()>,
652    /// Snapshot of the most recent line's sha256 for tamper-evidence.
653    /// Shared between the writer thread and the direct-write fallback
654    /// so the chain stays consistent across both paths.
655    last_hash: Arc<Mutex<Option<String>>>,
656    max_bytes: u64,
657    fsync_mode: FsyncMode,
658    stream_url: Option<String>,
659    /// Background-write flag; tests use `wait_idle()` to synchronise.
660    writer_alive: Arc<AtomicBool>,
661    pending: Arc<AtomicU64>,
662    handle: Mutex<Option<JoinHandle<()>>>,
663}
664
665impl AuditLogger {
666    /// Write audit events to stderr without creating a file or writer thread.
667    pub(crate) fn stderr() -> Self {
668        Self::with_settings(PathBuf::new(), 0, FsyncMode::Periodic, None)
669    }
670
671    /// Place the audit log next to the primary `.rdb` file so backup
672    /// + restore flows can ship it together.
673    pub fn for_data_path(data_path: &Path) -> Self {
674        Self::with_path(reddb_file::layout::legacy_audit_log_path(data_path))
675    }
676
677    /// Resolve a [`crate::storage::layout::LogDestination`] into a concrete
678    /// audit-log sink. `File(p)` writes to that exact path (Performance /
679    /// Max tier route here). `Stderr` and `Syslog` fall back to the legacy
680    /// `.audit.log` next to `fallback_data_path` — emit sites still get
681    /// durable storage while the dedicated stderr / syslog sinks are not
682    /// yet wired (ADR 0018 marks Syslog as a stub-and-warn lane).
683    pub fn for_destination(
684        dest: &crate::storage::layout::LogDestination,
685        fallback_data_path: &Path,
686    ) -> Self {
687        use crate::storage::layout::LogDestination;
688        match dest {
689            LogDestination::File(path) => Self::with_path(path.clone()),
690            LogDestination::Stderr => Self::for_data_path(fallback_data_path),
691            LogDestination::Syslog => {
692                tracing::warn!(
693                    target: "reddb::audit",
694                    "audit LogDestination::Syslog requested; sink not implemented, falling back to file next to data path"
695                );
696                Self::for_data_path(fallback_data_path)
697            }
698        }
699    }
700
701    /// Direct constructor primarily for tests that want a custom path.
702    pub fn with_path(path: PathBuf) -> Self {
703        let max_bytes = std::env::var("RED_AUDIT_MAX_BYTES")
704            .ok()
705            .and_then(|v| v.parse::<u64>().ok())
706            .unwrap_or(64 * 1024 * 1024);
707        let fsync_mode = FsyncMode::from_env();
708        let stream_url = std::env::var("RED_AUDIT_STREAM_URL")
709            .ok()
710            .filter(|s| !s.is_empty());
711        Self::with_settings(path, max_bytes, fsync_mode, stream_url)
712    }
713
714    /// Test/integration constructor with explicit settings — bypasses
715    /// env-var resolution so parallel tests don't race on `set_var`.
716    pub fn with_max_bytes(path: PathBuf, max_bytes: u64) -> Self {
717        Self::with_settings(path, max_bytes, FsyncMode::Periodic, None)
718    }
719
720    fn with_settings(
721        path: PathBuf,
722        max_bytes: u64,
723        fsync_mode: FsyncMode,
724        stream_url: Option<String>,
725    ) -> Self {
726        let writer_alive = Arc::new(AtomicBool::new(false));
727        let pending = Arc::new(AtomicU64::new(0));
728        // Seed the chain from the existing tail so a restart doesn't
729        // break tamper evidence.
730        let mut seed: Option<String> = None;
731        if !path.as_os_str().is_empty() {
732            if let Ok(body) = std::fs::read_to_string(&path) {
733                if let Some(line) = body.lines().last() {
734                    seed = Some(crate::utils::to_hex(&sha256::sha256(line.as_bytes())));
735                }
736            }
737        }
738        let last_hash = Arc::new(Mutex::new(seed));
739        let logger = Self {
740            path,
741            tx: Mutex::new(None),
742            fallback_lock: Mutex::new(()),
743            last_hash,
744            max_bytes,
745            fsync_mode,
746            stream_url,
747            writer_alive: Arc::clone(&writer_alive),
748            pending: Arc::clone(&pending),
749            handle: Mutex::new(None),
750        };
751        if !logger.path.as_os_str().is_empty() {
752            logger.start_writer_thread();
753        }
754        logger
755    }
756
757    pub fn path(&self) -> &Path {
758        &self.path
759    }
760
761    /// Active rotation threshold (bytes).
762    pub fn max_bytes(&self) -> u64 {
763        self.max_bytes
764    }
765
766    fn start_writer_thread(&self) {
767        let (tx, rx) = mpsc::sync_channel::<WriterMsg>(4096);
768        *self.tx.lock().unwrap_or_else(|e| e.into_inner()) = Some(tx);
769        let path = self.path.clone();
770        let max_bytes = self.max_bytes;
771        let fsync_mode = self.fsync_mode;
772        let stream_url = self.stream_url.clone();
773        let writer_alive = Arc::clone(&self.writer_alive);
774        let pending = Arc::clone(&self.pending);
775        let last_hash = Arc::clone(&self.last_hash);
776        writer_alive.store(true, Ordering::SeqCst);
777        let handle = thread::Builder::new()
778            .name("reddb-audit-writer".to_string())
779            .spawn(move || {
780                writer_loop(
781                    rx,
782                    path,
783                    max_bytes,
784                    fsync_mode,
785                    stream_url,
786                    writer_alive,
787                    pending,
788                    last_hash,
789                );
790            })
791            .expect("spawn audit writer thread");
792        *self.handle.lock().unwrap_or_else(|e| e.into_inner()) = Some(handle);
793    }
794
795    /// Latest tip-hash of the chain (for diagnostics + tests).
796    pub fn current_hash(&self) -> Option<String> {
797        self.last_hash
798            .lock()
799            .unwrap_or_else(|e| e.into_inner())
800            .clone()
801    }
802
803    /// Block until the writer thread has drained every pending event.
804    /// Tests use this to make assertions deterministic.
805    pub fn wait_idle(&self, timeout: Duration) -> bool {
806        let deadline = Instant::now() + timeout;
807        let tx_guard = self.tx.lock().unwrap_or_else(|e| e.into_inner());
808        if let Some(tx) = tx_guard.as_ref() {
809            let (back_tx, back_rx) = mpsc::channel();
810            if tx.send(WriterMsg::Flush(back_tx)).is_err() {
811                return false;
812            }
813            drop(tx_guard);
814            let remaining = deadline.saturating_duration_since(Instant::now());
815            return back_rx.recv_timeout(remaining).is_ok();
816        }
817        false
818    }
819
820    /// Back-compat record signature. Used by every existing emit site.
821    /// Wraps into the new schema and forwards to `record_event`.
822    pub fn record(
823        &self,
824        action: &str,
825        principal: &str,
826        target: &str,
827        result: &str,
828        details: JsonValue,
829    ) {
830        let event = AuditEvent::from_legacy(action, principal, target, result, details);
831        self.record_event(event);
832    }
833
834    /// Primary new entry point. Non-blocking when the channel has
835    /// capacity; falls back to a sync write when full or the writer
836    /// thread has shut down.
837    pub fn record_event(&self, event: AuditEvent) {
838        let tx_guard = self.tx.lock().unwrap_or_else(|e| e.into_inner());
839        let recovered_event: AuditEvent;
840        if let Some(tx) = tx_guard.as_ref() {
841            self.pending.fetch_add(1, Ordering::SeqCst);
842            match tx.try_send(WriterMsg::Event(event)) {
843                Ok(()) => return,
844                Err(mpsc::TrySendError::Full(msg)) => {
845                    self.pending.fetch_sub(1, Ordering::SeqCst);
846                    tracing::warn!(
847                        target: "reddb::audit",
848                        "audit channel saturated; falling back to sync write"
849                    );
850                    recovered_event = match msg {
851                        WriterMsg::Event(ev) => ev,
852                        _ => return,
853                    };
854                }
855                Err(mpsc::TrySendError::Disconnected(msg)) => {
856                    self.pending.fetch_sub(1, Ordering::SeqCst);
857                    recovered_event = match msg {
858                        WriterMsg::Event(ev) => ev,
859                        _ => return,
860                    };
861                }
862            }
863        } else {
864            recovered_event = event;
865        }
866        drop(tx_guard);
867        self.write_direct(recovered_event);
868    }
869
870    /// Fallback path: a direct, synchronous append. Used when the
871    /// background channel is full or the writer thread isn't running.
872    fn write_direct(&self, event: AuditEvent) {
873        let _g = self.fallback_lock.lock().unwrap_or_else(|e| e.into_inner());
874        let prev = self
875            .last_hash
876            .lock()
877            .unwrap_or_else(|e| e.into_inner())
878            .clone();
879        let line = event.to_json_line(prev.as_deref());
880        let written = if self.path.as_os_str().is_empty() {
881            writeln!(std::io::stderr().lock(), "{line}")
882        } else {
883            append_line_with_rotation(&self.path, &line, self.max_bytes)
884        };
885        if let Err(err) = written {
886            tracing::warn!(
887                target: "reddb::audit",
888                error = %err,
889                path = %self.path.display(),
890                "direct audit append failed"
891            );
892            return;
893        }
894        let new_hash = crate::utils::to_hex(&sha256::sha256(line.as_bytes()));
895        if let Ok(mut g) = self.last_hash.lock() {
896            *g = Some(new_hash);
897        }
898        if let Some(url) = &self.stream_url {
899            stream_post(url, &line);
900        }
901        tracing::info!(target: "reddb::audit", "{line}");
902    }
903}
904
905impl Drop for AuditLogger {
906    fn drop(&mut self) {
907        let mut tx_guard = self.tx.lock().unwrap_or_else(|e| e.into_inner());
908        if let Some(tx) = tx_guard.take() {
909            let _ = tx.send(WriterMsg::Shutdown);
910        }
911        drop(tx_guard);
912        if let Some(handle) = self.handle.lock().unwrap_or_else(|e| e.into_inner()).take() {
913            let _ = handle.join();
914        }
915    }
916}
917
918// ---------------------------------------------------------------------------
919// Writer thread
920// ---------------------------------------------------------------------------
921
922#[allow(clippy::too_many_arguments)]
923fn writer_loop(
924    rx: mpsc::Receiver<WriterMsg>,
925    path: PathBuf,
926    max_bytes: u64,
927    fsync_mode: FsyncMode,
928    stream_url: Option<String>,
929    writer_alive: Arc<AtomicBool>,
930    pending: Arc<AtomicU64>,
931    last_hash: Arc<Mutex<Option<String>>>,
932) {
933    if let Some(parent) = path.parent() {
934        if !parent.as_os_str().is_empty() {
935            let _ = std::fs::create_dir_all(parent);
936        }
937    }
938
939    let mut writer = match open_active(&path) {
940        Ok(w) => w,
941        Err(err) => {
942            tracing::error!(target: "reddb::audit", error = %err, "audit writer init failed");
943            writer_alive.store(false, Ordering::SeqCst);
944            return;
945        }
946    };
947    // Track size in-memory; BufWriter hides the on-disk size until
948    // flush, and we rotate on bytes-actually-written so a slow
949    // flush cadence doesn't run away.
950    let mut bytes_written: u64 = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
951
952    let periodic_interval = Duration::from_millis(250);
953    let mut last_flush = Instant::now();
954    let mut buffered_since_fsync: u64 = 0;
955
956    loop {
957        // Wake up periodically so the periodic-fsync mode can run even
958        // when no events arrive (compliance-driven).
959        let recv_timeout = match fsync_mode {
960            FsyncMode::Periodic => periodic_interval,
961            FsyncMode::Every | FsyncMode::Off => Duration::from_secs(1),
962        };
963        match rx.recv_timeout(recv_timeout) {
964            Ok(WriterMsg::Event(event)) => {
965                let prev = last_hash.lock().unwrap_or_else(|e| e.into_inner()).clone();
966                let line = event.to_json_line(prev.as_deref());
967
968                let line_bytes = line.len() as u64 + 1; // newline
969                if let Err(err) = write_line(&mut writer, &line) {
970                    tracing::warn!(
971                        target: "reddb::audit",
972                        error = %err,
973                        "audit write failed; reopening"
974                    );
975                    if let Ok(w2) = open_active(&path) {
976                        writer = w2;
977                        let _ = write_line(&mut writer, &line);
978                    }
979                }
980                bytes_written = bytes_written.saturating_add(line_bytes);
981                let new_hash = crate::utils::to_hex(&sha256::sha256(line.as_bytes()));
982                if let Ok(mut g) = last_hash.lock() {
983                    *g = Some(new_hash);
984                }
985                if let Some(url) = &stream_url {
986                    stream_post(url, &line);
987                }
988                tracing::info!(target: "reddb::audit", "{line}");
989                pending.fetch_sub(1, Ordering::SeqCst);
990                buffered_since_fsync += 1;
991
992                match fsync_mode {
993                    FsyncMode::Every => {
994                        let _ = writer.flush();
995                        let _ = writer.get_ref().sync_data();
996                        buffered_since_fsync = 0;
997                    }
998                    FsyncMode::Periodic => {
999                        if last_flush.elapsed() >= periodic_interval {
1000                            let _ = writer.flush();
1001                            let _ = writer.get_ref().sync_data();
1002                            last_flush = Instant::now();
1003                            buffered_since_fsync = 0;
1004                        }
1005                    }
1006                    FsyncMode::Off => {}
1007                }
1008
1009                // Rotation check based on in-memory accounting; BufWriter
1010                // metadata can lag.
1011                if bytes_written >= max_bytes {
1012                    let _ = writer.flush();
1013                    let _ = writer.get_ref().sync_data();
1014                    if let Err(err) = rotate(&path) {
1015                        tracing::warn!(
1016                            target: "reddb::audit",
1017                            error = %err,
1018                            "audit rotation failed; continuing in-place"
1019                        );
1020                    }
1021                    match open_active(&path) {
1022                        Ok(w2) => writer = w2,
1023                        Err(err) => {
1024                            tracing::error!(
1025                                target: "reddb::audit",
1026                                error = %err,
1027                                "audit reopen failed after rotate"
1028                            );
1029                            break;
1030                        }
1031                    }
1032                    last_flush = Instant::now();
1033                    buffered_since_fsync = 0;
1034                    bytes_written = 0;
1035                }
1036            }
1037            Ok(WriterMsg::Flush(ack)) => {
1038                let _ = writer.flush();
1039                let _ = writer.get_ref().sync_data();
1040                last_flush = Instant::now();
1041                buffered_since_fsync = 0;
1042                // Acks are sent only after pending == 0; in this design
1043                // every event sent before Flush has already been
1044                // processed (channel is FIFO), so we can ack now.
1045                let _ = ack.send(());
1046            }
1047            Ok(WriterMsg::Shutdown) => {
1048                let _ = writer.flush();
1049                let _ = writer.get_ref().sync_data();
1050                break;
1051            }
1052            Err(mpsc::RecvTimeoutError::Timeout) => {
1053                if buffered_since_fsync > 0 {
1054                    let _ = writer.flush();
1055                    let _ = writer.get_ref().sync_data();
1056                    last_flush = Instant::now();
1057                    buffered_since_fsync = 0;
1058                }
1059            }
1060            Err(mpsc::RecvTimeoutError::Disconnected) => {
1061                let _ = writer.flush();
1062                let _ = writer.get_ref().sync_data();
1063                break;
1064            }
1065        }
1066    }
1067
1068    writer_alive.store(false, Ordering::SeqCst);
1069}
1070
1071fn open_active(path: &Path) -> std::io::Result<BufWriter<std::fs::File>> {
1072    if let Some(parent) = path.parent() {
1073        if !parent.as_os_str().is_empty() {
1074            std::fs::create_dir_all(parent)?;
1075        }
1076    }
1077    let f = std::fs::OpenOptions::new()
1078        .create(true)
1079        .append(true)
1080        .open(path)?;
1081    Ok(BufWriter::new(f))
1082}
1083
1084fn write_line(writer: &mut BufWriter<std::fs::File>, line: &str) -> std::io::Result<()> {
1085    writer.write_all(line.as_bytes())?;
1086    writer.write_all(b"\n")?;
1087    Ok(())
1088}
1089
1090fn append_line_with_rotation(path: &Path, line: &str, max_bytes: u64) -> std::io::Result<()> {
1091    if let Some(parent) = path.parent() {
1092        if !parent.as_os_str().is_empty() {
1093            std::fs::create_dir_all(parent)?;
1094        }
1095    }
1096    let mut file = std::fs::OpenOptions::new()
1097        .create(true)
1098        .append(true)
1099        .open(path)?;
1100    file.write_all(line.as_bytes())?;
1101    file.write_all(b"\n")?;
1102    file.sync_data()?;
1103    drop(file);
1104    if let Ok(meta) = std::fs::metadata(path) {
1105        if meta.len() >= max_bytes {
1106            let _ = rotate(path);
1107        }
1108    }
1109    Ok(())
1110}
1111
1112/// Rename the active file to `<path>.<ms>.zst` and zstd-compress it
1113/// in-place. The compressed file replaces the renamed plaintext copy
1114/// so the on-disk artefact is `.audit.log.<ms>.zst`.
1115///
1116/// Rotation timestamp uses unix nanos so back-to-back rotations
1117/// under load (or in a tight test loop) don't collide on the same
1118/// filename.
1119fn rotate(active: &Path) -> std::io::Result<()> {
1120    let ts = crate::utils::now_unix_nanos();
1121    let rotation = reddb_file::rotate_audit_log(active, ts)?;
1122    if let Some(err) = rotation.compression_error {
1123        tracing::warn!(
1124            target: "reddb::audit",
1125            error = %err,
1126            "audit rotation: zstd compress failed; leaving plaintext"
1127        );
1128    }
1129    Ok(())
1130}
1131
1132// ---------------------------------------------------------------------------
1133// SIEM streaming (fire-and-forget)
1134// ---------------------------------------------------------------------------
1135
1136fn stream_post(url: &str, line: &str) {
1137    let url = url.to_string();
1138    let line = line.to_string();
1139    // Spawn a one-shot thread; ureq builds a fresh agent per call.
1140    // Best-effort: one attempt, no retry — SIEM ingestion lag is
1141    // not the RedDB hot path's problem.
1142    let _ = thread::Builder::new()
1143        .name("reddb-audit-siem".to_string())
1144        .spawn(move || {
1145            let agent: ureq::Agent = ureq::Agent::config_builder()
1146                .timeout_connect(Some(Duration::from_secs(2)))
1147                .timeout_send_request(Some(Duration::from_secs(3)))
1148                .timeout_recv_response(Some(Duration::from_secs(3)))
1149                .http_status_as_error(false)
1150                .build()
1151                .into();
1152            let _ = agent
1153                .post(&url)
1154                .header("content-type", "application/x-ndjson")
1155                .send(line.as_bytes());
1156        });
1157}
1158
1159// ---------------------------------------------------------------------------
1160// ISO-8601 helper (kept from the previous implementation)
1161// ---------------------------------------------------------------------------
1162
1163fn format_iso8601(ms_since_epoch: u64) -> String {
1164    let secs = ms_since_epoch / 1000;
1165    let ms = ms_since_epoch % 1000;
1166    let days = secs / 86_400;
1167    let rem = secs % 86_400;
1168    let (y, mo, d) = civil_from_days(days as i64);
1169    let h = rem / 3600;
1170    let mi = (rem % 3600) / 60;
1171    let s = rem % 60;
1172    format!(
1173        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",
1174        y, mo, d, h, mi, s, ms
1175    )
1176}
1177
1178fn civil_from_days(z: i64) -> (i64, u32, u32) {
1179    let z = z + 719_468;
1180    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
1181    let doe = (z - era * 146_097) as u64;
1182    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1183    let y = (yoe as i64) + era * 400;
1184    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1185    let mp = (5 * doy + 2) / 153;
1186    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
1187    let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
1188    (if m <= 2 { y + 1 } else { y }, m, d)
1189}
1190
1191// ---------------------------------------------------------------------------
1192// Tests
1193// ---------------------------------------------------------------------------
1194
1195#[cfg(test)]
1196mod tests {
1197    use super::*;
1198
1199    fn temp_data_path(tag: &str) -> PathBuf {
1200        let mut p = std::env::temp_dir();
1201        p.push(format!(
1202            "reddb-audit-{}-{}-{}",
1203            tag,
1204            std::process::id(),
1205            crate::utils::now_unix_nanos()
1206        ));
1207        std::fs::create_dir_all(&p).unwrap();
1208        p.push("data.rdb");
1209        p
1210    }
1211
1212    fn drain(logger: &AuditLogger) {
1213        assert!(logger.wait_idle(Duration::from_secs(2)));
1214    }
1215
1216    #[test]
1217    fn record_writes_one_line_per_call() {
1218        let data = temp_data_path("one-line");
1219        let logger = AuditLogger::for_data_path(&data);
1220        logger.record(
1221            "admin/readonly",
1222            "operator",
1223            "instance",
1224            "ok",
1225            JsonValue::Null,
1226        );
1227        drain(&logger);
1228        let body = std::fs::read_to_string(logger.path()).unwrap();
1229        let lines: Vec<&str> = body.lines().collect();
1230        assert_eq!(lines.len(), 1);
1231        assert!(lines[0].contains("\"action\":\"admin/readonly\""));
1232        assert!(lines[0].contains("\"outcome\":\"success\""));
1233    }
1234
1235    #[test]
1236    fn record_appends_across_calls() {
1237        let data = temp_data_path("append");
1238        let logger = AuditLogger::for_data_path(&data);
1239        logger.record("admin/drain", "op", "instance", "ok", JsonValue::Null);
1240        logger.record("admin/shutdown", "op", "instance", "ok", JsonValue::Null);
1241        drain(&logger);
1242        let lines = std::fs::read_to_string(logger.path()).unwrap();
1243        assert_eq!(lines.lines().count(), 2);
1244    }
1245
1246    #[test]
1247    fn record_event_emits_full_schema() {
1248        let data = temp_data_path("schema");
1249        let logger = AuditLogger::for_data_path(&data);
1250        let mut detail = Map::new();
1251        detail.insert("ms".to_string(), JsonValue::Number(412.0));
1252        let ev = AuditEvent::builder("admin/shutdown")
1253            .principal("alice@acme")
1254            .source(AuditAuthSource::Session)
1255            .tenant("acme")
1256            .resource("instance")
1257            .outcome(Outcome::Success)
1258            .detail(JsonValue::Object(detail))
1259            .remote_addr("203.0.113.5")
1260            .correlation_id("req-42")
1261            .build();
1262        logger.record_event(ev);
1263        drain(&logger);
1264        let body = std::fs::read_to_string(logger.path()).unwrap();
1265        assert!(body.contains("\"action\":\"admin/shutdown\""));
1266        assert!(body.contains("\"principal\":\"alice@acme\""));
1267        assert!(body.contains("\"tenant\":\"acme\""));
1268        assert!(body.contains("\"source\":\"session\""));
1269        assert!(body.contains("\"correlation_id\":\"req-42\""));
1270        assert!(body.contains("\"remote_addr\":\"203.0.113.5\""));
1271        assert!(body.contains("\"event_id\":\""));
1272        assert!(body.contains("\"prev_hash\":") || body.lines().count() == 1);
1273    }
1274
1275    #[test]
1276    fn hash_chain_links_every_event() {
1277        let data = temp_data_path("chain");
1278        let logger = AuditLogger::for_data_path(&data);
1279        for i in 0..5 {
1280            logger.record_event(
1281                AuditEvent::builder(format!("test/event/{i}"))
1282                    .principal("tester")
1283                    .build(),
1284            );
1285        }
1286        drain(&logger);
1287        let body = std::fs::read_to_string(logger.path()).unwrap();
1288        let lines: Vec<&str> = body.lines().collect();
1289        assert_eq!(lines.len(), 5);
1290        let mut prev: Option<String> = None;
1291        for (idx, line) in lines.iter().enumerate() {
1292            let parsed: JsonValue = crate::json::from_str(line).unwrap();
1293            let stored_prev = parsed
1294                .get("prev_hash")
1295                .and_then(|v| v.as_str())
1296                .map(|s| s.to_string());
1297            assert_eq!(stored_prev, prev, "line {idx} prev_hash mismatch");
1298            prev = Some(crate::utils::to_hex(&sha256::sha256(line.as_bytes())));
1299        }
1300    }
1301
1302    #[test]
1303    fn legacy_record_back_compat_maps_outcomes() {
1304        let data = temp_data_path("legacy");
1305        let logger = AuditLogger::for_data_path(&data);
1306        logger.record(
1307            "admin/restore",
1308            "operator",
1309            "instance",
1310            "err: disk full",
1311            JsonValue::Null,
1312        );
1313        drain(&logger);
1314        let body = std::fs::read_to_string(logger.path()).unwrap();
1315        assert!(body.contains("\"outcome\":\"error\""));
1316        assert!(body.contains("\"result_text\":\"err: disk full\""));
1317    }
1318
1319    #[test]
1320    fn iso8601_formats_known_epoch() {
1321        assert_eq!(
1322            format_iso8601(1_709_210_096_789),
1323            "2024-02-29T12:34:56.789Z"
1324        );
1325    }
1326
1327    #[test]
1328    fn rotation_at_threshold() {
1329        let data = temp_data_path("rotate");
1330        let parent = data.parent().unwrap().to_path_buf();
1331        let logger = AuditLogger::with_max_bytes(parent.join(".audit.log"), 1024);
1332        for i in 0..30 {
1333            logger.record_event(
1334                AuditEvent::builder(format!("test/rotate/{i}"))
1335                    .principal("rotator")
1336                    .detail(JsonValue::String(
1337                        "lorem ipsum dolor sit amet consectetur padding padding padding"
1338                            .to_string(),
1339                    ))
1340                    .build(),
1341            );
1342        }
1343        drain(&logger);
1344        let parent = logger.path().parent().unwrap();
1345        let rotated: Vec<_> = std::fs::read_dir(parent)
1346            .unwrap()
1347            .filter_map(|e| e.ok())
1348            .filter(|e| {
1349                e.file_name()
1350                    .to_str()
1351                    .map(|n| n.starts_with(".audit.log.") && n.ends_with(".zst"))
1352                    .unwrap_or(false)
1353            })
1354            .collect();
1355        assert!(
1356            !rotated.is_empty(),
1357            "expected at least one rotated .zst file"
1358        );
1359    }
1360
1361    #[test]
1362    fn parse_line_round_trips() {
1363        let ev = AuditEvent::builder("auth/login.ok")
1364            .principal("alice")
1365            .source(AuditAuthSource::Password)
1366            .tenant("acme")
1367            .outcome(Outcome::Success)
1368            .build();
1369        let line = ev.to_json_line(None);
1370        let parsed = AuditEvent::parse_line(&line).expect("round-trip parse");
1371        assert_eq!(parsed.action, "auth/login.ok");
1372        assert_eq!(parsed.principal.as_deref(), Some("alice"));
1373        assert_eq!(parsed.tenant.as_deref(), Some("acme"));
1374        assert_eq!(parsed.outcome, Outcome::Success);
1375        assert_eq!(parsed.source, AuditAuthSource::Password);
1376    }
1377
1378    #[test]
1379    fn event_id_is_lexicographically_sortable_by_time() {
1380        let a = new_event_id();
1381        std::thread::sleep(Duration::from_millis(2));
1382        let b = new_event_id();
1383        assert!(a < b, "event_id ordering broken: {a} >= {b}");
1384    }
1385
1386    // -------------------------------------------------------------------
1387    // AuditFieldEscaper / AuditValue tests (issue #177)
1388    // -------------------------------------------------------------------
1389
1390    #[test]
1391    fn audit_field_escaper_typed_string() {
1392        let f = AuditFieldEscaper::field("collection", "users");
1393        assert_eq!(f.name(), "collection");
1394        match f.value() {
1395            AuditValue::String(s) => assert_eq!(s, "users"),
1396            other => panic!("expected String, got {:?}", other),
1397        }
1398    }
1399
1400    #[test]
1401    fn audit_field_escaper_bytes_emit_base64() {
1402        let bytes = vec![0xDEu8, 0xAD, 0xBE, 0xEF];
1403        let f = AuditFieldEscaper::field("blob", bytes);
1404        let ev = AuditEvent::builder("test/bytes").field(f).build();
1405        let line = ev.to_json_line(None);
1406        // base64 of 0xDEADBEEF is "3q2+7w=="
1407        assert!(
1408            line.contains("\"blob\":\"3q2+7w==\""),
1409            "expected base64 emission: {line}"
1410        );
1411    }
1412
1413    #[test]
1414    fn audit_field_escaper_number_bool_null() {
1415        let ev = AuditEvent::builder("test/types")
1416            .field(AuditFieldEscaper::field("count", 42i64))
1417            .field(AuditFieldEscaper::field("ok", true))
1418            .field(AuditFieldEscaper::field("missing", AuditValue::Null))
1419            .build();
1420        let line = ev.to_json_line(None);
1421        assert!(line.contains("\"count\":42"));
1422        assert!(line.contains("\"ok\":true"));
1423        assert!(line.contains("\"missing\":null"));
1424    }
1425
1426    #[test]
1427    fn audit_field_escaper_adversarial_corpus_preserves_structure() {
1428        // The full F-01 / F-02 adversarial corpus: CRLF, NUL,
1429        // quote, semicolon, JSON-in-JSON, control bytes 0x00..0x20.
1430        // Every payload must encode to a single JSONL row that
1431        // round-trips through the in-house parser back to the
1432        // original bytes.
1433        let cases: &[(&str, &str)] = &[
1434            ("crlf", "line1\r\nline2"),
1435            ("nul", "before\0after"),
1436            ("quote", "she said \"hi\""),
1437            ("semicolon", "a;b;c"),
1438            ("json_in_json", r#"{"injected":"yes"}"#),
1439            ("low_ctrl", "\x01\x02\x03\x07\x1f"),
1440            ("backslash", "C:\\path\\file"),
1441            ("mixed", "name=\"x\"\n\\path\t\x01end"),
1442            ("empty", ""),
1443            // Note: legal Unicode payloads round-trip through the
1444            // RFC 8259 encoder fine; the in-house parser
1445            // (`utils::json`) used by `crate::json::from_str` has a
1446            // pre-existing byte-oriented bug for multi-byte UTF-8
1447            // sequences, which is orthogonal to the F-01 / F-02
1448            // boundary-smuggling threat model. ASCII-only here.
1449        ];
1450        let mut survivors = 0usize;
1451        for (label, payload) in cases {
1452            let f = AuditFieldEscaper::field("user_input", *payload);
1453            let ev = AuditEvent::builder(format!("test/adv/{label}"))
1454                .principal("attacker")
1455                .field(f)
1456                .build();
1457            let line = ev.to_json_line(None);
1458            // 1. exactly one row, no embedded newline.
1459            assert!(
1460                !line.contains('\n'),
1461                "{label}: embedded newline in JSONL row: {line:?}"
1462            );
1463            // 2. parse back via the canonical decoder and read user_input.
1464            let parsed: JsonValue = crate::json::from_str(&line)
1465                .unwrap_or_else(|err| panic!("{label}: line did not parse: {err} :: {line:?}"));
1466            let detail = parsed.get("detail").expect("detail present");
1467            let recovered = detail.get("user_input").and_then(|v| v.as_str()).unwrap();
1468            assert_eq!(
1469                recovered, *payload,
1470                "{label}: round-trip mismatch: {recovered:?} != {payload:?}"
1471            );
1472            survivors += 1;
1473        }
1474        assert_eq!(
1475            survivors,
1476            cases.len(),
1477            "adversarial corpus survival rate: {survivors}/{}",
1478            cases.len()
1479        );
1480    }
1481
1482    #[test]
1483    fn audit_emission_emits_one_line_per_call_through_guard() {
1484        let data = temp_data_path("guard-emission");
1485        let logger = AuditLogger::for_data_path(&data);
1486        // Smuggle attempt: NUL + CRLF + JSON-injection in collection name.
1487        let attacker = "users\";DROP\r\n{\"x\":1}\0";
1488        logger.record_event(
1489            AuditEvent::builder("admin/scan")
1490                .principal("evil")
1491                .field(AuditFieldEscaper::field("collection", attacker))
1492                .build(),
1493        );
1494        drain(&logger);
1495        let body = std::fs::read_to_string(logger.path()).unwrap();
1496        let lines: Vec<&str> = body.lines().collect();
1497        assert_eq!(lines.len(), 1, "guard must emit exactly one JSONL row");
1498        // The smuggled "{...}" cannot have escaped the JSON string.
1499        let parsed: JsonValue = crate::json::from_str(lines[0]).unwrap();
1500        let recovered = parsed
1501            .get("detail")
1502            .and_then(|d| d.get("collection"))
1503            .and_then(|v| v.as_str())
1504            .unwrap();
1505        assert_eq!(recovered, attacker);
1506    }
1507
1508    #[test]
1509    fn audit_field_escaper_chains_via_builder_fields() {
1510        let ev = AuditEvent::builder("test/multi")
1511            .fields([
1512                AuditFieldEscaper::field("a", "x"),
1513                AuditFieldEscaper::field("b", 7i64),
1514                AuditFieldEscaper::field("c", true),
1515            ])
1516            .build();
1517        let line = ev.to_json_line(None);
1518        let parsed: JsonValue = crate::json::from_str(&line).unwrap();
1519        let d = parsed.get("detail").unwrap();
1520        assert_eq!(d.get("a").and_then(|v| v.as_str()), Some("x"));
1521        assert_eq!(d.get("b").and_then(|v| v.as_i64()), Some(7));
1522        assert_eq!(d.get("c").and_then(|v| v.as_bool()), Some(true));
1523    }
1524
1525    proptest::proptest! {
1526        /// Random user-supplied strings must always round-trip through
1527        /// the typed-field guard exactly. No silent drops, no smuggling.
1528        ///
1529        /// ASCII-only here: the encoder is RFC 8259 §7 compliant for
1530        /// arbitrary Unicode, but the in-house decoder shared by
1531        /// `crate::json::from_str` (`utils::json::parse_string`) is
1532        /// byte-oriented for non-escape characters and does not
1533        /// recompose multi-byte UTF-8 sequences. The boundary-smuggling
1534        /// threat model is about control bytes (0x00..0x20) and
1535        /// structural bytes (`"`, `\`, `\r`, `\n`), not legal Unicode,
1536        /// so this restriction does not narrow the security claim.
1537        #[test]
1538        fn prop_audit_field_round_trips_arbitrary_strings(
1539            payload in proptest::string::string_regex("[\\x00-\\x7f]{0,128}").unwrap()
1540        ) {
1541            let f = AuditFieldEscaper::field("p", payload.as_str());
1542            let ev = AuditEvent::builder("prop/test").field(f).build();
1543            let line = ev.to_json_line(None);
1544            // Single-line invariant.
1545            proptest::prop_assert!(!line.contains('\n'));
1546            let parsed: JsonValue = crate::json::from_str(&line)
1547                .expect("emission must always parse");
1548            let recovered = parsed
1549                .get("detail")
1550                .and_then(|d| d.get("p"))
1551                .and_then(|v| v.as_str())
1552                .unwrap();
1553            proptest::prop_assert_eq!(recovered, payload.as_str());
1554        }
1555
1556        /// Random byte sequences via base64 round-trip — non-UTF-8
1557        /// payloads must never enter the JSON string channel raw.
1558        #[test]
1559        fn prop_audit_field_bytes_base64_round_trip(
1560            bytes in proptest::collection::vec(proptest::bits::u8::ANY, 0..64)
1561        ) {
1562            let f = AuditFieldEscaper::field("b", bytes.clone());
1563            let ev = AuditEvent::builder("prop/bytes").field(f).build();
1564            let line = ev.to_json_line(None);
1565            proptest::prop_assert!(!line.contains('\n'));
1566            let parsed: JsonValue = crate::json::from_str(&line).unwrap();
1567            let recovered_b64 = parsed
1568                .get("detail")
1569                .and_then(|d| d.get("b"))
1570                .and_then(|v| v.as_str())
1571                .unwrap()
1572                .to_string();
1573            proptest::prop_assert_eq!(recovered_b64, base64_encode(&bytes));
1574        }
1575    }
1576}