cribra 0.3.0

Privacy-first Rust core for detecting, querying, and safely transforming secrets and sensitive data
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! Rule definitions accepted by [`ScannerBuilder`](crate::ScannerBuilder).
//!
//! Public rules are declarative configuration values. They describe what the
//! scanner should detect, but they do not execute matching themselves.
//!
//! During [`ScannerBuilder::build`](crate::ScannerBuilder::build), every rule is
//! validated and moved into the private compiled execution engine. This keeps
//! rule construction ergonomic while allowing the scanner internals to evolve
//! without exposing matcher implementation details.

use std::{fmt, sync::Arc};

use regex::Regex;

use crate::{
    remediation::Remediation, rule_metadata::RuleMetadata, severity::Severity,
    validators::dispatch::ValidatorKind,
};

/// Stable identifier assigned to a detection rule.
///
/// A rule identifier is copied cheaply because its string storage is shared.
/// It should be concise, deterministic and suitable for structured output.
///
/// Identifiers are validated when a scanner is built. Empty identifiers are
/// rejected by [`ScannerBuilder::build`](crate::ScannerBuilder::build).
///
/// # Examples
///
/// ```
/// use cribra::RuleId;
///
/// let id = RuleId::from("github-personal-access-token");
/// assert_eq!(id.as_str(), "github-personal-access-token");
/// ```
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RuleId(Arc<str>);

impl RuleId {
    /// Returns this identifier as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for RuleId {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl From<&str> for RuleId {
    fn from(value: &str) -> Self {
        Self(Arc::from(value))
    }
}

impl From<String> for RuleId {
    fn from(value: String) -> Self {
        Self(Arc::from(value))
    }
}

impl From<Box<str>> for RuleId {
    fn from(value: Box<str>) -> Self {
        Self(Arc::from(value))
    }
}

impl From<Arc<str>> for RuleId {
    fn from(value: Arc<str>) -> Self {
        Self(value)
    }
}

impl fmt::Display for RuleId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Declarative matching strategy used by a static [`RuleSpec`].
///
/// The concrete matcher representation used during scanning is private.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum RuleKind {
    /// Match the exact text wherever it occurs.
    Literal,

    /// Match a token beginning with the configured text.
    ///
    /// The compiled engine requires a token boundary before the prefix and
    /// extends the finding through the remaining token characters.
    Prefix,

    /// Match a token ending with the configured text.
    ///
    /// The compiled engine requires a token boundary after the suffix and
    /// extends the finding backwards through preceding token characters.
    Suffix,

    /// Match spans produced by a regular expression.
    Pattern,
}

/// Allocation-free definition of a built-in rule.
///
/// `RuleSpec` stores only `'static` data and can therefore be declared as a
/// `const`. It is intended for built-in rule catalogs. User-defined runtime
/// configuration should normally use [`Rule`] directly.
///
/// A specification is converted into an owned [`Rule`] when a scanner is
/// built. Regular-expression specifications can fail during this conversion
/// when their pattern is invalid.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct RuleSpec {
    id: &'static str,
    kind: RuleKind,
    value: &'static str,
    severity: Severity,
    validator: ValidatorKind,
    remediation: Option<Remediation>,
    capture: Option<&'static str>,
}

impl RuleSpec {
    /// Defines a static exact-literal rule.
    #[must_use]
    pub const fn literal(id: &'static str, literal: &'static str, severity: Severity) -> Self {
        Self {
            id,
            kind: RuleKind::Literal,
            value: literal,
            severity,
            validator: ValidatorKind::None,
            remediation: None,
            capture: None,
        }
    }

    /// Defines a static token-prefix rule.
    #[must_use]
    pub const fn prefix(id: &'static str, prefix: &'static str, severity: Severity) -> Self {
        Self {
            id,
            kind: RuleKind::Prefix,
            value: prefix,
            severity,
            validator: ValidatorKind::None,
            remediation: None,
            capture: None,
        }
    }

