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