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