canarytrap 0.2.0

Rust-native canary tokens and honeytokens for early detection of suspicious access to secrets and configuration.
Documentation
use crate::{CanaryKind, TriggerSource};
use core::fmt;
use std::time::SystemTime;

/// Metadata event emitted when access to a canary token is detected.
///
/// `CanaryEvent` intentionally contains only metadata. It never contains the
/// canary value itself.
///
/// # Fields
///
/// - `token_id`: unique identifier of the triggered token;
/// - `token_name`: human-readable token name;
/// - `kind`: kind of canary value;
/// - `source`: source that triggered the event;
/// - `triggered_at`: time when the event was created;
/// - `correlation_id`: optional user-defined correlation identifier;
/// - `thread_id`: optional thread identifier where the event was created.
///
/// # Example
///
/// ```
/// use std::time::SystemTime;
/// use canarytrap::{CanaryEvent, CanaryKind, TriggerSource};
///
/// let event = CanaryEvent::new(
///     "id-1",
///     "prod.db.password",
///     CanaryKind::Password,
///     TriggerSource::Reveal,
/// )
/// .with_triggered_at(SystemTime::UNIX_EPOCH)
/// .with_correlation_id("req-abc-123");
///
/// assert_eq!(event.token_id, "id-1");
/// assert_eq!(event.correlation_id.as_deref(), Some("req-abc-123"));
/// assert!(event.thread_id.is_some());
/// ```
///
/// # Security
///
/// The event does not store the canary value. This is intentional: canary
/// values must not appear in logs, events, debug output, or sinks unless the
/// user explicitly reveals them.
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CanaryEvent {
    /// Unique identifier of the triggered token.
    pub token_id: String,
    /// Human-readable name of the triggered token.
    pub token_name: String,
    /// Kind of canary value associated with the token.
    pub kind: CanaryKind,
    /// Source that triggered the event.
    pub source: TriggerSource,
    /// Time when the event was created.
    pub triggered_at: SystemTime,
    /// Optional user-defined correlation identifier.
    ///
    /// Use this to group related events across tokens, requests, or
    /// operations. For example, a request id or transaction id.
    pub correlation_id: Option<String>,
    /// Optional thread identifier where the event was created.
    ///
    /// Automatically populated by [`CanaryEvent::new`]. Contains the
    /// debug representation of [`std::thread::ThreadId`].
    pub thread_id: Option<String>,
}

impl CanaryEvent {
    /// Creates a new canary event with the current time and thread id.
    ///
    /// # Example
    ///
    /// ```
    /// use canarytrap::{CanaryEvent, CanaryKind, TriggerSource};
    ///
    /// let event = CanaryEvent::new(
    ///     "id-1",
    ///     "prod.db.password",
    ///     CanaryKind::Password,
    ///     TriggerSource::Reveal,
    /// );
    ///
    /// assert_eq!(event.token_id, "id-1");
    /// assert_eq!(event.token_name, "prod.db.password");
    /// assert_eq!(event.kind, CanaryKind::Password);
    /// assert_eq!(event.source, TriggerSource::Reveal);
    /// assert!(event.thread_id.is_some());
    /// assert!(event.correlation_id.is_none());
    /// ```
    #[must_use]
    pub fn new(
        token_id: impl Into<String>,
        token_name: impl Into<String>,
        kind: CanaryKind,
        source: TriggerSource,
    ) -> Self {
        Self {
            token_id: token_id.into(),
            token_name: token_name.into(),
            kind,
            source,
            triggered_at: SystemTime::now(),
            correlation_id: None,
            thread_id: Some(format!("{:?}", std::thread::current().id())),
        }
    }

    /// Replaces the event timestamp.
    ///
    /// This is useful for deterministic tests and for replaying events with a
    /// known timestamp.
    ///
    /// # Example
    ///
    /// ```
    /// use std::time::SystemTime;
    /// use canarytrap::{CanaryEvent, CanaryKind, TriggerSource};
    ///
    /// let event = CanaryEvent::new(
    ///     "id-1",
    ///     "prod.db.password",
    ///     CanaryKind::Password,
    ///     TriggerSource::Reveal,
    /// )
    /// .with_triggered_at(SystemTime::UNIX_EPOCH);
    ///
    /// assert_eq!(event.triggered_at, SystemTime::UNIX_EPOCH);
    /// ```
    #[must_use]
    pub fn with_triggered_at(mut self, triggered_at: SystemTime) -> Self {
        self.triggered_at = triggered_at;
        self
    }

