canarytrap 0.2.0

Rust-native canary tokens and honeytokens for early detection of suspicious access to secrets and configuration.
Documentation
//! Rate limiting sink.
//!
//! Wraps another sink and limits the number of events delivered within
//! a sliding time window.

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

/// A sink wrapper that limits the rate of event delivery.
///
/// Events are delivered up to `max_events` times within any sliding `window`.
/// Events that exceed the limit are suppressed.
///
/// # Example
///
/// ```
/// use canarytrap::{CallbackSink, CanaryKind, CanaryToken, RateLimitedSink};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let inner = CallbackSink::new(|event| {
///     eprintln!("canary triggered: {}", event.token_name);
/// });
///
/// // At most 5 events per second.
/// let sink = RateLimitedSink::per_second(inner, 5);
///
/// let token = CanaryToken::builder("prod.api.key")
///     .kind(CanaryKind::ApiKey)
///     .value("fake")
///     .with_sink(sink)
///     .build()?;
///
/// token.reveal(); // delivered (within limit)
/// # Ok(())
/// # }
/// ```
pub struct RateLimitedSink<S> {
    inner: S,
    max_events: usize,
    window: Duration,
    timestamps: Mutex<VecDeque<Instant>>,
}

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

    /// Returns the maximum number of events allowed within the window.
    ///
    /// # Example
    ///
    /// ```
    /// use canarytrap::{CallbackSink, RateLimitedSink};
    /// use std::time::Duration;
    ///
    /// let inner = CallbackSink::new(|_event| {});
    /// let sink = RateLimitedSink::new(inner, 10, Duration::from_secs(60));
    /// assert_eq!(sink.max_events(), 10);
    /// ```
    #[must_use]
    pub fn max_events(&self) -> usize {
        self.max_events
    }

    /// Returns the sliding window duration.
    ///
    /// # Example
    ///
    /// ```
    /// use canarytrap::{CallbackSink, RateLimitedSink};
    /// use std::time::Duration;
    ///
    /// let inner = CallbackSink::new(|_event| {});
    /// let sink = RateLimitedSink::new(inner, 10, Duration::from_secs(60));
    /// assert_eq!(sink.window(), Duration::from_secs(60));
    /// ```
    #[must_use]
    pub fn window(&self) -> Duration {
        self.window
    }
}

impl<S: Sink> RateLimitedSink<S> {
    /// Creates a rate limiting sink.
    ///
    /// At most `max_events` events are delivered within any sliding `window`.
    /// Events exceeding the limit are suppressed.
    ///
    /// Setting `max_events` to `0` suppresses all events.
    ///
    /// # Example
    ///
    /// ```
    /// use canarytrap::{CallbackSink, RateLimitedSink};
    /// use std::time::Duration;
    ///
    /// let inner = CallbackSink::new(|_event| {});
    /// let sink = RateLimitedSink::new(inner, 10, Duration::from_secs(60));
    /// ```
    #[must_use]
    pub fn new(inner: S, max_events: usize, window: Duration) -> Self {
        Self {
            inner,
            max_events,
            window,
            timestamps: Mutex::new(VecDeque::new()),
        }
    }

    /// Creates a rate limiting sink with a one-second sliding window.
    ///
    /// # Example
    ///
    /// ```
    /// use canarytrap::{CallbackSink, RateLimitedSink};
    ///
    /// let inner = CallbackSink::new(|_event| {});
    /// let sink = RateLimitedSink::per_second(inner, 5);
    /// ```
    #[must_use]
    pub fn per_second(inner: S, max_events: usize) -> Self {
        Self::new(inner, max_events, Duration::from_secs(1))
    }

    /// Creates a rate limiting sink with a one-minute sliding window.
    ///
    /// # Example
    ///
    /// ```
    /// use canarytrap::{CallbackSink, RateLimitedSink};
    ///
    /// let inner = CallbackSink::new(|_event| {});
    /// let sink = RateLimitedSink::per_minute(inner, 100);
    /// ```
    #[must_use]
    pub fn per_minute(inner: S, max_events: usize) -> Self {
        Self::new(inner, max_events, Duration::from_secs(60))
    }
}

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

        let should_emit = {
            let mut timestamps = self.timestamps.lock().expect("rate limit mutex poisoned");

            // Remove expired entries from the front of the window.
            while let Some(front) = timestamps.front() {
                if now.duration_since(*front) >= self.window {
                    timestamps.pop_front();
                } else {
                    break;
                }
            }

            if timestamps.len() < self.max_events {
                timestamps.push_back(now);
                true
            } else {
                false
            }
        };

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

impl<S> fmt::Debug for RateLimitedSink<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RateLimitedSink")
            .field("max_events", &self.max_events)
            .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() -> CanaryEvent {
        CanaryEvent {
            token_id: "test-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 events_within_limit_are_delivered() {
        let counter = CountingSink::default();
        let count = counter.count.clone();
        let sink = RateLimitedSink::per_second(counter, 5);

        for _ in 0..5 {
            sink.emit(&sample_event());
        }

        assert_eq!(count.load(Ordering::SeqCst), 5);
    }

    #[test]
    fn events_exceeding_limit_are_suppressed() {
        let counter = CountingSink::default();
        let count = counter.count.clone();
        let sink = RateLimitedSink::per_second(counter, 3);

        for _ in 0..10 {
            sink.emit(&sample_event());
        }

        assert_eq!(count.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn zero_max_events_suppresses_all() {
        let counter = CountingSink::default();
        let count = counter.count.clone();
        let sink = RateLimitedSink::per_second(counter, 0);

        sink.emit(&sample_event());
        sink.emit(&sample_event());

        assert_eq!(count.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn events_allowed_after_window_expires() {
        let counter = CountingSink::default();
        let count = counter.count.clone();
        let sink = RateLimitedSink::new(counter, 2, Duration::from_millis(10));

        sink.emit(&sample_event());
        sink.emit(&sample_event());
        assert_eq!(count.load(Ordering::SeqCst), 2);

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

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

        // After window: delivered.
        sink.emit(&sample_event());
        assert_eq!(count.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn accessors_return_configured_values() {
        let sink = RateLimitedSink::new(CountingSink::default(), 10, Duration::from_secs(30));
        assert_eq!(sink.max_events(), 10);
        assert_eq!(sink.window(), Duration::from_secs(30));
    }

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