Skip to main content

fallow_security/
lib.rs

1//! Data-driven catalogue of syntactic security-sink candidate matchers.
2//!
3//! The catalogue is community-maintainable: every matcher lives in
4//! `crates/security/data/security_matchers.toml`, embedded via `include_str!` and
5//! parsed once behind a `OnceLock`. There is NO regeneration step. Adding a
6//! category is a single `[[matcher]]` TOML edit plus ZERO Rust enum or
7//! discriminant churn (the `tainted_sink` detector matches captured
8//! category-blind `SinkSite`s against the loaded catalogue).
9//!
10//! Findings are CANDIDATES for downstream agent verification, NOT verified
11//! vulnerabilities: fallow is deterministic and syntactic, never taint-proof.
12//! Matchers default to non-literal arguments. A row can opt into narrowly
13//! captured literal or context predicates when the literal itself is the signal.
14//!
15//! User documentation is on [`fallow security`](https://fallow.tools/docs/cli/security/).
16
17use fallow_config::EffectKind;
18use fallow_types::extract::{SinkArgKind, SinkLiteralValue, SinkShape};
19use rustc_hash::FxHashSet;
20
21mod identity;
22mod predicates;
23mod provenance;
24mod rules;
25mod severity;
26mod stable_id;
27
28pub use identity::{security_rule_id, stamp_security_finding_ids};
29pub use provenance::{ProvenanceBindings, import_source_matches};
30pub use rules::{
31    enable_security_rules, resolve_security_finding_severity, retain_enabled_security_findings,
32    security_rules_can_error,
33};
34pub use severity::{derive_security_severity, security_catalogue_title};
35pub use stable_id::STABLE_SECURITY_ID_SCHEME;
36
37pub const HARDCODED_SECRET_CATEGORY_ID: &str = "hardcoded-secret";
38const HARDCODED_SECRET_CATEGORY_TITLE: &str = "Hardcoded secret candidate";
39
40/// Embedded catalogue source. Because it is `include_str!`-embedded at compile
41/// time, a green `security_catalogue_parses` test guarantees the released
42/// binary parses.
43const CATALOGUE_TOML: &str = include_str!("../data/security_matchers.toml");
44
45#[derive(serde::Deserialize)]
46struct RawCatalogue {
47    #[serde(default)]
48    matcher: Vec<RawMatcher>,
49    #[serde(default)]
50    source: Vec<RawSource>,
51}
52
53/// A raw untrusted-source row (issue #859). Names member-access paths that carry
54/// attacker-controlled input; the analyze layer matches captured tainted-binding
55/// source paths against these to mark source-tainted locals.
56#[derive(serde::Deserialize)]
57struct RawSource {
58    id: String,
59    title: String,
60    /// Optional framework enabler, same semantics as matcher enablers.
61    #[serde(default)]
62    enabler: Option<String>,
63    path_patterns: Vec<String>,
64    /// Optional allowlist of receiver names for leading-`*.` wildcard patterns
65    /// (issue #1092). When non-empty, a wildcard pattern fires only if the
66    /// matched member's receiver is one of these (case-insensitive), so
67    /// `*.query` matches `req.query` but not `db.query`. Empty / absent leaves
68    /// the row ungated (every receiver matches). Has no effect on exact
69    /// patterns, whose receiver is fixed in the pattern itself.
70    #[serde(default)]
71    receiver_allowlist: Vec<String>,
72    /// Marks a deployment-secret source (`process.env`). A secret is not
73    /// attacker-controlled input: it backs only the rows that name it in
74    /// `requires_source_kinds`, and it never starts an untrusted-source trace.
75    #[serde(default)]
76    secret: bool,
77}
78
79#[derive(serde::Deserialize)]
80struct RawMatcher {
81    id: String,
82    cwe: u32,
83    title: String,
84    effect: EffectKind,
85    /// Kebab-case shape string, validated into [`SinkShape`].
86    sink_shape: String,
87    callee_patterns: Vec<String>,
88    arg_index: u32,
89    /// Optional variadic gate: when `true`, the row also matches every
90    /// argument after `arg_index`. Lets `path.join` / `path.resolve` inspect
91    /// each path segment, not only the first one (issue #3712).
92    #[serde(default)]
93    variadic: bool,
94    evidence_template: String,
95    #[serde(default)]
96    import_provenance: Option<String>,
97    /// Optional framework enabler: a package name that gates this row on the
98    /// active framework (issue #861). The plugin system already activates on the
99    /// declared dependency set, so a row carrying `enabler = "@angular/platform-browser"`
100    /// fires only when that package (or, with a trailing `/`, any package under
101    /// that prefix) is present in the project's declared dependencies. Lets a
102    /// framework-specific idiom (`bypassSecurityTrustHtml`, `dangerouslySetInnerHTML`)
103    /// be recognized with higher precision without a new enum variant. Unset means
104    /// the row is global (the prior behavior).
105    #[serde(default)]
106    enabler: Option<String>,
107    /// Optional allowlist of argument shapes. When set, the captured sink site's
108    /// `arg_kind` must be one of the listed kebab-case kinds for the matcher to
109    /// fire. Lets a matcher require the unsafe SQL shapes (`concat`,
110    /// `template-with-subst`) and exclude the safely-parameterized forms
111    /// (`object` for `.execute({ sql, args })`, the bare `sql` tag). Unset means
112    /// any non-literal argument shape matches (the prior behavior).
113    #[serde(default)]
114    arg_kinds: Option<Vec<String>>,
115    /// Optional string-literal equality predicates for literal-aware rows.
116    #[serde(default)]
117    literal_values: Option<Vec<String>>,
118    /// Optional string-literal substring predicates for literal-aware rows.
119    #[serde(default)]
120    literal_contains: Option<Vec<String>>,
121    /// Optional integer-literal equality predicates for literal-aware rows.
122    #[serde(default)]
123    literal_integers: Option<Vec<i64>>,
124    /// Optional object-literal property equality predicates.
125    #[serde(default)]
126    object_properties: Option<Vec<RawObjectPropertyPredicate>>,
127    /// Optional object-literal flags that are unsafe when missing or `false`.
128    #[serde(default)]
129    object_missing_or_false: Option<Vec<String>>,
130    /// Optional object-literal keys that are unsafe when absent. Unlike
131    /// `object_missing_or_false`, this checks key presence only and refuses
132    /// incomplete object shapes.
133    #[serde(default)]
134    object_missing: Option<Vec<String>>,
135    /// Optional call options that must be able to hold a value other than
136    /// `false`. The row matches unless the extractor proved that each listed
137    /// option is absent or `false`.
138    #[serde(default)]
139    options_may_enable: Option<Vec<String>>,
140    /// Optional context-name keywords for zero-arg sinks like `Math.random()`.
141    #[serde(default)]
142    context_keywords: Option<Vec<String>>,
143    /// Optional precision gate: require the captured sink argument to reference
144    /// a local binding that came from a configured untrusted source.
145    #[serde(default)]
146    requires_source: bool,
147    /// Optional precision gate narrowing `requires_source` to SPECIFIC source
148    /// kinds by catalogue source id (issue #890). Empty (default) admits any
149    /// matched source (the prior behavior); when set, the matched source's id
150    /// must be one of these. Lets `secret-to-network` fire only when backed by a
151    /// SECRET source (`process-env` / `import-meta-env`), not request input
152    /// (which the `ssrf` rows already cover).
153    #[serde(default)]
154    requires_source_kinds: Vec<String>,
155    /// Optional precision gate, looser than `requires_source`: the sink must
156    /// either trace to a source in its argument, or sit in a module that reads
157    /// untrusted input or whose direct importers all read untrusted input.
158    #[serde(default)]
159    requires_module_source: bool,
160    /// Optional source kinds that neither back this row nor satisfy
161    /// `requires_module_source` (for example `process-argv` for a path join:
162    /// the user who runs a CLI owns the file system it reads).
163    #[serde(default)]
164    ignored_source_kinds: Vec<String>,
165    /// Optional: let a deployment-secret source (`secret = true`) back this
166    /// row. Off by default, because a secret is not attacker input.
167    #[serde(default)]
168    secret_sources: bool,
169}
170
171#[derive(Debug, serde::Deserialize)]
172struct RawObjectPropertyPredicate {
173    key: String,
174    #[serde(default)]
175    string: Option<String>,
176    #[serde(default)]
177    boolean: Option<bool>,
178    #[serde(default)]
179    integer: Option<i64>,
180    #[serde(default)]
181    null: bool,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub enum LiteralPredicate {
186    String(String),
187    Integer(i64),
188    Boolean(bool),
189    Null,
190}
191
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct ObjectPropertyPredicate {
194    key: String,
195    value: LiteralPredicate,
196}
197
198/// A pre-segmented callee pattern. Matching is segment-aware (NOT substring):
199/// the pattern is split on `.`, a leading `*` segment means "any object"
200/// (`*.innerHTML` matches `el.innerHTML` and `this.node.innerHTML` by
201/// suffix-matching the trailing non-`*` segments), and a trailing `*` segment
202/// means "any member" (`child_process.*` matches `child_process.exec` by
203/// prefix-matching the leading non-`*` segments). The security catalogue uses
204/// exact and leading-wildcard rows; the trailing form serves the boundary
205/// forbidden-call detector.
206#[derive(Debug, Clone)]
207pub struct CalleePattern {
208    /// The literal source pattern (`"*.innerHTML"`, `"child_process.exec"`),
209    /// surfaced in evidence rendering as `{pattern}`.
210    raw: String,
211    /// Segments between any leading and trailing `*` (e.g. `["innerHTML"]`
212    /// for `*.innerHTML`, `["child_process"]` for `child_process.*`,
213    /// `["child_process", "exec"]` for the exact dotted form).
214    suffix_segments: Vec<String>,
215    /// Whether the pattern began with a `*` wildcard object segment.
216    leading_wildcard: bool,
217    /// Whether the pattern ended with a `*` wildcard member segment.
218    trailing_wildcard: bool,
219}
220
221impl CalleePattern {
222    /// Parse a raw pattern string into its segmented form. Returns `None` for
223    /// an empty or whitespace-only pattern. Public constructor for non-security
224    /// reusers of the segment-aware matcher (the boundary forbidden-call
225    /// detector); the catalogue's own rows go through the same parser.
226    #[must_use]
227    pub fn parse(raw: &str) -> Option<Self> {
228        parse_callee_pattern(raw)
229    }
230
231    /// The original pattern text, for evidence templating.
232    #[must_use]
233    pub fn raw(&self) -> &str {
234        &self.raw
235    }
236
237    /// Segment-aware match against a captured dotted/bare callee path.
238    ///
239    /// With a leading `*`, the trailing segments must equal the tail of the
240    /// candidate's segments (suffix match), so `*.innerHTML` matches
241    /// `el.innerHTML` but not `el.innerHTMLFoo`. With a trailing `*`, the
242    /// leading segments must equal the head of the candidate's segments
243    /// (prefix match), so `child_process.*` matches `child_process.exec` but
244    /// not the bare `child_process`. Without either, the whole segment list
245    /// must match exactly, so `fetch` matches `fetch` but not `myfetch`.
246    /// Patterns carrying BOTH wildcards match nothing (rejected by the config
247    /// layer; never produced by catalogue rows).
248    #[must_use]
249    pub fn matches(&self, callee_path: &str) -> bool {
250        // With only wildcards and no concrete segments, match nothing.
251        if self.suffix_segments.is_empty() || (self.leading_wildcard && self.trailing_wildcard) {
252            return false;
253        }
254        let candidate: Vec<&str> = callee_path.split('.').collect();
255        if self.leading_wildcard {
256            // A leading `*.` requires at least one object segment before the
257            // suffix, so the candidate must have strictly more segments than
258            // the suffix (`*.innerHTML` matches `el.innerHTML`, not `innerHTML`).
259            if self.suffix_segments.len() >= candidate.len() {
260                return false;
261            }
262            let tail = &candidate[candidate.len() - self.suffix_segments.len()..];
263            self.suffix_segments
264                .iter()
265                .zip(tail)
266                .all(|(pat, seg)| pat == seg)
267        } else if self.trailing_wildcard {
268            // A trailing `.*` requires at least one member segment after the
269            // prefix (`child_process.*` matches `child_process.exec`, not the
270            // bare `child_process`).
271            if self.suffix_segments.len() >= candidate.len() {
272                return false;
273            }
274            let head = &candidate[..self.suffix_segments.len()];
275            self.suffix_segments
276                .iter()
277                .zip(head)
278                .all(|(pat, seg)| pat == seg)
279        } else {
280            self.suffix_segments.len() == candidate.len()
281                && self
282                    .suffix_segments
283                    .iter()
284                    .zip(&candidate)
285                    .all(|(pat, seg)| pat == seg)
286        }
287    }
288
289    /// The receiver segment immediately before this pattern's matched suffix,
290    /// for a leading-`*.` wildcard pattern: `*.query` against `db.query` returns
291    /// `Some("db")`, against `ctx.req.query` returns `Some("req")` (the segment
292    /// right before `query`, which is the receiver of the matched member). Used
293    /// by a source row's receiver allowlist to keep HTTP-input patterns from
294    /// firing on ORM / data-access receivers (issue #1092). Returns `None` for
295    /// an exact (non-wildcard) pattern, whose receiver is fixed in the pattern
296    /// itself, and for any `callee_path` this pattern does not match.
297    #[must_use]
298    fn matched_receiver<'p>(&self, callee_path: &'p str) -> Option<&'p str> {
299        if !self.leading_wildcard || !self.matches(callee_path) {
300            return None;
301        }
302        let candidate: Vec<&str> = callee_path.split('.').collect();
303        // `matches` guarantees `candidate.len() > suffix_segments.len()` for a
304        // leading-wildcard hit, so the receiver index is always in range.
305        let recv_idx = candidate.len() - self.suffix_segments.len() - 1;
306        candidate.get(recv_idx).copied()
307    }
308}
309
310/// Parse a raw pattern string into its segmented form. Returns `None` for an
311/// empty or whitespace-only pattern (rejected at parse time).
312fn parse_callee_pattern(raw: &str) -> Option<CalleePattern> {
313    if raw.trim().is_empty() {
314        return None;
315    }
316    let mut segments: Vec<&str> = raw.split('.').collect();
317    let leading_wildcard = segments.first() == Some(&"*");
318    if leading_wildcard {
319        segments.remove(0);
320    }
321    let trailing_wildcard = segments.last() == Some(&"*");
322    if trailing_wildcard {
323        segments.pop();
324    }
325    Some(CalleePattern {
326        raw: raw.to_string(),
327        suffix_segments: segments.into_iter().map(str::to_string).collect(),
328        leading_wildcard,
329        trailing_wildcard,
330    })
331}
332
333/// A parsed, validated matcher with the sink shape resolved to the typed enum
334/// and callee patterns pre-segmented for O(1)-ish matching.
335#[derive(Debug, Clone)]
336pub struct Matcher {
337    pub id: String,
338    pub cwe: u32,
339    pub title: String,
340    pub effect: EffectKind,
341    pub sink_shape: SinkShape,
342    pub callee_patterns: Vec<CalleePattern>,
343    pub arg_index: u32,
344    /// Whether the row also matches every argument after `arg_index`. A
345    /// variadic row reports at most one candidate per call.
346    pub variadic: bool,
347    pub evidence_template: String,
348    pub import_provenance: Option<String>,
349    /// Framework enabler package gate (issue #861). `None` = global row.
350    /// `Some("pkg")` requires an exact dependency match; `Some("@scope/")`
351    /// (trailing slash) requires any dependency under that prefix.
352    pub enabler: Option<String>,
353    /// Resolved allowlist of admitted argument shapes. `None` admits any
354    /// non-literal shape; `Some` requires the captured `arg_kind` to be listed.
355    pub arg_kinds: Option<Vec<SinkArgKind>>,
356    /// Whether this matcher only fires when the sink argument traces to a
357    /// configured untrusted source binding.
358    pub requires_source: bool,
359    /// When non-empty, narrows `requires_source` to these catalogue source ids
360    /// (issue #890): the matched source's id must be one of these. Empty admits
361    /// any matched source.
362    pub requires_source_kinds: Vec<String>,
363    /// Whether this matcher fires only when the sink argument traces to an
364    /// untrusted source, or the sink module or every direct importer reads
365    /// untrusted input.
366    pub requires_module_source: bool,
367    /// Source kinds that neither back this row nor satisfy
368    /// `requires_module_source`.
369    pub ignored_source_kinds: Vec<String>,
370    /// Whether a deployment-secret source can back this row without naming
371    /// its kind in `requires_source_kinds`.
372    pub secret_sources: bool,
373    /// String-literal values admitted by this row.
374    pub literal_values: Vec<String>,
375    /// String fragments admitted by this row.
376    pub literal_contains: Vec<String>,
377    /// Integer literal values admitted by this row.
378    pub literal_integers: Vec<i64>,
379    /// Required literal object properties.
380    pub object_properties: Vec<ObjectPropertyPredicate>,
381    /// Object properties whose absence or boolean `false` makes the row match.
382    pub object_missing_or_false: Vec<String>,
383    /// Object keys whose absence makes the row match.
384    pub object_missing: Vec<String>,
385    /// Call options that make the row match when they can hold a value other
386    /// than `false`.
387    pub options_may_enable: Vec<String>,
388    /// Context-name keywords admitted by this row.
389    pub context_keywords: Vec<String>,
390}
391
392/// A parsed, validated untrusted-source matcher (issue #859). Its
393/// `path_patterns` reuse the segment-aware [`CalleePattern`] engine: a leading
394/// `*.` matches any object prefix (`*.query` matches `req.query` and
395/// `ctx.req.query`); a bare path matches exactly.
396#[derive(Debug, Clone)]
397pub struct SourceMatcher {
398    id: String,
399    title: String,
400    enabler: Option<String>,
401    path_patterns: Vec<CalleePattern>,
402    /// Lowercased receiver allowlist for leading-wildcard patterns (issue
403    /// #1092). Empty leaves the row ungated.
404    receiver_allowlist: Vec<String>,
405    /// Whether this row names a deployment secret, not attacker input.
406    secret: bool,
407}
408
409impl SourceMatcher {
410    #[must_use]
411    fn matches_with_extra_receivers(
412        &self,
413        source_path: &str,
414        extra_receivers: &FxHashSet<String>,
415    ) -> bool {
416        self.path_patterns.iter().any(|p| {
417            p.matches(source_path) && self.receiver_allowed(p, source_path, extra_receivers)
418        })
419    }
420
421    /// Whether `pattern`'s match on `source_path` is admitted by the receiver
422    /// allowlist. An empty allowlist admits everything. For a leading-wildcard
423    /// pattern the matched receiver must be in the allowlist (case-insensitive);
424    /// an exact pattern (receiver fixed in the pattern) is always admitted.
425    fn receiver_allowed(
426        &self,
427        pattern: &CalleePattern,
428        source_path: &str,
429        extra_receivers: &FxHashSet<String>,
430    ) -> bool {
431        if self.receiver_allowlist.is_empty() {
432            return true;
433        }
434        match pattern.matched_receiver(source_path) {
435            Some(receiver) => {
436                self.receiver_allowlist
437                    .iter()
438                    .any(|allowed| allowed.eq_ignore_ascii_case(receiver))
439                    || extra_receivers.contains(&receiver.to_ascii_lowercase())
440            }
441            None => true,
442        }
443    }
444
445    /// Whether this source row's framework enabler is satisfied by the
446    /// project's declared dependency set. Unset means global.
447    #[must_use]
448    fn enabler_satisfied(&self, declared_deps: &rustc_hash::FxHashSet<String>) -> bool {
449        enabler_satisfied(self.enabler.as_deref(), declared_deps)
450    }
451}
452
453/// The parsed catalogue: an ordered list of sink matchers plus untrusted-source
454/// matchers. Order is preserved from the TOML so the detector can break on the
455/// first match deterministically.
456#[derive(Debug)]
457pub struct Catalogue {
458    matchers: Vec<Matcher>,
459    sources: Vec<SourceMatcher>,
460}
461
462impl Matcher {
463    /// The first callee pattern that matches the given path, if any. The first
464    /// match wins, matching the deterministic declaration order.
465    #[must_use]
466    pub fn first_matching_pattern(&self, callee_path: &str) -> Option<&CalleePattern> {
467        self.callee_patterns.iter().find(|p| p.matches(callee_path))
468    }
469
470    /// Whether a captured argument position is admitted by this matcher. A
471    /// variadic row admits `arg_index` and every later position.
472    #[must_use]
473    pub fn admits_arg_index(&self, arg_index: u32) -> bool {
474        arg_index == self.arg_index || (self.variadic && arg_index > self.arg_index)
475    }
476
477    /// Whether a captured argument shape is admitted by this matcher. `None`
478    /// `arg_kinds` admits any shape; `Some` requires the kind to be listed.
479    #[must_use]
480    pub fn admits_arg_kind(&self, arg_kind: SinkArgKind) -> bool {
481        self.arg_kinds
482            .as_ref()
483            .is_none_or(|kinds| kinds.contains(&arg_kind))
484    }
485
486    /// Whether this row has opted into matching a literal, object-property, or
487    /// context-only sink that is not covered by the default non-literal model.
488    #[must_use]
489    pub fn is_literal_aware(&self) -> bool {
490        !self.literal_values.is_empty()
491            || !self.literal_contains.is_empty()
492            || !self.literal_integers.is_empty()
493            || !self.object_properties.is_empty()
494            || !self.object_missing_or_false.is_empty()
495            || !self.object_missing.is_empty()
496            || !self.context_keywords.is_empty()
497            || self.arg_kinds.as_ref().is_some_and(|kinds| {
498                kinds
499                    .iter()
500                    .any(|kind| matches!(kind, SinkArgKind::Literal | SinkArgKind::NoArg))
501            })
502    }
503
504    /// Whether this matcher's framework enabler is satisfied by the project's
505    /// declared dependency set (issue #861). `None` enabler is always satisfied
506    /// (a global row). A `Some` enabler matches by exact package name, or, when
507    /// it ends with `/`, by prefix (`@angular/` matches `@angular/platform-browser`),
508    /// mirroring the plugin-system `enablers()` semantics so framework rows
509    /// activate on exactly the dependency universe the plugins do.
510    #[must_use]
511    pub fn enabler_satisfied(&self, declared_deps: &rustc_hash::FxHashSet<String>) -> bool {
512        enabler_satisfied(self.enabler.as_deref(), declared_deps)
513    }
514}
515
516fn enabler_satisfied(enabler: Option<&str>, declared_deps: &rustc_hash::FxHashSet<String>) -> bool {
517    let Some(enabler) = enabler else {
518        return true;
519    };
520    if let Some(prefix) = enabler.strip_suffix('/') {
521        // Trailing-slash prefix match, e.g. `@fastify/` -> `@fastify/static`.
522        // Also admit the bare scope name itself (`@fastify`).
523        declared_deps
524            .iter()
525            .any(|d| d == prefix || d.starts_with(enabler))
526    } else {
527        declared_deps.contains(enabler)
528    }
529}
530
531impl LiteralPredicate {
532    fn matches(&self, value: &SinkLiteralValue) -> bool {
533        match (self, value) {
534            (Self::String(expected), SinkLiteralValue::String(actual)) => {
535                expected.eq_ignore_ascii_case(actual)
536            }
537            (Self::Integer(expected), SinkLiteralValue::Integer(actual)) => expected == actual,
538            (Self::Boolean(expected), SinkLiteralValue::Boolean(actual)) => expected == actual,
539            (Self::Null, SinkLiteralValue::Null) => true,
540            _ => false,
541        }
542    }
543}
544
545impl Catalogue {
546    /// All matchers in declaration order.
547    #[must_use]
548    pub fn matchers(&self) -> &[Matcher] {
549        &self.matchers
550    }
551
552    /// The id + human title of the first untrusted-source matcher whose pattern,
553    /// optional framework enabler, and configured request-receiver extension
554    /// match the given source path.
555    #[must_use]
556    pub fn matching_source_for_deps_with_receivers(
557        &self,
558        source_path: &str,
559        declared_deps: &FxHashSet<String>,
560        request_receivers: &FxHashSet<String>,
561    ) -> Option<(&str, &str)> {
562        let empty_receivers = FxHashSet::default();
563        self.sources
564            .iter()
565            .find(|s| {
566                let extra_receivers = if s.id == "http-request-input" {
567                    request_receivers
568                } else {
569                    &empty_receivers
570                };
571                s.enabler_satisfied(declared_deps)
572                    && s.matches_with_extra_receivers(source_path, extra_receivers)
573            })
574            .map(|s| (s.id.as_str(), s.title.as_str()))
575    }
576
577    /// Whether the catalogue source id names a deployment secret
578    /// (`process-env`, `import-meta-env`) instead of attacker-controlled input.
579    #[must_use]
580    pub fn is_secret_source(&self, id: &str) -> bool {
581        self.sources.iter().any(|s| s.id == id && s.secret)
582    }
583
584    /// The human-readable title for a category id, if any matcher declares it.
585    #[must_use]
586    fn title_for(&self, id: &str) -> Option<&str> {
587        self.matchers
588            .iter()
589            .find(|m| m.id == id)
590            .map(|m| m.title.as_str())
591    }
592}
593
594/// The human-readable title for a category id, used by the CLI renderer.
595#[must_use]
596fn catalogue_title(id: &str) -> Option<&'static str> {
597    catalogue().title_for(id)
598}
599
600/// The catalogue id of the secret-to-network exfil category (CWE-201). Like
601/// [`HARDCODED_SECRET_CATEGORY_ID`], it is include-required: it runs only when
602/// listed in `security.categories.include`.
603const SECRET_TO_NETWORK_CATEGORY_ID: &str = "secret-to-network";
604
605/// Whether a `security.categories` id is include-required, i.e. it stays off
606/// even when no include list is set and fires only when named in
607/// `categories.include`. Both the standalone hardcoded-secret detector and the
608/// secret-to-network catalogue category are include-required.
609#[must_use]
610fn is_include_required_category(id: &str) -> bool {
611    id == HARDCODED_SECRET_CATEGORY_ID || id == SECRET_TO_NETWORK_CATEGORY_ID
612}
613
614/// A user-facing security candidate category, valid in `security.categories`
615/// `include` / `exclude`.
616#[derive(Debug, Clone)]
617pub struct SecurityCategory {
618    /// The category id used in `security.categories.include` / `exclude`.
619    pub id: String,
620    /// Human-readable title.
621    pub title: String,
622    /// The CWE number, when the category maps to one (`None` for the
623    /// entropy-based hardcoded-secret detector).
624    pub cwe: Option<u32>,
625    /// Whether the category runs only when explicitly named in
626    /// `categories.include`.
627    pub include_required: bool,
628}
629
630/// Every security candidate category an agent can name in
631/// `security.categories.include` / `exclude`, deduped by id and sorted.
632///
633/// This is the canonical, machine-readable vocabulary for the `security`
634/// config surface: the embedded catalogue's distinct sink categories plus the
635/// standalone hardcoded-secret detector. Because the catalogue is
636/// `include_str!`-embedded, the set is deterministic per build.
637#[must_use]
638pub fn security_categories() -> Vec<SecurityCategory> {
639    let mut seen = FxHashSet::default();
640    let mut out = Vec::new();
641    for matcher in catalogue().matchers() {
642        if seen.insert(matcher.id.clone()) {
643            out.push(SecurityCategory {
644                id: matcher.id.clone(),
645                title: matcher.title.clone(),
646                cwe: Some(matcher.cwe),
647                include_required: is_include_required_category(&matcher.id),
648            });
649        }
650    }
651    if seen.insert(HARDCODED_SECRET_CATEGORY_ID.to_owned()) {
652        out.push(SecurityCategory {
653            id: HARDCODED_SECRET_CATEGORY_ID.to_owned(),
654            title: HARDCODED_SECRET_CATEGORY_TITLE.to_owned(),
655            cwe: None,
656            include_required: true,
657        });
658    }
659    out.sort_by(|a, b| a.id.cmp(&b.id));
660    out
661}
662
663/// Resolve a kebab-case sink-shape string into the typed [`SinkShape`].
664fn parse_sink_shape(s: &str) -> Option<SinkShape> {
665    match s {
666        "call" => Some(SinkShape::Call),
667        "member-call" => Some(SinkShape::MemberCall),
668        "member-assign" => Some(SinkShape::MemberAssign),
669        "tagged-template" => Some(SinkShape::TaggedTemplate),
670        "jsx-attr" => Some(SinkShape::JsxAttr),
671        "new-expression" => Some(SinkShape::NewExpression),
672        _ => None,
673    }
674}
675
676/// Resolve a kebab-case arg-kind string into the typed [`SinkArgKind`].
677fn parse_arg_kind(s: &str) -> Option<SinkArgKind> {
678    match s {
679        "template-with-subst" => Some(SinkArgKind::TemplateWithSubst),
680        "concat" => Some(SinkArgKind::Concat),
681        "object" => Some(SinkArgKind::Object),
682        "call" => Some(SinkArgKind::Call),
683        "literal" => Some(SinkArgKind::Literal),
684        "no-arg" => Some(SinkArgKind::NoArg),
685        "other" => Some(SinkArgKind::Other),
686        _ => None,
687    }
688}
689
690fn parse_object_property_predicates(
691    id: &str,
692    raw: Option<Vec<RawObjectPropertyPredicate>>,
693) -> Result<Vec<ObjectPropertyPredicate>, String> {
694    let Some(raw_predicates) = raw else {
695        return Ok(Vec::new());
696    };
697    let mut predicates = Vec::with_capacity(raw_predicates.len());
698    for predicate in raw_predicates {
699        if predicate.key.trim().is_empty() {
700            return Err(format!(
701                "matcher {id:?} has an object_properties predicate with an empty key"
702            ));
703        }
704        let value_count = usize::from(predicate.string.is_some())
705            + usize::from(predicate.boolean.is_some())
706            + usize::from(predicate.integer.is_some())
707            + usize::from(predicate.null);
708        if value_count != 1 {
709            return Err(format!(
710                "matcher {id:?} object_properties predicate for {:?} must set exactly one of string | boolean | integer | null",
711                predicate.key
712            ));
713        }
714        let value = if let Some(string) = predicate.string {
715            LiteralPredicate::String(string)
716        } else if let Some(boolean) = predicate.boolean {
717            LiteralPredicate::Boolean(boolean)
718        } else if let Some(integer) = predicate.integer {
719            LiteralPredicate::Integer(integer)
720        } else {
721            LiteralPredicate::Null
722        };
723        predicates.push(ObjectPropertyPredicate {
724            key: predicate.key,
725            value,
726        });
727    }
728    Ok(predicates)
729}
730
731/// Parse + validate the catalogue source. Returns a `Result` (NOT a panic) so
732/// the validation tests can assert on error messages; `catalogue()` unwraps it.
733///
734/// Validates: non-empty id; cwe > 0; sink_shape resolves; callee_patterns
735/// non-empty and every pattern non-empty/non-whitespace; non-empty
736/// evidence_template.
737fn parse_catalogue(src: &str) -> Result<Catalogue, String> {
738    let raw: RawCatalogue =
739        toml::from_str(src).map_err(|e| format!("security_matchers.toml parse error: {e}"))?;
740
741    let mut matchers = Vec::with_capacity(raw.matcher.len());
742    for entry in raw.matcher {
743        matchers.push(parse_matcher_entry(entry)?);
744    }
745
746    if matchers.is_empty() {
747        return Err("security_matchers.toml has no [[matcher]] entries".to_string());
748    }
749
750    let sources = parse_source_catalogue(raw.source)?;
751
752    Ok(Catalogue { matchers, sources })
753}
754
755/// Validate one raw matcher entry and convert it to a `Matcher`. Validates a
756/// non-empty id, cwe > 0, a resolvable sink_shape, non-empty callee_patterns /
757/// arg_kinds / evidence_template, and a non-empty enabler when present.
758fn parse_matcher_entry(entry: RawMatcher) -> Result<Matcher, String> {
759    let (sink_shape, callee_patterns) = validate_matcher_core(&entry)?;
760    let arg_kinds = parse_matcher_arg_kinds(&entry.id, entry.arg_kinds.as_deref())?;
761    let enabler = validate_matcher_enabler(&entry.id, entry.enabler)?;
762    let object_properties = parse_object_property_predicates(&entry.id, entry.object_properties)?;
763    Ok(Matcher {
764        id: entry.id,
765        cwe: entry.cwe,
766        title: entry.title,
767        effect: entry.effect,
768        sink_shape,
769        callee_patterns,
770        arg_index: entry.arg_index,
771        variadic: entry.variadic,
772        evidence_template: entry.evidence_template,
773        import_provenance: entry.import_provenance,
774        enabler,
775        arg_kinds,
776        requires_source: entry.requires_source,
777        requires_source_kinds: entry.requires_source_kinds,
778        requires_module_source: entry.requires_module_source,
779        ignored_source_kinds: entry.ignored_source_kinds,
780        secret_sources: entry.secret_sources,
781        literal_values: entry.literal_values.unwrap_or_default(),
782        literal_contains: entry.literal_contains.unwrap_or_default(),
783        literal_integers: entry.literal_integers.unwrap_or_default(),
784        object_properties,
785        object_missing_or_false: entry.object_missing_or_false.unwrap_or_default(),
786        object_missing: entry.object_missing.unwrap_or_default(),
787        options_may_enable: entry.options_may_enable.unwrap_or_default(),
788        context_keywords: entry.context_keywords.unwrap_or_default(),
789    })
790}
791
792/// Validate a matcher's scalar fields (id, cwe, evidence_template) and parse its
793/// sink_shape plus non-empty callee_patterns.
794fn validate_matcher_core(entry: &RawMatcher) -> Result<(SinkShape, Vec<CalleePattern>), String> {
795    if entry.id.trim().is_empty() {
796        return Err("matcher id must be non-empty / non-whitespace".to_string());
797    }
798    if entry.cwe == 0 {
799        return Err(format!("matcher {:?} has cwe 0; cwe must be > 0", entry.id));
800    }
801    let sink_shape = parse_sink_shape(&entry.sink_shape).ok_or_else(|| {
802        format!(
803            "matcher {:?} has unknown sink_shape {:?}; expected one of \
804             call | member-call | member-assign | tagged-template | jsx-attr | new-expression",
805            entry.id, entry.sink_shape
806        )
807    })?;
808    if entry.callee_patterns.is_empty() {
809        return Err(format!(
810            "matcher {:?} has no callee_patterns; at least one is required",
811            entry.id
812        ));
813    }
814    if entry.evidence_template.trim().is_empty() {
815        return Err(format!(
816            "matcher {:?} has an empty evidence_template",
817            entry.id
818        ));
819    }
820    let mut callee_patterns = Vec::with_capacity(entry.callee_patterns.len());
821    for pat in &entry.callee_patterns {
822        let parsed = parse_callee_pattern(pat).ok_or_else(|| {
823            format!(
824                "matcher {:?} has an empty / whitespace callee_pattern {pat:?}",
825                entry.id
826            )
827        })?;
828        callee_patterns.push(parsed);
829    }
830    Ok((sink_shape, callee_patterns))
831}
832
833/// Validate the optional `enabler`: present but empty / whitespace is rejected;
834/// absent or non-empty passes through unchanged.
835fn validate_matcher_enabler(id: &str, enabler: Option<String>) -> Result<Option<String>, String> {
836    match enabler {
837        Some(e) if e.trim().is_empty() => Err(format!(
838            "matcher {id:?} has an empty / whitespace enabler; omit the key for a global row"
839        )),
840        other => Ok(other),
841    }
842}
843
844/// Parse the optional `arg_kinds` list: `None` admits any shape, an empty list
845/// is rejected, and each entry must resolve to a known `ArgKind`.
846fn parse_matcher_arg_kinds(
847    id: &str,
848    raw_kinds: Option<&[String]>,
849) -> Result<Option<Vec<SinkArgKind>>, String> {
850    let Some(raw_kinds) = raw_kinds else {
851        return Ok(None);
852    };
853    if raw_kinds.is_empty() {
854        return Err(format!(
855            "matcher {id:?} has an empty arg_kinds list; omit the key to admit any shape"
856        ));
857    }
858    let mut kinds = Vec::with_capacity(raw_kinds.len());
859    for raw in raw_kinds {
860        let kind = parse_arg_kind(raw).ok_or_else(|| {
861            format!(
862                "matcher {id:?} has unknown arg_kind {raw:?}; expected one of \
863                 template-with-subst | concat | object | call | literal | no-arg | other"
864            )
865        })?;
866        kinds.push(kind);
867    }
868    Ok(Some(kinds))
869}
870
871fn parse_source_catalogue(raw_sources: Vec<RawSource>) -> Result<Vec<SourceMatcher>, String> {
872    let mut sources = Vec::with_capacity(raw_sources.len());
873    for entry in raw_sources {
874        if entry.id.trim().is_empty() {
875            return Err("source id must be non-empty / non-whitespace".to_string());
876        }
877        if entry.path_patterns.is_empty() {
878            return Err(format!(
879                "source {:?} has no path_patterns; at least one is required",
880                entry.id
881            ));
882        }
883        let path_patterns = parse_source_path_patterns(&entry)?;
884        let receiver_allowlist = parse_source_receiver_allowlist(&entry)?;
885        let enabler = match entry.enabler {
886            Some(e) if e.trim().is_empty() => {
887                return Err(format!(
888                    "source {:?} has an empty / whitespace enabler; omit the key for a global row",
889                    entry.id
890                ));
891            }
892            other => other,
893        };
894        sources.push(SourceMatcher {
895            id: entry.id,
896            title: entry.title,
897            enabler,
898            path_patterns,
899            receiver_allowlist,
900            secret: entry.secret,
901        });
902    }
903    Ok(sources)
904}
905
906fn parse_source_path_patterns(entry: &RawSource) -> Result<Vec<CalleePattern>, String> {
907    let mut path_patterns = Vec::with_capacity(entry.path_patterns.len());
908    for pattern in &entry.path_patterns {
909        let parsed = parse_callee_pattern(pattern).ok_or_else(|| {
910            format!(
911                "source {:?} has an empty / whitespace path_pattern {pattern:?}",
912                entry.id
913            )
914        })?;
915        path_patterns.push(parsed);
916    }
917    Ok(path_patterns)
918}
919
920fn parse_source_receiver_allowlist(entry: &RawSource) -> Result<Vec<String>, String> {
921    let mut receiver_allowlist = Vec::with_capacity(entry.receiver_allowlist.len());
922    for receiver in &entry.receiver_allowlist {
923        if receiver.trim().is_empty() {
924            return Err(format!(
925                "source {:?} has an empty / whitespace receiver_allowlist entry; omit the key for an ungated row",
926                entry.id
927            ));
928        }
929        receiver_allowlist.push(receiver.to_ascii_lowercase());
930    }
931    Ok(receiver_allowlist)
932}
933
934/// Parse and cache the embedded catalogue once. Unwraps the parse `Result`; in
935/// a released binary this is unreachable because the bytes are compile-time
936/// embedded and gated by `security_catalogue_parses`.
937///
938/// # Panics
939///
940/// Panics if the embedded matcher catalogue does not parse.
941#[expect(
942    clippy::expect_used,
943    reason = "compile-time-embedded catalogue pinned by security_catalogue_parses"
944)]
945pub fn catalogue() -> &'static Catalogue {
946    static CATALOGUE: std::sync::OnceLock<Catalogue> = std::sync::OnceLock::new();
947    CATALOGUE.get_or_init(|| {
948        parse_catalogue(CATALOGUE_TOML).expect(
949            "embedded crates/security/data/security_matchers.toml must parse; run \
950             `cargo test -p fallow-security security_catalogue_parses` to see the error",
951        )
952    })
953}
954
955#[cfg(test)]
956#[expect(
957    clippy::expect_used,
958    clippy::unwrap_used,
959    reason = "catalogue parser tests assert fixture invariants directly"
960)]
961mod tests {
962    use super::*;
963    use fallow_types::extract::SinkObjectProperty;
964    use rustc_hash::FxHashSet;
965
966    /// Source lookup through the production method, with no extra request
967    /// receivers.
968    fn source_for<'a>(
969        cat: &'a Catalogue,
970        source_path: &str,
971        declared_deps: &FxHashSet<String>,
972    ) -> Option<(&'a str, &'a str)> {
973        cat.matching_source_for_deps_with_receivers(
974            source_path,
975            declared_deps,
976            &FxHashSet::default(),
977        )
978    }
979
980    /// Whether the production lookup finds a source with no declared dependencies.
981    fn is_source(cat: &Catalogue, source_path: &str) -> bool {
982        source_for(cat, source_path, &FxHashSet::default()).is_some()
983    }
984
985    #[test]
986    fn security_categories_are_deduped_and_flag_include_required() {
987        let cats = security_categories();
988        assert!(!cats.is_empty(), "catalogue must yield categories");
989        // deduped by id
990        let mut ids = FxHashSet::default();
991        for c in &cats {
992            assert!(ids.insert(c.id.clone()), "duplicate category id {}", c.id);
993        }
994        // sorted by id
995        let sorted: Vec<&String> = {
996            let mut v: Vec<&String> = cats.iter().map(|c| &c.id).collect();
997            v.sort();
998            v
999        };
1000        assert_eq!(
1001            cats.iter().map(|c| &c.id).collect::<Vec<_>>(),
1002            sorted,
1003            "categories must be sorted by id"
1004        );
1005        // both include-required categories present and flagged; hardcoded-secret
1006        // carries no CWE (entropy detector).
1007        let by_id = |id: &str| cats.iter().find(|c| c.id == id);
1008        let hs = by_id(HARDCODED_SECRET_CATEGORY_ID).expect("hardcoded-secret present");
1009        assert!(hs.include_required && hs.cwe.is_none());
1010        let stn = by_id(SECRET_TO_NETWORK_CATEGORY_ID).expect("secret-to-network present");
1011        assert!(
1012            stn.include_required,
1013            "secret-to-network must be include-required"
1014        );
1015        // a normal category is NOT include-required
1016        assert!(
1017            cats.iter().any(|c| !c.include_required),
1018            "most categories are admitted by default"
1019        );
1020    }
1021
1022    #[test]
1023    fn secret_to_network_const_matches_catalogue() {
1024        assert!(
1025            catalogue()
1026                .matchers()
1027                .iter()
1028                .any(|m| m.id == SECRET_TO_NETWORK_CATEGORY_ID),
1029            "SECRET_TO_NETWORK_CATEGORY_ID must name a real catalogue category"
1030        );
1031    }
1032
1033    #[test]
1034    fn security_catalogue_parses() {
1035        let cat = catalogue();
1036        assert!(!cat.matchers().is_empty(), "catalogue must have matchers");
1037        assert!(
1038            cat.matchers().iter().any(|m| m.id == "dangerous-html"),
1039            "catalogue must contain the dangerous-html seed"
1040        );
1041    }
1042
1043    #[test]
1044    fn catalogue_rows_are_unique() {
1045        // Multiple rows legitimately share an `id` (dangerous-html spans three
1046        // shapes), so uniqueness is keyed on the FULL row: id + sink_shape +
1047        // callee_patterns + gates. No two identical matcher rows. Keyed off the
1048        // raw source so the test does not require `SinkShape: Hash`.
1049        let raw: RawCatalogue = toml::from_str(CATALOGUE_TOML).unwrap();
1050        let mut seen = FxHashSet::default();
1051        for m in &raw.matcher {
1052            let pats = m.callee_patterns.join("|");
1053            // Uniqueness includes the enabler: framework-scoped rows (#861) may
1054            // legitimately share id + shape + patterns and differ only by their
1055            // framework gate (e.g. one `route-send-file` row per framework).
1056            let enabler = m.enabler.as_deref().unwrap_or("");
1057            let import_provenance = m.import_provenance.as_deref().unwrap_or("");
1058            let arg_kinds = m
1059                .arg_kinds
1060                .as_ref()
1061                .map_or_else(String::new, |kinds| kinds.join("|"));
1062            let literal_values = m
1063                .literal_values
1064                .as_ref()
1065                .map_or_else(String::new, |values| values.join("|"));
1066            let literal_contains = m
1067                .literal_contains
1068                .as_ref()
1069                .map_or_else(String::new, |values| values.join("|"));
1070            let literal_integers = m
1071                .literal_integers
1072                .as_ref()
1073                .map_or_else(String::new, |values| {
1074                    values
1075                        .iter()
1076                        .map(i64::to_string)
1077                        .collect::<Vec<_>>()
1078                        .join("|")
1079                });
1080            let object_properties = format!("{:?}", m.object_properties);
1081            let object_missing_or_false = m
1082                .object_missing_or_false
1083                .as_ref()
1084                .map_or_else(String::new, |keys| keys.join("|"));
1085            let object_missing = m
1086                .object_missing
1087                .as_ref()
1088                .map_or_else(String::new, |keys| keys.join("|"));
1089            let options_may_enable = m
1090                .options_may_enable
1091                .as_ref()
1092                .map_or_else(String::new, |keys| keys.join("|"));
1093            let context_keywords = m
1094                .context_keywords
1095                .as_ref()
1096                .map_or_else(String::new, |keywords| keywords.join("|"));
1097            let key = format!(
1098                "{}::{}::{pats}::{enabler}::{import_provenance}::{}::{arg_kinds}::{literal_values}::{literal_contains}::{literal_integers}::{object_properties}::{object_missing_or_false}::{object_missing}::{options_may_enable}::{context_keywords}",
1099                m.id, m.sink_shape, m.requires_source
1100            );
1101            assert!(seen.insert(key.clone()), "duplicate matcher row: {key}");
1102        }
1103    }
1104
1105    #[test]
1106    fn path_join_row_admits_every_path_segment() {
1107        let row = catalogue()
1108            .matchers()
1109            .iter()
1110            .find(|m| m.id == "path-traversal" && m.first_matching_pattern("path.join").is_some())
1111            .expect("path.join row exists");
1112        assert!(row.variadic, "path.join must inspect every segment (#3712)");
1113        assert!(row.admits_arg_index(0));
1114        assert!(row.admits_arg_index(3));
1115
1116        let rename_destination = catalogue()
1117            .matchers()
1118            .iter()
1119            .find(|m| m.id == "path-traversal" && m.arg_index == 1)
1120            .expect("fs.rename destination row exists");
1121        assert!(!rename_destination.admits_arg_index(0));
1122        assert!(!rename_destination.admits_arg_index(2));
1123    }
1124
1125    #[test]
1126    fn catalogue_ids_non_empty() {
1127        for m in catalogue().matchers() {
1128            assert!(
1129                !m.id.trim().is_empty(),
1130                "matcher id must be non-empty / non-whitespace"
1131            );
1132        }
1133    }
1134
1135    #[test]
1136    fn catalogue_cwe_valid() {
1137        for m in catalogue().matchers() {
1138            assert!(m.cwe > 0, "matcher {:?} has cwe 0", m.id);
1139        }
1140    }
1141
1142    #[test]
1143    fn catalogue_sink_shapes_known() {
1144        // Every parsed matcher already carries a typed SinkShape, so re-parse
1145        // the raw source to assert the kebab strings all resolve.
1146        let raw: RawCatalogue = toml::from_str(CATALOGUE_TOML).unwrap();
1147        for m in &raw.matcher {
1148            assert!(
1149                parse_sink_shape(&m.sink_shape).is_some(),
1150                "matcher {:?} has unknown sink_shape {:?}",
1151                m.id,
1152                m.sink_shape
1153            );
1154        }
1155    }
1156
1157    #[test]
1158    fn catalogue_callee_patterns_non_empty() {
1159        for m in catalogue().matchers() {
1160            assert!(
1161                !m.callee_patterns.is_empty(),
1162                "matcher {:?} has no callee_patterns",
1163                m.id
1164            );
1165            for p in &m.callee_patterns {
1166                assert!(
1167                    !p.raw().trim().is_empty(),
1168                    "matcher {:?} has an empty callee_pattern",
1169                    m.id
1170                );
1171            }
1172        }
1173    }
1174
1175    #[test]
1176    fn catalogue_evidence_templates_non_empty() {
1177        for m in catalogue().matchers() {
1178            assert!(
1179                !m.evidence_template.trim().is_empty(),
1180                "matcher {:?} has an empty evidence_template",
1181                m.id
1182            );
1183        }
1184    }
1185
1186    #[test]
1187    fn parse_rejects_empty_id() {
1188        let toml = r#"
1189[[matcher]]
1190id = ""
1191cwe = 79
1192title = "x"
1193effect = "unknown"
1194sink_shape = "member-assign"
1195callee_patterns = ["*.innerHTML"]
1196arg_index = 0
1197evidence_template = "x"
1198"#;
1199        let err = parse_catalogue(toml).unwrap_err();
1200        assert!(err.contains("id must be non-empty"), "got: {err}");
1201    }
1202
1203    #[test]
1204    fn parse_rejects_zero_cwe() {
1205        let toml = r#"
1206[[matcher]]
1207id = "x"
1208cwe = 0
1209title = "x"
1210effect = "unknown"
1211sink_shape = "member-assign"
1212callee_patterns = ["*.innerHTML"]
1213arg_index = 0
1214evidence_template = "x"
1215"#;
1216        let err = parse_catalogue(toml).unwrap_err();
1217        assert!(err.contains("cwe"), "got: {err}");
1218    }
1219
1220    #[test]
1221    fn parse_rejects_missing_effect() {
1222        let toml = r#"
1223[[matcher]]
1224id = "x"
1225cwe = 79
1226title = "x"
1227sink_shape = "member-assign"
1228callee_patterns = ["*.innerHTML"]
1229arg_index = 0
1230evidence_template = "x"
1231"#;
1232        let err = parse_catalogue(toml).unwrap_err();
1233        assert!(err.contains("missing field `effect`"), "got: {err}");
1234    }
1235
1236    #[test]
1237    fn parse_rejects_unknown_sink_shape() {
1238        let toml = r#"
1239[[matcher]]
1240id = "x"
1241cwe = 79
1242title = "x"
1243effect = "unknown"
1244sink_shape = "not-a-shape"
1245callee_patterns = ["*.innerHTML"]
1246arg_index = 0
1247evidence_template = "x"
1248"#;
1249        let err = parse_catalogue(toml).unwrap_err();
1250        assert!(err.contains("unknown sink_shape"), "got: {err}");
1251    }
1252
1253    #[test]
1254    fn parse_rejects_empty_callee_patterns() {
1255        let toml = r#"
1256[[matcher]]
1257id = "x"
1258cwe = 79
1259title = "x"
1260effect = "unknown"
1261sink_shape = "member-assign"
1262callee_patterns = []
1263arg_index = 0
1264evidence_template = "x"
1265"#;
1266        let err = parse_catalogue(toml).unwrap_err();
1267        assert!(err.contains("callee_patterns"), "got: {err}");
1268    }
1269
1270    #[test]
1271    fn parse_rejects_empty_pattern_string() {
1272        let toml = r#"
1273[[matcher]]
1274id = "x"
1275cwe = 79
1276title = "x"
1277effect = "unknown"
1278sink_shape = "member-assign"
1279callee_patterns = ["   "]
1280arg_index = 0
1281evidence_template = "x"
1282"#;
1283        let err = parse_catalogue(toml).unwrap_err();
1284        assert!(err.contains("empty"), "got: {err}");
1285    }
1286
1287    #[test]
1288    fn parse_rejects_empty_evidence_template() {
1289        let toml = r#"
1290[[matcher]]
1291id = "x"
1292cwe = 79
1293title = "x"
1294effect = "unknown"
1295sink_shape = "member-assign"
1296callee_patterns = ["*.innerHTML"]
1297arg_index = 0
1298evidence_template = "   "
1299"#;
1300        let err = parse_catalogue(toml).unwrap_err();
1301        assert!(err.contains("evidence_template"), "got: {err}");
1302    }
1303
1304    #[test]
1305    fn parse_rejects_no_matchers() {
1306        let err = parse_catalogue("").unwrap_err();
1307        assert!(err.contains("no [[matcher]]"), "got: {err}");
1308    }
1309
1310    #[test]
1311    fn segment_match_is_not_substring() {
1312        let bare = parse_callee_pattern("fetch").unwrap();
1313        assert!(bare.matches("fetch"));
1314        assert!(!bare.matches("myfetch"));
1315        assert!(!bare.matches("fetcher"));
1316
1317        let wildcard = parse_callee_pattern("*.innerHTML").unwrap();
1318        assert!(wildcard.matches("el.innerHTML"));
1319        assert!(wildcard.matches("this.node.innerHTML"));
1320        assert!(!wildcard.matches("el.innerHTMLFoo"));
1321        assert!(!wildcard.matches("innerHTML")); // wildcard requires an object
1322
1323        let dotted = parse_callee_pattern("child_process.exec").unwrap();
1324        assert!(dotted.matches("child_process.exec"));
1325        assert!(!dotted.matches("exec"));
1326        assert!(!dotted.matches("child_process.execSync"));
1327        assert!(!dotted.matches("my_child_process.exec"));
1328    }
1329
1330    #[test]
1331    fn every_jsx_attr_row_is_followed_through_jsx_spread() {
1332        let missing: Vec<&str> = catalogue()
1333            .matchers()
1334            .iter()
1335            .filter(|matcher| matcher.sink_shape == SinkShape::JsxAttr)
1336            .flat_map(|matcher| matcher.callee_patterns.iter().map(CalleePattern::raw))
1337            .filter(|raw| !fallow_types::security_sinks::JSX_SPREAD_SINK_PROPS.contains(raw))
1338            .collect();
1339        assert!(
1340            missing.is_empty(),
1341            "add these jsx-attr patterns to JSX_SPREAD_SINK_PROPS: {missing:?}"
1342        );
1343    }
1344
1345    #[test]
1346    fn wildcard_only_pattern_matches_nothing() {
1347        // Guard against a degenerate `*` pattern matching every callee.
1348        let star = parse_callee_pattern("*").unwrap();
1349        assert!(!star.matches("el.innerHTML"));
1350        assert!(!star.matches("anything"));
1351    }
1352
1353    #[test]
1354    fn trailing_wildcard_prefix_matches() {
1355        let trailing = parse_callee_pattern("child_process.*").unwrap();
1356        assert!(trailing.matches("child_process.exec"));
1357        assert!(trailing.matches("child_process.exec.call"));
1358        assert!(!trailing.matches("child_process")); // requires a member
1359        assert!(!trailing.matches("my_child_process.exec"));
1360        assert!(!trailing.matches("exec"));
1361
1362        let console = parse_callee_pattern("console.*").unwrap();
1363        assert!(console.matches("console.log"));
1364        assert!(!console.matches("myconsole.log"));
1365    }
1366
1367    #[test]
1368    fn double_wildcard_pattern_matches_nothing() {
1369        // `*.x.*` and `*.*` are rejected by config validation; the matcher
1370        // guards against them anyway.
1371        let both = parse_callee_pattern("*.query.*").unwrap();
1372        assert!(!both.matches("db.query.run"));
1373        let stars = parse_callee_pattern("*.*").unwrap();
1374        assert!(!stars.matches("a.b"));
1375    }
1376
1377    #[test]
1378    fn arg_kinds_unset_admits_any_shape() {
1379        // A matcher with no arg_kinds (e.g. dangerous-html) admits every shape.
1380        let html = catalogue()
1381            .matchers()
1382            .iter()
1383            .find(|m| m.id == "dangerous-html")
1384            .expect("dangerous-html present");
1385        for kind in [
1386            SinkArgKind::TemplateWithSubst,
1387            SinkArgKind::Concat,
1388            SinkArgKind::Object,
1389            SinkArgKind::Call,
1390            SinkArgKind::Literal,
1391            SinkArgKind::NoArg,
1392            SinkArgKind::Other,
1393        ] {
1394            assert!(html.admits_arg_kind(kind), "html admits {kind:?}");
1395        }
1396    }
1397
1398    #[test]
1399    fn sql_injection_query_execute_excludes_object_arg_kind() {
1400        // The `.query` / `.execute` matchers must require unsafe shapes (concat /
1401        // interpolated template) and reject the parameterized object-literal form
1402        // (`.execute({ sql, args })`). The separate `sql.raw` escape-hatch row is
1403        // intentionally shape-agnostic and is excluded from this check.
1404        let query_matchers: Vec<&Matcher> = catalogue()
1405            .matchers()
1406            .iter()
1407            .filter(|m| {
1408                m.id == "sql-injection"
1409                    && m.callee_patterns
1410                        .iter()
1411                        .any(|p| p.raw() == "*.query" || p.raw() == "*.execute")
1412            })
1413            .collect();
1414        assert!(
1415            !query_matchers.is_empty(),
1416            "sql-injection .query/.execute rows present"
1417        );
1418        for m in query_matchers {
1419            let kinds = m
1420                .arg_kinds
1421                .as_ref()
1422                .unwrap_or_else(|| panic!("sql-injection query/execute must constrain arg_kinds"));
1423            assert!(
1424                !kinds.contains(&SinkArgKind::Object),
1425                "sql-injection .query/.execute must not admit the object (parameterized) form"
1426            );
1427            assert!(
1428                !m.admits_arg_kind(SinkArgKind::Object),
1429                "admits_arg_kind agrees: object excluded"
1430            );
1431            assert!(
1432                m.admits_arg_kind(SinkArgKind::Concat),
1433                "sql-injection .query/.execute admits the concat (unsafe) form"
1434            );
1435        }
1436    }
1437
1438    #[test]
1439    fn source_required_matchers_are_explicit() {
1440        let mass_assignment = catalogue()
1441            .matchers()
1442            .iter()
1443            .find(|m| m.id == "mass-assignment")
1444            .expect("mass-assignment row present");
1445        assert!(
1446            mass_assignment.requires_source,
1447            "mass-assignment should only fire for source-backed arguments"
1448        );
1449    }
1450
1451    #[test]
1452    fn literal_integer_predicate_matches_integer_literals() {
1453        let chmod = catalogue()
1454            .matchers()
1455            .iter()
1456            .find(|m| m.id == "world-writable-permission" && m.sink_shape == SinkShape::MemberCall)
1457            .expect("world-writable permission row present");
1458
1459        assert!(chmod.literal_value_satisfied(Some(&SinkLiteralValue::Integer(511))));
1460        assert!(!chmod.literal_value_satisfied(Some(&SinkLiteralValue::Integer(420))));
1461        assert!(
1462            !chmod.literal_value_satisfied(Some(&SinkLiteralValue::String("0o777".to_string())))
1463        );
1464    }
1465
1466    #[test]
1467    fn object_property_predicate_matches_nested_integer_values() {
1468        let toml = r#"
1469[[matcher]]
1470id = "x"
1471cwe = 732
1472title = "x"
1473effect = "unknown"
1474sink_shape = "member-call"
1475callee_patterns = ["fs.chmod"]
1476arg_index = 0
1477arg_kinds = ["object"]
1478object_properties = [{ key = "mode.value", integer = 511 }]
1479evidence_template = "x"
1480"#;
1481        let cat = parse_catalogue(toml).expect("catalogue parses");
1482        let matcher = cat.matchers().first().expect("matcher present");
1483        let properties = vec![SinkObjectProperty {
1484            key: "mode.value".to_string(),
1485            value: SinkLiteralValue::Integer(511),
1486        }];
1487
1488        assert!(matcher.object_properties_satisfied(&properties));
1489    }
1490
1491    #[test]
1492    fn object_missing_requires_complete_key_metadata() {
1493        let jwt_verify = catalogue()
1494            .matchers()
1495            .iter()
1496            .find(|m| m.id == "jwt-verify-missing-algorithms")
1497            .expect("jwt verify missing algorithms row present");
1498
1499        assert!(
1500            jwt_verify.is_literal_aware(),
1501            "object_missing rows opt into literal-aware matching"
1502        );
1503        assert!(jwt_verify.object_missing_satisfied(&[], true));
1504        assert!(jwt_verify.object_missing_satisfied(&["audience".to_string()], true));
1505        assert!(!jwt_verify.object_missing_satisfied(&["algorithms".to_string()], true));
1506        assert!(!jwt_verify.object_missing_satisfied(&["audience".to_string()], false));
1507    }
1508
1509    #[test]
1510    fn parse_rejects_unknown_arg_kind() {
1511        let toml = r#"
1512[[matcher]]
1513id = "x"
1514cwe = 89
1515title = "x"
1516effect = "unknown"
1517sink_shape = "member-call"
1518callee_patterns = ["*.query"]
1519arg_index = 0
1520arg_kinds = ["not-a-kind"]
1521evidence_template = "x"
1522"#;
1523        let err = parse_catalogue(toml).unwrap_err();
1524        assert!(err.contains("unknown arg_kind"), "got: {err}");
1525    }
1526
1527    #[test]
1528    fn enabler_unset_is_global() {
1529        // A matcher with no enabler is satisfied by ANY (even empty) dep set.
1530        let html = catalogue()
1531            .matchers()
1532            .iter()
1533            .find(|m| m.id == "dangerous-html")
1534            .expect("dangerous-html present");
1535        assert!(html.enabler.is_none(), "dangerous-html is a global row");
1536        assert!(html.enabler_satisfied(&FxHashSet::default()));
1537    }
1538
1539    #[test]
1540    fn enabler_satisfied_exact_and_prefix() {
1541        let mut m = catalogue()
1542            .matchers()
1543            .iter()
1544            .find(|m| m.id == "dangerous-html")
1545            .cloned()
1546            .expect("dangerous-html present");
1547
1548        // Exact match.
1549        m.enabler = Some("jquery".to_string());
1550        let mut deps = FxHashSet::default();
1551        assert!(!m.enabler_satisfied(&deps), "absent dep is not satisfied");
1552        deps.insert("jquery".to_string());
1553        assert!(m.enabler_satisfied(&deps), "present exact dep satisfies");
1554
1555        // Trailing-slash prefix match, plus the bare scope name.
1556        m.enabler = Some("@angular/".to_string());
1557        let mut scoped = FxHashSet::default();
1558        assert!(!m.enabler_satisfied(&scoped));
1559        scoped.insert("@angular/platform-browser".to_string());
1560        assert!(m.enabler_satisfied(&scoped), "prefix dep satisfies");
1561        let mut bare_scope = FxHashSet::default();
1562        bare_scope.insert("@angular".to_string());
1563        assert!(
1564            m.enabler_satisfied(&bare_scope),
1565            "bare scope name satisfies the prefix form"
1566        );
1567
1568        // A near-miss exact name does not satisfy a prefix-less enabler.
1569        m.enabler = Some("react".to_string());
1570        let mut reactish = FxHashSet::default();
1571        reactish.insert("react-dom".to_string());
1572        assert!(
1573            !m.enabler_satisfied(&reactish),
1574            "exact enabler must not prefix-match"
1575        );
1576    }
1577
1578    #[test]
1579    fn framework_scoped_rows_are_present() {
1580        // The framework-scoped rows added in #861 carry an enabler.
1581        let cat = catalogue();
1582        let angular = cat
1583            .matchers()
1584            .iter()
1585            .find(|m| m.id == "angular-trusted-html")
1586            .expect("angular-trusted-html present");
1587        assert_eq!(
1588            angular.enabler.as_deref(),
1589            Some("@angular/platform-browser")
1590        );
1591        assert!(
1592            cat.matchers().iter().any(|m| m.id == "jquery-html"),
1593            "jquery-html present"
1594        );
1595        assert!(
1596            cat.matchers().iter().any(|m| m.id == "dom-document-write"),
1597            "dom-document-write present"
1598        );
1599    }
1600
1601    #[test]
1602    fn parse_rejects_empty_enabler() {
1603        let toml = r#"
1604[[matcher]]
1605id = "x"
1606cwe = 79
1607title = "x"
1608effect = "unknown"
1609sink_shape = "member-call"
1610callee_patterns = ["*.html"]
1611arg_index = 0
1612enabler = "   "
1613evidence_template = "x"
1614"#;
1615        let err = parse_catalogue(toml).unwrap_err();
1616        assert!(err.contains("empty / whitespace enabler"), "got: {err}");
1617    }
1618
1619    #[test]
1620    fn catalogue_has_untrusted_sources() {
1621        // Issue #859: the embedded catalogue ships at least one [[source]] row,
1622        // each with a non-empty id, title, and path_patterns.
1623        let cat = catalogue();
1624        assert!(
1625            !cat.sources.is_empty(),
1626            "catalogue must ship untrusted-source rows"
1627        );
1628        for s in &cat.sources {
1629            assert!(!s.id.trim().is_empty(), "source id non-empty");
1630            assert!(!s.title.trim().is_empty(), "source title non-empty");
1631            assert!(!s.path_patterns.is_empty(), "source has path patterns");
1632        }
1633    }
1634
1635    #[test]
1636    fn source_paths_match_expected_request_inputs() {
1637        let cat = catalogue();
1638        // Wildcard object prefix matches common framework request accessors.
1639        assert!(is_source(cat, "req.query"));
1640        assert!(is_source(cat, "ctx.req.query"));
1641        assert!(is_source(cat, "request.body"));
1642        assert!(is_source(cat, "req.params"));
1643        assert!(is_source(cat, "process.argv"));
1644        assert!(is_source(cat, "event.data"));
1645        assert!(is_source(cat, "request.rawBody"));
1646        assert!(is_source(cat, "document.referrer"));
1647        assert!(is_source(cat, "window.name"));
1648        assert!(is_source(cat, "document.cookie"));
1649        // A plain object path that is not an untrusted source does not match.
1650        assert!(!is_source(cat, "config.value"));
1651        assert!(!is_source(cat, "user.name"));
1652        assert!(!is_source(cat, "profile.name"));
1653        assert!(!is_source(cat, "jar.cookie"));
1654    }
1655
1656    #[test]
1657    fn message_event_data_needs_a_message_event_receiver() {
1658        let cat = catalogue();
1659        for path in [
1660            "event.data",
1661            "e.data",
1662            "evt.data",
1663            "msg.data",
1664            "message.data",
1665        ] {
1666            assert_eq!(
1667                source_for(cat, path, &FxHashSet::default()).map(|(id, _)| id),
1668                Some("message-event-data"),
1669                "{path}"
1670            );
1671        }
1672        // A `data` field on a parse result, a response or a store is not a
1673        // message payload.
1674        for path in ["input.data", "result.data", "response.data", "ctx.data"] {
1675            assert!(!is_source(cat, path), "{path}");
1676        }
1677    }
1678
1679    #[test]
1680    fn source_matcher_matches_helper() {
1681        let cat = catalogue();
1682        let http = cat
1683            .sources
1684            .iter()
1685            .find(|s| s.id == "http-request-input")
1686            .expect("http-request-input source present");
1687        assert!(http.matches_with_extra_receivers("req.query", &FxHashSet::default()));
1688        assert!(!http.matches_with_extra_receivers("process.argv", &FxHashSet::default()));
1689    }
1690
1691    #[test]
1692    fn matched_receiver_returns_segment_before_suffix() {
1693        // Leading-wildcard `*.query`: the receiver is the segment right before
1694        // the matched `query`, regardless of how many object segments precede.
1695        let pat = parse_callee_pattern("*.query").expect("pattern parses");
1696        assert_eq!(pat.matched_receiver("db.query"), Some("db"));
1697        assert_eq!(pat.matched_receiver("req.query"), Some("req"));
1698        // Hono `c.req.query` flattens so the receiver of `.query` is `req`.
1699        assert_eq!(pat.matched_receiver("ctx.req.query"), Some("req"));
1700        // A non-matching path has no receiver.
1701        assert_eq!(pat.matched_receiver("req.body"), None);
1702        // An exact (non-wildcard) pattern's receiver is fixed in the pattern, so
1703        // `matched_receiver` returns None even on a match.
1704        let exact = parse_callee_pattern("process.env").expect("pattern parses");
1705        assert_eq!(exact.matched_receiver("process.env"), None);
1706    }
1707
1708    #[test]
1709    fn receiver_allowlist_rejects_orm_query_builders_keeps_request_objects() {
1710        // Issue #1092: the global HTTP-input row is receiver-gated. ORM /
1711        // data-access receivers no longer classify their module as a source...
1712        let cat = catalogue();
1713        assert!(!is_source(cat, "db.query"), "Drizzle db.query");
1714        assert!(!is_source(cat, "prisma.query"), "Prisma prisma.query");
1715        assert!(!is_source(cat, "drizzle.query"));
1716        assert!(!is_source(cat, "knex.body"));
1717        assert!(!is_source(cat, "client.query"));
1718        // ...nor do non-request receivers that merely happen to have a `.query`
1719        // member (a sibling-collision check: `dbConn` is not `db`).
1720        assert!(!is_source(cat, "dbConn.query"));
1721        assert!(!is_source(cat, "database.params"));
1722        // A genuine request receiver still classifies as a source.
1723        assert!(is_source(cat, "req.query"), "Express req.query");
1724        assert!(is_source(cat, "request.body"));
1725        assert!(is_source(cat, "ctx.params"), "Koa/Elysia ctx.params");
1726        assert!(is_source(cat, "context.body"));
1727        assert!(is_source(cat, "event.query"), "SvelteKit event.query");
1728        // Hono `c.req.query`: the matched receiver is `req`, which is allowed.
1729        assert!(is_source(cat, "ctx.req.query"));
1730        // The allowlist is case-insensitive.
1731        assert!(is_source(cat, "Req.query"));
1732    }
1733
1734    #[test]
1735    fn configured_request_receivers_extend_http_request_source_allowlist() {
1736        let cat = catalogue();
1737        let deps = FxHashSet::default();
1738        let receivers = FxHashSet::from_iter(["h".to_string(), "httpreq".to_string()]);
1739
1740        assert!(
1741            cat.matching_source_for_deps_with_receivers("h.query", &deps, &receivers)
1742                .is_some()
1743        );
1744        assert!(
1745            cat.matching_source_for_deps_with_receivers("HttpReq.body", &deps, &receivers)
1746                .is_some()
1747        );
1748        assert!(
1749            cat.matching_source_for_deps_with_receivers("req.params", &deps, &receivers)
1750                .is_some()
1751        );
1752        assert!(
1753            cat.matching_source_for_deps_with_receivers("db.query", &deps, &receivers)
1754                .is_none()
1755        );
1756    }
1757
1758    #[test]
1759    fn search_params_source_stays_ungated() {
1760        // Issue #1092: `*.searchParams` is intentionally NOT receiver-gated, so a
1761        // `new URL(...).searchParams` binding on an arbitrary local still counts.
1762        let cat = catalogue();
1763        assert!(is_source(cat, "u.searchParams"));
1764        assert!(is_source(cat, "url.searchParams"));
1765        assert!(is_source(cat, "params.searchParams"));
1766    }
1767
1768    #[test]
1769    fn parse_rejects_empty_receiver_allowlist_entry() {
1770        let toml = r#"
1771[[matcher]]
1772id = "x"
1773cwe = 79
1774title = "x"
1775effect = "unknown"
1776sink_shape = "member-assign"
1777callee_patterns = ["*.innerHTML"]
1778arg_index = 0
1779evidence_template = "x"
1780
1781[[source]]
1782id = "http"
1783title = "HTTP"
1784path_patterns = ["*.query"]
1785receiver_allowlist = ["req", "  "]
1786"#;
1787        let err = parse_catalogue(toml).unwrap_err();
1788        assert!(err.contains("receiver_allowlist"), "got: {err}");
1789    }
1790
1791    #[test]
1792    fn source_enabler_gates_framework_param_sources() {
1793        let cat = catalogue();
1794        let source = cat
1795            .sources
1796            .iter()
1797            .find(|s| s.id == "framework-handler-input" && s.enabler.as_deref() == Some("express"))
1798            .expect("express handler source present");
1799        assert!(source.matches_with_extra_receivers("framework.request", &FxHashSet::default()));
1800
1801        let empty = FxHashSet::default();
1802        assert!(!source.enabler_satisfied(&empty));
1803        assert!(
1804            source_for(cat, "framework.request", &empty).is_none(),
1805            "framework handler params require an enabler"
1806        );
1807
1808        let mut deps = FxHashSet::default();
1809        deps.insert("express".to_string());
1810        assert!(source.enabler_satisfied(&deps));
1811        assert_eq!(
1812            source_for(cat, "framework.request", &deps),
1813            Some(("framework-handler-input", "Framework handler input"))
1814        );
1815    }
1816
1817    #[test]
1818    fn source_enabler_gates_graphql_and_trpc_param_sources() {
1819        let cat = catalogue();
1820        let empty = FxHashSet::default();
1821        assert!(
1822            source_for(cat, "graphql.args", &empty).is_none(),
1823            "GraphQL resolver args require a matching package"
1824        );
1825        assert!(
1826            source_for(cat, "trpc.input", &empty).is_none(),
1827            "tRPC procedure input requires a matching package"
1828        );
1829
1830        let mut graphql_deps = FxHashSet::default();
1831        graphql_deps.insert("@apollo/server".to_string());
1832        assert_eq!(
1833            source_for(cat, "graphql.args", &graphql_deps),
1834            Some(("graphql-resolver-args", "GraphQL resolver args"))
1835        );
1836
1837        let mut trpc_deps = FxHashSet::default();
1838        trpc_deps.insert("@trpc/server".to_string());
1839        assert_eq!(
1840            source_for(cat, "trpc.input", &trpc_deps),
1841            Some(("trpc-procedure-input", "tRPC procedure input"))
1842        );
1843    }
1844
1845    #[test]
1846    fn parse_rejects_source_without_patterns() {
1847        let toml = r#"
1848[[matcher]]
1849id = "x"
1850cwe = 79
1851title = "x"
1852effect = "unknown"
1853sink_shape = "member-assign"
1854callee_patterns = ["*.innerHTML"]
1855arg_index = 0
1856evidence_template = "x"
1857
1858[[source]]
1859id = "bad"
1860title = "bad"
1861path_patterns = []
1862"#;
1863        let err = parse_catalogue(toml).unwrap_err();
1864        assert!(err.contains("path_patterns"), "got: {err}");
1865    }
1866
1867    #[test]
1868    fn parse_rejects_empty_arg_kinds() {
1869        let toml = r#"
1870[[matcher]]
1871id = "x"
1872cwe = 89
1873title = "x"
1874effect = "unknown"
1875sink_shape = "member-call"
1876callee_patterns = ["*.query"]
1877arg_index = 0
1878arg_kinds = []
1879evidence_template = "x"
1880"#;
1881        let err = parse_catalogue(toml).unwrap_err();
1882        assert!(err.contains("empty arg_kinds"), "got: {err}");
1883    }
1884}