    /// Defines a static token-suffix rule.
    #[must_use]
    pub const fn suffix(id: &'static str, suffix: &'static str, severity: Severity) -> Self {
        Self {
            id,
            kind: RuleKind::Suffix,
            value: suffix,
            severity,
            validator: ValidatorKind::None,
            remediation: None,
            capture: None,
        }
    }

    /// Defines a static regular-expression rule.
    ///
    /// The expression is compiled only when this specification is converted
    /// into an owned [`Rule`].
    #[must_use]
    pub const fn pattern(id: &'static str, pattern: &'static str, severity: Severity) -> Self {
        Self {
            id,
            kind: RuleKind::Pattern,
            value: pattern,
            severity,
            validator: ValidatorKind::None,
            remediation: None,
            capture: None,
        }
    }

    /// Defines an internal regular-expression rule whose finding span is
    /// projected from the named capture group.
    ///
    /// The complete expression discovers the candidate and its surrounding
    /// context, while only `capture` is passed to validation and exposed as the
    /// finding location.
    pub(crate) const fn captured_pattern(
        id: &'static str,
        pattern: &'static str,
        capture: &'static str,
        severity: Severity,
    ) -> Self {
        Self {
            id,
            kind: RuleKind::Pattern,
            value: pattern,
            severity,
            validator: ValidatorKind::None,
            remediation: None,
            capture: Some(capture),
        }
    }

    /// Returns the stable identifier assigned to this specification.
    #[must_use]
    pub const fn id(self) -> &'static str {
        self.id
    }

    /// Returns the declarative matching strategy.
    #[must_use]
    pub const fn kind(self) -> RuleKind {
        self.kind
    }

    /// Returns the literal, prefix, suffix or regular-expression source.
    #[must_use]
    pub const fn value(self) -> &'static str {
        self.value
    }

    /// Returns the severity assigned to findings from this rule.
    #[must_use]
    pub const fn severity(self) -> Severity {
        self.severity
    }

    /// Returns the remediation assigned to findings from this specification.
    #[must_use]
    pub const fn remediation(self) -> Option<Remediation> {
        self.remediation
    }

    /// Associates remediation guidance with this specification.
    #[must_use]
    pub const fn with_remediation(mut self, remediation: Remediation) -> Self {
        self.remediation = Some(remediation);
        self
    }

    /// Associates an internal validator with this built-in specification.
    ///
    /// This remains crate-private because validator selection is part of the
    /// built-in detection contract, not the public custom-rule API.
    pub(crate) const fn with_validator(mut self, validator: ValidatorKind) -> Self {
        self.validator = validator;
        self
    }

    /// Converts this static specification into an owned rule.
    ///
    /// # Errors
    ///
    /// Returns [`RuleError::InvalidPattern`] when this is a pattern
    /// specification whose regular expression cannot be compiled.
    pub fn to_rule(self) -> Result<Rule, RuleError> {
        let rule = match (self.kind, self.capture) {
            (RuleKind::Literal, None) => Rule::literal(self.id, self.value, self.severity),
            (RuleKind::Prefix, None) => Rule::prefix(self.id, self.value, self.severity),
            (RuleKind::Suffix, None) => Rule::suffix(self.id, self.value, self.severity),
            (RuleKind::Pattern, None) => Rule::pattern(self.id, self.value, self.severity)?,
            (RuleKind::Pattern, Some(capture)) => {
                Rule::captured_pattern(self.id, self.value, capture, self.severity)?
            }
            (_, Some(_)) => unreachable!("only pattern specifications support captures"),
        };

        let rule = if let Some(remediation) = self.remediation {
            rule.with_remediation(remediation)
        } else {
            rule
        };

        Ok(rule.with_validator(self.validator))
    }
}

/// Private owned matcher retained by a [`Rule`] before scanner compilation.
#[derive(Debug, Clone)]
pub(crate) enum Matcher {
    Literal(Box<str>),
    Prefix(Box<str>),
    Suffix(Box<str>),
    Pattern {
        regex: Regex,
        capture: Option<usize>,
    },
}

