Skip to main content

redact_secret/
configuration_compare.rs

1//! Comparing detection configurations over one input
2//! (`decision-define-the-artifact-manifest-and-configuration-data-contracts`,
3//! section 7, `configuration-comparison/v1`; issue #1254).
4//!
5//! [`compare_configurations`] is the other half of
6//! [`compare_action_policies`](crate::compare_action_policies). That function
7//! changes only the action over **one** detection pass. This one is for a
8//! change that may alter detection (the detector selection, the PII selection,
9//! a ruleset, the limits): it runs one **independent** pass per side, each over
10//! its own registry, and then says how the sides' finalized findings
11//! correspond. Both are observations of one input; neither is enforcement.
12//!
13//! # What a comparison is not
14//!
15//! - It is **not a handle** and holds nothing. The caller builds each side's
16//!   registry (a temporary one, for example from a [`ConfigSnapshot`]) and the
17//!   function reads them; no owner changes and no registry is retained.
18//! - It covers **finalized findings only**. An overlap loser, a candidate a
19//!   gate removed and a suppressed PII alternative are never inputs, so the
20//!   result makes no claim about them. The detection that "removing a
21//!   provider exposes a contextual detector on the same span" is visible only
22//!   as the finalized finding that now holds that span.
23//! - It is **about this input only** (`scope: "input"`). A side with no
24//!   finding, or a pair with no difference, says nothing about absence of
25//!   risk, about other input, or that a rule is ineffective.
26//! - It carries **no plaintext**: ranges, fixed identifiers, counts and
27//!   digests of configuration only. Findings carry no per-scan id here,
28//!   because that id is not a stable identity across scans.
29//!
30//! # Correspondence
31//!
32//! Findings of different passes have no stable identity, so correspondence is
33//! derived from the byte ranges every side reports over the same input (a
34//! binding converts to its range unit only when it reports, so Unicode never
35//! changes which findings correspond). Findings are grouped into **clusters**:
36//! maximal sets joined by overlapping ranges, across both sides. Per cluster,
37//! the base side (side 0) against another side:
38//!
39//! | base | other | outcome |
40//! | --- | --- | --- |
41//! | 0 | n | [`DifferenceKind::Added`], one per finding |
42//! | n | 0 | [`DifferenceKind::Removed`], one per finding |
43//! | 1 | 1, same range | the same finding; a difference only when an attribute changed ([`Correspondence::Exact`]) |
44//! | 1 | 1, other range | [`DifferenceKind::Changed`] with the range among the changes ([`Correspondence::Overlap`]) |
45//! | 1 | n > 1 | [`DifferenceKind::Split`] |
46//! | n > 1 | 1 | [`DifferenceKind::Merged`] |
47//! | n > 1 | m > 1 | [`DifferenceKind::Regrouped`] |
48//!
49//! A split, merge or regrouping is [`Correspondence::Ambiguous`]: it names all
50//! members and does not pair them or claim an attribute changed. An unchanged
51//! pair is counted, not listed.
52//!
53//! # Failed sides
54//!
55//! A side that cannot be scanned is reported with a fixed code and a
56//! [`SideStatus`] (`limited` for a limit, `unsupported` for something its
57//! artifact cannot do, `error` otherwise), never as an empty side. A
58//! difference is reported only between two scanned sides; against a failed
59//! side (or a failed base) there is none, so a failure is never read as
60//! equivalence or as "found nothing".
61//!
62//! # Callbacks
63//!
64//! A [`ComparedPolicy::Callback`] side may have side effects and has no stable
65//! identity. Sides run one at a time in the order supplied, each callback once
66//! per finalized finding of its own side in finding order (the call sequence
67//! `scan` gives it). A callback failure fails the whole comparison with no
68//! partial result, as it does for `compare_action_policies`.
69
70use crate::compare::{
71    ActionComparison, ComparedFinding, ComparedPolicy, MAX_COMPARED_POLICIES, PolicyBinding,
72    binding_of, compare_action_policies_with_limits,
73};
74use crate::config::ConfigSnapshot;
75use crate::error::{SecretScanError, SecretScanErrorCode};
76use crate::limits::WholeInputLimits;
77use crate::registry::DetectorRegistry;
78
79/// One configuration taking part in a comparison: a registry (or the reason it
80/// could not be built), the policy evaluated over its findings, its limits and
81/// the identity digests of the configuration it was built from.
82#[derive(Clone, Copy, Debug)]
83pub struct ConfigurationSide<'a> {
84    registry: Result<&'a DetectorRegistry, &'static str>,
85    policy: ComparedPolicy<'a>,
86    limits: WholeInputLimits,
87    digests: Option<(&'a str, &'a str)>,
88}
89
90impl<'a> ConfigurationSide<'a> {
91    /// A side scanned over `registry` and judged by `policy`, under the
92    /// default limits.
93    #[must_use]
94    pub fn new(registry: &'a DetectorRegistry, policy: ComparedPolicy<'a>) -> Self {
95        Self {
96            registry: Ok(registry),
97            policy,
98            limits: WholeInputLimits::default(),
99            digests: None,
100        }
101    }
102
103    /// A side that could not be built, with the fixed code that says why (a
104    /// configuration diagnostic code or an error code). It is reported as
105    /// failed and is never scanned.
106    #[must_use]
107    pub fn failed(code: &'static str, policy: ComparedPolicy<'a>) -> Self {
108        Self {
109            registry: Err(code),
110            policy,
111            limits: WholeInputLimits::default(),
112            digests: None,
113        }
114    }
115
116    /// Replaces the side's whole-input limits.
117    #[must_use]
118    pub const fn with_limits(mut self, limits: WholeInputLimits) -> Self {
119        self.limits = limits;
120        self
121    }
122
123    /// Names the configuration this side was built from, by the snapshot
124    /// digest and the detection digest. Equal detection digests mean the same
125    /// detection; a different ruleset or selection always differs here, whatever
126    /// the policy bytes are.
127    #[must_use]
128    pub fn with_snapshot(mut self, snapshot: &'a ConfigSnapshot) -> Self {
129        self.digests = Some((snapshot.digest(), snapshot.detection_digest()));
130        self
131    }
132}
133
134/// Whether a side produced findings.
135#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
136#[non_exhaustive]
137pub enum SideStatus {
138    /// The pass ran and the side holds its finalized findings (possibly none).
139    Scanned,
140    /// A whole-input limit stopped the pass.
141    Limited,
142    /// The side asked for something its artifact cannot do.
143    Unsupported,
144    /// The configuration was invalid or the pass failed.
145    Error,
146}
147
148impl SideStatus {
149    /// The fixed wire name: `"scanned"`, `"limited"`, `"unsupported"` or
150    /// `"error"`.
151    #[must_use]
152    pub const fn as_str(self) -> &'static str {
153        match self {
154            Self::Scanned => "scanned",
155            Self::Limited => "limited",
156            Self::Unsupported => "unsupported",
157            Self::Error => "error",
158        }
159    }
160
161    fn of(code: &str) -> Self {
162        match code {
163            "INPUT_LIMIT_EXCEEDED" | "FINDING_LIMIT_EXCEEDED" => Self::Limited,
164            "DETECTION_SELECTION_UNSUPPORTED"
165            | "PII_SELECTOR_UNSUPPORTED"
166            | "PII_SELECTOR_UNAVAILABLE" => Self::Unsupported,
167            _ => Self::Error,
168        }
169    }
170}
171
172/// One side of a [`ConfigurationComparison`].
173#[derive(Clone, Debug, PartialEq, Eq)]
174pub struct ConfigurationResult {
175    digests: Option<(String, String)>,
176    binding: PolicyBinding,
177    scan: Result<ActionComparison, &'static str>,
178}
179
180impl ConfigurationResult {
181    /// The side's policy binding: the document digest of a declarative
182    /// policy, and for a callback nothing (the library keeps no identity of a
183    /// callback, and it may have side effects).
184    #[must_use]
185    pub const fn policy(&self) -> &PolicyBinding {
186        &self.binding
187    }
188
189    /// The snapshot digest of the configuration, when the side named one.
190    #[must_use]
191    pub fn digest(&self) -> Option<&str> {
192        self.digests.as_ref().map(|pair| pair.0.as_str())
193    }
194
195    /// The detection digest of the configuration, when the side named one.
196    #[must_use]
197    pub fn detection_digest(&self) -> Option<&str> {
198        self.digests.as_ref().map(|pair| pair.1.as_str())
199    }
200
201    /// Whether the side was scanned, and if not, why not.
202    #[must_use]
203    pub fn status(&self) -> SideStatus {
204        self.scan
205            .as_ref()
206            .err()
207            .map_or(SideStatus::Scanned, |code| SideStatus::of(code))
208    }
209
210    /// The fixed code of a failed side.
211    #[must_use]
212    pub fn failure(&self) -> Option<&'static str> {
213        self.scan.as_ref().err().copied()
214    }
215
216    /// The side's policy and detection facts, for a scanned side.
217    #[must_use]
218    pub fn scan(&self) -> Option<&ActionComparison> {
219        self.scan.as_ref().ok()
220    }
221
222    /// The side's finalized findings in input order, with the side's own
223    /// decision as the only entry of each finding's decisions. Empty for a
224    /// failed side, which is not the same as "found nothing": check
225    /// [`Self::status`].
226    #[must_use]
227    pub fn findings(&self) -> &[ComparedFinding] {
228        self.scan.as_ref().map_or(&[], ActionComparison::findings)
229    }
230}
231
232/// How one entry of a difference list relates the two sides.
233#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
234#[non_exhaustive]
235pub enum DifferenceKind {
236    /// A finding only the other side has.
237    Added,
238    /// A finding only the base side has.
239    Removed,
240    /// One finding on each side over overlapping ranges, with at least one
241    /// attribute changed.
242    Changed,
243    /// One base finding against several of the other side.
244    Split,
245    /// Several base findings against one of the other side.
246    Merged,
247    /// Several against several.
248    Regrouped,
249}
250
251impl DifferenceKind {
252    /// The fixed wire name.
253    #[must_use]
254    pub const fn as_str(self) -> &'static str {
255        match self {
256            Self::Added => "added",
257            Self::Removed => "removed",
258            Self::Changed => "changed",
259            Self::Split => "split",
260            Self::Merged => "merged",
261            Self::Regrouped => "regrouped",
262        }
263    }
264}
265
266/// How sure the pairing of an entry's findings is.
267#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
268#[non_exhaustive]
269pub enum Correspondence {
270    /// The same range on both sides.
271    Exact,
272    /// One finding each over overlapping, different ranges.
273    Overlap,
274    /// Several findings share the overlap; none is paired with another.
275    Ambiguous,
276}
277
278impl Correspondence {
279    /// The fixed wire name: `"exact"`, `"overlap"` or `"ambiguous"`.
280    #[must_use]
281    pub const fn as_str(self) -> &'static str {
282        match self {
283            Self::Exact => "exact",
284            Self::Overlap => "overlap",
285            Self::Ambiguous => "ambiguous",
286        }
287    }
288}
289
290/// The attributes a [`DifferenceKind::Changed`] entry names, in bit order.
291const CHANGE_NAMES: [&str; 6] = [
292    "range",
293    "type",
294    "detector",
295    "confidence",
296    "action",
297    "reason",
298];
299
300/// One difference between the base side and another.
301#[derive(Clone, Debug, PartialEq, Eq)]
302pub struct ConfigurationDifference {
303    kind: DifferenceKind,
304    base: Vec<usize>,
305    other: Vec<usize>,
306    changes: u8,
307}
308
309impl ConfigurationDifference {
310    /// The kind of difference.
311    #[must_use]
312    pub const fn kind(&self) -> DifferenceKind {
313        self.kind
314    }
315
316    /// The positions, among the base side's findings, of the findings involved.
317    #[must_use]
318    pub fn base(&self) -> &[usize] {
319        &self.base
320    }
321
322    /// The positions, among the other side's findings, of the findings
323    /// involved.
324    #[must_use]
325    pub fn other(&self) -> &[usize] {
326        &self.other
327    }
328
329    /// How the findings are paired; `None` for an added or removed finding.
330    #[must_use]
331    pub const fn correspondence(&self) -> Option<Correspondence> {
332        match self.kind {
333            DifferenceKind::Added | DifferenceKind::Removed => None,
334            DifferenceKind::Changed if self.changes & 1 == 0 => Some(Correspondence::Exact),
335            DifferenceKind::Changed => Some(Correspondence::Overlap),
336            _ => Some(Correspondence::Ambiguous),
337        }
338    }
339
340    /// The changed attributes as a bit set: bit 0 is `range`, then `type`, `detector`, `confidence`, `action` and `reason`.
341    #[must_use]
342    pub const fn change_bits(&self) -> u8 {
343        self.changes
344    }
345
346    /// The attributes that changed, (in the order `range`, `type`, `detector`, `confidence`, `action`, `reason`); empty unless the
347    /// kind is [`DifferenceKind::Changed`].
348    pub fn changes(&self) -> impl Iterator<Item = &'static str> + '_ {
349        CHANGE_NAMES
350            .iter()
351            .enumerate()
352            .filter(|(bit, _)| self.changes >> bit & 1 == 1)
353            .map(|(_, name)| *name)
354    }
355}
356
357/// The differences of one side against the base side, on this input only.
358#[derive(Clone, Debug, PartialEq, Eq)]
359pub struct ConfigurationDifferences {
360    entries: Vec<ConfigurationDifference>,
361    unchanged: usize,
362}
363
364impl ConfigurationDifferences {
365    /// The differences, in input order.
366    #[must_use]
367    pub fn entries(&self) -> &[ConfigurationDifference] {
368        &self.entries
369    }
370
371    /// How many findings correspond exactly and are identical in every
372    /// attribute.
373    #[must_use]
374    pub const fn unchanged(&self) -> usize {
375        self.unchanged
376    }
377}
378
379/// The result of [`compare_configurations`].
380#[derive(Clone, Debug, PartialEq, Eq)]
381pub struct ConfigurationComparison {
382    sides: Vec<ConfigurationResult>,
383    differences: Vec<Option<ConfigurationDifferences>>,
384}
385
386impl ConfigurationComparison {
387    /// The sides, in the order supplied.
388    #[must_use]
389    pub fn sides(&self) -> &[ConfigurationResult] {
390        &self.sides
391    }
392
393    /// One entry per side: `None` for the base side itself, and for a side
394    /// where either it or the base failed.
395    #[must_use]
396    pub fn differences(&self) -> &[Option<ConfigurationDifferences>] {
397        &self.differences
398    }
399}
400
401/// Runs one independent detection pass per side over `input` and relates every
402/// side to the first. See the module documentation (`configuration_compare`).
403///
404/// # Examples
405///
406/// ```
407/// use redact_secret::{
408///     ComparedPolicy, ConfigurationSide, DetectionSelection, DetectorRegistry,
409///     compare_configurations,
410/// };
411///
412/// let all = DetectorRegistry::with_built_in([])?;
413/// let jwt_only = DetectorRegistry::with_built_in([])?
414///     .with_detection(&DetectionSelection::include(["jwt"]))?;
415/// let comparison = compare_configurations(
416///     "API_KEY=ghp_SYNTHETICREVOKED00000000000000000000",
417///     &[
418///         ConfigurationSide::new(&all, ComparedPolicy::Default),
419///         ConfigurationSide::new(&jwt_only, ComparedPolicy::Default),
420///     ],
421/// )?;
422/// assert_eq!(comparison.differences()[1].as_ref().unwrap().entries().len(), 1);
423/// # Ok::<(), Box<dyn std::error::Error>>(())
424/// ```
425///
426/// # Errors
427///
428/// [`SecretScanErrorCode::InvalidOptions`] when `sides` is empty or holds more
429/// than [`MAX_COMPARED_POLICIES`]; [`SecretScanErrorCode::PolicyFailure`] or
430/// [`SecretScanErrorCode::InvalidPolicyAction`] when a callback fails, with no
431/// partial result. Every other failure is a failed side, not an error.
432pub fn compare_configurations(
433    input: &str,
434    sides: &[ConfigurationSide<'_>],
435) -> Result<ConfigurationComparison, SecretScanError> {
436    if sides.is_empty() || sides.len() > MAX_COMPARED_POLICIES {
437        return Err(SecretScanErrorCode::InvalidOptions.into());
438    }
439    let mut results = Vec::with_capacity(sides.len());
440    for side in sides {
441        let scan = match side.registry {
442            Err(code) => Err(code),
443            Ok(registry) => {
444                match compare_action_policies_with_limits(
445                    input,
446                    registry,
447                    &[side.policy],
448                    &side.limits,
449                ) {
450                    Ok(comparison) => Ok(comparison),
451                    Err(error) => match error.code() {
452                        SecretScanErrorCode::PolicyFailure
453                        | SecretScanErrorCode::InvalidPolicyAction => return Err(error),
454                        code => Err(code.as_str()),
455                    },
456                }
457            }
458        };
459        results.push(ConfigurationResult {
460            binding: binding_of(&side.policy),
461            digests: side
462                .digests
463                .map(|(digest, detection)| (digest.to_owned(), detection.to_owned())),
464            scan,
465        });
466    }
467    let differences = results
468        .iter()
469        .enumerate()
470        .map(|(index, side)| {
471            (index > 0 && side.scan.is_ok() && results[0].scan.is_ok())
472                .then(|| relate(results[0].findings(), side.findings()))
473        })
474        .collect();
475    Ok(ConfigurationComparison {
476        sides: results,
477        differences,
478    })
479}
480
481/// Groups both sides' findings into overlap clusters and relates each.
482fn relate(base: &[ComparedFinding], other: &[ComparedFinding]) -> ConfigurationDifferences {
483    // (start, end, is-other, position)
484    let mut spans: Vec<(usize, usize, bool, usize)> = Vec::with_capacity(base.len() + other.len());
485    for (is_other, side) in [(false, base), (true, other)] {
486        for (position, compared) in side.iter().enumerate() {
487            let range = compared.finding().range();
488            spans.push((range.start(), range.end(), is_other, position));
489        }
490    }
491    spans.sort_unstable();
492
493    let mut entries = Vec::new();
494    let mut unchanged = 0;
495    let mut start = 0;
496    while start < spans.len() {
497        let mut end = spans[start].1;
498        let mut stop = start + 1;
499        while stop < spans.len() && spans[stop].0 < end {
500            end = end.max(spans[stop].1);
501            stop += 1;
502        }
503        let (mut left, mut right) = (Vec::new(), Vec::new());
504        for &(_, _, is_other, position) in &spans[start..stop] {
505            if is_other { &mut right } else { &mut left }.push(position);
506        }
507        start = stop;
508
509        let kind = match (left.len(), right.len()) {
510            (0, _) => DifferenceKind::Added,
511            (_, 0) => DifferenceKind::Removed,
512            (1, 1) => DifferenceKind::Changed,
513            (1, _) => DifferenceKind::Split,
514            (_, 1) => DifferenceKind::Merged,
515            _ => DifferenceKind::Regrouped,
516        };
517        let changes = if kind == DifferenceKind::Changed {
518            changed(&base[left[0]], &other[right[0]])
519        } else {
520            0
521        };
522        if kind == DifferenceKind::Changed && changes == 0 {
523            unchanged += 1;
524            continue;
525        }
526        // An added or removed cluster holds one finding per entry.
527        let single = matches!(kind, DifferenceKind::Added | DifferenceKind::Removed);
528        let members = if kind == DifferenceKind::Added {
529            &right
530        } else {
531            &left
532        };
533        if single {
534            for &position in members {
535                let (base, other) = match kind {
536                    DifferenceKind::Added => (vec![], vec![position]),
537                    _ => (vec![position], vec![]),
538                };
539                entries.push(ConfigurationDifference {
540                    kind,
541                    base,
542                    other,
543                    changes,
544                });
545            }
546        } else {
547            entries.push(ConfigurationDifference {
548                kind,
549                base: left,
550                other: right,
551                changes,
552            });
553        }
554    }
555    ConfigurationDifferences { entries, unchanged }
556}
557
558/// The attribute bits (see [`CHANGE_NAMES`]) in which two findings differ.
559fn changed(base: &ComparedFinding, other: &ComparedFinding) -> u8 {
560    let (a, b) = (base.finding(), other.finding());
561    let (x, y) = (&base.decisions()[0], &other.decisions()[0]);
562    [
563        a.range() != b.range(),
564        a.type_name() != b.type_name(),
565        a.detector() != b.detector(),
566        a.confidence() != b.confidence(),
567        x.action() != y.action(),
568        x.basis() != y.basis(),
569    ]
570    .iter()
571    .enumerate()
572    .fold(0, |bits, (bit, differs)| bits | u8::from(*differs) << bit)
573}