1use fallow_types::extract::ModuleInfo;
10
11use crate::Matcher;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum ProvenanceBindings {
16 Imports,
18 ImportsAndRequires,
23 ReleasedModule,
32}
33
34const 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 #[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 #[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 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
105fn 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#[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#[allow(
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 local_name: local.map(str::to_owned),
184 is_type_only: false,
185 }
186 }
187
188 fn export(name: &str) -> ExportInfo {
189 ExportInfo {
190 name: ExportName::Named(name.to_owned()),
191 local_name: None,
192 is_type_only: false,
193 is_side_effect_used: false,
194 visibility: VisibilityTag::None,
195 expected_unused_reason: None,
196 deprecated: false,
197 deprecated_reason: None,
198 span: Span::default(),
199 members: Vec::new(),
200 super_class: None,
201 }
202 }
203
204 fn module(imports: Vec<ImportInfo>, requires: Vec<RequireCallInfo>) -> ModuleInfo {
205 ModuleInfo {
206 imports,
207 require_calls: requires,
208 ..ModuleInfo::empty(FileId(0))
209 }
210 }
211
212 #[test]
213 fn a_local_get_does_not_satisfy_the_https_row() {
214 let tls = row("tls-validation-disabled", SinkShape::Call, "get");
215 let local = module(vec![import("./get", "get")], Vec::new());
216 assert!(!tls.provenance_satisfied(&local, "get", ProvenanceBindings::ImportsAndRequires));
217 let unbound = module(Vec::new(), Vec::new());
218 assert!(!tls.provenance_satisfied(&unbound, "get", ProvenanceBindings::Imports));
219 }
220
221 #[test]
222 fn the_https_import_must_bind_the_leading_identifier() {
223 let tls = row("tls-validation-disabled", SinkShape::Call, "get");
224 let named = module(vec![import("node:https", "get")], Vec::new());
225 assert!(tls.provenance_satisfied(&named, "get", ProvenanceBindings::Imports));
226 let other = module(vec![import("https", "request")], Vec::new());
227 assert!(!tls.provenance_satisfied(&other, "get", ProvenanceBindings::Imports));
228 }
229
230 #[test]
231 fn a_node_root_proves_only_its_own_module() {
232 let vm = row(
233 "code-injection",
234 SinkShape::MemberCall,
235 "node:vm.runInNewContext",
236 );
237 let bare = module(Vec::new(), Vec::new());
238 assert!(vm.provenance_satisfied(
239 &bare,
240 "node:vm.runInNewContext",
241 ProvenanceBindings::Imports
242 ));
243 assert!(!vm.provenance_satisfied(&bare, "vm.runInNewContext", ProvenanceBindings::Imports));
244 assert!(!vm.provenance_satisfied(
245 &bare,
246 "node:fs.runInNewContext",
247 ProvenanceBindings::Imports
248 ));
249 }
250
251 #[test]
252 fn a_row_without_binding_trace_accepts_any_import_of_the_source() {
253 let fs = row("path-traversal", SinkShape::MemberCall, "fs.readFile");
254 assert!(!fs.requires_binding_trace());
255 let imported = module(vec![import("fs", "files")], Vec::new());
256 assert!(fs.provenance_satisfied(&imported, "fs.readFile", ProvenanceBindings::Imports));
257 }
258
259 #[test]
260 fn a_require_call_counts_only_when_the_caller_admits_requires() {
261 let tls = row(
262 "tls-validation-disabled",
263 SinkShape::MemberCall,
264 "https.get",
265 );
266 let namespace = module(Vec::new(), vec![require("https", Some("https"), &[])]);
267 assert!(!tls.provenance_satisfied(&namespace, "https.get", ProvenanceBindings::Imports));
268 assert!(tls.provenance_satisfied(
269 &namespace,
270 "https.get",
271 ProvenanceBindings::ImportsAndRequires
272 ));
273 let destructured = module(Vec::new(), vec![require("node:https", None, &["get"])]);
274 assert!(tls.provenance_satisfied(
275 &destructured,
276 "get",
277 ProvenanceBindings::ImportsAndRequires
278 ));
279 }
280
281 #[test]
282 fn a_released_module_treats_an_unbound_identifier_as_a_hidden_require() {
283 let tls = row(
284 "tls-validation-disabled",
285 SinkShape::MemberCall,
286 "https.get",
287 );
288 let mode = ProvenanceBindings::ReleasedModule;
289 let unbound = module(Vec::new(), Vec::new());
290 assert!(tls.provenance_satisfied(&unbound, "https.get", mode));
291 let elsewhere = module(vec![import("./client", "https")], Vec::new());
292 assert!(!tls.provenance_satisfied(&elsewhere, "https.get", mode));
293 let get = row("tls-validation-disabled", SinkShape::Call, "get");
294 let exported = ModuleInfo {
295 exports: vec![export("get")].into(),
296 ..module(Vec::new(), Vec::new())
297 };
298 assert!(!get.provenance_satisfied(&exported, "get", mode));
299 let imported = module(vec![import("node:https", "get")], Vec::new());
300 assert!(get.provenance_satisfied(&imported, "get", mode));
301 }
302
303 #[test]
304 fn a_row_without_provenance_is_always_satisfied() {
305 let row = crate::catalogue()
306 .matchers()
307 .iter()
308 .find(|matcher| matcher.import_provenance.is_none())
309 .expect("a row without provenance exists");
310 let empty = module(Vec::new(), Vec::new());
311 assert!(row.provenance_satisfied(&empty, "anything", ProvenanceBindings::Imports));
312 }
313
314 #[test]
315 fn the_source_match_admits_the_node_prefix_and_package_subpaths() {
316 assert!(import_source_matches("node:child_process", "child_process"));
317 assert!(import_source_matches("child_process", "node:child_process"));
318 assert!(import_source_matches("mysql2/promise", "mysql2"));
319 assert!(!import_source_matches("mysql2-extra", "mysql2"));
320 }
321}