/// Owned declarative detection rule.
///
/// A `Rule` contains configuration only. Calling a constructor does not scan
/// text, and no matcher is rebuilt during [`Scanner::scan`](crate::Scanner::scan).
///
/// Literal, prefix and suffix rules are infallible to construct. Empty values
/// are rejected later when the complete scanner configuration is validated.
/// Pattern rules compile their regular expression immediately and therefore
/// return a [`Result`].
#[derive(Debug, Clone)]
pub struct Rule {
    pub(crate) id: RuleId,
    pub(crate) severity: Severity,
    pub(crate) validator: ValidatorKind,
    pub(crate) matcher: Matcher,
    pub(crate) remediation: Option<Remediation>,
}

impl Rule {
    /// Creates a rule that reports every exact occurrence of `literal`.
    ///
    /// Literal matching does not impose token-boundary semantics.
    #[must_use]
    pub fn literal(
        id: impl Into<RuleId>,
        literal: impl Into<Box<str>>,
        severity: Severity,
    ) -> Self {
        Self {
            id: id.into(),
            severity,
            validator: ValidatorKind::None,
            matcher: Matcher::Literal(literal.into()),
            remediation: None,
        }
    }

    /// Creates a rule that reports complete tokens beginning with `prefix`.
    ///
    /// The prefix must begin at a token boundary. After a candidate is found,
    /// the compiled engine extends the match through ASCII alphanumeric
    /// characters, `_` and `-`.
    #[must_use]
    pub fn prefix(id: impl Into<RuleId>, prefix: impl Into<Box<str>>, severity: Severity) -> Self {
        Self {
            id: id.into(),
            severity,
            validator: ValidatorKind::None,
            matcher: Matcher::Prefix(prefix.into()),
            remediation: None,
        }
    }

    /// Creates a rule that reports complete tokens ending with `suffix`.
    ///
    /// The suffix must end at a token boundary. The compiled engine extends
    /// the match backwards through ASCII alphanumeric characters, `_` and `-`.
    #[must_use]
    pub fn suffix(id: impl Into<RuleId>, suffix: impl Into<Box<str>>, severity: Severity) -> Self {
        Self {
            id: id.into(),
            severity,
            validator: ValidatorKind::None,
            matcher: Matcher::Suffix(suffix.into()),
            remediation: None,
        }
    }

    /// Creates a regular-expression rule.
    ///
    /// The expression is compiled once during rule construction and moved into
    /// the scanner's compiled rule set. It is never recompiled by `scan`.
    ///
    /// Each non-overlapping, non-empty span returned by the regex engine
    /// becomes one finding.
    ///
    /// Custom patterns that can match the empty string are rejected. Empty
    /// findings have no useful secret-detection semantics and can otherwise
    /// produce large numbers of zero-length results from anchors, optional
    /// expressions or zero-width assertions.
    ///
    /// # Errors
    ///
    /// Returns [`RuleError::InvalidPattern`] when `pattern` is not a valid
    /// regular expression.
    ///
    /// Returns [`RuleError::PatternMatchesEmpty`] when the expression can
    /// produce a zero-length match.
    pub fn pattern(
        id: impl Into<RuleId>,
        pattern: impl AsRef<str>,
        severity: Severity,
    ) -> Result<Self, RuleError> {
        let pattern = pattern.as_ref();
        let regex = Regex::new(pattern).map_err(RuleError::InvalidPattern)?;
        let hir = regex_syntax::parse(pattern)
            .map_err(|error| RuleError::InvalidPattern(regex::Error::Syntax(error.to_string())))?;

        if hir.properties().minimum_len() == Some(0) {
            return Err(RuleError::PatternMatchesEmpty);
        }

        Ok(Self {
            id: id.into(),
            severity,
            validator: ValidatorKind::None,
            remediation: None,
            matcher: Matcher::Pattern {
                regex,
                capture: None,
            },
        })
    }

