Skip to main content

silens_scan/
rule.rs

1//! Rule definitions accepted by [`ScannerBuilder`](crate::ScannerBuilder).
2//!
3//! Public rules are declarative configuration values. They describe what the
4//! scanner should detect, but they do not execute matching themselves.
5//!
6//! During [`ScannerBuilder::build`](crate::ScannerBuilder::build), every rule is
7//! validated and moved into the private compiled execution engine. This keeps
8//! rule construction ergonomic while allowing the scanner internals to evolve
9//! without exposing matcher implementation details.
10
11use std::{error::Error, fmt, sync::Arc};
12
13use regex::Regex;
14
15use crate::{remediation::Remediation, severity::Severity, validators::dispatch::ValidatorKind};
16
17/// Stable identifier assigned to a detection rule.
18///
19/// A rule identifier is copied cheaply because its string storage is shared.
20/// It should be concise, deterministic and suitable for structured output.
21///
22/// Identifiers are validated when a scanner is built. Empty identifiers are
23/// rejected by [`ScannerBuilder::build`](crate::ScannerBuilder::build).
24///
25/// # Examples
26///
27/// ```
28/// use silens_scan::RuleId;
29///
30/// let id = RuleId::from("github-personal-access-token");
31/// assert_eq!(id.as_str(), "github-personal-access-token");
32/// ```
33#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
34#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
35pub struct RuleId(Arc<str>);
36
37impl RuleId {
38    /// Returns this identifier as a string slice.
39    #[must_use]
40    pub fn as_str(&self) -> &str {
41        &self.0
42    }
43}
44
45impl AsRef<str> for RuleId {
46    fn as_ref(&self) -> &str {
47        self.as_str()
48    }
49}
50
51impl From<&str> for RuleId {
52    fn from(value: &str) -> Self {
53        Self(Arc::from(value))
54    }
55}
56
57impl From<String> for RuleId {
58    fn from(value: String) -> Self {
59        Self(Arc::from(value))
60    }
61}
62
63impl From<Box<str>> for RuleId {
64    fn from(value: Box<str>) -> Self {
65        Self(Arc::from(value))
66    }
67}
68
69impl From<Arc<str>> for RuleId {
70    fn from(value: Arc<str>) -> Self {
71        Self(value)
72    }
73}
74
75impl fmt::Display for RuleId {
76    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
77        formatter.write_str(self.as_str())
78    }
79}
80
81/// Declarative matching strategy used by a static [`RuleSpec`].
82///
83/// The concrete matcher representation used during scanning is private.
84#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
85#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
86#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
87pub enum RuleKind {
88    /// Match the exact text wherever it occurs.
89    Literal,
90
91    /// Match a token beginning with the configured text.
92    ///
93    /// The compiled engine requires a token boundary before the prefix and
94    /// extends the finding through the remaining token characters.
95    Prefix,
96
97    /// Match a token ending with the configured text.
98    ///
99    /// The compiled engine requires a token boundary after the suffix and
100    /// extends the finding backwards through preceding token characters.
101    Suffix,
102
103    /// Match spans produced by a regular expression.
104    Pattern,
105}
106
107/// Allocation-free definition of a built-in rule.
108///
109/// `RuleSpec` stores only `'static` data and can therefore be declared as a
110/// `const`. It is intended for built-in rule catalogs. User-defined runtime
111/// configuration should normally use [`Rule`] directly.
112///
113/// A specification is converted into an owned [`Rule`] when a scanner is
114/// built. Regular-expression specifications can fail during this conversion
115/// when their pattern is invalid.
116#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
117pub struct RuleSpec {
118    id: &'static str,
119    kind: RuleKind,
120    value: &'static str,
121    severity: Severity,
122    validator: ValidatorKind,
123    remediation: Option<Remediation>,
124    capture: Option<&'static str>,
125}
126
127impl RuleSpec {
128    /// Defines a static exact-literal rule.
129    #[must_use]
130    pub const fn literal(id: &'static str, literal: &'static str, severity: Severity) -> Self {
131        Self {
132            id,
133            kind: RuleKind::Literal,
134            value: literal,
135            severity,
136            validator: ValidatorKind::None,
137            remediation: None,
138            capture: None,
139        }
140    }
141
142    /// Defines a static token-prefix rule.
143    #[must_use]
144    pub const fn prefix(id: &'static str, prefix: &'static str, severity: Severity) -> Self {
145        Self {
146            id,
147            kind: RuleKind::Prefix,
148            value: prefix,
149            severity,
150            validator: ValidatorKind::None,
151            remediation: None,
152            capture: None,
153        }
154    }
155
156    /// Defines a static token-suffix rule.
157    #[must_use]
158    pub const fn suffix(id: &'static str, suffix: &'static str, severity: Severity) -> Self {
159        Self {
160            id,
161            kind: RuleKind::Suffix,
162            value: suffix,
163            severity,
164            validator: ValidatorKind::None,
165            remediation: None,
166            capture: None,
167        }
168    }
169
170    /// Defines a static regular-expression rule.
171    ///
172    /// The expression is compiled only when this specification is converted
173    /// into an owned [`Rule`].
174    #[must_use]
175    pub const fn pattern(id: &'static str, pattern: &'static str, severity: Severity) -> Self {
176        Self {
177            id,
178            kind: RuleKind::Pattern,
179            value: pattern,
180            severity,
181            validator: ValidatorKind::None,
182            remediation: None,
183            capture: None,
184        }
185    }
186
187    /// Defines an internal regular-expression rule whose finding span is
188    /// projected from the named capture group.
189    ///
190    /// The complete expression discovers the candidate and its surrounding
191    /// context, while only `capture` is passed to validation and exposed as the
192    /// finding location.
193    pub(crate) const fn captured_pattern(
194        id: &'static str,
195        pattern: &'static str,
196        capture: &'static str,
197        severity: Severity,
198    ) -> Self {
199        Self {
200            id,
201            kind: RuleKind::Pattern,
202            value: pattern,
203            severity,
204            validator: ValidatorKind::None,
205            remediation: None,
206            capture: Some(capture),
207        }
208    }
209
210    /// Returns the stable identifier assigned to this specification.
211    #[must_use]
212    pub const fn id(self) -> &'static str {
213        self.id
214    }
215
216    /// Returns the declarative matching strategy.
217    #[must_use]
218    pub const fn kind(self) -> RuleKind {
219        self.kind
220    }
221
222    /// Returns the literal, prefix, suffix or regular-expression source.
223    #[must_use]
224    pub const fn value(self) -> &'static str {
225        self.value
226    }
227
228    /// Returns the severity assigned to findings from this rule.
229    #[must_use]
230    pub const fn severity(self) -> Severity {
231        self.severity
232    }
233
234    /// Returns the remediation assigned to findings from this specification.
235    #[must_use]
236    pub const fn remediation(self) -> Option<Remediation> {
237        self.remediation
238    }
239
240    /// Associates remediation guidance with this specification.
241    #[must_use]
242    pub const fn with_remediation(mut self, remediation: Remediation) -> Self {
243        self.remediation = Some(remediation);
244        self
245    }
246
247    /// Associates an internal validator with this built-in specification.
248    ///
249    /// This remains crate-private because validator selection is part of the
250    /// built-in detection contract, not the public custom-rule API.
251    pub(crate) const fn with_validator(mut self, validator: ValidatorKind) -> Self {
252        self.validator = validator;
253        self
254    }
255
256    /// Converts this static specification into an owned rule.
257    ///
258    /// # Errors
259    ///
260    /// Returns [`RuleError::InvalidPattern`] when this is a pattern
261    /// specification whose regular expression cannot be compiled.
262    pub fn to_rule(self) -> Result<Rule, RuleError> {
263        let rule = match (self.kind, self.capture) {
264            (RuleKind::Literal, None) => Rule::literal(self.id, self.value, self.severity),
265            (RuleKind::Prefix, None) => Rule::prefix(self.id, self.value, self.severity),
266            (RuleKind::Suffix, None) => Rule::suffix(self.id, self.value, self.severity),
267            (RuleKind::Pattern, None) => Rule::pattern(self.id, self.value, self.severity)?,
268            (RuleKind::Pattern, Some(capture)) => {
269                Rule::captured_pattern(self.id, self.value, capture, self.severity)?
270            }
271            (_, Some(_)) => unreachable!("only pattern specifications support captures"),
272        };
273
274        let rule = if let Some(remediation) = self.remediation {
275            rule.with_remediation(remediation)
276        } else {
277            rule
278        };
279
280        Ok(rule.with_validator(self.validator))
281    }
282}
283
284/// Private owned matcher retained by a [`Rule`] before scanner compilation.
285#[derive(Debug, Clone)]
286pub(crate) enum Matcher {
287    Literal(Box<str>),
288    Prefix(Box<str>),
289    Suffix(Box<str>),
290    Pattern {
291        regex: Regex,
292        capture: Option<usize>,
293    },
294}
295
296/// Owned declarative detection rule.
297///
298/// A `Rule` contains configuration only. Calling a constructor does not scan
299/// text, and no matcher is rebuilt during [`Scanner::scan`](crate::Scanner::scan).
300///
301/// Literal, prefix and suffix rules are infallible to construct. Empty values
302/// are rejected later when the complete scanner configuration is validated.
303/// Pattern rules compile their regular expression immediately and therefore
304/// return a [`Result`].
305#[derive(Debug, Clone)]
306pub struct Rule {
307    pub(crate) id: RuleId,
308    pub(crate) severity: Severity,
309    pub(crate) validator: ValidatorKind,
310    pub(crate) matcher: Matcher,
311    pub(crate) remediation: Option<Remediation>,
312}
313
314impl Rule {
315    /// Creates a rule that reports every exact occurrence of `literal`.
316    ///
317    /// Literal matching does not impose token-boundary semantics.
318    #[must_use]
319    pub fn literal(
320        id: impl Into<RuleId>,
321        literal: impl Into<Box<str>>,
322        severity: Severity,
323    ) -> Self {
324        Self {
325            id: id.into(),
326            severity,
327            validator: ValidatorKind::None,
328            matcher: Matcher::Literal(literal.into()),
329            remediation: None,
330        }
331    }
332
333    /// Creates a rule that reports complete tokens beginning with `prefix`.
334    ///
335    /// The prefix must begin at a token boundary. After a candidate is found,
336    /// the compiled engine extends the match through ASCII alphanumeric
337    /// characters, `_` and `-`.
338    #[must_use]
339    pub fn prefix(id: impl Into<RuleId>, prefix: impl Into<Box<str>>, severity: Severity) -> Self {
340        Self {
341            id: id.into(),
342            severity,
343            validator: ValidatorKind::None,
344            matcher: Matcher::Prefix(prefix.into()),
345            remediation: None,
346        }
347    }
348
349    /// Creates a rule that reports complete tokens ending with `suffix`.
350    ///
351    /// The suffix must end at a token boundary. The compiled engine extends
352    /// the match backwards through ASCII alphanumeric characters, `_` and `-`.
353    #[must_use]
354    pub fn suffix(id: impl Into<RuleId>, suffix: impl Into<Box<str>>, severity: Severity) -> Self {
355        Self {
356            id: id.into(),
357            severity,
358            validator: ValidatorKind::None,
359            matcher: Matcher::Suffix(suffix.into()),
360            remediation: None,
361        }
362    }
363
364    /// Creates a regular-expression rule.
365    ///
366    /// The expression is compiled once during rule construction and moved into
367    /// the scanner's compiled rule set. It is never recompiled by `scan`.
368    ///
369    /// Each non-overlapping span returned by the regex engine becomes one
370    /// finding.
371    ///
372    /// # Errors
373    ///
374    /// Returns [`RuleError::InvalidPattern`] when `pattern` is not a valid
375    /// regular expression.
376    pub fn pattern(
377        id: impl Into<RuleId>,
378        pattern: impl AsRef<str>,
379        severity: Severity,
380    ) -> Result<Self, RuleError> {
381        let pattern = Regex::new(pattern.as_ref()).map_err(RuleError::InvalidPattern)?;
382
383        Ok(Self {
384            id: id.into(),
385            severity,
386            validator: ValidatorKind::None,
387            remediation: None,
388            matcher: Matcher::Pattern {
389                regex: pattern,
390                capture: None,
391            },
392        })
393    }
394
395    /// Creates an internal pattern rule that projects findings from a named
396    /// capture group.
397    ///
398    /// The capture name is resolved once during rule construction. The hot path
399    /// stores only its numeric index.
400    pub(crate) fn captured_pattern(
401        id: impl Into<RuleId>,
402        pattern: impl AsRef<str>,
403        capture: impl AsRef<str>,
404        severity: Severity,
405    ) -> Result<Self, RuleError> {
406        let regex = Regex::new(pattern.as_ref()).map_err(RuleError::InvalidPattern)?;
407        let capture_name = capture.as_ref();
408        let capture_index = regex
409            .capture_names()
410            .position(|name| name == Some(capture_name))
411            .ok_or_else(|| RuleError::MissingCaptureGroup {
412                name: capture_name.into(),
413            })?;
414
415        Ok(Self {
416            id: id.into(),
417            severity,
418            validator: ValidatorKind::None,
419            remediation: None,
420            matcher: Matcher::Pattern {
421                regex,
422                capture: Some(capture_index),
423            },
424        })
425    }
426
427    /// Associates an internal validator with this rule.
428    ///
429    /// Public custom rules intentionally default to [`ValidatorKind::None`].
430    /// Built-in rule catalogs use this method while assembling their private
431    /// detection contracts.
432    pub(crate) const fn with_validator(mut self, validator: ValidatorKind) -> Self {
433        self.validator = validator;
434        self
435    }
436
437    /// Returns this rule's stable identifier.
438    #[must_use]
439    pub fn id(&self) -> &RuleId {
440        &self.id
441    }
442
443    /// Returns the severity assigned to findings produced by this rule.
444    #[must_use]
445    pub const fn severity(&self) -> Severity {
446        self.severity
447    }
448
449    /// Returns the remediation assigned to findings produced by this rule.
450    #[must_use]
451    pub const fn remediation(&self) -> Option<Remediation> {
452        self.remediation
453    }
454
455    /// Returns this rule with the specified remediation assigned.
456    #[must_use]
457    pub fn with_remediation(mut self, remediation: Remediation) -> Self {
458        self.remediation = Some(remediation);
459        self
460    }
461}
462
463impl fmt::Display for Rule {
464    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
465        self.id.fmt(formatter)
466    }
467}
468
469/// Error produced while constructing an individual [`Rule`].
470///
471/// Errors that involve validating or compiling a complete collection of rules
472/// are represented by [`ScannerBuildError`](crate::ScannerBuildError).
473#[derive(Debug)]
474pub enum RuleError {
475    /// The supplied regular expression is invalid.
476    InvalidPattern(regex::Error),
477
478    /// An internal capture-aware rule references a group absent from its
479    /// regular expression.
480    MissingCaptureGroup {
481        /// Missing named capture.
482        name: Box<str>,
483    },
484}
485
486impl fmt::Display for RuleError {
487    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
488        match self {
489            Self::InvalidPattern(error) => write!(formatter, "invalid rule pattern: {error}"),
490            Self::MissingCaptureGroup { name } => {
491                write!(formatter, "missing named capture group `{name}`")
492            }
493        }
494    }
495}
496
497impl Error for RuleError {
498    fn source(&self) -> Option<&(dyn Error + 'static)> {
499        match self {
500            Self::InvalidPattern(error) => Some(error),
501            Self::MissingCaptureGroup { .. } => None,
502        }
503    }
504}
505
506#[cfg(test)]
507mod tests {
508    use super::*;
509
510    #[test]
511    fn rule_id_supports_owned_and_borrowed_strings() {
512        let borrowed = RuleId::from("borrowed");
513        let owned = RuleId::from(String::from("owned"));
514
515        assert_eq!(borrowed.as_str(), "borrowed");
516        assert_eq!(owned.as_str(), "owned");
517    }
518
519    #[test]
520    fn static_literal_spec_converts_to_owned_rule() {
521        let rule = RuleSpec::literal("literal", "SECRET", Severity::High)
522            .to_rule()
523            .expect("literal specification should convert");
524
525        assert_eq!(rule.id().as_str(), "literal");
526        assert_eq!(rule.severity(), Severity::High);
527    }
528
529    #[test]
530    fn static_spec_preserves_internal_validator() {
531        let rule = RuleSpec::prefix("github", "ghp_", Severity::Critical)
532            .with_validator(ValidatorKind::GitHub)
533            .to_rule()
534            .expect("prefix specification should convert");
535
536        assert_eq!(rule.validator, ValidatorKind::GitHub);
537    }
538
539    #[test]
540    fn captured_pattern_resolves_named_group_once() {
541        let rule = RuleSpec::captured_pattern(
542            "assignment",
543            r#"KEY=(?P<value>[A-Za-z0-9_]+)"#,
544            "value",
545            Severity::High,
546        )
547        .to_rule()
548        .expect("named capture should resolve");
549
550        assert!(matches!(
551            rule.matcher,
552            Matcher::Pattern {
553                capture: Some(1),
554                ..
555            }
556        ));
557    }
558
559    #[test]
560    fn captured_pattern_rejects_missing_named_group() {
561        let error = RuleSpec::captured_pattern(
562            "assignment",
563            r#"KEY=([A-Za-z0-9_]+)"#,
564            "value",
565            Severity::High,
566        )
567        .to_rule()
568        .expect_err("missing capture should fail");
569
570        assert!(matches!(error, RuleError::MissingCaptureGroup { .. }));
571    }
572
573    #[test]
574    fn invalid_pattern_is_rejected_during_rule_construction() {
575        let error =
576            Rule::pattern("invalid", "(", Severity::High).expect_err("invalid regex should fail");
577
578        assert!(matches!(error, RuleError::InvalidPattern(_)));
579    }
580}