Skip to main content

redact_secret/
config.rs

1//! Effective configuration: the detector-id selection and the pure
2//! `resolve_config` / `describe_config` that explain it (issue #1251,
3//! `decision-define-detector-id-selection-and-configuration-replacement-precedence`
4//! and `decision-define-the-artifact-manifest-and-configuration-data-contracts`).
5//!
6//! # Two things, kept apart
7//!
8//! - A [`DetectionSelection`] chooses which of an artifact's **included**
9//!   built-in detectors are **enabled**. It acts when a registry is composed
10//!   ([`DetectorRegistry::with_detection`](crate::DetectorRegistry::with_detection)),
11//!   before the shared prefilter, candidate collection and overlap
12//!   resolution, so a disabled detector is not constructed, not prefiltered,
13//!   no overlap competitor and no retention input.
14//! - [`resolve_config`] and [`describe_config`] are **data**: they read an
15//!   [`ArtifactManifest`] and explicit input, scan nothing, build no
16//!   registry, initialize nothing and hold nothing. A [`ConfigSnapshot`]
17//!   cannot scan.
18//!
19//! # The truth table
20//!
21//! There are two layers and no third: the artifact's build defaults, then the
22//! runtime input. This module is the one place the table is implemented; the
23//! bindings forward to it and keep no copy.
24//!
25//! | Key | Absent | Explicit empty | Explicit value |
26//! | --- | --- | --- | --- |
27//! | `detection.include` | all included enabled | no built-in enabled | exactly the list |
28//! | `detection.exclude` | none excluded | same as absent | every included detector but the list |
29//! | `pii` | off | off | the canonical selector set |
30//! | `ruleset` | none | not expressible | adds the ruleset's detectors |
31//! | `actionPolicy` | the artifact's default evaluation | `rules: []` is the base | replaces the whole document |
32//! | `limits.*` | artifact default | zero is rejected | replaces that field only |
33//! | callback `policy` | none | n/a | replaces the default; with `actionPolicy` is `INVALID_OPTIONS` |
34//!
35//! Arrays replace and are never unioned or concatenated, a policy document
36//! replaces the document and its rules are never merged, and an action
37//! (including `allow`) never enables or disables a detector.
38
39use crate::action_policy::{ActionPolicy, load_action_policy};
40use crate::detectors::built_in_ids;
41use crate::error::SecretScanErrorCode;
42use crate::json::{self, Value};
43use crate::limits::{DEFAULT_MAX_FINDINGS, DEFAULT_MAX_INPUT_BYTES, WholeInputLimits};
44use crate::manifest::{ArtifactKind, ArtifactManifest};
45use crate::pii::{PiiSelection, is_reserved_detector_id};
46use crate::policy_diagnostics;
47use crate::registry::DetectorRegistry;
48use crate::ruleset::load_ruleset;
49use crate::selection::{
50    CLASS_UNKNOWN_FIELD, CLASS_UNSUPPORTED, CLASS_WRONG_TYPE, DetectionSelection, PII_ADAPTER_ID,
51    selection_from_value,
52};
53use crate::sha256::{sha256, to_hex};
54use crate::types::is_identifier;
55use std::fmt::{self, Write as _};
56
57/// The most diagnostics one resolution reports.
58const DIAGNOSTICS_MAX: usize = 256;
59/// The largest `runtime-config/v1` document, checked before parsing.
60const RUNTIME_CONFIG_BYTES_MAX: usize = 262_144;
61/// The largest limit value every binding can carry (`u32`).
62const LIMIT_MAX: u64 = 0xffff_ffff;
63
64// ---------------------------------------------------------------------------
65// Diagnostics
66// ---------------------------------------------------------------------------
67
68/// How serious a [`ConfigDiagnostic`] is.
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70#[non_exhaustive]
71pub enum ConfigSeverity {
72    /// The input cannot be resolved.
73    Error,
74    /// The input resolves, and something deserves attention.
75    Warning,
76    /// A consequence worth knowing.
77    Info,
78}
79
80impl ConfigSeverity {
81    /// `error`, `warning` or `info`.
82    #[must_use]
83    pub const fn as_str(self) -> &'static str {
84        match self {
85            Self::Error => "error",
86            Self::Warning => "warning",
87            Self::Info => "info",
88        }
89    }
90}
91
92/// One safe finding about a configuration input (`config-diagnostics/v1`).
93///
94/// `path` is a fixed-syntax pointer such as `detection.include[3]`; an
95/// unknown member is addressed by its position (`detection.@1`), never its
96/// name. `id` is only ever a canonical detector id from the catalog or the id
97/// of a rule in a validated action policy. No input string is echoed: a user
98/// can paste a secret where an id belongs.
99#[derive(Clone, Debug, PartialEq, Eq)]
100pub struct ConfigDiagnostic {
101    code: &'static str,
102    severity: ConfigSeverity,
103    path: String,
104    id: Option<String>,
105    related: Option<String>,
106}
107
108impl ConfigDiagnostic {
109    /// The fixed code, for example `UNKNOWN_DETECTOR_ID`.
110    #[must_use]
111    pub const fn code(&self) -> &'static str {
112        self.code
113    }
114
115    /// The severity.
116    #[must_use]
117    pub const fn severity(&self) -> ConfigSeverity {
118        self.severity
119    }
120
121    /// The pointer to the offending part of the input.
122    #[must_use]
123    pub fn path(&self) -> &str {
124        &self.path
125    }
126
127    /// The canonical detector id, or the action policy rule id, this
128    /// concerns, when it concerns one.
129    #[must_use]
130    pub fn id(&self) -> Option<&str> {
131        self.id.as_deref()
132    }
133
134    /// The pointer to a second part of the input that explains this finding
135    /// (the earlier rule that shadows a later one), when there is one.
136    #[must_use]
137    pub fn related(&self) -> Option<&str> {
138        self.related.as_deref()
139    }
140}
141
142/// Collects diagnostics without growing past what the output can show: at most
143/// [`DIAGNOSTICS_MAX`] of each severity are kept (the final list takes errors
144/// first, so no more can ever appear), and every one is still counted, so the
145/// output says when it was cut.
146#[derive(Default)]
147pub(crate) struct Diagnostics {
148    items: Vec<ConfigDiagnostic>,
149    seen: [usize; 3],
150}
151
152const fn rank(severity: ConfigSeverity) -> usize {
153    match severity {
154        ConfigSeverity::Error => 0,
155        ConfigSeverity::Warning => 1,
156        ConfigSeverity::Info => 2,
157    }
158}
159
160impl Diagnostics {
161    fn push(&mut self, severity: ConfigSeverity, code: &'static str, path: &str) {
162        self.push_item(severity, code, path, None, None);
163    }
164
165    /// A diagnostic with an `id` and an optional `related` pointer.
166    pub(crate) fn push_item(
167        &mut self,
168        severity: ConfigSeverity,
169        code: &'static str,
170        path: &str,
171        id: Option<&str>,
172        related: Option<&str>,
173    ) {
174        let slot = rank(severity);
175        self.seen[slot] += 1;
176        if self.seen[slot] > DIAGNOSTICS_MAX {
177            return;
178        }
179        self.items.push(ConfigDiagnostic {
180            code,
181            severity,
182            path: path.to_owned(),
183            id: id.map(str::to_owned),
184            related: related.map(str::to_owned),
185        });
186    }
187
188    fn error(&mut self, code: &'static str, path: &str) {
189        self.push(ConfigSeverity::Error, code, path);
190    }
191
192    pub(crate) const fn has_error(&self) -> bool {
193        self.seen[0] > 0
194    }
195
196    /// Errors first, then warnings, then notes, each in document order; at
197    /// most [`DIAGNOSTICS_MAX`].
198    pub(crate) fn finish(self) -> (Vec<ConfigDiagnostic>, bool) {
199        let total: usize = self.seen.iter().sum();
200        let mut ordered = Vec::with_capacity(self.items.len().min(DIAGNOSTICS_MAX));
201        for severity in [
202            ConfigSeverity::Error,
203            ConfigSeverity::Warning,
204            ConfigSeverity::Info,
205        ] {
206            for item in self.items.iter().filter(|item| item.severity == severity) {
207                if ordered.len() < DIAGNOSTICS_MAX {
208                    ordered.push(item.clone());
209                }
210            }
211        }
212        (ordered, total > DIAGNOSTICS_MAX)
213    }
214}
215
216// ---------------------------------------------------------------------------
217// The request and the result
218// ---------------------------------------------------------------------------
219
220/// What to resolve: explicit runtime input over the artifact's defaults.
221///
222/// The input is `runtime-config/v1` text for the members that are data
223/// (`schema`, `detection`, `pii`, `limits`) plus the exact bytes of the two
224/// documents a binding already receives as bytes (`ruleset`, `actionPolicy`),
225/// so the policy identity is the digest of the bytes a call would load. A
226/// callback is not data: it is only recorded as present.
227#[derive(Clone, Copy, Debug, Default)]
228pub struct ConfigRequest<'a> {
229    runtime_config: Option<&'a str>,
230    ruleset: Option<&'a [u8]>,
231    action_policy: Option<&'a [u8]>,
232    callback: bool,
233    disclose_ruleset: bool,
234    closed_types: Option<&'a [&'a str]>,
235    closed_detectors: Option<&'a [&'a str]>,
236}
237
238impl<'a> ConfigRequest<'a> {
239    /// An empty request: nothing given, so every key inherits.
240    #[must_use]
241    pub const fn new() -> Self {
242        Self {
243            runtime_config: None,
244            ruleset: None,
245            action_policy: None,
246            callback: false,
247            disclose_ruleset: false,
248            closed_types: None,
249            closed_detectors: None,
250        }
251    }
252
253    /// A `runtime-config/v1` or explicitly tagged `runtime-config/v2` document:
254    /// at most 262,144 bytes. Version 2 also accepts `closedTypes` and
255    /// `closedDetectors` for strict policy diagnostics.
256    #[must_use]
257    pub const fn runtime_config(mut self, json: &'a str) -> Self {
258        self.runtime_config = Some(json);
259        self
260    }
261
262    /// The exact bytes of a declarative ruleset.
263    #[must_use]
264    pub const fn ruleset(mut self, bytes: &'a [u8]) -> Self {
265        self.ruleset = Some(bytes);
266        self
267    }
268
269    /// The exact bytes of an action policy document.
270    #[must_use]
271    pub const fn action_policy(mut self, bytes: &'a [u8]) -> Self {
272        self.action_policy = Some(bytes);
273        self
274    }
275
276    /// A callback policy is in force. It is reported as a dynamic reference
277    /// without content.
278    #[must_use]
279    pub const fn callback_policy(mut self) -> Self {
280        self.callback = true;
281        self
282    }
283
284    /// Declares the finding types of the caller's own closed vocabulary: the
285    /// types an action policy rule may name beyond those the artifact's
286    /// detectors declare. With it, a rule `type` that is neither declared by
287    /// an enabled detector nor listed here is an **error**
288    /// (`ACTION_POLICY_UNKNOWN_TYPE`, severity `error`) and the resolution is
289    /// rejected. Without it the same finding is only a warning, because a
290    /// custom, ruleset or future type is legitimate under the revision-1 open
291    /// vocabulary. Loading an action policy is unaffected either way.
292    #[must_use]
293    pub const fn closed_types(mut self, types: &'a [&'a str]) -> Self {
294        self.closed_types = Some(types);
295        self
296    }
297
298    /// Declares the caller's closed set of custom detector ids an action
299    /// policy rule may name beyond the catalog and the supplied ruleset. With
300    /// it, a rule `detector` that is none of those is an **error**
301    /// (`ACTION_POLICY_UNKNOWN_DETECTOR`, severity `error`); without it, a
302    /// warning.
303    #[must_use]
304    pub const fn closed_detectors(mut self, detectors: &'a [&'a str]) -> Self {
305        self.closed_detectors = Some(detectors);
306        self
307    }
308
309    /// Includes the ruleset's detector ids and byte digest in the snapshot.
310    /// Off by default: a ruleset's identity can be sensitive, and the
311    /// snapshot's `detectionDigest` already says whether two detections are
312    /// the same.
313    #[must_use]
314    pub const fn disclose_ruleset_identity(mut self) -> Self {
315        self.disclose_ruleset = true;
316        self
317    }
318}
319
320/// The resolved, effective configuration (`config-snapshot/v1`): immutable
321/// data. It is not a handle and cannot scan.
322///
323/// The snapshot holds ids, counts, digests and fixed words. It never holds an
324/// input byte, a ruleset body or a rule's pattern, a matched value or a path.
325#[derive(Clone, Debug, PartialEq, Eq)]
326pub struct ConfigSnapshot {
327    json: String,
328    digest: String,
329    detection_digest: String,
330    enabled: Vec<String>,
331    inert: bool,
332    selection: DetectionSelection,
333    pii: PiiSelection,
334    limits: (usize, usize),
335}
336
337impl ConfigSnapshot {
338    /// The document: UTF-8 JSON with `schema` first, every other member at
339    /// every depth in bytewise order, no whitespace.
340    #[must_use]
341    pub fn as_json(&self) -> &str {
342        &self.json
343    }
344
345    /// `sha256:` over the canonical JSON of the snapshot without `digest`
346    /// (all members, `schema` included, in bytewise order).
347    #[must_use]
348    pub fn digest(&self) -> &str {
349        &self.digest
350    }
351
352    /// `sha256:` over the canonical `{ manifestDigest, enabled, ruleset digest,
353    /// PII activation }`: equal digests mean the same detection.
354    #[must_use]
355    pub fn detection_digest(&self) -> &str {
356        &self.detection_digest
357    }
358
359    /// The enabled built-in detector ids, in canonical order.
360    pub fn enabled_ids(&self) -> impl Iterator<Item = &str> {
361        self.enabled.iter().map(String::as_str)
362    }
363
364    /// Whether nothing at all is enabled (no built-in detector, no ruleset,
365    /// PII off). Binding such a configuration to a scan owner fails with
366    /// `EMPTY_DETECTION_SET`; describing it succeeds.
367    #[must_use]
368    pub const fn is_inert(&self) -> bool {
369        self.inert
370    }
371
372    /// The detector-id selection to apply to the artifact's built-ins when a
373    /// registry is composed from this snapshot.
374    #[must_use]
375    pub const fn detection_selection(&self) -> &DetectionSelection {
376        &self.selection
377    }
378
379    /// The PII selection to compose a registry with.
380    #[must_use]
381    pub const fn pii_selection(&self) -> &PiiSelection {
382        &self.pii
383    }
384
385    /// The whole-input limits the snapshot resolved: the artifact defaults
386    /// where the input gave none.
387    #[must_use]
388    pub fn whole_input_limits(&self) -> WholeInputLimits {
389        WholeInputLimits::new(self.limits.0, self.limits.1).unwrap_or_default()
390    }
391}
392
393/// The result of [`resolve_config`] (`config-resolution/v1`): the snapshot
394/// when the input is valid, and every safe diagnostic either way.
395#[derive(Clone, Debug, PartialEq, Eq)]
396pub struct ConfigResolution {
397    json: String,
398    snapshot: Option<ConfigSnapshot>,
399    diagnostics: Vec<ConfigDiagnostic>,
400}
401
402impl ConfigResolution {
403    /// The envelope `{ schema, ok, snapshot, diagnostics }` as UTF-8 JSON,
404    /// `schema` first. `snapshot` is `null` when `ok` is false.
405    #[must_use]
406    pub fn as_json(&self) -> &str {
407        &self.json
408    }
409
410    /// Whether the input resolved without an error.
411    #[must_use]
412    pub const fn is_ok(&self) -> bool {
413        self.snapshot.is_some()
414    }
415
416    /// The snapshot, `None` when the input was rejected.
417    #[must_use]
418    pub const fn snapshot(&self) -> Option<&ConfigSnapshot> {
419        self.snapshot.as_ref()
420    }
421
422    /// Every diagnostic: errors first, then in document order, at most 256.
423    #[must_use]
424    pub fn diagnostics(&self) -> &[ConfigDiagnostic] {
425        &self.diagnostics
426    }
427}
428
429// ---------------------------------------------------------------------------
430// Resolution
431// ---------------------------------------------------------------------------
432
433/// The effective values the snapshot is built from.
434struct Effective<'a> {
435    selection: DetectionSelection,
436    detection_mode: &'static str,
437    detection_origin: &'static str,
438    enabled: Vec<&'a str>,
439    custom_detectors: usize,
440    pii: PiiSelection,
441    pii_origin: &'static str,
442    ruleset: Option<RulesetFacts>,
443    policy: PolicyFacts,
444    policy_origin: &'static str,
445    max_input_bytes: usize,
446    max_input_origin: &'static str,
447    max_findings: usize,
448    max_findings_origin: &'static str,
449}
450
451struct RulesetFacts {
452    detector_ids: Vec<String>,
453    digest: String,
454}
455
456enum PolicyFacts {
457    Default,
458    Document {
459        digest: String,
460        rule_count: usize,
461        policy: ActionPolicy,
462    },
463    Callback,
464}
465
466/// Resolves explicit runtime input over `manifest`'s build defaults into an
467/// immutable [`ConfigSnapshot`], with no hidden concatenation and no silent
468/// fallback.
469///
470/// Invalid input is data, never a panic or an error value to unwrap: the
471/// returned [`ConfigResolution`] says `ok = false`, holds no snapshot and lists
472/// every problem, so a tool can show them all. It reads no file, network or
473/// environment value, scans nothing, builds no registry and changes no
474/// owner. Nothing in the request is hashed except the two policy documents'
475/// own bytes, which are configuration and never a secret.
476///
477/// A request for something above the artifact's ceiling (a detector it does
478/// not include, a PII family it lacks, detector selection on an artifact
479/// without that capability) is rejected with a coded diagnostic, never
480/// ignored and never satisfied by another artifact.
481#[must_use]
482pub fn resolve_config(
483    manifest: &ArtifactManifest,
484    request: &ConfigRequest<'_>,
485) -> ConfigResolution {
486    let mut diagnostics = Diagnostics::default();
487    let document = read_document(request, &mut diagnostics);
488    let member = |name: &str| document.as_ref().and_then(|value| value.member(name));
489
490    // Sections are judged in a fixed order, so the diagnostics' order does not
491    // depend on the order of the document's members.
492    let (selection, detection_given, enabled) =
493        resolve_detection(member("detection"), manifest, &mut diagnostics);
494    let (pii, pii_given) = resolve_pii(manifest, member("pii"), &mut diagnostics);
495    let (limit_input, limit_findings) = read_limits(member("limits"), &mut diagnostics);
496    let ruleset = request
497        .ruleset
498        .and_then(|bytes| resolve_ruleset(bytes, &mut diagnostics));
499    let (policy, policy_given) = resolve_policy(request, &mut diagnostics);
500    let closed_types =
501        read_closed_vocabulary(member("closedTypes"), "closedTypes", &mut diagnostics);
502    let closed_detectors = read_closed_vocabulary(
503        member("closedDetectors"),
504        "closedDetectors",
505        &mut diagnostics,
506    );
507    // A binding must not silently replace a Rust caller's declaration.
508    if (closed_types.is_some() && request.closed_types.is_some())
509        || (closed_detectors.is_some() && request.closed_detectors.is_some())
510    {
511        diagnostics.error("INVALID_OPTIONS", "$");
512    }
513
514    if diagnostics.has_error() {
515        let (items, truncated) = diagnostics.finish();
516        return envelope(None, items, truncated);
517    }
518
519    let effective = Effective {
520        detection_mode: selection.mode(),
521        selection,
522        detection_origin: origin(detection_given),
523        custom_detectors: 0,
524        pii,
525        pii_origin: origin(pii_given),
526        ruleset,
527        policy,
528        policy_origin: origin(policy_given),
529        max_input_bytes: limit_input.unwrap_or(DEFAULT_MAX_INPUT_BYTES),
530        max_input_origin: origin(limit_input.is_some()),
531        max_findings: limit_findings.unwrap_or(DEFAULT_MAX_FINDINGS),
532        max_findings_origin: origin(limit_findings.is_some()),
533        enabled,
534    };
535
536    let mut diagnostic_request = *request;
537    if let Some(types) = &closed_types {
538        diagnostic_request.closed_types = Some(types);
539    }
540    if let Some(detectors) = &closed_detectors {
541        diagnostic_request.closed_detectors = Some(detectors);
542    }
543    advise(manifest, &effective, &diagnostic_request, &mut diagnostics);
544    // A declared closed vocabulary turns an unknown policy name into an error.
545    if diagnostics.has_error() {
546        let (items, truncated) = diagnostics.finish();
547        return envelope(None, items, truncated);
548    }
549    let snapshot = build_snapshot(manifest, &effective, request.disclose_ruleset);
550    let (items, truncated) = diagnostics.finish();
551    envelope(Some(snapshot), items, truncated)
552}
553
554/// Parses the runtime-config text and judges its top level: size, shape,
555/// member names and `schema`. Returns the document when it is an object.
556#[inline(never)]
557fn read_document(request: &ConfigRequest<'_>, diagnostics: &mut Diagnostics) -> Option<Value> {
558    let text = request.runtime_config?;
559    if text.len() > RUNTIME_CONFIG_BYTES_MAX {
560        diagnostics.error(CLASS_WRONG_TYPE, "$");
561        return None;
562    }
563    let Some(document) = json::parse(text) else {
564        diagnostics.error(CLASS_WRONG_TYPE, "$");
565        return None;
566    };
567    let Value::Object(members) = &document else {
568        diagnostics.error(CLASS_WRONG_TYPE, "$");
569        return None;
570    };
571    let v2 =
572        matches!(document.member("schema"), Some(Value::Str(name)) if name == "runtime-config/v2");
573    for (position, (name, _)) in members.iter().enumerate() {
574        if !(matches!(name.as_str(), "schema" | "detection" | "pii" | "limits")
575            || (v2 && matches!(name.as_str(), "closedTypes" | "closedDetectors")))
576        {
577            diagnostics.error(CLASS_UNKNOWN_FIELD, &format!("@{position}"));
578        }
579    }
580    match document.member("schema") {
581        None => {}
582        Some(Value::Str(name))
583            if matches!(name.as_str(), "runtime-config/v1" | "runtime-config/v2") => {}
584        Some(Value::Str(_)) => diagnostics.error("UNKNOWN_SCHEMA", "schema"),
585        Some(_) => diagnostics.error(CLASS_WRONG_TYPE, "schema"),
586    }
587    Some(document)
588}
589
590fn read_closed_vocabulary<'a>(
591    value: Option<&'a Value>,
592    path: &str,
593    diagnostics: &mut Diagnostics,
594) -> Option<Vec<&'a str>> {
595    let value = value?;
596    let Value::Array(values) = value else {
597        diagnostics.error(CLASS_WRONG_TYPE, path);
598        return None;
599    };
600    let mut names = Vec::with_capacity(values.len());
601    for (index, value) in values.iter().enumerate() {
602        if let Value::Str(name) = value {
603            names.push(name.as_str());
604        } else {
605            diagnostics.error(CLASS_WRONG_TYPE, &format!("{path}[{index}]"));
606        }
607    }
608    Some(names)
609}
610
611/// The `detection` row of the truth table: absent inherits every included
612/// detector; a value replaces. Returns the parsed selection, whether the
613/// document gave one, and the enabled ids in canonical order.
614#[inline(never)]
615fn resolve_detection<'a>(
616    value: Option<&Value>,
617    manifest: &'a ArtifactManifest,
618    diagnostics: &mut Diagnostics,
619) -> (DetectionSelection, bool, Vec<&'a str>) {
620    let included: Vec<&str> = manifest.detector_ids().collect();
621    let Some(value) = value else {
622        return (DetectionSelection::all(), false, included);
623    };
624    let selection = match selection_from_value(value) {
625        Ok(selection) => selection,
626        Err(fault) => {
627            diagnostics.error(fault.class, &fault.path());
628            return (DetectionSelection::all(), true, included);
629        }
630    };
631    // Step 4: an artifact without the capability cannot take a selection.
632    // `{}` asks for nothing.
633    if !selection.is_all() && !manifest.detector_selection() {
634        diagnostics.error(CLASS_UNSUPPORTED, "detection");
635        return (DetectionSelection::all(), true, included);
636    }
637    match selection.enabled_of(&included) {
638        Ok(enabled) => (selection, true, enabled),
639        Err(fault) => {
640            diagnostics.error(fault.class, &fault.path());
641            (DetectionSelection::all(), true, included)
642        }
643    }
644}
645
646/// The `limits` row: each scalar inherits independently; zero, a fraction or
647/// a value no binding can carry is rejected.
648#[inline(never)]
649fn read_limits(
650    value: Option<&Value>,
651    diagnostics: &mut Diagnostics,
652) -> (Option<usize>, Option<usize>) {
653    let mut input = None;
654    let mut findings = None;
655    let Some(value) = value else {
656        return (input, findings);
657    };
658    let Value::Object(members) = value else {
659        diagnostics.error(CLASS_WRONG_TYPE, "limits");
660        return (input, findings);
661    };
662    for (position, (name, member)) in members.iter().enumerate() {
663        let (slot, path) = match name.as_str() {
664            "maxInputBytes" => (&mut input, "limits.maxInputBytes"),
665            "maxFindings" => (&mut findings, "limits.maxFindings"),
666            _ => {
667                diagnostics.error(CLASS_UNKNOWN_FIELD, &format!("limits.@{position}"));
668                continue;
669            }
670        };
671        match member {
672            Value::Int(number) if (1..=LIMIT_MAX).contains(number) => {
673                *slot = usize::try_from(*number).ok();
674            }
675            Value::Int(_) | Value::Other => diagnostics.error("INVALID_LIMITS", path),
676            _ => diagnostics.error(CLASS_WRONG_TYPE, path),
677        }
678    }
679    (input, findings)
680}
681
682/// The `pii` row: absent and explicit empty are both off; a list replaces.
683#[inline(never)]
684fn resolve_pii(
685    manifest: &ArtifactManifest,
686    value: Option<&Value>,
687    diagnostics: &mut Diagnostics,
688) -> (PiiSelection, bool) {
689    let Some(value) = value else {
690        return (PiiSelection::default(), false);
691    };
692    let Value::Array(items) = value else {
693        diagnostics.error(CLASS_WRONG_TYPE, "pii");
694        return (PiiSelection::default(), true);
695    };
696    let mut selectors: Vec<&str> = Vec::with_capacity(items.len());
697    for (index, item) in items.iter().enumerate() {
698        let Value::Str(selector) = item else {
699            diagnostics.error(CLASS_WRONG_TYPE, &format!("pii[{index}]"));
700            return (PiiSelection::default(), true);
701        };
702        selectors.push(selector);
703    }
704    match PiiSelection::parse(&selectors) {
705        Ok(selection) => {
706            if !selection.is_off() && !manifest.pii_linked() {
707                diagnostics.error("PII_SELECTOR_UNAVAILABLE", "pii");
708            }
709            (selection, true)
710        }
711        Err(error) => {
712            let code = match error.code() {
713                SecretScanErrorCode::PiiSelectorInvalid => "PII_SELECTOR_INVALID",
714                SecretScanErrorCode::PiiSelectorUnsupported => "PII_SELECTOR_UNSUPPORTED",
715                _ => "PII_SELECTOR_UNAVAILABLE",
716            };
717            diagnostics.error(code, "pii");
718            (PiiSelection::default(), true)
719        }
720    }
721}
722
723#[inline(never)]
724fn resolve_ruleset(bytes: &[u8], diagnostics: &mut Diagnostics) -> Option<RulesetFacts> {
725    let Ok(detectors) = load_ruleset(bytes) else {
726        diagnostics.error("INVALID_RULESET", "ruleset");
727        return None;
728    };
729    let ids: Vec<String> = detectors
730        .iter()
731        .map(|detector| detector.id().to_owned())
732        .collect();
733    // The ids a registry would refuse: a built-in or PII id, or a repeat.
734    let refused = ids.iter().enumerate().any(|(index, id)| {
735        !is_identifier(id)
736            || is_reserved_detector_id(id)
737            || built_in_ids().any(|known| known == id)
738            || ids[..index].contains(id)
739    });
740    if refused {
741        diagnostics.error("INVALID_RULESET", "ruleset");
742        return None;
743    }
744    Some(RulesetFacts {
745        detector_ids: ids,
746        digest: format!("sha256:{}", to_hex(&sha256(bytes))),
747    })
748}
749
750#[inline(never)]
751fn resolve_policy(
752    request: &ConfigRequest<'_>,
753    diagnostics: &mut Diagnostics,
754) -> (PolicyFacts, bool) {
755    match (request.action_policy, request.callback) {
756        (Some(_), true) => {
757            diagnostics.error("INVALID_OPTIONS", "actionPolicy");
758            (PolicyFacts::Default, true)
759        }
760        (Some(bytes), false) => match load_action_policy(bytes) {
761            Ok(policy) => (
762                PolicyFacts::Document {
763                    digest: format!("sha256:{}", policy.document_sha256_hex()),
764                    rule_count: policy.rule_count(),
765                    policy,
766                },
767                true,
768            ),
769            Err(error) => {
770                let path = error.rule_index().map_or_else(
771                    || "actionPolicy".to_owned(),
772                    |index| format!("actionPolicy.rules[{index}]"),
773                );
774                diagnostics.error("INVALID_ACTION_POLICY", &path);
775                (PolicyFacts::Default, true)
776            }
777        },
778        (None, true) => (PolicyFacts::Callback, true),
779        (None, false) => (PolicyFacts::Default, false),
780    }
781}
782
783/// The warnings and notes that need the resolved facts.
784#[inline(never)]
785fn advise(
786    manifest: &ArtifactManifest,
787    effective: &Effective<'_>,
788    request: &ConfigRequest<'_>,
789    diagnostics: &mut Diagnostics,
790) {
791    if effective.enabled.is_empty() {
792        diagnostics.push(
793            ConfigSeverity::Warning,
794            "NO_BUILT_IN_DETECTORS",
795            "detection",
796        );
797    }
798    if effective.enabled.len() < manifest.detector_ids().count() {
799        diagnostics.push(
800            ConfigSeverity::Info,
801            "OVERLAP_OUTCOMES_MAY_CHANGE",
802            "detection",
803        );
804    }
805    match &effective.policy {
806        PolicyFacts::Document { policy, .. } => {
807            let ruleset: &[String] = effective
808                .ruleset
809                .as_ref()
810                .map_or(&[], |facts| &facts.detector_ids);
811            policy_diagnostics::analyze(
812                policy,
813                &policy_diagnostics::Context {
814                    manifest,
815                    enabled: &effective.enabled,
816                    ruleset_ids: ruleset,
817                    ruleset_present: effective.ruleset.is_some(),
818                    pii_active: !effective.pii.is_off(),
819                    closed_types: request.closed_types,
820                    closed_detectors: request.closed_detectors,
821                },
822                diagnostics,
823            );
824        }
825        PolicyFacts::Callback => diagnostics.push(
826            ConfigSeverity::Info,
827            policy_diagnostics::UNCERTAIN,
828            "actionPolicy",
829        ),
830        PolicyFacts::Default => {}
831    }
832}
833
834fn owner_word(manifest: &ArtifactManifest) -> &'static str {
835    match manifest.kind() {
836        ArtifactKind::RustRegistry => "registry",
837        _ => "initialize",
838    }
839}
840
841const fn origin(given: bool) -> &'static str {
842    if given { "runtime" } else { "artifact-default" }
843}
844
845/// `sha256:` and the lowercase hex of the digest of `text`.
846fn sha256_text(text: &str) -> String {
847    format!("sha256:{}", to_hex(&sha256(text.as_bytes())))
848}
849
850// The documents below are rendered with `format!` rather than a JSON writer:
851// every string they hold is a fixed word, a catalog id, a validated
852// identifier, a selector or a digest, none of which needs escaping, and a
853// format string is data, where a writer is code that ships in every
854// WebAssembly artifact. Every object's members are written in bytewise order,
855// which is the canonical form a digest is taken over.
856
857/// A JSON array of strings.
858struct Strs<'a>(&'a [&'a str]);
859
860impl fmt::Display for Strs<'_> {
861    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
862        formatter.write_str("[")?;
863        for (index, item) in self.0.iter().enumerate() {
864            if index > 0 {
865                formatter.write_str(",")?;
866            }
867            write!(formatter, "\"{item}\"")?;
868        }
869        formatter.write_str("]")
870    }
871}
872
873/// A JSON string, or `null`.
874struct OptStr<'a>(Option<&'a str>);
875
876impl fmt::Display for OptStr<'_> {
877    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
878        match self.0 {
879            Some(text) => write!(formatter, "\"{text}\""),
880            None => formatter.write_str("null"),
881        }
882    }
883}
884
885/// A JSON integer, or `null`.
886struct OptInt(Option<usize>);
887
888impl fmt::Display for OptInt {
889    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
890        match self.0 {
891            Some(number) => write!(formatter, "{number}"),
892            None => formatter.write_str("null"),
893        }
894    }
895}
896
897/// Everything a snapshot document states, borrowed, so the same facts render
898/// twice: once as the canonical form a digest is taken over and once as the
899/// emitted document.
900struct SnapshotFacts<'a> {
901    manifest: &'a ArtifactManifest,
902    effective: &'a Effective<'a>,
903    disclose_ruleset: bool,
904    activation: &'a str,
905    disabled: &'a [&'a str],
906    detection_digest: &'a str,
907    inert: bool,
908}
909
910impl SnapshotFacts<'_> {
911    /// Renders the snapshot. The canonical form (`digest` absent, `schema` in
912    /// its bytewise place) is what the digest is taken over; the emitted form
913    /// (`schema_first`, with `digest` between `detectionDigest` and `effects`)
914    /// is the document.
915    #[allow(
916        clippy::too_many_lines,
917        reason = "one format string states the whole document in bytewise order; splitting it would scatter that order"
918    )]
919    fn render(&self, schema_first: bool, digest: Option<&str>) -> String {
920        const SCHEMA: &str = "\"schema\":\"config-snapshot/v1\"";
921        let manifest = self.manifest;
922        let effective = self.effective;
923        let head = if schema_first {
924            format!("{SCHEMA},")
925        } else {
926            String::new()
927        };
928        let tail = if schema_first {
929            String::new()
930        } else {
931            format!(",{SCHEMA}")
932        };
933        let digest_member =
934            digest.map_or_else(String::new, |digest| format!("\"digest\":\"{digest}\","));
935
936        let (policy_source, policy_digest, policy_rules) = match &effective.policy {
937            PolicyFacts::Default => ("default", None, None),
938            PolicyFacts::Document {
939                digest, rule_count, ..
940            } => ("document", Some(digest.as_str()), Some(*rule_count)),
941            PolicyFacts::Callback => ("callback", None, None),
942        };
943        let policy_revision = policy_rules.map(|_| 1);
944        let explainable = !matches!(effective.policy, PolicyFacts::Callback);
945
946        let compiled = manifest.detector_ids().count();
947        let unavailable: Vec<&str> = manifest.not_included_ids().collect();
948        let families: Vec<&str> = effective
949            .pii
950            .families()
951            .iter()
952            .map(String::as_str)
953            .collect();
954        let selectors: Vec<&str> = effective
955            .pii
956            .selectors()
957            .iter()
958            .map(String::as_str)
959            .collect();
960        let owner = owner_word(manifest);
961
962        let ruleset = effective.ruleset.as_ref();
963        let rs_ids: Vec<&str> = ruleset
964            .filter(|_| self.disclose_ruleset)
965            .map(|facts| facts.detector_ids.iter().map(String::as_str).collect())
966            .unwrap_or_default();
967        let rs_ids_json = if ruleset.is_some() && self.disclose_ruleset {
968            Strs(&rs_ids).to_string()
969        } else {
970            "null".to_owned()
971        };
972        let rs_digest = ruleset
973            .filter(|_| self.disclose_ruleset)
974            .map(|facts| facts.digest.as_str());
975        let rs_count = ruleset.map(|facts| facts.detector_ids.len());
976        let rs_present = ruleset.is_some();
977        let rs_disclosed = rs_present && self.disclose_ruleset;
978        let rs_revision = rs_count.map(|_| 1);
979
980        let enabled = Strs(&effective.enabled);
981        let disabled = Strs(self.disabled);
982        let unavailable = Strs(&unavailable);
983        let families = Strs(&families);
984        let selectors = Strs(&selectors);
985        let policy_digest = OptStr(policy_digest);
986        let policy_rules = OptInt(policy_rules);
987        let policy_revision = OptInt(policy_revision);
988        let rs_digest = OptStr(rs_digest);
989        let rs_count = OptInt(rs_count);
990        let rs_revision = OptInt(rs_revision);
991        let kind = manifest.kind().as_str();
992        let manifest_digest = manifest.digest();
993        let profile = manifest.profile().as_str();
994        let composition_id = OptStr(manifest.composition_id());
995        let version = crate::VERSION;
996        let custom = effective.custom_detectors;
997        let enabled_count = effective.enabled.len();
998        let mode = effective.detection_mode;
999        let detection_digest = self.detection_digest;
1000        let inert = self.inert;
1001        let overlap = !self.disabled.is_empty();
1002        let max_findings = effective.max_findings;
1003        let max_input = effective.max_input_bytes;
1004        let origin_policy = effective.policy_origin;
1005        let origin_detection = effective.detection_origin;
1006        let origin_findings = effective.max_findings_origin;
1007        let origin_input = effective.max_input_origin;
1008        let origin_pii = effective.pii_origin;
1009        let origin_ruleset = origin(rs_present);
1010        let activation = self.activation;
1011        let pii_available = manifest.pii_linked();
1012
1013        format!(
1014            "{{{head}\"actionPolicy\":{{\"digest\":{policy_digest},\"explainable\":{explainable},\
1015             \"revision\":{policy_revision},\"ruleCount\":{policy_rules},\"source\":\"{policy_source}\"}},\
1016             \"artifact\":{{\"compositionId\":{composition_id},\"kind\":\"{kind}\",\"manifestDigest\":\"{manifest_digest}\",\
1017             \"profile\":\"{profile}\",\"version\":\"{version}\"}},\
1018             \"detection\":{{\"compiledCount\":{compiled},\"customDetectors\":{custom},\"disabled\":{disabled},\
1019             \"enabled\":{enabled},\"enabledCount\":{enabled_count},\"mode\":\"{mode}\",\"unavailable\":{unavailable}}},\
1020             \"detectionDigest\":\"{detection_digest}\",{digest_member}\
1021             \"effects\":{{\"inert\":{inert},\"overlapOutcomesMayChange\":{overlap}}},\
1022             \"limits\":{{\"maxFindings\":{max_findings},\"maxInputBytes\":{max_input}}},\
1023             \"origins\":{{\"actionPolicy\":\"{origin_policy}\",\"detection\":\"{origin_detection}\",\
1024             \"maxFindings\":\"{origin_findings}\",\"maxInputBytes\":\"{origin_input}\",\"pii\":\"{origin_pii}\",\
1025             \"ruleset\":\"{origin_ruleset}\"}},\
1026             \"owners\":{{\"actionPolicy\":\"call\",\"detection\":\"{owner}\",\"incremental\":\"session\",\
1027             \"limits\":\"call\",\"pii\":\"{owner}\",\"ruleset\":\"call\"}},\
1028             \"pii\":{{\"activation\":\"{activation}\",\"available\":{pii_available},\"families\":{families},\
1029             \"selectors\":{selectors}}},\
1030             \"ruleset\":{{\"detectorCount\":{rs_count},\"detectorIds\":{rs_ids_json},\"digest\":{rs_digest},\
1031             \"disclosed\":{rs_disclosed},\"present\":{rs_present},\"revision\":{rs_revision}}}{tail}}}"
1032        )
1033    }
1034}
1035
1036fn build_snapshot(
1037    manifest: &ArtifactManifest,
1038    effective: &Effective<'_>,
1039    disclose_ruleset: bool,
1040) -> ConfigSnapshot {
1041    let disabled: Vec<&str> = manifest
1042        .detector_ids()
1043        .filter(|id| !effective.enabled.contains(id))
1044        .collect();
1045    let activation = effective.pii.activation_identity(manifest.profile());
1046    let inert = effective.enabled.is_empty()
1047        && effective.ruleset.is_none()
1048        && effective.pii.is_off()
1049        && effective.custom_detectors == 0;
1050
1051    // What makes two detections the same: the artifact, the enabled
1052    // detectors, the ruleset's bytes and the PII activation.
1053    let detection_digest = {
1054        let enabled = Strs(&effective.enabled);
1055        let manifest_digest = manifest.digest();
1056        let ruleset_digest = OptStr(
1057            effective
1058                .ruleset
1059                .as_ref()
1060                .map(|facts| facts.digest.as_str()),
1061        );
1062        sha256_text(&format!(
1063            "{{\"enabled\":{enabled},\"manifestDigest\":\"{manifest_digest}\",\
1064             \"piiActivation\":\"{activation}\",\"rulesetDigest\":{ruleset_digest}}}"
1065        ))
1066    };
1067
1068    let facts = SnapshotFacts {
1069        manifest,
1070        effective,
1071        disclose_ruleset,
1072        activation: &activation,
1073        disabled: &disabled,
1074        detection_digest: &detection_digest,
1075        inert,
1076    };
1077    // The digest is over the canonical form without `digest`; the document
1078    // that is emitted carries it, with `schema` first.
1079    let digest = sha256_text(&facts.render(false, None));
1080    let json = facts.render(true, Some(&digest));
1081    ConfigSnapshot {
1082        json,
1083        digest,
1084        detection_digest,
1085        enabled: effective
1086            .enabled
1087            .iter()
1088            .map(|id| (*id).to_owned())
1089            .collect(),
1090        inert,
1091        selection: effective.selection.clone(),
1092        pii: effective.pii.clone(),
1093        limits: (effective.max_input_bytes, effective.max_findings),
1094    }
1095}
1096
1097fn envelope(
1098    snapshot: Option<ConfigSnapshot>,
1099    items: Vec<ConfigDiagnostic>,
1100    truncated: bool,
1101) -> ConfigResolution {
1102    let mut rendered = String::new();
1103    for (index, item) in items.iter().enumerate() {
1104        if index > 0 {
1105            rendered.push(',');
1106        }
1107        let (code, path, severity) = (item.code, &item.path, item.severity.as_str());
1108        let id = OptStr(item.id.as_deref());
1109        // `path` is fixed syntax: letters, digits and `.@[]$` only. A rule id
1110        // and a detector id are validated identifiers.
1111        let _ = write!(
1112            rendered,
1113            "{{\"code\":\"{code}\",\"id\":{id},\"path\":\"{path}\","
1114        );
1115        if let Some(related) = &item.related {
1116            let _ = write!(rendered, "\"related\":\"{related}\",");
1117        }
1118        let _ = write!(rendered, "\"severity\":\"{severity}\"}}");
1119    }
1120    let ok = snapshot.is_some();
1121    // The snapshot is spliced in as already-rendered JSON so its member order
1122    // and digest are exactly what its own accessors report.
1123    let snapshot_json = snapshot
1124        .as_ref()
1125        .map_or("null", |snapshot| snapshot.json.as_str());
1126    let json = format!(
1127        "{{\"schema\":\"config-resolution/v1\",\"diagnostics\":{{\"schema\":\"config-diagnostics/v1\",\
1128         \"items\":[{rendered}],\"truncated\":{truncated}}},\"ok\":{ok},\"snapshot\":{snapshot_json}}}"
1129    );
1130    ConfigResolution {
1131        json,
1132        snapshot,
1133        diagnostics: items,
1134    }
1135}
1136
1137/// Describes the configuration a registry is fixed to: its enabled built-in
1138/// detectors, PII selection and the artifact's defaults for everything a call
1139/// supplies. Input-free: it reads no scan input, builds nothing and does not
1140/// change the registry.
1141///
1142/// Custom detectors the registry holds are code, not data; they are counted
1143/// in `detection.customDetectors` and are not described further.
1144///
1145/// A registry that is not a profile registry of `manifest`'s artifact (it has
1146/// no built-in the manifest lacks, and every id it holds is a manifest id or a
1147/// custom one) is described by what it holds; ids the manifest does not
1148/// include are never reported as enabled.
1149#[must_use]
1150pub fn describe_config(manifest: &ArtifactManifest, registry: &DetectorRegistry) -> ConfigSnapshot {
1151    let included: Vec<&str> = manifest.detector_ids().collect();
1152    let enabled: Vec<&str> = registry
1153        .built_in_ids()
1154        .filter(|id| included.contains(id))
1155        .collect();
1156    let custom = registry.len()
1157        - registry.built_in_ids().count()
1158        - usize::from(registry.contains(PII_ADAPTER_ID));
1159    let effective = Effective {
1160        selection: registry.detection().clone(),
1161        detection_mode: registry.detection().mode(),
1162        detection_origin: origin(!registry.detection().is_all()),
1163        enabled,
1164        custom_detectors: custom,
1165        pii: registry.pii_selection().clone(),
1166        pii_origin: origin(!registry.pii_selection().is_off()),
1167        ruleset: None,
1168        policy: PolicyFacts::Default,
1169        policy_origin: origin(false),
1170        max_input_bytes: DEFAULT_MAX_INPUT_BYTES,
1171        max_input_origin: origin(false),
1172        max_findings: DEFAULT_MAX_FINDINGS,
1173        max_findings_origin: origin(false),
1174    };
1175    build_snapshot(manifest, &effective, false)
1176}