    /// Sets a correlation identifier for this event.
    ///
    /// Use this to link related events across tokens, requests, or
    /// operations. For example, a request id, trace id, or transaction id.
    ///
    /// # Example
    ///
    /// ```
    /// use canarytrap::{CanaryEvent, CanaryKind, TriggerSource};
    ///
    /// let event = CanaryEvent::new(
    ///     "id-1",
    ///     "prod.db.password",
    ///     CanaryKind::Password,
    ///     TriggerSource::Reveal,
    /// )
    /// .with_correlation_id("req-abc-123");
    ///
    /// assert_eq!(event.correlation_id.as_deref(), Some("req-abc-123"));
    /// ```
    #[must_use]
    pub fn with_correlation_id(mut self, correlation_id: impl Into<String>) -> Self {
        self.correlation_id = Some(correlation_id.into());
        self
    }

    /// Replaces the thread identifier.
    ///
    /// By default, [`CanaryEvent::new`] captures the current thread id.
    /// Use this method to override it, for example in async contexts
    /// where task ids are more meaningful than OS thread ids.
    ///
    /// # Example
    ///
    /// ```
    /// use canarytrap::{CanaryEvent, CanaryKind, TriggerSource};
    ///
    /// let event = CanaryEvent::new(
    ///     "id-1",
    ///     "prod.db.password",
    ///     CanaryKind::Password,
    ///     TriggerSource::Reveal,
    /// )
    /// .with_thread_id("tokio-task-42");
    ///
    /// assert_eq!(event.thread_id.as_deref(), Some("tokio-task-42"));
    /// ```
    #[must_use]
    pub fn with_thread_id(mut self, thread_id: impl Into<String>) -> Self {
        self.thread_id = Some(thread_id.into());
        self
    }
}

impl fmt::Debug for CanaryEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut d = f.debug_struct("CanaryEvent");
        d.field("token_id", &self.token_id)
            .field("token_name", &self.token_name)
            .field("kind", &self.kind)
            .field("source", &self.source)
            .field("triggered_at", &self.triggered_at);
        if let Some(ref cid) = self.correlation_id {
            d.field("correlation_id", cid);
        }
        if let Some(ref tid) = self.thread_id {
            d.field("thread_id", tid);
        }
        d.finish()
    }
}

