canarytrap 0.2.0

Rust-native canary tokens and honeytokens for early detection of suspicious access to secrets and configuration.
Documentation
//! Deduplicating sink.
//!
//! Wraps another sink and suppresses duplicate events based on a
//! deduplication key derived from the event's token id and trigger source.

use crate::{CanaryEvent, Sink};
use std::collections::HashMap;
use std::fmt;
use std::sync::Mutex;
use std::time::{Duration, Instant};

/// A sink wrapper that suppresses duplicate events.
///
/// Events are considered duplicates if they have the same token id and
/// trigger source. Two modes are supported:
///
/// - **Permanent** ([`DeduplicatingSink::new`]): once an event key is seen,
///   all future events with the same key are suppressed.
/// - **Windowed** ([`DeduplicatingSink::with_window`]): events with the same
///   key are suppressed for a configurable duration after the last delivery.
///
/// # Memory
///
/// The internal set of seen keys grows with the number of unique events.
/// For long-running applications with many distinct tokens, prefer the
/// windowed mode to allow re-delivery after the window expires.
///
/// # Example
///
/// ```
/// use canarytrap::{CallbackSink, CanaryKind, CanaryToken, DeduplicatingSink};
/// use std::time::Duration;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let inner = CallbackSink::new(|event| {
///     eprintln!("canary triggered: {}", event.token_name);
/// });
///
/// let sink = DeduplicatingSink::with_window(inner, Duration::from_secs(60));
///
/// let token = CanaryToken::builder("prod.api.key")
///     .kind(CanaryKind::ApiKey)
///     .value("fake")
///     .with_sink(sink)
///     .build()?;
///
/// token.reveal(); // delivered
/// token.reveal(); // suppressed (duplicate within window)
/// # Ok(())
/// # }
/// ```
pub struct DeduplicatingSink<S> {
    inner: S,
    seen: Mutex<HashMap<String, Instant>>,
    window: Option<Duration>,
}

impl<S> DeduplicatingSink<S> {
    /// Returns a reference to the inner sink.
    ///
    /// # Example
    ///
    /// ```
    /// use canarytrap::{CallbackSink, DeduplicatingSink};
    ///
    /// let inner = CallbackSink::new(|_event| {});
    /// let sink = DeduplicatingSink::new(inner);
    /// let _ = sink.inner();
    /// ```
    #[must_use]
    pub fn inner(&self) -> &S {
        &self.inner
    }

    /// Computes the deduplication key for an event.
    fn dedup_key(event: &CanaryEvent) -> String {
        format!("{}:{}", event.token_id, event.source)
    }
}

impl<S: Sink> DeduplicatingSink<S> {
    /// Creates a deduplicating sink with permanent deduplication.
    ///
    /// Once an event with a given key is delivered, all future events with
    /// the same key are suppressed for the lifetime of the sink.
    ///
    /// # Example
    ///
    /// ```
    /// use canarytrap::{CallbackSink, DeduplicatingSink};
    ///
    /// let inner = CallbackSink::new(|_event| {});
    /// let sink = DeduplicatingSink::new(inner);
    /// ```
    #[must_use]
    pub fn new(inner: S) -> Self {
        Self {
            inner,
            seen: Mutex::new(HashMap::new()),
            window: None,
        }
    }

    /// Creates a deduplicating sink with a time window.
    ///
    /// Events with the same key are suppressed for `window` duration
    /// after the last delivery. After the window expires, the next event
    /// with the same key is delivered.
    ///
    /// # Example
    ///
    /// ```
    /// use canarytrap::{CallbackSink, DeduplicatingSink};
    /// use std::time::Duration;
    ///
    /// let inner = CallbackSink::new(|_event| {});
    /// let sink = DeduplicatingSink::with_window(inner, Duration::from_secs(30));
    /// ```
    #[must_use]
    pub fn with_window(inner: S, window: Duration) -> Self {
        Self {
            inner,
            seen: Mutex::new(HashMap::new()),
            window: Some(window),
        }
    }
}

impl<S: Sink> Sink for DeduplicatingSink<S> {
    fn emit(&self, event: &CanaryEvent) {
        let key = Self::dedup_key(event);
        let now = Instant::now();

        let should_emit = {
            let mut seen = self.seen.lock().expect("dedup sink mutex poisoned");

            match self.window {
                None => {
                    // Permanent mode: first occurrence wins, forever.
                    seen.insert(key, now).is_none()
                }
                Some(window) => {
                    match seen.get(&key) {
                        Some(last) if now.duration_since(*last) < window => {
                            // Within window: suppress.
                            false
                        }
                        _ => {
                            // First occurrence or window expired: deliver.
                            seen.insert(key, now);
                            true
                        }
                    }
                }
            }
        };

        if should_emit {
            self.inner.emit(event);
        }
    }
}

impl<S> fmt::Debug for DeduplicatingSink<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DeduplicatingSink")
            .field("window", &self.window)
            .finish_non_exhaustive()
    }
}

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

    #[derive(Debug, Clone, Default)]
    struct CountingSink {
        count: Arc<AtomicUsize>,
    }

    impl Sink for CountingSink {
        fn emit(&self, _event: &CanaryEvent) {
            self.count.fetch_add(1, Ordering::SeqCst);
        }
    }

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

    #[test]
    fn first_event_is_delivered() {
        let counter = CountingSink::default();
        let count = counter.count.clone();
        let sink = DeduplicatingSink::new(counter);

        sink.emit(&sample_event("id-1"));
        assert_eq!(count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn duplicate_event_is_suppressed_permanently() {
        let counter = CountingSink::default();
        let count = counter.count.clone();
        let sink = DeduplicatingSink::new(counter);

        sink.emit(&sample_event("id-1"));
        sink.emit(&sample_event("id-1"));
        sink.emit(&sample_event("id-1"));
        assert_eq!(count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn different_tokens_are_not_duplicates() {
        let counter = CountingSink::default();
        let count = counter.count.clone();
        let sink = DeduplicatingSink::new(counter);

        sink.emit(&sample_event("id-1"));
        sink.emit(&sample_event("id-2"));
        assert_eq!(count.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn window_suppresses_within_duration() {
        let counter = CountingSink::default();
        let count = counter.count.clone();
        let sink = DeduplicatingSink::with_window(counter, Duration::from_secs(60));

        sink.emit(&sample_event("id-1"));
        sink.emit(&sample_event("id-1"));
        assert_eq!(count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn window_allows_redelivery_after_expiry() {
        let counter = CountingSink::default();
        let count = counter.count.clone();
        let sink = DeduplicatingSink::with_window(counter, Duration::from_millis(10));

        sink.emit(&sample_event("id-1"));
        assert_eq!(count.load(Ordering::SeqCst), 1);

        // Within window: suppressed.
        sink.emit(&sample_event("id-1"));
        assert_eq!(count.load(Ordering::SeqCst), 1);

        // Wait for window to expire.
        std::thread::sleep(Duration::from_millis(20));

        // After window: delivered.
        sink.emit(&sample_event("id-1"));
        assert_eq!(count.load(Ordering::SeqCst), 2);
    }

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