use crate::{CallbackSink, CanaryEvent, CanaryKind, Sink, TriggerSource};
use core::fmt;
use std::panic::{AssertUnwindSafe, catch_unwind};
use uuid::Uuid;
pub struct CanaryToken {
id: String,
name: String,
kind: CanaryKind,
value: String,
sinks: Vec<Box<dyn Sink>>,
}
impl CanaryToken {
#[must_use]
pub fn new(name: impl Into<String>, kind: CanaryKind, value: impl Into<String>) -> Self {
Self {
id: Uuid::new_v4().to_string(),
name: name.into(),
kind,
value: value.into(),
sinks: Vec::new(),
}
}
#[must_use]
pub fn builder(name: impl Into<String>) -> crate::builder::CanaryTokenBuilder {
crate::builder::CanaryTokenBuilder::new(name)
}
pub(crate) fn from_parts(
name: String,
kind: CanaryKind,
value: String,
sinks: Vec<Box<dyn Sink>>,
) -> Self {
Self {
id: Uuid::new_v4().to_string(),
name,
kind,
value,
sinks,
}
}
#[cfg(feature = "generators")]
pub fn generate(name: impl Into<String>, kind: CanaryKind) -> crate::Result<Self> {
let value = crate::generator::generate(&kind)?;
Ok(Self::new(name, kind, value))
}
#[must_use]
pub fn id(&self) -> &str {
&self.id
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn kind(&self) -> &CanaryKind {
&self.kind
}
#[must_use]
pub fn on_trigger(mut self, callback: impl Fn(&CanaryEvent) + Send + Sync + 'static) -> Self {
self.sinks.push(Box::new(CallbackSink::new(callback)));
self
}
#[must_use]
pub fn with_sink(mut self, sink: impl Sink + 'static) -> Self {
self.sinks.push(Box::new(sink));
self
}
#[must_use]
pub fn reveal(&self) -> String {
self.trigger(TriggerSource::Reveal);
self.value.clone()
}
#[must_use]
pub fn reveal_with_source(&self, source: TriggerSource) -> String {
self.trigger(source);
self.value.clone()
}
pub fn with_value<R>(&self, f: impl FnOnce(&str) -> R) -> R {
self.trigger(TriggerSource::WithValue);
f(&self.value)
}
pub fn trigger(&self, source: TriggerSource) {
let event = CanaryEvent::new(
self.id.clone(),
self.name.clone(),
self.kind.clone(),
source,
);
self.emit(&event);
}
fn emit(&self, event: &CanaryEvent) {
for sink in &self.sinks {
let result = catch_unwind(AssertUnwindSafe(|| sink.emit(event)));
if let Err(_panic) = result {
}
}
}
}
impl fmt::Debug for CanaryToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CanaryToken")
.field("id", &self.id)
.field("name", &self.name)
.field("kind", &self.kind)
.field("value", &"[REDACTED]")
.field("sinks", &self.sinks.len())
.finish()
}
}
impl fmt::Display for CanaryToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"canary token: name={name} id={id} kind={kind} value=[REDACTED]",
name = self.name,
id = self.id,
kind = self.kind,
)
}
}
#[cfg(test)]
mod tests {
use super::CanaryToken;
use crate::{CallbackSink, CanaryEvent, CanaryKind, Sink, TriggerSource};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone, Default)]
struct RecordingSink {
events: Arc<Mutex<Vec<CanaryEvent>>>,
}
impl Sink for RecordingSink {
fn emit(&self, event: &CanaryEvent) {
self.events
.lock()
.expect("recording sink mutex poisoned")
.push(event.clone());
}
}
fn sample_token() -> CanaryToken {
CanaryToken::new(
"prod.db.password",
CanaryKind::Password,
"canary-fake-password",
)
}
#[test]
fn new_generates_unique_identifiers() {
let first = sample_token();
let second = sample_token();
assert!(!first.id().is_empty());
assert!(!second.id().is_empty());
assert_ne!(first.id(), second.id());
}
#[test]
fn new_stores_name_and_kind() {
let token = sample_token();
assert_eq!(token.name(), "prod.db.password");
assert_eq!(token.kind(), &CanaryKind::Password);
}
#[test]
fn reveal_returns_value_and_triggers_event() {
let events = Arc::new(Mutex::new(Vec::new()));
let events_clone = events.clone();
let token = sample_token().on_trigger(move |event| {
events_clone
.lock()
.expect("events mutex poisoned")
.push(event.clone());
});
let value = token.reveal();
assert_eq!(value, "canary-fake-password");
let events = events.lock().expect("events mutex poisoned");
assert_eq!(events.len(), 1);
let event = &events[0];
assert_eq!(event.token_id, token.id());
assert_eq!(event.token_name, "prod.db.password");
assert_eq!(event.kind, CanaryKind::Password);
assert_eq!(event.source, TriggerSource::Reveal);
}
#[test]
fn with_value_returns_closure_result_and_triggers_event() {
let events = Arc::new(Mutex::new(Vec::new()));
let events_clone = events.clone();
let token = sample_token().on_trigger(move |event| {
events_clone
.lock()
.expect("events mutex poisoned")
.push(event.clone());
});
let len = token.with_value(|value| value.len());
assert_eq!(len, "canary-fake-password".len());
let events = events.lock().expect("events mutex poisoned");
assert_eq!(events.len(), 1);
assert_eq!(events[0].source, TriggerSource::WithValue);
}
#[test]
fn trigger_emits_custom_source() {
let events = Arc::new(Mutex::new(Vec::new()));
let events_clone = events.clone();
let token = sample_token().on_trigger(move |event| {
events_clone
.lock()
.expect("events mutex poisoned")
.push(event.clone());
});
token.trigger(TriggerSource::Custom("manual"));
let events = events.lock().expect("events mutex poisoned");
assert_eq!(events.len(), 1);
assert_eq!(events[0].source, TriggerSource::Custom("manual"));
}
#[test]
fn multiple_callbacks_are_called_in_registration_order() {
let calls = Arc::new(Mutex::new(Vec::new()));
let first_calls = calls.clone();
let second_calls = calls.clone();
let token = sample_token()
.on_trigger(move |_| {
first_calls.lock().expect("calls mutex poisoned").push(1);
})
.on_trigger(move |_| {
second_calls.lock().expect("calls mutex poisoned").push(2);
});
token.trigger(TriggerSource::Reveal);
let calls = calls.lock().expect("calls mutex poisoned");
assert_eq!(*calls, vec![1, 2]);
}
#[test]
fn with_sink_accepts_custom_sink() {
let sink = RecordingSink::default();
let events = sink.events.clone();
let token = sample_token().with_sink(sink);
token.trigger(TriggerSource::Reveal);
let events = events.lock().expect("events mutex poisoned");
assert_eq!(events.len(), 1);
assert_eq!(events[0].source, TriggerSource::Reveal);
}
#[test]
fn on_trigger_and_with_sink_can_be_combined() {
let calls = Arc::new(Mutex::new(Vec::new()));
let callback_calls = calls.clone();
let sink_calls = calls.clone();
let sink = CallbackSink::new(move |_| {
sink_calls
.lock()
.expect("sink calls mutex poisoned")
.push("sink");
});
let token = sample_token()
.on_trigger(move |_| {
callback_calls
.lock()
.expect("callback calls mutex poisoned")
.push("callback");
})
.with_sink(sink);
token.trigger(TriggerSource::Reveal);
let calls = calls.lock().expect("calls mutex poisoned");
assert_eq!(*calls, vec!["callback", "sink"]);
}
#[test]
fn debug_redacts_canary_value() {
let token = sample_token();
let debug = format!("{token:?}");
assert!(debug.contains("CanaryToken"));
assert!(debug.contains("prod.db.password"));
assert!(debug.contains("[REDACTED]"));
assert!(!debug.contains("canary-fake-password"));
}
#[test]
fn display_redacts_canary_value() {
let token = sample_token();
let display = token.to_string();
assert!(display.contains("canary token"));
assert!(display.contains("prod.db.password"));
assert!(display.contains("[REDACTED]"));
assert!(!display.contains("canary-fake-password"));
}
#[test]
fn event_does_not_contain_canary_value() {
let events = Arc::new(Mutex::new(Vec::new()));
let events_clone = events.clone();
let token = sample_token().on_trigger(move |event| {
events_clone
.lock()
.expect("events mutex poisoned")
.push(event.clone());
});
token.trigger(TriggerSource::Reveal);
let events = events.lock().expect("events mutex poisoned");
let event = &events[0];
let event_debug = format!("{event:?}");
let event_display = event.to_string();
assert!(!event_debug.contains("canary-fake-password"));
assert!(!event_display.contains("canary-fake-password"));
}
#[test]
fn supports_custom_kind_and_source() {
let events = Arc::new(Mutex::new(Vec::new()));
let events_clone = events.clone();
let token = CanaryToken::new(
"ldap.bind.password",
CanaryKind::custom("ldap"),
"canary-fake-ldap",
)
.on_trigger(move |event| {
events_clone
.lock()
.expect("events mutex poisoned")
.push(event.clone());
});
token.trigger(TriggerSource::custom("manual"));
let events = events.lock().expect("events mutex poisoned");
let event = &events[0];
assert_eq!(event.kind.to_string(), "custom:ldap");
assert_eq!(event.source.to_string(), "custom:manual");
}
#[test]
fn trigger_count_is_correct() {
let count = Arc::new(AtomicUsize::new(0));
let counter = count.clone();
let token = sample_token().on_trigger(move |_| {
counter.fetch_add(1, Ordering::SeqCst);
});
token.trigger(TriggerSource::Reveal);
token.with_value(|_| {});
token.trigger(TriggerSource::Registry);
assert_eq!(count.load(Ordering::SeqCst), 3);
}
#[test]
fn token_is_send_and_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<CanaryToken>();
}
#[test]
fn event_metadata_matches_token() {
let events = Arc::new(Mutex::new(Vec::new()));
let events_clone = events.clone();
let token = sample_token().on_trigger(move |event| {
events_clone
.lock()
.expect("events mutex poisoned")
.push(event.clone());
});
token.trigger(TriggerSource::Reveal);
let events = events.lock().expect("events mutex poisoned");
let event: &CanaryEvent = &events[0];
assert_eq!(event.token_id, token.id());
assert_eq!(event.token_name, token.name());
assert_eq!(event.kind, *token.kind());
}
#[test]
fn reveal_with_source_emits_given_source() {
let events = Arc::new(Mutex::new(Vec::new()));
let events_clone = events.clone();
let token = sample_token().on_trigger(move |event| {
events_clone
.lock()
.expect("events mutex poisoned")
.push(event.clone());
});
let value = token.reveal_with_source(TriggerSource::Registry);
assert_eq!(value, "canary-fake-password");
let events = events.lock().expect("events mutex poisoned");
assert_eq!(events.len(), 1);
assert_eq!(events[0].source, TriggerSource::Registry);
}
}