canarytrap 0.2.0

Rust-native canary tokens and honeytokens for early detection of suspicious access to secrets and configuration.
Documentation
//! JSONL file audit sink.
//!
//! Appends canary events as JSON lines to a file. Each line is a
//! self-contained JSON object with event metadata. The sink never writes
//! the canary value.

use crate::json::json_escape;
use crate::{CanaryEvent, Sink};
use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;

/// A sink that appends canary events to a file in JSONL format.
///
/// Each event is written as a single JSON line containing only event
/// metadata. The canary value is never written.
///
/// # Errors
///
/// IO errors during [`Sink::emit`] are silently ignored to satisfy the
/// sink contract (sinks must not panic or break the application).
/// Use [`FileAuditSink::try_emit`] if you need to handle IO errors.
///
/// # Example
///
/// ```
/// use canarytrap::{CanaryKind, CanaryToken, FileAuditSink};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let dir = std::env::temp_dir();
/// let path = dir.join("canarytrap_doctest_audit.jsonl");
///
/// let sink = FileAuditSink::new(&path)?;
///
/// let token = CanaryToken::builder("prod.db.password")
///     .kind(CanaryKind::Password)
///     .value("fake")
///     .with_sink(sink)
///     .build()?;
///
/// token.reveal();
///
/// // The event was appended to the file as a JSON line.
/// # std::fs::remove_file(&path).ok();
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct FileAuditSink {
    path: PathBuf,
}

impl FileAuditSink {
    /// Creates a new file audit sink.
    ///
    /// The parent directory must exist. The file is created if it does not
    /// exist.
    ///
    /// # Errors
    ///
    /// Returns [`std::io::Error`] if the file cannot be opened for appending.
    ///
    /// # Example
    ///
    /// ```
    /// use canarytrap::FileAuditSink;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let path = std::env::temp_dir().join("canarytrap_doctest_new.jsonl");
    /// let sink = FileAuditSink::new(&path)?;
    /// assert_eq!(sink.path(), path.as_path());
    /// # std::fs::remove_file(&path).ok();
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(path: impl AsRef<Path>) -> std::io::Result<Self> {
        let path = path.as_ref().to_path_buf();
        // Validate that we can open the file for appending.
        Self::open_file(&path)?;
        Ok(Self { path })
    }

    /// Returns the path of the audit file.
    ///
    /// # Example
    ///
    /// ```
    /// use canarytrap::FileAuditSink;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let path = std::env::temp_dir().join("canarytrap_doctest_path.jsonl");
    /// let sink = FileAuditSink::new(&path)?;
    /// assert_eq!(sink.path(), path.as_path());
    /// # std::fs::remove_file(&path).ok();
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Appends an event to the file, returning any IO error.
    ///
    /// This is the fallible version of [`Sink::emit`]. Use this method
    /// when you need to handle IO errors explicitly.
    ///
    /// # Errors
    ///
    /// Returns [`std::io::Error`] if the file cannot be opened or written.
    pub fn try_emit(&self, event: &CanaryEvent) -> std::io::Result<()> {
        let mut file = Self::open_file(&self.path)?;
        let line = format_event(event);
        file.write_all(line.as_bytes())?;
        file.write_all(b"\n")?;
        Ok(())
    }

    fn open_file(path: &Path) -> std::io::Result<std::fs::File> {
        OpenOptions::new().create(true).append(true).open(path)
    }
}

impl Sink for FileAuditSink {
    fn emit(&self, event: &CanaryEvent) {
        // IO errors are intentionally ignored to satisfy the Sink contract:
        // sinks must not panic or break the application.
        let _ = self.try_emit(event);
    }
}

fn format_event(event: &CanaryEvent) -> String {
    let duration = event
        .triggered_at
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();

    let mut line = format!(
        "{{\"token_id\":\"{}\",\"token_name\":\"{}\",\"kind\":\"{}\",\"source\":\"{}\",\"triggered_at_secs\":{},\"triggered_at_nanos\":{}",
        json_escape(&event.token_id),
        json_escape(&event.token_name),
        json_escape(&event.kind.to_string()),
        json_escape(&event.source.to_string()),
        duration.as_secs(),
        duration.subsec_nanos(),
    );

    if let Some(ref cid) = event.correlation_id {
        line.push_str(&format!(",\"correlation_id\":\"{}\"", json_escape(cid),));
    }

    if let Some(ref tid) = event.thread_id {
        line.push_str(&format!(",\"thread_id\":\"{}\"", json_escape(tid),));
    }

    line.push('}');
    line
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{CanaryKind, CanaryToken};
    use std::sync::{Arc, Mutex};

    fn temp_path(name: &str) -> PathBuf {
        std::env::temp_dir().join(format!("canarytrap_test_{name}.jsonl"))
    }

    /// Captures a real event by triggering a token through the public API.
    fn capture_event() -> CanaryEvent {
        let events = Arc::new(Mutex::new(Vec::new()));
        let events_clone = events.clone();

        let token = CanaryToken::builder("test-token")
            .kind(CanaryKind::Password)
            .value("fake")
            .on_trigger(move |event| {
                events_clone.lock().expect("mutex").push(event.clone());
            })
            .build()
            .expect("build should succeed");

        let _ = token.reveal();

        let mut events = events.lock().expect("mutex");
        events.pop().expect("should have one event")
    }

    #[test]
    fn new_creates_file() {
        let path = temp_path("new_creates");
        let _ = std::fs::remove_file(&path);

        let sink = FileAuditSink::new(&path).expect("sink creation should succeed");
        assert!(path.exists());
        assert_eq!(sink.path(), path.as_path());

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn try_emit_appends_json_line() {
        let path = temp_path("try_emit");
        let _ = std::fs::remove_file(&path);

        let sink = FileAuditSink::new(&path).expect("sink creation should succeed");
        let event = capture_event();
        sink.try_emit(&event).expect("emit should succeed");

        let content = std::fs::read_to_string(&path).expect("read should succeed");
        let lines: Vec<&str> = content.lines().collect();
        assert_eq!(lines.len(), 1);

        let line = lines[0];
        assert!(line.contains("\"token_name\":\"test-token\""));
        assert!(line.contains("\"kind\":\"password\""));
        assert!(line.contains("\"source\":\"reveal\""));
        assert!(line.contains("\"triggered_at_secs\":"));
        assert!(line.contains("\"triggered_at_nanos\":"));

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn try_emit_appends_multiple_lines() {
        let path = temp_path("multiple");
        let _ = std::fs::remove_file(&path);

        let sink = FileAuditSink::new(&path).expect("sink creation should succeed");
        let event = capture_event();
        sink.try_emit(&event).expect("first emit");
        sink.try_emit(&event).expect("second emit");

        let content = std::fs::read_to_string(&path).expect("read should succeed");
        assert_eq!(content.lines().count(), 2);

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn emit_does_not_panic() {
        let path = temp_path("emit_no_panic");
        let _ = std::fs::remove_file(&path);

        let sink = FileAuditSink::new(&path).expect("sink creation should succeed");
        let event = capture_event();
        sink.emit(&event); // must not panic

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn sink_is_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<FileAuditSink>();
    }
}