1use 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;
37pub const AUDIT_TARGET: &str = "guardrail::audit";
42
43#[derive(Debug, thiserror::Error)]
45pub enum AuditLogError {
46 #[error("failed to create audit log directory '{path}': {source}")]
48 CreateDir {
49 path: String,
51 #[source]
53 source: std::io::Error,
54 },
55 #[error("failed to open audit log file '{path}': {source}")]
57 OpenFile {
58 path: String,
60 #[source]
62 source: std::io::Error,
63 },
64}
65
66struct SizeRotatingWriter {
81 inner: Mutex<SizeRotatingState>,
82}
83
84struct SizeRotatingState {
85 path: PathBuf,
86 file: Option<File>,
89 current_size: u64,
90 max_size_bytes: u64,
91}
92
93impl SizeRotatingWriter {
94 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 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 if let Some(file) = self.file.as_mut() {
162 file.flush()?;
163 }
164 self.file.take(); 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 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(()), }
211 }
212}
213
214pub 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
255pub 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 assert!(
377 contents.contains("pipeline decision") || contents.contains("decision"),
378 "missing audit event in: {contents:?}"
379 );
380 assert!(!contents.contains("should not appear"));
382
383 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 #[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}