    /// Creates an internal pattern rule that projects findings from a named
    /// capture group.
    ///
    /// The capture name is resolved once during rule construction. The hot path
    /// stores only its numeric index.
    pub(crate) fn captured_pattern(
        id: impl Into<RuleId>,
        pattern: impl AsRef<str>,
        capture: impl AsRef<str>,
        severity: Severity,
    ) -> Result<Self, RuleError> {
        let regex = Regex::new(pattern.as_ref()).map_err(RuleError::InvalidPattern)?;
        let capture_name = capture.as_ref();
        let capture_index = regex
            .capture_names()
            .position(|name| name == Some(capture_name))
            .ok_or_else(|| RuleError::MissingCaptureGroup {
                name: capture_name.into(),
            })?;

        Ok(Self {
            id: id.into(),
            severity,
            validator: ValidatorKind::None,
            remediation: None,
            matcher: Matcher::Pattern {
                regex,
                capture: Some(capture_index),
            },
        })
    }

    /// Associates an internal validator with this rule.
    ///
    /// Public custom rules intentionally default to [`ValidatorKind::None`].
    /// Built-in rule catalogs use this method while assembling their private
    /// detection contracts.
    pub(crate) const fn with_validator(mut self, validator: ValidatorKind) -> Self {
        self.validator = validator;
        self
    }

    /// Returns this rule's stable identifier.
    #[must_use]
    pub fn id(&self) -> &RuleId {
        &self.id
    }

    /// Returns the severity assigned to findings produced by this rule.
    #[must_use]
    pub const fn severity(&self) -> Severity {
        self.severity
    }

    /// Returns the remediation assigned to findings produced by this rule.
    #[must_use]
    pub const fn remediation(&self) -> Option<Remediation> {
        self.remediation
    }

    /// Returns the matching family used by this rule.
    #[must_use]
    pub const fn kind(&self) -> RuleKind {
        match self.matcher {
            Matcher::Literal(_) => RuleKind::Literal,
            Matcher::Prefix(_) => RuleKind::Prefix,
            Matcher::Suffix(_) => RuleKind::Suffix,
            Matcher::Pattern { .. } => RuleKind::Pattern,
        }
    }

    /// Returns this rule with the specified remediation assigned.
    #[must_use]
    pub fn with_remediation(mut self, remediation: Remediation) -> Self {
        self.remediation = Some(remediation);
        self
    }

    /// Returns presentation-safe metadata for this rule.
    #[must_use]
    pub fn metadata(&self) -> RuleMetadata<'_> {
        RuleMetadata::new(
            self.id.as_str(),
            self.kind(),
            self.validator.detection_mode(),
            self.severity,
            self.remediation,
        )
    }
}

impl fmt::Display for Rule {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.id.fmt(formatter)
    }
}

/// Error produced while constructing an individual [`Rule`].
///
/// Errors that involve validating or compiling a complete collection of rules
/// are represented by [`ScannerBuildError`](crate::ScannerBuildError).
#[derive(Debug)]
pub enum RuleError {
    /// The supplied regular expression is invalid.
    InvalidPattern(regex::Error),

    /// A public custom pattern can produce a zero-length match.
    ///
    /// Zero-length findings are not useful secret detections and are rejected
    /// at rule construction rather than filtered later in the scan hot path.
    PatternMatchesEmpty,

    /// An internal capture-aware rule references a group absent from its
    /// regular expression.
    MissingCaptureGroup {
        /// Missing named capture.
        name: Box<str>,
    },
}

impl fmt::Display for RuleError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidPattern(error) => write!(formatter, "invalid rule pattern: {error}"),
            Self::PatternMatchesEmpty => {
                formatter.write_str("rule pattern can produce a zero-length match")
            }
            Self::MissingCaptureGroup { name } => {
                write!(formatter, "missing named capture group `{name}`")
            }
        }
    }
}

