Skip to main content

guardrail_proxy/
audit_log.rs

1//! NDJSON audit log writer (spec §10).
2//!
3//! When `observability.audit_log.enabled = true`, every pipeline decision is
4//! written as a newline-delimited JSON record to `observability.audit_log.path`.
5//! When the file would exceed `observability.audit_log.max_size_mb`, it is
6//! rotated: the current file is renamed to `<path>.<unix_timestamp>` and a
7//! fresh file is opened at `path`. Rotation is checked before each write
8//! (not on a timer), so the file never grows meaningfully past the
9//! configured limit.
10//!
11//! The returned [`tracing_appender::non_blocking::WorkerGuard`] must be kept
12//! alive for the process lifetime; dropping it stops the background writer.
13//!
14//! # Example
15//!
16//! ```rust,no_run
17//! use guardrail_config::schema::AuditLogConfig;
18//! use guardrail_proxy::audit_log;
19//! use tracing_subscriber::prelude::*;
20//!
21//! let config = AuditLogConfig {
22//!     enabled: true,
23//!     path: "/var/log/guardrail/audit.ndjson".into(),
24//!     max_size_mb: 100,
25//! };
26//!
27//! let _ = audit_log::build_layer(&config).unwrap();
28//! ```
29
30use std::fs::{File, OpenOptions};
31use std::io::{self, Write};
32use std::path::{Path, PathBuf};
33use std::sync::Mutex;
34
35use guardrail_config::schema::AuditLogConfig;
36use tracing_appender::non_blocking::WorkerGuard;
37// filter_fn/FmtSpan are composed by callers when constructing concrete
38// `fmt` layers; this module only builds the writer+guard pair.
39
40/// The tracing target audit records are emitted under.
41pub const AUDIT_TARGET: &str = "guardrail::audit";
42
43/// Errors that can occur while setting up the audit log writer.
44#[derive(Debug, thiserror::Error)]
45pub enum AuditLogError {
46    /// The parent directory could not be created.
47    #[error("failed to create audit log directory '{path}': {source}")]
48    CreateDir {
49        /// The directory path.
50        path: String,
51        /// Underlying I/O error.
52        #[source]
53        source: std::io::Error,
54    },
55    /// The audit log file could not be opened.
56    #[error("failed to open audit log file '{path}': {source}")]
57    OpenFile {
58        /// The file path.
59        path: String,
60        /// Underlying I/O error.
61        #[source]
62        source: std::io::Error,
63    },
64}
65
66/// A [`Write`] implementation that rotates the underlying file by renaming
67/// it to `<path>.<unix_timestamp>` once it would exceed `max_size_bytes`,
68/// then opening a fresh file at `path`.
69///
70/// Rotation is checked before each `write_all` call rather than on a timer,
71/// so a burst of writes can momentarily exceed the threshold within a single
72/// write (a single audit record is always written atomically, never split
73/// across the rotation boundary) but never by more than one record's worth.
74///
75/// Wrapped in a [`Mutex`] so it satisfies `Write + Send + 'static` as
76/// required by [`tracing_appender::non_blocking`] — the non-blocking
77/// appender already serializes writes onto a single background thread, so
78/// the lock is never contended in practice, but the type system requires
79/// `Sync` regardless since `non_blocking` stores the writer behind an `Arc`.
80struct SizeRotatingWriter {
81    inner: Mutex<SizeRotatingState>,
82}
83
84struct SizeRotatingState {
85    path: PathBuf,
86    /// `None` only transiently during `rotate()`, between dropping the old
87    /// handle and opening the new one — never observable outside this type.
88    file: Option<File>,
89    current_size: u64,
90    max_size_bytes: u64,
91}
92
93impl SizeRotatingWriter {
94    /// Open (or create) the file at `path` and prepare to rotate it once it
95    /// would exceed `max_size_bytes`.
96    fn open(path: &Path, max_size_bytes: u64) -> io::Result<Self> {
97        let file = OpenOptions::new().create(true).append(true).open(path)?;
98        let current_size = file.metadata()?.len();
99
100        Ok(Self {
101            inner: Mutex::new(SizeRotatingState {
102                path: path.to_path_buf(),
103                file: Some(file),
104                current_size,
105                max_size_bytes,
106            }),
107        })
108    }
109}
110
111impl SizeRotatingState {
112    /// Rotate the current file: rename it to `<path>.<unix_timestamp>` and
113    /// open a fresh file at `path`. If a file with the timestamped name
114    /// already exists (clock resolution collision), append an incrementing
115    /// suffix until a free name is found.
116    ///
117    /// The old file handle is flushed and dropped (via `self.file.take()`)
118    /// *before* the rename syscall runs. On POSIX this would work either way
119    /// (rename operates on the inode regardless of open handles), but on
120    /// Windows `std::fs::File` does not request `FILE_SHARE_DELETE` by
121    /// default, so renaming a file that is still open elsewhere in the
122    /// process can fail with an access-denied error. Dropping the handle
123    /// first avoids that failure mode on every platform.
124    ///
125    /// `self.file` is `None` only for the brief window between the
126    /// `.take()` and the reassignment a few lines later; if anything in
127    /// between returns early via `?`, the writer is left in a permanently
128    /// broken state (every subsequent `write()` call returns an error)
129    /// rather than silently losing data or writing to a stale handle —
130    /// this is the only sound choice once the rename itself has failed,
131    /// since there is no original file left to fall back to write into.
132    fn rotate(&mut self) -> io::Result<()> {
133        let timestamp = std::time::SystemTime::now()
134            .duration_since(std::time::UNIX_EPOCH)
135            .map(|d| d.as_secs())
136            .unwrap_or(0);
137
138        let rotated_extension = |suffix: Option<u32>| {
139            let base_ext = self
140                .path
141                .extension()
142                .and_then(|e| e.to_str())
143                .unwrap_or("ndjson");
144            match suffix {
145                Some(n) => format!("{base_ext}.{timestamp}.{n}"),
146                None => format!("{base_ext}.{timestamp}"),
147            }
148        };
149
150        let mut rotated_path = self.path.with_extension(rotated_extension(None));
151        let mut suffix = 1u32;
152        while rotated_path.exists() {
153            rotated_path = self.path.with_extension(rotated_extension(Some(suffix)));
154            suffix += 1;
155        }
156
157        // Flush any buffered bytes, then explicitly drop the handle (via
158        // `.take()`) so no file-share restriction (most relevant on
159        // Windows, where `std::fs::File` does not request
160        // `FILE_SHARE_DELETE` by default) blocks the rename below.
161        if let Some(file) = self.file.as_mut() {
162            file.flush()?;
163        }
164        self.file.take(); // drops the old handle here
165
166        std::fs::rename(&self.path, &rotated_path)?;
167
168        self.file = Some(
169            OpenOptions::new()
170                .create(true)
171                .append(true)
172                .open(&self.path)?,
173        );
174        self.current_size = 0;
175
176        Ok(())
177    }
178}
179
180impl Write for SizeRotatingWriter {
181    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
182        let mut state = self
183            .inner
184            .lock()
185            .unwrap_or_else(std::sync::PoisonError::into_inner);
186
187        // Rotate first if this write would push us over the threshold and
188        // we've already written at least one byte (never rotate an empty
189        // file just because a single record is itself huge).
190        if state.current_size > 0 && state.current_size + buf.len() as u64 > state.max_size_bytes {
191            state.rotate()?;
192        }
193
194        let file = state.file.as_mut().ok_or_else(|| {
195            io::Error::other("audit log file handle unexpectedly absent after rotation")
196        })?;
197        let written = file.write(buf)?;
198        state.current_size += written as u64;
199        Ok(written)
200    }
201
202    fn flush(&mut self) -> io::Result<()> {
203        let mut state = self
204            .inner
205            .lock()
206            .unwrap_or_else(std::sync::PoisonError::into_inner);
207        match state.file.as_mut() {
208            Some(file) => file.flush(),
209            None => Ok(()), // transient mid-rotation state; nothing to flush
210        }
211    }
212}
213
214/// Build a `tracing_subscriber::Layer` writing audit events as NDJSON to
215/// `config.path`, rotating by size per `config.max_size_mb`. Returns
216/// `Ok(None)` when `config.enabled = false`.
217///
218/// # Errors
219///
220/// Returns [`AuditLogError::CreateDir`] if the parent directory cannot be
221/// created, or [`AuditLogError::OpenFile`] if the audit log file itself
222/// cannot be opened (e.g. permissions).
223pub fn build_layer(
224    config: &AuditLogConfig,
225) -> Result<Option<(tracing_appender::non_blocking::NonBlocking, WorkerGuard)>, AuditLogError>
226where
227{
228    if !config.enabled {
229        return Ok(None);
230    }
231
232    let audit_path = Path::new(&config.path);
233    if let Some(parent) = audit_path.parent() {
234        if !parent.as_os_str().is_empty() {
235            std::fs::create_dir_all(parent).map_err(|source| AuditLogError::CreateDir {
236                path: parent.to_string_lossy().into_owned(),
237                source,
238            })?;
239        }
240    }
241
242    let max_size_bytes = config.max_size_mb.saturating_mul(1024 * 1024);
243    let writer = SizeRotatingWriter::open(audit_path, max_size_bytes).map_err(|source| {
244        AuditLogError::OpenFile {
245            path: config.path.clone(),
246            source,
247        }
248    })?;
249
250    let (non_blocking, guard) = tracing_appender::non_blocking(writer);
251
252    Ok(Some((non_blocking, guard)))
253}
254
255/// Build the NDJSON audit-log [`Layer`](tracing_subscriber::Layer) that
256/// `guardrail run` installs: JSON lines, one per event under
257/// [`AUDIT_TARGET`] and nothing else, written to `config.path` through the
258/// size-rotating writer from [`build_layer`]. Returns `Ok(None)` when
259/// `config.enabled = false`.
260///
261/// Keep the returned [`WorkerGuard`] alive for as long as events should be
262/// written; dropping it flushes and stops the background writer.
263///
264/// # Errors
265///
266/// As for [`build_layer`].
267pub fn ndjson_layer<S>(
268    config: &AuditLogConfig,
269) -> Result<
270    Option<(
271        impl tracing_subscriber::Layer<S> + Send + Sync + 'static,
272        WorkerGuard,
273    )>,
274    AuditLogError,
275>
276where
277    S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
278{
279    use tracing_subscriber::filter::filter_fn;
280    use tracing_subscriber::fmt::format::FmtSpan;
281    use tracing_subscriber::Layer as _;
282
283    let Some((writer, guard)) = build_layer(config)? else {
284        return Ok(None);
285    };
286    let layer = tracing_subscriber::fmt::layer()
287        .json()
288        .with_span_events(FmtSpan::NONE)
289        .with_target(false)
290        .with_writer(writer)
291        .with_filter(filter_fn(|metadata| metadata.target() == AUDIT_TARGET));
292    Ok(Some((layer, guard)))
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use crate::audit::AuditRecord;
299    use guardrail_core::{decision::Decision, test_helpers::clean_request};
300    use tracing_subscriber::filter::filter_fn;
301    use tracing_subscriber::prelude::*;
302
303    fn temp_config() -> (tempfile::TempDir, AuditLogConfig) {
304        let dir = tempfile::tempdir().unwrap();
305        let path = dir
306            .path()
307            .join("audit-test.ndjson")
308            .to_string_lossy()
309            .into_owned();
310        let config = AuditLogConfig {
311            enabled: true,
312            path,
313            max_size_mb: 100,
314        };
315        (dir, config)
316    }
317
318    #[test]
319    fn test_disabled_returns_none() {
320        let config = AuditLogConfig {
321            enabled: false,
322            path: "/tmp/x.ndjson".into(),
323            max_size_mb: 100,
324        };
325        assert!(build_layer(&config).unwrap().is_none());
326    }
327
328    #[test]
329    fn test_builds_with_valid_config() {
330        let (_dir, config) = temp_config();
331        assert!(build_layer(&config).unwrap().is_some());
332    }
333
334    #[test]
335    fn test_creates_parent_directory() {
336        let tmp = tempfile::tempdir().unwrap();
337        let path = tmp
338            .path()
339            .join("sub")
340            .join("dir")
341            .join("audit.ndjson")
342            .to_string_lossy()
343            .into_owned();
344        let config = AuditLogConfig {
345            enabled: true,
346            path,
347            max_size_mb: 100,
348        };
349        assert!(build_layer(&config).is_ok());
350    }
351
352    #[test]
353    fn test_writes_audit_events_as_ndjson() {
354        let (_dir, config) = temp_config();
355        let path = config.path.clone();
356
357        let (non_blocking, _guard) = build_layer(&config).unwrap().unwrap();
358        let layer = tracing_subscriber::fmt::layer()
359            .json()
360            .with_writer(non_blocking)
361            .with_filter(filter_fn(|meta| meta.target().starts_with(AUDIT_TARGET)));
362
363        let subscriber = tracing_subscriber::registry().with(layer);
364
365        tracing::subscriber::with_default(subscriber, || {
366            let req = clean_request();
367            AuditRecord::from_decision(&req, &Decision::Allow, 0.05, 120.0).emit();
368            tracing::info!(target: "unrelated::module", "should not appear");
369        });
370
371        std::thread::sleep(std::time::Duration::from_millis(250));
372
373        let contents = std::fs::read_to_string(&path).unwrap_or_default();
374
375        // Must contain an audit event.
376        assert!(
377            contents.contains("pipeline decision") || contents.contains("decision"),
378            "missing audit event in: {contents:?}"
379        );
380        // Must NOT contain the unrelated event.
381        assert!(!contents.contains("should not appear"));
382
383        // Every non-empty line must be valid JSON.
384        for line in contents.lines().filter(|l| !l.trim().is_empty()) {
385            serde_json::from_str::<serde_json::Value>(line)
386                .unwrap_or_else(|e| panic!("not valid JSON: {line:?}: {e}"));
387        }
388    }
389
390    // ── SizeRotatingWriter unit tests ───────────────────────────────────────
391    // These exercise the rotation logic directly (no tracing machinery, no
392    // async flushing delay) for fast, precise coverage of the size threshold.
393
394    #[test]
395    fn test_rotating_writer_no_rotation_under_threshold() {
396        let dir = tempfile::tempdir().unwrap();
397        let path = dir.path().join("audit.ndjson");
398
399        let mut writer = SizeRotatingWriter::open(&path, 1024).unwrap();
400        writer.write_all(b"a short line\n").unwrap();
401        writer.flush().unwrap();
402
403        let entries: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
404        assert_eq!(
405            entries.len(),
406            1,
407            "expected exactly one file, found: {entries:?}"
408        );
409
410        let contents = std::fs::read_to_string(&path).unwrap();
411        assert_eq!(contents, "a short line\n");
412    }
413
414    #[test]
415    fn test_rotating_writer_rotates_when_threshold_exceeded() {
416        let dir = tempfile::tempdir().unwrap();
417        let path = dir.path().join("audit.ndjson");
418
419        let mut writer = SizeRotatingWriter::open(&path, 20).unwrap();
420        writer.write_all(b"0123456789012345\n").unwrap();
421        writer.flush().unwrap();
422        writer.write_all(b"this write pushes us over\n").unwrap();
423        writer.flush().unwrap();
424
425        let entries: Vec<_> = std::fs::read_dir(dir.path())
426            .unwrap()
427            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
428            .collect();
429
430        assert_eq!(
431            entries.len(),
432            2,
433            "expected original + 1 rotated file, found: {entries:?}"
434        );
435        assert!(entries.iter().any(|n| n == "audit.ndjson"));
436        assert!(
437            entries
438                .iter()
439                .any(|n| n.starts_with("audit.") && n != "audit.ndjson"),
440            "expected a rotated backup file, found: {entries:?}"
441        );
442
443        let current_contents = std::fs::read_to_string(&path).unwrap();
444        assert_eq!(current_contents, "this write pushes us over\n");
445    }
446
447    #[test]
448    fn test_rotating_writer_preserves_old_content_in_backup() {
449        let dir = tempfile::tempdir().unwrap();
450        let path = dir.path().join("audit.ndjson");
451
452        let mut writer = SizeRotatingWriter::open(&path, 10).unwrap();
453        writer.write_all(b"first\n").unwrap();
454        writer.flush().unwrap();
455        writer.write_all(b"second\n").unwrap();
456        writer.flush().unwrap();
457
458        let backup = std::fs::read_dir(dir.path())
459            .unwrap()
460            .map(|e| e.unwrap().path())
461            .find(|p| {
462                p.file_name()
463                    .unwrap()
464                    .to_string_lossy()
465                    .starts_with("audit.")
466                    && p.file_name().unwrap() != "audit.ndjson"
467            })
468            .expect("expected a rotated backup file");
469
470        let backup_contents = std::fs::read_to_string(&backup).unwrap();
471        assert_eq!(backup_contents, "first\n");
472
473        let current_contents = std::fs::read_to_string(&path).unwrap();
474        assert_eq!(current_contents, "second\n");
475    }
476
477    #[test]
478    fn test_rotating_writer_never_rotates_an_empty_file() {
479        let dir = tempfile::tempdir().unwrap();
480        let path = dir.path().join("audit.ndjson");
481
482        let mut writer = SizeRotatingWriter::open(&path, 5).unwrap();
483        writer
484            .write_all(b"this single line is longer than 5 bytes\n")
485            .unwrap();
486        writer.flush().unwrap();
487
488        let entries: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
489        assert_eq!(
490            entries.len(),
491            1,
492            "must not rotate an empty file: {entries:?}"
493        );
494    }
495
496    #[test]
497    fn test_rotating_writer_resumes_existing_file_size() {
498        let dir = tempfile::tempdir().unwrap();
499        let path = dir.path().join("audit.ndjson");
500
501        std::fs::write(&path, b"pre-existing content (20 bytes)\n").unwrap();
502        let preexisting_size = std::fs::metadata(&path).unwrap().len();
503        assert!(preexisting_size > 0);
504
505        let mut writer = SizeRotatingWriter::open(&path, preexisting_size + 5).unwrap();
506        writer.write_all(b"more than 5 extra bytes here\n").unwrap();
507        writer.flush().unwrap();
508
509        let entries: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
510        assert_eq!(
511            entries.len(),
512            2,
513            "expected rotation on resumed file size, found: {entries:?}"
514        );
515    }
516
517    #[test]
518    fn test_max_size_mb_zero_does_not_panic() {
519        let dir = tempfile::tempdir().unwrap();
520        let path = dir.path().join("audit.ndjson");
521
522        let mut writer = SizeRotatingWriter::open(&path, 0).unwrap();
523        writer.write_all(b"first\n").unwrap();
524        writer.flush().unwrap();
525        writer.write_all(b"second\n").unwrap();
526        writer.flush().unwrap();
527
528        let entries: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
529        assert!(!entries.is_empty());
530    }
531}