canarytrap 0.2.0

Rust-native canary tokens and honeytokens for early detection of suspicious access to secrets and configuration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use core::fmt;

/// The source that triggered access to a canary token.
///
/// `TriggerSource` describes which instrumented API path observed access to a
/// canary value. It is metadata only and must never contain the canary value
/// itself.
///
/// # Built-in sources
///
/// ```
/// use canarytrap::TriggerSource;
///
/// assert_eq!(TriggerSource::Reveal.to_string(), "reveal");
/// assert_eq!(TriggerSource::WithValue.to_string(), "with-value");
/// assert_eq!(TriggerSource::Registry.to_string(), "registry");
/// assert_eq!(TriggerSource::Serialize.to_string(), "serialize");
/// ```
///
/// # Custom sources
///
/// Custom sources borrow a `'static` string and are serialized with a `custom:`
/// prefix:
///
/// ```
/// use canarytrap::TriggerSource;
///
/// let source = TriggerSource::custom("serde");
/// assert_eq!(source.to_string(), "custom:serde");
/// ```
///
/// # Parsing
///
/// Because [`TriggerSource::Custom`] stores a `'static` string, parsing is
/// provided for static input through [`TriggerSource::from_static`] and
/// [`TryFrom<&'static str>`](core::convert::TryFrom). This avoids leaking
/// dynamically allocated strings.
///
/// ```
/// use canarytrap::TriggerSource;
///
/// assert_eq!(
///     TriggerSource::from_static("reveal"),
///     Ok(TriggerSource::Reveal)
/// );
/// assert_eq!(
///     TriggerSource::from_static("custom:serde"),
///     Ok(TriggerSource::Custom("serde"))
/// );
/// assert!(TriggerSource::from_static("unknown-source").is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum TriggerSource {
    /// The canary value was accessed through an explicit reveal API.
    Reveal,

    /// The canary value was accessed through a closure-based API.
    WithValue,

    /// The canary value was accessed through a registry lookup or dispatch.
    Registry,

    /// The canary value was accessed during serialization.
    Serialize,

    /// A user-defined trigger source.
    ///
    /// Custom sources are serialized as `custom:<name>`.
    Custom(&'static str),
}

impl TriggerSource {
    /// Built-in trigger sources supported by this version of the crate.
    ///
    /// This list does not include [`TriggerSource::Custom`].
    ///
    /// ```
    /// use canarytrap::TriggerSource;
    ///
    /// assert!(!TriggerSource::BUILT_IN.is_empty());
    /// assert!(TriggerSource::BUILT_IN.iter().all(TriggerSource::is_builtin));
    /// ```
    pub const BUILT_IN: &'static [TriggerSource] = &[
        Self::Reveal,
        Self::WithValue,
        Self::Registry,
        Self::Serialize,
    ];

    /// Creates a user-defined trigger source.
    ///
    /// The name should be a stable identifier. It is serialized with a
    /// `custom:` prefix by the [`Display`](std::fmt::Display) implementation.
    ///
    /// ```
    /// use canarytrap::TriggerSource;
    ///
    /// let source = TriggerSource::custom("serde");
    /// assert_eq!(source.to_string(), "custom:serde");
    /// ```
    #[must_use]
    pub fn custom(name: &'static str) -> Self {
        Self::Custom(name.trim())
    }

    /// Parses a trigger source from a static string.
    ///
    /// Built-in sources are parsed case-insensitively and accept common
    /// aliases. Custom sources must use the `custom:` prefix.
    ///
    /// ```
    /// use canarytrap::TriggerSource;
    ///
    /// assert_eq!(
    ///     TriggerSource::from_static("with-value"),
    ///     Ok(TriggerSource::WithValue)
    /// );
    /// assert_eq!(
    ///     TriggerSource::from_static("CUSTOM:serde"),
    ///     Ok(TriggerSource::Custom("serde"))
    /// );
    /// assert!(TriggerSource::from_static("not-a-source").is_err());
    /// ```
    pub fn from_static(input: &'static str) -> Result<Self, ParseTriggerSourceError> {
        const CUSTOM_PREFIX: &str = "custom:";

        let input = input.trim();

        if input.is_empty() {
            return Err(ParseTriggerSourceError::new());
        }

        let has_custom_prefix = input
            .get(..CUSTOM_PREFIX.len())
            .is_some_and(|prefix| prefix.eq_ignore_ascii_case(CUSTOM_PREFIX));

        if has_custom_prefix {
            // SAFETY: `has_custom_prefix` is true only when `input.get(..7)`
            // returned `Some`, which means byte index 7 is a char boundary.
            let name = input[CUSTOM_PREFIX.len()..].trim();

            if name.is_empty() {
                return Err(ParseTriggerSourceError::new());
            }

            return Ok(Self::Custom(name));
        }

        if input.eq_ignore_ascii_case("reveal") || input.eq_ignore_ascii_case("revealed") {
            return Ok(Self::Reveal);
        }

        if input.eq_ignore_ascii_case("with-value")
            || input.eq_ignore_ascii_case("with_value")
            || input.eq_ignore_ascii_case("withvalue")
            || input.eq_ignore_ascii_case("value")
        {
            return Ok(Self::WithValue);
        }

        if input.eq_ignore_ascii_case("registry") {
            return Ok(Self::Registry);
        }

        if input.eq_ignore_ascii_case("serialize")
            || input.eq_ignore_ascii_case("serialization")
            || input.eq_ignore_ascii_case("serde")
        {
            return Ok(Self::Serialize);
        }

        Err(ParseTriggerSourceError::new())
    }

    /// Returns the canonical string representation for built-in sources.
    ///
    /// Returns `None` for [`TriggerSource::Custom`].
    ///
    /// ```
    /// use canarytrap::TriggerSource;
    ///
    /// assert_eq!(TriggerSource::Reveal.as_builtin_str(), Some("reveal"));
    /// assert_eq!(TriggerSource::custom("serde").as_builtin_str(), None);
    /// ```
    #[must_use]
    pub fn as_builtin_str(&self) -> Option<&'static str> {
        match self {
            Self::Reveal => Some("reveal"),
            Self::WithValue => Some("with-value"),
            Self::Registry => Some("registry"),
            Self::Serialize => Some("serialize"),
            Self::Custom(_) => None,
        }
    }

    /// Returns the custom source name if this is a custom trigger source.
    ///
    /// ```
    /// use canarytrap::TriggerSource;
    ///
    /// assert_eq!(TriggerSource::custom("serde").as_custom_str(), Some("serde"));
    /// assert_eq!(TriggerSource::Reveal.as_custom_str(), None);
    /// ```
    #[must_use]
    pub fn as_custom_str(&self) -> Option<&'static str> {
        match self {
            Self::Custom(name) => Some(name),
            _ => None,
        }
    }

    /// Returns `true` if this is a built-in trigger source.
    ///
    /// ```
    /// use canarytrap::TriggerSource;
    ///
    /// assert!(TriggerSource::Registry.is_builtin());
    /// assert!(!TriggerSource::custom("serde").is_builtin());
    /// ```
    #[must_use]
    pub fn is_builtin(&self) -> bool {
        self.as_builtin_str().is_some()
    }

    /// Returns `true` if this is a user-defined trigger source.
    ///
    /// ```
    /// use canarytrap::TriggerSource;
    ///
    /// assert!(TriggerSource::custom("serde").is_custom());
    /// assert!(!TriggerSource::Serialize.is_custom());
    /// ```
    #[must_use]
    pub fn is_custom(&self) -> bool {
        matches!(self, Self::Custom(_))
    }
}