impl fmt::Display for CanaryEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "canary event: token={token} id={id} kind={kind} source={source}",
            token = self.token_name,
            id = self.token_id,
            kind = self.kind,
            source = self.source,
        )?;
        if let Some(ref cid) = self.correlation_id {
            write!(f, " correlation_id={cid}")?;
        }
        if let Some(ref tid) = self.thread_id {
            write!(f, " thread_id={tid}")?;
        }
        Ok(())
    }
}

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

    fn sample_event() -> CanaryEvent {
        CanaryEvent::new(
            "id-1",
            "prod.db.password",
            CanaryKind::Password,
            TriggerSource::Reveal,
        )
        .with_triggered_at(SystemTime::UNIX_EPOCH)
    }

    #[test]
    fn new_stores_metadata() {
        let event = sample_event();
        assert_eq!(event.token_id, "id-1");
        assert_eq!(event.token_name, "prod.db.password");
        assert_eq!(event.kind, CanaryKind::Password);
        assert_eq!(event.source, TriggerSource::Reveal);
        assert_eq!(event.triggered_at, SystemTime::UNIX_EPOCH);
    }

    #[test]
    fn new_captures_thread_id() {
        let event = CanaryEvent::new("id-1", "test", CanaryKind::Password, TriggerSource::Reveal);
        assert!(event.thread_id.is_some());
        let tid = event.thread_id.as_ref().unwrap();
        assert!(!tid.is_empty());
    }

    #[test]
    fn new_has_no_correlation_id_by_default() {
        let event = CanaryEvent::new("id-1", "test", CanaryKind::Password, TriggerSource::Reveal);
        assert!(event.correlation_id.is_none());
    }

    #[test]
    fn with_triggered_at_replaces_timestamp() {
        let event = CanaryEvent::new(
            "id-1",
            "prod.db.password",
            CanaryKind::Password,
            TriggerSource::Reveal,
        )
        .with_triggered_at(SystemTime::UNIX_EPOCH);
        assert_eq!(event.triggered_at, SystemTime::UNIX_EPOCH);
    }

    #[test]
    fn with_correlation_id_sets_value() {
        let event = sample_event().with_correlation_id("req-abc-123");
        assert_eq!(event.correlation_id.as_deref(), Some("req-abc-123"));
    }

    #[test]
    fn with_thread_id_overrides_default() {
        let event = sample_event().with_thread_id("tokio-task-42");
        assert_eq!(event.thread_id.as_deref(), Some("tokio-task-42"));
    }

    #[test]
    fn display_contains_metadata() {
        let event = sample_event();
        let display = event.to_string();
        assert!(display.contains("token=prod.db.password"));
        assert!(display.contains("id=id-1"));
        assert!(display.contains("kind=password"));
        assert!(display.contains("source=reveal"));
    }

    #[test]
    fn display_includes_optional_fields_when_present() {
        let event = sample_event()
            .with_correlation_id("req-1")
            .with_thread_id("thread-1");
        let display = event.to_string();
        assert!(display.contains("correlation_id=req-1"));
        assert!(display.contains("thread_id=thread-1"));
    }

    #[test]
    fn display_omits_optional_fields_when_absent() {
        let event = CanaryEvent::new("id-1", "test", CanaryKind::Password, TriggerSource::Reveal)
            .with_triggered_at(SystemTime::UNIX_EPOCH);
        // Clear thread_id to test omission.
        let event = CanaryEvent {
            thread_id: None,
            ..event
        };
        let display = event.to_string();
        assert!(!display.contains("correlation_id"));
        assert!(!display.contains("thread_id"));
    }

    #[test]
    fn display_does_not_include_canary_value() {
        let canary_value = "canary-fake-password-9f8a7b";
        let event = sample_event();
        let display = event.to_string();
        assert!(!display.contains(canary_value));
    }

    #[test]
    fn debug_contains_metadata() {
        let event = sample_event();
        let debug = format!("{event:?}");
        assert!(debug.contains("CanaryEvent"));
        assert!(debug.contains("token_id"));
        assert!(debug.contains("id-1"));
        assert!(debug.contains("token_name"));
        assert!(debug.contains("prod.db.password"));
        assert!(debug.contains("kind"));
        assert!(debug.contains("source"));
        assert!(debug.contains("triggered_at"));
    }

    #[test]
    fn debug_includes_optional_fields_when_present() {
        let event = sample_event()
            .with_correlation_id("req-1")
            .with_thread_id("thread-1");
        let debug = format!("{event:?}");
        assert!(debug.contains("correlation_id"));
        assert!(debug.contains("req-1"));
        assert!(debug.contains("thread_id"));
        assert!(debug.contains("thread-1"));
    }

    #[test]
    fn debug_does_not_include_canary_value() {
        let canary_value = "canary-fake-password-9f8a7b";
        let event = sample_event();
        let debug = format!("{event:?}");
        assert!(!debug.contains(canary_value));
    }

    #[test]
    fn clone_and_eq_work() {
        let event = sample_event().with_correlation_id("req-1");
        let cloned = event.clone();
        assert_eq!(event, cloned);
    }

    #[test]
    fn supports_custom_kind_and_source() {
        let event = CanaryEvent::new(
            "id-2",
            "ldap.bind.password",
            CanaryKind::custom("ldap"),
            TriggerSource::custom("serde"),
        )
        .with_triggered_at(SystemTime::UNIX_EPOCH);
        assert_eq!(event.kind.to_string(), "custom:ldap");
        assert_eq!(event.source.to_string(), "custom:serde");
    }
}