impl std::error::Error for RuleError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::InvalidPattern(error) => Some(error),
            Self::PatternMatchesEmpty | Self::MissingCaptureGroup { .. } => None,
        }
    }
}

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

    #[test]
    fn rule_id_supports_owned_and_borrowed_strings() {
        let borrowed = RuleId::from("borrowed");
        let owned = RuleId::from(String::from("owned"));

        assert_eq!(borrowed.as_str(), "borrowed");
        assert_eq!(owned.as_str(), "owned");
    }

    #[test]
    fn static_literal_spec_converts_to_owned_rule() {
        let rule = RuleSpec::literal("literal", "SECRET", Severity::High)
            .to_rule()
            .expect("literal specification should convert");

        assert_eq!(rule.id().as_str(), "literal");
        assert_eq!(rule.severity(), Severity::High);
    }

    #[test]
    fn static_spec_preserves_internal_validator() {
        let rule = RuleSpec::prefix("github", "ghp_", Severity::Critical)
            .with_validator(ValidatorKind::GitHub)
            .to_rule()
            .expect("prefix specification should convert");

        assert_eq!(rule.validator, ValidatorKind::GitHub);
    }

    #[test]
    fn metadata_exposes_validator_detection_mode() {
        let deterministic = RuleSpec::prefix("github", "ghp_", Severity::Critical)
            .with_validator(ValidatorKind::GitHub)
            .to_rule()
            .expect("prefix specification should convert");
        let contextual =
            RuleSpec::pattern("password", r#"(?i)password\s*=\s*[^\s]+"#, Severity::High)
                .with_validator(ValidatorKind::Password)
                .to_rule()
                .expect("pattern specification should convert");

        assert_eq!(
            deterministic.metadata().detection_mode(),
            crate::DetectionMode::Deterministic
        );
        assert_eq!(
            contextual.metadata().detection_mode(),
            crate::DetectionMode::Contextual
        );
    }

    #[test]
    fn captured_pattern_resolves_named_group_once() {
        let rule = RuleSpec::captured_pattern(
            "assignment",
            r#"KEY=(?P<value>[A-Za-z0-9_]+)"#,
            "value",
            Severity::High,
        )
        .to_rule()
        .expect("named capture should resolve");

        assert!(matches!(
            rule.matcher,
            Matcher::Pattern {
                capture: Some(1),
                ..
            }
        ));
    }

    #[test]
    fn captured_pattern_rejects_missing_named_group() {
        let error = RuleSpec::captured_pattern(
            "assignment",
            r#"KEY=([A-Za-z0-9_]+)"#,
            "value",
            Severity::High,
        )
        .to_rule()
        .expect_err("missing capture should fail");

        assert!(matches!(error, RuleError::MissingCaptureGroup { .. }));
    }

    #[test]
    fn invalid_pattern_is_rejected_during_rule_construction() {
        let error =
            Rule::pattern("invalid", "(", Severity::High).expect_err("invalid regex should fail");

        assert!(matches!(error, RuleError::InvalidPattern(_)));
    }
    #[test]
    fn public_pattern_rejects_zero_length_language() {
        for pattern in [r"", r".*", r"a?", r"(?:secret)?", r"\b", r"secret|"] {
            let error = Rule::pattern("empty-capable", pattern, Severity::High)
                .expect_err("zero-length-capable pattern should fail");

            assert!(matches!(error, RuleError::PatternMatchesEmpty), "{pattern}");
        }
    }

    #[test]
    fn public_pattern_accepts_non_empty_unicode_and_anchored_patterns() {
        for pattern in [
            r"\p{L}+",
            r"\A[A-Z2-9]{4}(?:-[A-Z2-9]{4}){3}\z",
            r"\bsecret\b",
            r"(?:foo|bar)+",
        ] {
            let rule = Rule::pattern("non-empty", pattern, Severity::High)
                .expect("non-empty pattern should compile");

            assert_eq!(rule.kind(), RuleKind::Pattern);
            assert_eq!(
                rule.metadata().detection_mode(),
                crate::DetectionMode::MatcherOnly
            );
        }
    }
}