impl fmt::Display for TriggerSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Reveal => f.write_str("reveal"),
            Self::WithValue => f.write_str("with-value"),
            Self::Registry => f.write_str("registry"),
            Self::Serialize => f.write_str("serialize"),
            Self::Custom(name) => write!(f, "custom:{name}"),
        }
    }
}

impl TryFrom<&'static str> for TriggerSource {
    type Error = ParseTriggerSourceError;

    fn try_from(value: &'static str) -> Result<Self, Self::Error> {
        Self::from_static(value)
    }
}

/// Error returned when a string cannot be parsed as a [`TriggerSource`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseTriggerSourceError {
    _private: (),
}

impl ParseTriggerSourceError {
    const fn new() -> Self {
        Self { _private: () }
    }
}

impl fmt::Display for ParseTriggerSourceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("invalid trigger source")
    }
}

impl core::error::Error for ParseTriggerSourceError {}

#[cfg(test)]
mod tests {
    use super::ParseTriggerSourceError;
    use super::TriggerSource;

    #[test]
    fn display_uses_canonical_builtin_values() {
        assert_eq!(TriggerSource::Reveal.to_string(), "reveal");
        assert_eq!(TriggerSource::WithValue.to_string(), "with-value");
        assert_eq!(TriggerSource::Registry.to_string(), "registry");
        assert_eq!(TriggerSource::Serialize.to_string(), "serialize");
    }

    #[test]
    fn display_uses_custom_prefix() {
        assert_eq!(TriggerSource::custom("serde").to_string(), "custom:serde");
        assert_eq!(
            TriggerSource::Custom("manual-check").to_string(),
            "custom:manual-check"
        );
    }

    #[test]
    fn custom_constructor_trims_name() {
        assert_eq!(
            TriggerSource::custom("  serde  "),
            TriggerSource::Custom("serde")
        );
    }

    #[test]
    fn as_builtin_str_returns_canonical_values_for_builtin_sources() {
        assert_eq!(TriggerSource::Reveal.as_builtin_str(), Some("reveal"));
        assert_eq!(
            TriggerSource::WithValue.as_builtin_str(),
            Some("with-value")
        );
        assert_eq!(TriggerSource::Registry.as_builtin_str(), Some("registry"));
        assert_eq!(TriggerSource::Serialize.as_builtin_str(), Some("serialize"));
    }

