Skip to main content

fallow_security/
provenance.rs

1//! Import provenance of catalogue rows.
2//!
3//! A row with an `import_provenance` matches a callee only when the module
4//! imports that source. The security detectors, the policy effect lookup and
5//! the mutation plan all use the one predicate in this module, so a callee
6//! name such as `get` never counts as `https.get` in a module that does not
7//! import `node:https`.
8
9use fallow_types::extract::ModuleInfo;
10
11use crate::Matcher;
12
13/// The module bindings that can prove an import provenance.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum ProvenanceBindings {
16    /// ES `import` declarations only.
17    Imports,
18    /// ES `import` declarations and CommonJS `require()` calls.
19    ///
20    /// `ModuleInfo::release_resolution_payload` drains `require_calls`, so a
21    /// caller that reads a released module sees ES imports only.
22    ImportsAndRequires,
23    /// [`Self::ImportsAndRequires`], and also a leading identifier that no ES
24    /// import and no export of the module binds.
25    ///
26    /// A released module keeps no `require()` facts, so such an identifier
27    /// can be a CommonJS binding of the source. A caller that must not miss
28    /// a sink, such as the side-effect prune of the mutation plan, uses this
29    /// mode. An identifier that an ES import of another source or a local
30    /// export binds does not satisfy the row.
31    ReleasedModule,
32}
33
34/// Rows that must bind the provenance import to the leading identifier of the
35/// callee path. A module that only imports the source is not sufficient for
36/// these rows (the `child_process.fork()` precedent).
37const BINDING_TRACE_ROWS: [&str; 10] = [
38    "command-injection",
39    "permissive-cors",
40    "react-router-open-redirect",
41    "electron-unsafe-webpreferences",
42    "insecure-temp-file",
43    "jwt-alg-none",
44    "jwt-verify-missing-algorithms",
45    "tls-validation-disabled",
46    "mysql-multiple-statements",
47    "world-writable-permission",
48];
49
50impl Matcher {
51    /// Whether the row requires the provenance import's local binding to be
52    /// the leading identifier of the callee path.
53    #[must_use]
54    pub fn requires_binding_trace(&self) -> bool {
55        BINDING_TRACE_ROWS.contains(&self.id.as_str())
56            || (self.id == "weak-crypto" && self.is_literal_aware())
57    }
58
59    /// Whether the module satisfies the row's import provenance for the
60    /// callee path.
61    ///
62    /// A row without provenance is always satisfied. Otherwise the module
63    /// must import a source that matches the spec (see
64    /// [`import_source_matches`]). For a binding-trace row
65    /// ([`Self::requires_binding_trace`]), the import must also bind the
66    /// leading identifier of `callee_path`.
67    #[must_use]
68    pub fn provenance_satisfied(
69        &self,
70        module: &ModuleInfo,
71        callee_path: &str,
72        bindings: ProvenanceBindings,
73    ) -> bool {
74        let Some(spec) = &self.import_provenance else {
75            return true;
76        };
77        let leading_ident = callee_path.split('.').next().unwrap_or(callee_path);
78        // A `node:` root is not an identifier. The extractor writes it only
79        // for a binding that it traced to that module import.
80        if leading_ident.starts_with("node:") {
81            return import_source_matches(leading_ident, spec);
82        }
83        let binding_trace = self.requires_binding_trace();
84        let by_import = module.imports.iter().any(|import| {
85            import_source_matches(&import.source, spec)
86                && (!binding_trace || import.local_name == leading_ident)
87        });
88        if by_import || bindings == ProvenanceBindings::Imports {
89            return by_import;
90        }
91        let by_require = module.require_calls.iter().any(|call| {
92            import_source_matches(&call.source, spec)
93                && (!binding_trace
94                    || call.local_name.as_deref() == Some(leading_ident)
95                    || call
96                        .destructured_names
97                        .iter()
98                        .any(|name| name == leading_ident))
99        });
100        by_require
101            || (bindings == ProvenanceBindings::ReleasedModule
102                && !binds_locally(module, leading_ident))
103    }
104}
105
106/// Whether an ES import or an export of the module binds the identifier.
107fn binds_locally(module: &ModuleInfo, ident: &str) -> bool {
108    module
109        .imports
110        .iter()
111        .any(|import| import.local_name == ident)
112        || module.exports.iter().any(|export| {
113            export
114                .local_name
115                .as_deref()
116                .map_or_else(|| export.name.matches_str(ident), |local| local == ident)
117        })
118}
119
120/// Compare an import source with a provenance spec.
121///
122/// The `node:` prefix is optional on both sides (`node:child_process` matches
123/// `child_process`), and a package subpath matches its package
124/// (`mysql2/promise` matches `mysql2`).
125#[must_use]
126pub fn import_source_matches(source: &str, spec: &str) -> bool {
127    let source = strip_node_prefix(source);
128    let spec = strip_node_prefix(spec);
129    source == spec
130        || source
131            .strip_prefix(spec)
132            .is_some_and(|rest| rest.starts_with('/'))
133}
134
135fn strip_node_prefix(value: &str) -> &str {
136    value.strip_prefix("node:").unwrap_or(value)
137}
138
139#[cfg(test)]
140#[expect(
141    clippy::expect_used,
142    reason = "the tests look up catalogue rows that the catalogue must contain"
143)]
144mod tests {
145    use fallow_types::discover::FileId;
146    use fallow_types::extract::{
147        ExportInfo, ExportName, ImportInfo, ImportedName, RequireCallInfo, SinkShape, VisibilityTag,
148    };
149    use oxc_span::Span;
150
151    use super::*;
152
153    fn row(id: &str, shape: SinkShape, callee: &str) -> &'static Matcher {
154        crate::catalogue()
155            .matchers()
156            .iter()
157            .find(|matcher| {
158                matcher.id == id
159                    && matcher.sink_shape == shape
160                    && matcher.first_matching_pattern(callee).is_some()
161            })
162            .expect("catalogue row exists")
163    }
164
165    fn import(source: &str, local: &str) -> ImportInfo {
166        ImportInfo {
167            source: source.to_owned(),
168            imported_name: ImportedName::Named(local.to_owned()),
169            local_name: local.to_owned(),
170            is_type_only: false,
171            is_type_only_star: false,
172            from_style: false,
173            span: Span::default(),
174            source_span: Span::default(),
175        }
176    }
177
178    fn require(source: &str, local: Option<&str>, destructured: &[&str]) -> RequireCallInfo {
179        RequireCallInfo {
180            source: source.to_owned(),
181            span: Span::default(),
182            source_span: Span::default(),
183            destructured_names: destructured.iter().map(|&name| name.to_owned()).collect(),
184            destructured_locals: Vec::new(),
185            local_name: local.map(str::to_owned),
186            is_type_only: false,
187        }
188    }
189
190    fn export(name: &str) -> ExportInfo {
191        ExportInfo {
192            name: ExportName::Named(name.to_owned()),
193            local_name: None,
194            is_type_only: false,
195            is_side_effect_used: false,
196            visibility: VisibilityTag::None,
197            expected_unused_reason: None,
198            deprecated: false,
199            deprecated_reason: None,
200            span: Span::default(),
201            members: Vec::new(),
202            super_class: None,
203        }
204    }
205
206    fn module(imports: Vec<ImportInfo>, requires: Vec<RequireCallInfo>) -> ModuleInfo {
207        ModuleInfo {
208            imports,
209            require_calls: requires,
210            ..ModuleInfo::empty(FileId(0))
211        }
212    }
213
214    #[test]
215    fn a_local_get_does_not_satisfy_the_https_row() {
216        let tls = row("tls-validation-disabled", SinkShape::Call, "get");
217        let local = module(vec![import("./get", "get")], Vec::new());
218        assert!(!tls.provenance_satisfied(&local, "get", ProvenanceBindings::ImportsAndRequires));
219        let unbound = module(Vec::new(), Vec::new());
220        assert!(!tls.provenance_satisfied(&unbound, "get", ProvenanceBindings::Imports));
221    }
222
223    #[test]
224    fn the_https_import_must_bind_the_leading_identifier() {
225        let tls = row("tls-validation-disabled", SinkShape::Call, "get");
226        let named = module(vec![import("node:https", "get")], Vec::new());
227        assert!(tls.provenance_satisfied(&named, "get", ProvenanceBindings::Imports));
228        let other = module(vec![import("https", "request")], Vec::new());
229        assert!(!tls.provenance_satisfied(&other, "get", ProvenanceBindings::Imports));
230    }
231
232    #[test]
233    fn a_node_root_proves_only_its_own_module() {
234        let vm = row(
235            "code-injection",
236            SinkShape::MemberCall,
237            "node:vm.runInNewContext",
238        );
239        let bare = module(Vec::new(), Vec::new());
240        assert!(vm.provenance_satisfied(
241            &bare,
242            "node:vm.runInNewContext",
243            ProvenanceBindings::Imports
244        ));
245        assert!(!vm.provenance_satisfied(&bare, "vm.runInNewContext", ProvenanceBindings::Imports));
246        assert!(!vm.provenance_satisfied(
247            &bare,
248            "node:fs.runInNewContext",
249            ProvenanceBindings::Imports
250        ));
251    }
252
253    #[test]
254    fn a_row_without_binding_trace_accepts_any_import_of_the_source() {
255        let fs = row("path-traversal", SinkShape::MemberCall, "fs.readFile");
256        assert!(!fs.requires_binding_trace());
257        let imported = module(vec![import("fs", "files")], Vec::new());
258        assert!(fs.provenance_satisfied(&imported, "fs.readFile", ProvenanceBindings::Imports));
259    }
260
261    #[test]
262    fn a_require_call_counts_only_when_the_caller_admits_requires() {
263        let tls = row(
264            "tls-validation-disabled",
265            SinkShape::MemberCall,
266            "https.get",
267        );
268        let namespace = module(Vec::new(), vec![require("https", Some("https"), &[])]);
269        assert!(!tls.provenance_satisfied(&namespace, "https.get", ProvenanceBindings::Imports));
270        assert!(tls.provenance_satisfied(
271            &namespace,
272            "https.get",
273            ProvenanceBindings::ImportsAndRequires
274        ));
275        let destructured = module(Vec::new(), vec![require("node:https", None, &["get"])]);
276        assert!(tls.provenance_satisfied(
277            &destructured,
278            "get",
279            ProvenanceBindings::ImportsAndRequires
280        ));
281    }
282
283    #[test]
284    fn a_released_module_treats_an_unbound_identifier_as_a_hidden_require() {
285        let tls = row(
286            "tls-validation-disabled",
287            SinkShape::MemberCall,
288            "https.get",
289        );
290        let mode = ProvenanceBindings::ReleasedModule;
291        let unbound = module(Vec::new(), Vec::new());
292        assert!(tls.provenance_satisfied(&unbound, "https.get", mode));
293        let elsewhere = module(vec![import("./client", "https")], Vec::new());
294        assert!(!tls.provenance_satisfied(&elsewhere, "https.get", mode));
295        let get = row("tls-validation-disabled", SinkShape::Call, "get");
296        let exported = ModuleInfo {
297            exports: vec![export("get")].into(),
298            ..module(Vec::new(), Vec::new())
299        };
300        assert!(!get.provenance_satisfied(&exported, "get", mode));
301        let imported = module(vec![import("node:https", "get")], Vec::new());
302        assert!(get.provenance_satisfied(&imported, "get", mode));
303    }
304
305    #[test]
306    fn a_row_without_provenance_is_always_satisfied() {
307        let row = crate::catalogue()
308            .matchers()
309            .iter()
310            .find(|matcher| matcher.import_provenance.is_none())
311            .expect("a row without provenance exists");
312        let empty = module(Vec::new(), Vec::new());
313        assert!(row.provenance_satisfied(&empty, "anything", ProvenanceBindings::Imports));
314    }
315
316    #[test]
317    fn the_source_match_admits_the_node_prefix_and_package_subpaths() {
318        assert!(import_source_matches("node:child_process", "child_process"));
319        assert!(import_source_matches("child_process", "node:child_process"));
320        assert!(import_source_matches("mysql2/promise", "mysql2"));
321        assert!(!import_source_matches("mysql2-extra", "mysql2"));
322    }
323}