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