    #[test]
    fn as_builtin_str_returns_none_for_custom() {
        assert_eq!(TriggerSource::custom("serde").as_builtin_str(), None);
    }

    #[test]
    fn as_custom_str_returns_name_only_for_custom() {
        assert_eq!(
            TriggerSource::custom("serde").as_custom_str(),
            Some("serde")
        );
        assert_eq!(TriggerSource::Reveal.as_custom_str(), None);
    }

    #[test]
    fn is_builtin_and_is_custom_are_complementary() {
        for source in TriggerSource::BUILT_IN {
            assert!(source.is_builtin());
            assert!(!source.is_custom());
        }

        let custom = TriggerSource::custom("serde");
        assert!(custom.is_custom());
        assert!(!custom.is_builtin());
    }

    #[test]
    fn built_in_contains_only_builtin_sources() {
        assert_eq!(TriggerSource::BUILT_IN.len(), 4);
        assert!(
            TriggerSource::BUILT_IN
                .iter()
                .all(TriggerSource::is_builtin)
        );
    }

    #[test]
    fn from_static_accepts_canonical_builtin_values() {
        for source in TriggerSource::BUILT_IN {
            let canonical = source
                .as_builtin_str()
                .expect("built-in source must have canonical string");

            assert_eq!(TriggerSource::from_static(canonical), Ok(*source));
        }
    }

    #[test]
    fn from_static_accepts_common_aliases() {
        assert_eq!(
            TriggerSource::from_static("revealed"),
            Ok(TriggerSource::Reveal)
        );

        assert_eq!(
            TriggerSource::from_static("with_value"),
            Ok(TriggerSource::WithValue)
        );
        assert_eq!(
            TriggerSource::from_static("withvalue"),
            Ok(TriggerSource::WithValue)
        );
        assert_eq!(
            TriggerSource::from_static("value"),
            Ok(TriggerSource::WithValue)
        );

        assert_eq!(
            TriggerSource::from_static("serialization"),
            Ok(TriggerSource::Serialize)
        );
        assert_eq!(
            TriggerSource::from_static("serde"),
            Ok(TriggerSource::Serialize)
        );
    }

    #[test]
    fn from_static_trims_whitespace_and_ignores_ascii_case() {
        assert_eq!(
            TriggerSource::from_static("  REVEAL "),
            Ok(TriggerSource::Reveal)
        );
        assert_eq!(
            TriggerSource::from_static("With-Value"),
            Ok(TriggerSource::WithValue)
        );
        assert_eq!(
            TriggerSource::from_static("Registry"),
            Ok(TriggerSource::Registry)
        );
        assert_eq!(
            TriggerSource::from_static("SERIALIZE"),
            Ok(TriggerSource::Serialize)
        );
    }

    #[test]
    fn from_static_accepts_custom_sources_with_prefix() {
        assert_eq!(
            TriggerSource::from_static("custom:serde"),
            Ok(TriggerSource::Custom("serde"))
        );
        assert_eq!(
            TriggerSource::from_static("CUSTOM:serde"),
            Ok(TriggerSource::Custom("serde"))
        );
        assert_eq!(
            TriggerSource::from_static("  custom: manual-check  "),
            Ok(TriggerSource::Custom("manual-check"))
        );
    }

    #[test]
    fn try_from_static_str_matches_from_static() {
        assert_eq!(
            TriggerSource::try_from("serialize"),
            Ok(TriggerSource::Serialize)
        );
        assert_eq!(
            TriggerSource::try_from("custom:serde"),
            Ok(TriggerSource::Custom("serde"))
        );
    }

    #[test]
    fn from_static_rejects_empty_custom_name() {
        assert_eq!(
            TriggerSource::from_static("custom:"),
            Err(ParseTriggerSourceError::new())
        );
        assert_eq!(
            TriggerSource::from_static("custom:   "),
            Err(ParseTriggerSourceError::new())
        );
    }

    #[test]
    fn from_static_rejects_unknown_values_without_custom_prefix() {
        assert_eq!(
            TriggerSource::from_static(""),
            Err(ParseTriggerSourceError::new())
        );
        assert_eq!(
            TriggerSource::from_static("   "),
            Err(ParseTriggerSourceError::new())
        );
        assert_eq!(
            TriggerSource::from_static("drop"),
            Err(ParseTriggerSourceError::new())
        );
        assert_eq!(
            TriggerSource::from_static("reveal "),
            Ok(TriggerSource::Reveal)
        );
        assert_eq!(
            TriggerSource::from_static("reveal-with-suffix"),
            Err(ParseTriggerSourceError::new())
        );
    }

    #[test]
    fn error_display_is_stable() {
        assert_eq!(
            ParseTriggerSourceError::new().to_string(),
            "invalid trigger source"
        );
    }
}