Skip to main content

fallow_security/
lib.rs

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