canarytrap 0.2.0

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

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

/// A sink that emits canary events as `tracing` warnings.
///
/// Events are emitted with target `"canarytrap"` and structured fields:
/// `token_id`, `token_name`, `kind`, `source`, `triggered_at_secs`,
/// and `triggered_at_nanos`. The canary value is never logged.
///
/// # Example
///
/// ```
/// use canarytrap::{CanaryKind, CanaryToken, TracingSink};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let token = CanaryToken::builder("prod.api.key")
///     .kind(CanaryKind::ApiKey)
///     .value("fake")
///     .with_sink(TracingSink::new())
///     .build()?;
///
/// token.reveal();
/// // A tracing warning was emitted (visible if a subscriber is active).
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct TracingSink;

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

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

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

#[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_subscriber() {
        let sink = TracingSink::new();
        sink.emit(&sample_event());
    }

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

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