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