canarytrap 0.2.0

Rust-native canary tokens and honeytokens for early detection of suspicious access to secrets and configuration.
Documentation
//! Log sink.
//!
//! Emits canary events as log warnings.

use crate::{CanaryEvent, Sink};
use std::time::UNIX_EPOCH;

/// A sink that emits canary events as `log` warnings.
///
/// Events are logged with target `"canarytrap"` and include event metadata
/// as a formatted message. The canary value is never logged.
///
/// # Example
///
/// ```
/// use canarytrap::{CanaryKind, CanaryToken, LogSink};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let token = CanaryToken::builder("prod.api.key")
///     .kind(CanaryKind::ApiKey)
///     .value("fake")
///     .with_sink(LogSink::new())
///     .build()?;
///
/// token.reveal();
/// // A log warning was emitted (visible if a logger is installed).
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct LogSink;

impl LogSink {
    /// Creates a new log sink.
    ///
    /// # Example
    ///
    /// ```
    /// use canarytrap::LogSink;
    /// let sink = LogSink::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self
    }
}

impl Sink for LogSink {
    fn emit(&self, event: &CanaryEvent) {
        let duration = event
            .triggered_at
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default();

        log::warn!(
            target: "canarytrap",
            "canary token triggered: token_id={}, token_name={}, kind={}, source={}, triggered_at_secs={}, triggered_at_nanos={}, correlation_id={:?}, thread_id={:?}",
            event.token_id,
            event.token_name,
            event.kind,
            event.source,
            duration.as_secs(),
            duration.subsec_nanos(),
            event.correlation_id,
            event.thread_id,
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{CanaryKind, TriggerSource};
    use std::time::SystemTime;

    fn sample_event() -> CanaryEvent {
        CanaryEvent {
            token_id: "test-id".to_owned(),
            token_name: "test-name".to_owned(),
            kind: CanaryKind::Password,
            source: TriggerSource::Reveal,
            triggered_at: SystemTime::now(),
            correlation_id: None,
            thread_id: None,
        }
    }

    #[test]
    fn emit_does_not_panic_without_logger() {
        let sink = LogSink::new();
        sink.emit(&sample_event());
    }

    #[test]
    fn default_creates_sink() {
        let _sink = LogSink;
    }

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