Skip to main content

redact_secret/
selection.rs

1//! Detector-id selection (issue #1251,
2//! `decision-define-detector-id-selection-and-configuration-replacement-precedence`).
3//!
4//! A [`DetectionSelection`] chooses which of an artifact's **included**
5//! built-in detectors are **enabled**. It acts when a registry is composed
6//! ([`DetectorRegistry::with_detection`](crate::DetectorRegistry::with_detection)),
7//! before the shared prefilter, candidate collection and overlap resolution,
8//! so a disabled detector is not constructed, not prefiltered, no overlap
9//! competitor and no retention input.
10//!
11//! This module is the selection grammar and its judgment only. It reads no
12//! manifest and builds no registry, so the registry can depend on it without
13//! the configuration resolver; the resolver (`crate::config`) judges the same
14//! selection against an artifact manifest through the same functions.
15
16use crate::detectors::built_in_ids;
17use crate::error::SecretScanErrorCode;
18use crate::json::{self, Value};
19use crate::types::is_identifier;
20
21/// The most ids one `include` or `exclude` array may hold.
22const DETECTOR_IDS_MAX: usize = 256;
23/// The built-in id of the PII adapter, which a selection cannot name.
24pub(crate) const PII_ADAPTER_ID: &str = "pii-domain";
25
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
27pub(crate) enum Mode {
28    #[default]
29    All,
30    Include,
31    Exclude,
32}
33
34/// Which of an artifact's included built-in detectors are enabled
35/// (`detection` of `runtime-config/v1`).
36///
37/// - [`all`](Self::all): every included detector (the build default).
38/// - [`include`](Self::include): exactly these, an allowlist. A detector
39///   added in a later release is not enabled.
40/// - [`exclude`](Self::exclude): every included detector except these, a
41///   denylist. A detector added later is enabled.
42///
43/// Ids are `Finding.detector` values such as `github-token`, not types. They
44/// are not case-folded or trimmed, and request order never matters: the
45/// enabled set is the artifact's canonical order filtered to the enabled ids.
46/// Nothing is validated until the selection is applied
47/// ([`DetectorRegistry::with_detection`](crate::DetectorRegistry::with_detection))
48/// or resolved ([`resolve_config`](crate::resolve_config)), when an unknown, not-included or repeated
49/// id is rejected rather than ignored.
50#[derive(Clone, Debug, Default, PartialEq, Eq)]
51pub struct DetectionSelection {
52    pub(crate) mode: Mode,
53    ids: Vec<String>,
54}
55
56impl DetectionSelection {
57    /// Every included detector is enabled.
58    #[must_use]
59    pub const fn all() -> Self {
60        Self {
61            mode: Mode::All,
62            ids: Vec::new(),
63        }
64    }
65
66    /// Exactly `ids` are enabled. An empty list enables no built-in detector.
67    #[must_use]
68    pub fn include<I, S>(ids: I) -> Self
69    where
70        I: IntoIterator<Item = S>,
71        S: Into<String>,
72    {
73        Self {
74            mode: Mode::Include,
75            ids: ids.into_iter().map(Into::into).collect(),
76        }
77    }
78
79    /// Every included detector except `ids` is enabled. An empty list is the
80    /// same selection as [`all`](Self::all).
81    #[must_use]
82    pub fn exclude<I, S>(ids: I) -> Self
83    where
84        I: IntoIterator<Item = S>,
85        S: Into<String>,
86    {
87        Self {
88            mode: Mode::Exclude,
89            ids: ids.into_iter().map(Into::into).collect(),
90        }
91    }
92
93    /// Parses the `detection` object of `runtime-config/v1`: `{}`,
94    /// `{"include":[ids]}` or `{"exclude":[ids]}`.
95    ///
96    /// Only the grammar is judged here (member names and types, at most 256
97    /// ids, each an identifier); the ids are judged against an artifact when
98    /// the selection is applied.
99    ///
100    /// # Errors
101    ///
102    /// A [`DetectionConfigError`] naming the first violation. It carries no
103    /// input text.
104    pub fn from_json(json: &str) -> Result<Self, DetectionConfigError> {
105        let value = json::parse(json).ok_or(DetectionConfigError::class(CLASS_WRONG_TYPE, None))?;
106        selection_from_value(&value).map_err(Fault::error)
107    }
108
109    /// Whether this enables every included detector: the build default, and
110    /// also `exclude` with no ids, which is the same selection.
111    #[must_use]
112    pub fn is_all(&self) -> bool {
113        self.mode == Mode::All || (self.mode == Mode::Exclude && self.ids.is_empty())
114    }
115
116    /// `all-included`, `include` or `exclude`.
117    #[must_use]
118    pub const fn mode(&self) -> &'static str {
119        match self.mode {
120            Mode::All => "all-included",
121            Mode::Include => "include",
122            Mode::Exclude => "exclude",
123        }
124    }
125
126    /// The ids as given, in request order. Empty for [`all`](Self::all).
127    pub fn ids(&self) -> impl Iterator<Item = &str> {
128        self.ids.iter().map(String::as_str)
129    }
130}
131
132pub(crate) const CLASS_UNKNOWN_FIELD: &str = "UNKNOWN_FIELD";
133pub(crate) const CLASS_WRONG_TYPE: &str = "WRONG_TYPE";
134pub(crate) const CLASS_TOO_MANY: &str = "TOO_MANY_DETECTOR_IDS";
135pub(crate) const CLASS_IDENTIFIER: &str = "INVALID_IDENTIFIER";
136pub(crate) const CLASS_UNSUPPORTED: &str = "DETECTION_SELECTION_UNSUPPORTED";
137pub(crate) const CLASS_DUPLICATE: &str = "DUPLICATE_DETECTOR_ID";
138pub(crate) const CLASS_NOT_SELECTABLE: &str = "DETECTOR_NOT_SELECTABLE";
139pub(crate) const CLASS_NOT_INCLUDED: &str = "DETECTOR_NOT_INCLUDED";
140pub(crate) const CLASS_UNKNOWN_ID: &str = "UNKNOWN_DETECTOR_ID";
141pub(crate) const CLASS_CONFLICT: &str = "DETECTION_SELECTOR_CONFLICT";
142pub(crate) const CLASS_EMPTY: &str = "EMPTY_DETECTION_SET";
143
144/// Why a detector selection was rejected: a fixed class and, for a problem in
145/// one id, that id's zero-based position in its array.
146///
147/// The class is one of the `config-diagnostics/v1` error codes
148/// (`UNKNOWN_FIELD`, `WRONG_TYPE`, `TOO_MANY_DETECTOR_IDS`,
149/// `INVALID_IDENTIFIER`, `DUPLICATE_DETECTOR_ID`, `DETECTOR_NOT_SELECTABLE`,
150/// `DETECTOR_NOT_INCLUDED`, `UNKNOWN_DETECTOR_ID`, `DETECTION_SELECTOR_CONFLICT`
151/// or `EMPTY_DETECTION_SET`). Nothing of the rejected input is carried, so a
152/// pasted secret in place of an id is never echoed.
153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
154pub struct DetectionConfigError {
155    code: SecretScanErrorCode,
156    class: &'static str,
157    index: Option<usize>,
158}
159
160impl DetectionConfigError {
161    const fn class(class: &'static str, index: Option<usize>) -> Self {
162        let code = if matches!(class.as_bytes(), b"EMPTY_DETECTION_SET") {
163            SecretScanErrorCode::EmptyDetectionSet
164        } else {
165            SecretScanErrorCode::InvalidDetectionConfig
166        };
167        Self { code, class, index }
168    }
169
170    /// `INVALID_DETECTION_CONFIG`, or `EMPTY_DETECTION_SET` when the selection
171    /// leaves nothing to detect.
172    #[must_use]
173    pub const fn code(self) -> SecretScanErrorCode {
174        self.code
175    }
176
177    /// The fixed diagnostic class, for example `DETECTOR_NOT_INCLUDED`.
178    #[must_use]
179    pub const fn class_name(self) -> &'static str {
180        self.class
181    }
182
183    /// The zero-based position of the offending id in its array, if one id is
184    /// to blame.
185    #[must_use]
186    pub const fn index(self) -> Option<usize> {
187        self.index
188    }
189}
190
191impl std::fmt::Display for DetectionConfigError {
192    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193        formatter.write_str(self.code.message())
194    }
195}
196
197impl std::error::Error for DetectionConfigError {}
198
199impl From<DetectionConfigError> for crate::SecretScanError {
200    fn from(error: DetectionConfigError) -> Self {
201        error.code.into()
202    }
203}
204
205/// A selection problem before it becomes a public error or a diagnostic: the
206/// class plus the array it concerns and the position inside it.
207#[derive(Clone, Copy)]
208pub(crate) struct Fault {
209    pub(crate) class: &'static str,
210    array: Option<&'static str>,
211    index: Option<usize>,
212}
213
214impl Fault {
215    const fn new(class: &'static str) -> Self {
216        Self {
217            class,
218            array: None,
219            index: None,
220        }
221    }
222
223    const fn at(class: &'static str, array: &'static str, index: usize) -> Self {
224        Self {
225            class,
226            array: Some(array),
227            index: Some(index),
228        }
229    }
230
231    const fn error(self) -> DetectionConfigError {
232        DetectionConfigError::class(self.class, self.index)
233    }
234
235    pub(crate) fn path(self) -> String {
236        match (self.array, self.index) {
237            // An unknown member is addressed by position, never by name.
238            (None, Some(index)) if self.class == CLASS_UNKNOWN_FIELD => {
239                format!("detection.@{index}")
240            }
241            (Some(array), Some(index)) => format!("detection.{array}[{index}]"),
242            (Some(array), None) => format!("detection.{array}"),
243            _ => "detection".to_owned(),
244        }
245    }
246}
247
248/// Parses a `detection` value: members, types, id count, identifier grammar,
249/// in that order, first violation first.
250pub(crate) fn selection_from_value(value: &Value) -> Result<DetectionSelection, Fault> {
251    let Value::Object(members) = value else {
252        return Err(Fault::new(CLASS_WRONG_TYPE));
253    };
254    let mut include: Option<&Value> = None;
255    let mut exclude: Option<&Value> = None;
256    for (position, (name, member)) in members.iter().enumerate() {
257        match name.as_str() {
258            "include" => include = Some(member),
259            "exclude" => exclude = Some(member),
260            _ => {
261                return Err(Fault {
262                    class: CLASS_UNKNOWN_FIELD,
263                    array: None,
264                    index: Some(position),
265                });
266            }
267        }
268    }
269    let list = |member: &Value, array: &'static str| -> Result<Vec<String>, Fault> {
270        let Value::Array(items) = member else {
271            return Err(Fault {
272                class: CLASS_WRONG_TYPE,
273                array: Some(array),
274                index: None,
275            });
276        };
277        let mut ids = Vec::with_capacity(items.len().min(DETECTOR_IDS_MAX));
278        for (index, item) in items.iter().enumerate() {
279            let Value::Str(id) = item else {
280                return Err(Fault::at(CLASS_WRONG_TYPE, array, index));
281            };
282            ids.push(id.clone());
283        }
284        if ids.len() > DETECTOR_IDS_MAX {
285            return Err(Fault {
286                class: CLASS_TOO_MANY,
287                array: Some(array),
288                index: None,
289            });
290        }
291        if let Some(index) = ids.iter().position(|id| !is_identifier(id)) {
292            return Err(Fault::at(CLASS_IDENTIFIER, array, index));
293        }
294        Ok(ids)
295    };
296    match (include, exclude) {
297        (Some(_), Some(_)) => Err(Fault::new(CLASS_CONFLICT)),
298        (Some(member), None) => Ok(DetectionSelection::include(list(member, "include")?)),
299        (None, Some(member)) => Ok(DetectionSelection::exclude(list(member, "exclude")?)),
300        (None, None) => Ok(DetectionSelection::all()),
301    }
302}
303
304/// One entry of a registry as selection planning sees it.
305pub(crate) struct PlanEntry<'a> {
306    pub(crate) id: &'a str,
307    /// A built-in detector, the only kind a selection can name or remove.
308    pub(crate) built_in: bool,
309}
310
311/// Judges `selection` over `entries`, in registration order, and returns
312/// which entries stay. Entries that are not built-in always stay.
313///
314/// `included` is what the selection can name: the registry's built-ins. An
315/// id that is a `full` built-in absent from the registry is not included; an
316/// id that names a registered custom or PII-adapter detector is not
317/// selectable; anything else is unknown.
318pub(crate) fn plan_selection(
319    selection: &DetectionSelection,
320    entries: &[PlanEntry<'_>],
321) -> Result<Vec<bool>, DetectionConfigError> {
322    let included: Vec<&str> = entries
323        .iter()
324        .filter(|entry| entry.built_in)
325        .map(|entry| entry.id)
326        .collect();
327    let named = judge(selection, &included, |id| {
328        id == PII_ADAPTER_ID
329            || entries
330                .iter()
331                .any(|entry| !entry.built_in && entry.id == id)
332    })
333    .map_err(Fault::error)?;
334    let keep: Vec<bool> = entries
335        .iter()
336        .map(|entry| {
337            !entry.built_in
338                || match selection.mode {
339                    Mode::All => true,
340                    Mode::Include => named.contains(&entry.id),
341                    Mode::Exclude => !named.contains(&entry.id),
342                }
343        })
344        .collect();
345    if selection.mode != Mode::All && !keep.iter().any(|kept| *kept) {
346        return Err(DetectionConfigError::class(CLASS_EMPTY, None));
347    }
348    Ok(keep)
349}
350
351/// Step 5 of the validation order: every named id, in array order, must be
352/// included, and none may repeat. Returns the named ids.
353pub(crate) fn judge<'a>(
354    selection: &'a DetectionSelection,
355    included: &[&str],
356    not_selectable: impl Fn(&str) -> bool,
357) -> Result<Vec<&'a str>, Fault> {
358    let array = match selection.mode {
359        Mode::Exclude => "exclude",
360        _ => "include",
361    };
362    // At most 256 ids, so a linear scan is cheaper than a set in code size and
363    // in time.
364    let mut named: Vec<&str> = Vec::new();
365    for (index, id) in selection.ids.iter().enumerate() {
366        let id = id.as_str();
367        let class = if named.contains(&id) {
368            CLASS_DUPLICATE
369        } else if included.contains(&id) {
370            named.push(id);
371            continue;
372        } else if not_selectable(id) {
373            CLASS_NOT_SELECTABLE
374        } else if built_in_ids().any(|known| known == id) {
375            CLASS_NOT_INCLUDED
376        } else {
377            CLASS_UNKNOWN_ID
378        };
379        return Err(Fault::at(class, array, index));
380    }
381    Ok(named)
382}
383
384impl DetectionSelection {
385    /// The ids of `included` this selection enables, in the order of
386    /// `included` (the artifact's canonical order), judged as the validation
387    /// order requires: every named id must be included, and none may repeat.
388    pub(crate) fn enabled_of<'a>(&self, included: &[&'a str]) -> Result<Vec<&'a str>, Fault> {
389        let named = judge(self, included, |id| id == PII_ADAPTER_ID)?;
390        Ok(included
391            .iter()
392            .copied()
393            .filter(|id| match self.mode {
394                Mode::All => true,
395                Mode::Include => named.contains(id),
396                Mode::Exclude => !named.contains(id),
397            })
398            .collect())
399    }
400}