repotoire 0.7.0

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! Shared AST helpers for security detectors.
//!
//! Consolidates `unwrap_callee`, `collect_named_args`, `node_text`,
//! `receiver_chain_label`, `receiver_chain_label_go`, and
//! `receiver_chain_label_js` formerly duplicated across 5+ detectors.
//! Caught by `AIDuplicateBlockDetector` during repotoire dogfooding (see
//! `docs/plans/2026-05-08-security-detector-ast-architecture.md`).
//!
//! Layering: this module depends only on `tree_sitter`. It MUST NOT depend
//! on any other module in the crate to avoid circular imports.

use tree_sitter::Node;

/// Decode a node's source-text slice as UTF-8.
///
/// Returns `None` if the byte range is not valid UTF-8. The end byte is
/// clamped to `source.len()` to defend against tree-sitter overshoot on
/// truncated input.
///
/// Formerly duplicated 6 times across the security detectors.
pub(crate) fn node_text<'a>(node: Node<'_>, source: &'a [u8]) -> Option<&'a str> {
    let start = node.start_byte();
    let end = node.end_byte().min(source.len());
    std::str::from_utf8(&source[start..end]).ok()
}

/// Strip parenthesisation and JS comma-operator wrappers from a callee
/// expression, returning the innermost expression that should be matched
/// against the call shape.
///
/// Handles:
/// - `parenthesized_expression` → first named child
/// - `sequence_expression` → last named child (comma operator: result is
///   the rightmost expression)
///
/// Formerly duplicated 5 times across the security detectors with
/// identical bodies (only comments differed).
pub(crate) fn unwrap_callee(mut node: Node<'_>) -> Node<'_> {
    loop {
        match node.kind() {
            "parenthesized_expression" => {
                let mut next = None;
                for i in 0..node.named_child_count() {
                    if let Some(c) = node.named_child(i) {
                        next = Some(c);
                        break;
                    }
                }
                match next {
                    Some(n) => node = n,
                    None => return node,
                }
            }
            "sequence_expression" => {
                // Last named child wins (comma operator).
                let last = (0..node.named_child_count())
                    .rev()
                    .find_map(|i| node.named_child(i));
                match last {
                    Some(n) => node = n,
                    None => return node,
                }
            }
            _ => return node,
        }
    }
}

/// Collect the named children of an arguments / parameter-list node.
///
/// This is the standard "give me the actual argument expressions, not
/// commas/parens" walk used in every JS/TS/Python call-shape matcher in
/// the security layer.
///
/// Formerly duplicated 6 times (5 as `collect_named_args`, once as
/// `collect_call_args` in `cleartext_credentials.rs` — functionally
/// identical, unified under the more descriptive name).
pub(crate) fn collect_named_args<'a>(args: Node<'a>) -> Vec<Node<'a>> {
    let mut out = Vec::new();
    let mut cursor = args.walk();
    for child in args.children(&mut cursor) {
        if child.is_named() {
            out.push(child);
        }
    }
    out
}

/// Locate a Python `keyword_argument` by name and return its value node.
///
/// Handles the common case where security detectors need to inspect a
/// specific kwarg passed to a function call (e.g. `shell` in
/// `subprocess.run(...)`, `Loader` in `yaml.load(...)`,
/// `allow_pickle` in `numpy.load(...)`).
///
/// The input slice is expected to be the named children of an
/// `argument_list` node (typically obtained via [`collect_named_args`]).
/// Non-keyword positional arguments are ignored.
pub(crate) fn python_kwarg_value<'a>(
    args: &[Node<'a>],
    name: &str,
    source: &[u8],
) -> Option<Node<'a>> {
    for a in args {
        if a.kind() != "keyword_argument" {
            continue;
        }
        let arg_name = a
            .child_by_field_name("name")
            .and_then(|n| node_text(n, source));
        if arg_name == Some(name) {
            return a.child_by_field_name("value");
        }
    }
    None
}

/// Decide whether a Python boolean keyword argument is passed truthy.
///
/// Returns:
/// - `true` if the kwarg's value is the literal `True`.
/// - `false` if the kwarg's value is the literal `False`.
/// - `unknown_default` if the kwarg is present but the value is a
///   non-literal expression (variable, function call, attribute, ...).
///   Detectors choose this based on whether the unsafe path is the
///   conservative default for the call site (e.g. `shell=` and
///   `allow_pickle=` use `true`; `weights_only=` uses `false`).
/// - `false` if the kwarg is absent.
pub(crate) fn python_kwarg_truthy(
    args: &[Node<'_>],
    name: &str,
    source: &[u8],
    unknown_default: bool,
) -> bool {
    match python_kwarg_value(args, name, source) {
        Some(value) => match value.kind() {
            "true" => true,
            "false" => false,
            _ => unknown_default,
        },
        None => false,
    }
}

/// Compute the lower-cased "label" of a receiver expression in a method
/// chain — i.e. the last name in the chain (`a.b.c` → `"c"`,
/// `os.path.join` → `"join"`).
///
/// `call_resolver` is invoked when the receiver itself is a
/// `call_expression`; it lets the detector recognise patterns like
/// `require('child_process').exec` or `(await import('crypto')).randomBytes`
/// by mapping the call to a canonical module name. Pass `None` if the
/// detector does not need module-aware resolution.
///
/// Recognised receiver shapes:
/// - `member_expression` (JS/TS): take the `property` field.
/// - `attribute` (Python): take the `attribute` field.
/// - `selector_expression` (Go): take the `field` field.
/// - `member_access_expression` (C#): take the `name` field.
/// - `call_expression`: try `call_resolver`, otherwise fall back to text.
/// - `await_expression` / `parenthesized_expression`: descend into the
///   first named child.
/// - Anything else: lower-cased source text (covers bare identifiers,
///   `this`, `self`, `super`, etc.).
///
/// Formerly five separate impls with overlapping but divergent shape
/// support. The unified version is a strict superset of every prior
/// behavior. See the migration commit message for the per-detector
/// before/after.
pub(crate) fn receiver_chain_label(
    node: Node<'_>,
    source: &[u8],
    call_resolver: Option<&dyn Fn(Node<'_>, &[u8]) -> Option<&'static str>>,
) -> String {
    match node.kind() {
        // JS/TS `member_expression` and Python `attribute` are unified
        // here: try both field names so a grammar quirk in either
        // language doesn't silently fall through. (`cleartext_credentials`
        // historically did this defensive `or_else` chain.)
        "member_expression" | "attribute" => {
            if let Some(prop) = node
                .child_by_field_name("property")
                .or_else(|| node.child_by_field_name("attribute"))
            {
                if let Some(s) = node_text(prop, source) {
                    return s.to_lowercase();
                }
            }
            node_text(node, source).unwrap_or("").to_lowercase()
        }
        "selector_expression" => {
            if let Some(field) = node.child_by_field_name("field") {
                if let Some(s) = node_text(field, source) {
                    return s.to_lowercase();
                }
            }
            node_text(node, source).unwrap_or("").to_lowercase()
        }
        "member_access_expression" => {
            if let Some(name) = node.child_by_field_name("name") {
                if let Some(s) = node_text(name, source) {
                    return s.to_lowercase();
                }
            }
            node_text(node, source).unwrap_or("").to_lowercase()
        }
        "call_expression" => {
            if let Some(resolver) = call_resolver {
                if let Some(label) = resolver(node, source) {
                    return label.to_string();
                }
            }
            node_text(node, source).unwrap_or("").to_lowercase()
        }
        "await_expression" | "parenthesized_expression" => {
            for i in 0..node.named_child_count() {
                if let Some(c) = node.named_child(i) {
                    return receiver_chain_label(c, source, call_resolver);
                }
            }
            node_text(node, source).unwrap_or("").to_lowercase()
        }
        _ => node_text(node, source).unwrap_or("").to_lowercase(),
    }
}

/// Go-specific receiver-chain label.
///
/// Tree-sitter-go represents method-chains as `selector_expression` with a
/// `field` child, so we don't need the broader JS/Python repertoire here.
/// Kept separate from the unified [`receiver_chain_label`] for clarity at
/// the callsite — `match_go_call` should never see a `member_expression`
/// or `attribute` node.
pub(crate) fn receiver_chain_label_go(node: Node<'_>, source: &[u8]) -> String {
    match node.kind() {
        "selector_expression" => {
            if let Some(field) = node.child_by_field_name("field") {
                if let Some(s) = node_text(field, source) {
                    return s.to_lowercase();
                }
            }
            node_text(node, source).unwrap_or("").to_lowercase()
        }
        _ => node_text(node, source).unwrap_or("").to_lowercase(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tree_sitter::Parser;

    fn parse_js(src: &str) -> tree_sitter::Tree {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_javascript::LANGUAGE.into())
            .expect("load js grammar");
        parser.parse(src, None).expect("parse")
    }

    fn parse_ts(src: &str) -> tree_sitter::Tree {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into())
            .expect("load ts grammar");
        parser.parse(src, None).expect("parse")
    }

    fn parse_python(src: &str) -> tree_sitter::Tree {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_python::LANGUAGE.into())
            .expect("load python grammar");
        parser.parse(src, None).expect("parse")
    }

    fn parse_go(src: &str) -> tree_sitter::Tree {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_go::LANGUAGE.into())
            .expect("load go grammar");
        parser.parse(src, None).expect("parse")
    }

    /// Walk the tree and return the first node whose `kind()` matches.
    fn find_kind<'a>(root: Node<'a>, kind: &str) -> Option<Node<'a>> {
        let mut stack = vec![root];
        while let Some(n) = stack.pop() {
            if n.kind() == kind {
                return Some(n);
            }
            for i in (0..n.child_count()).rev() {
                if let Some(c) = n.child(i) {
                    stack.push(c);
                }
            }
        }
        None
    }

    // ----- unwrap_callee -----

    #[test]
    fn unwrap_callee_parenthesized() {
        // `(eval)("alert(1)")` — the call expression's `function` field is a
        // parenthesized_expression wrapping `eval`.
        let src = "(eval)('x');\n";
        let tree = parse_js(src);
        let call = find_kind(tree.root_node(), "call_expression").expect("call");
        let func = call.child_by_field_name("function").expect("func");
        assert_eq!(func.kind(), "parenthesized_expression");
        let unwrapped = unwrap_callee(func);
        assert_eq!(unwrapped.kind(), "identifier");
        assert_eq!(node_text(unwrapped, src.as_bytes()), Some("eval"));
    }

    #[test]
    fn unwrap_callee_ts_passthrough() {
        // TS `as_expression` is NOT handled here (out of scope of the
        // current consolidated behavior — none of the prior copies handled
        // it either). This test pins that contract: `as` casts pass
        // through unchanged.
        let src = "(x as Foo)();\n";
        let tree = parse_ts(src);
        let call = find_kind(tree.root_node(), "call_expression").expect("call");
        let func = call.child_by_field_name("function").expect("func");
        // The outer wrap is a parenthesized_expression around `x as Foo`.
        let unwrapped = unwrap_callee(func);
        // Should descend through the parens to the as_expression.
        assert_eq!(unwrapped.kind(), "as_expression");
    }

    #[test]
    fn unwrap_callee_plain_identifier() {
        let src = "eval('x');\n";
        let tree = parse_js(src);
        let call = find_kind(tree.root_node(), "call_expression").expect("call");
        let func = call.child_by_field_name("function").expect("func");
        let unwrapped = unwrap_callee(func);
        assert_eq!(unwrapped.kind(), "identifier");
        assert_eq!(unwrapped.id(), func.id());
    }

    // ----- collect_named_args -----

    #[test]
    fn collect_named_args_positional_only() {
        let src = "f(1, 2, 3);\n";
        let tree = parse_js(src);
        let call = find_kind(tree.root_node(), "call_expression").expect("call");
        let args = call.child_by_field_name("arguments").expect("args");
        let collected = collect_named_args(args);
        assert_eq!(collected.len(), 3);
        assert!(collected.iter().all(|n| n.kind() == "number"));
    }

    #[test]
    fn collect_named_args_python_keyword() {
        // Python lets us mix kwargs; both kinds are named children of the
        // argument_list.
        let src = "f(name='x')\n";
        let tree = parse_python(src);
        let call = find_kind(tree.root_node(), "call").expect("call");
        let args = call.child_by_field_name("arguments").expect("args");
        let collected = collect_named_args(args);
        assert_eq!(collected.len(), 1);
        assert_eq!(collected[0].kind(), "keyword_argument");
    }

    #[test]
    fn collect_named_args_mixed() {
        let src = "f(1, 'two', x);\n";
        let tree = parse_js(src);
        let call = find_kind(tree.root_node(), "call_expression").expect("call");
        let args = call.child_by_field_name("arguments").expect("args");
        let collected = collect_named_args(args);
        assert_eq!(collected.len(), 3);
        // commas are unnamed and must be filtered out.
        assert!(!collected.iter().any(|n| n.kind() == ","));
    }

    // ----- python_kwarg_value / python_kwarg_truthy -----

    fn collect_py_call_args<'a>(tree: &'a tree_sitter::Tree) -> Vec<Node<'a>> {
        let call = find_kind(tree.root_node(), "call").expect("call");
        let args = call.child_by_field_name("arguments").expect("args");
        collect_named_args(args)
    }

    #[test]
    fn python_kwarg_value_locates_named_arg() {
        let src = "f(shell=True, timeout=30)\n";
        let tree = parse_python(src);
        let args = collect_py_call_args(&tree);
        let v = python_kwarg_value(&args, "shell", src.as_bytes()).expect("shell value");
        assert_eq!(v.kind(), "true");
        let v2 = python_kwarg_value(&args, "timeout", src.as_bytes()).expect("timeout value");
        assert_eq!(v2.kind(), "integer");
    }

    #[test]
    fn python_kwarg_value_returns_none_for_absent() {
        let src = "f(shell=True)\n";
        let tree = parse_python(src);
        let args = collect_py_call_args(&tree);
        assert!(python_kwarg_value(&args, "missing", src.as_bytes()).is_none());
    }

    #[test]
    fn python_kwarg_value_skips_positional_args() {
        // Positional args are not keyword_arguments; the helper must not
        // misidentify them.
        let src = "f(\"shell\", x)\n";
        let tree = parse_python(src);
        let args = collect_py_call_args(&tree);
        assert!(python_kwarg_value(&args, "shell", src.as_bytes()).is_none());
    }

    #[test]
    fn python_kwarg_truthy_literal_true() {
        let src = "f(shell=True)\n";
        let tree = parse_python(src);
        let args = collect_py_call_args(&tree);
        assert!(python_kwarg_truthy(&args, "shell", src.as_bytes(), false));
        assert!(python_kwarg_truthy(&args, "shell", src.as_bytes(), true));
    }

    #[test]
    fn python_kwarg_truthy_literal_false() {
        let src = "f(shell=False)\n";
        let tree = parse_python(src);
        let args = collect_py_call_args(&tree);
        // Literal False overrides unknown_default in either direction.
        assert!(!python_kwarg_truthy(&args, "shell", src.as_bytes(), false));
        assert!(!python_kwarg_truthy(&args, "shell", src.as_bytes(), true));
    }

    #[test]
    fn python_kwarg_truthy_non_literal_uses_default() {
        let src = "f(shell=some_var)\n";
        let tree = parse_python(src);
        let args = collect_py_call_args(&tree);
        assert!(python_kwarg_truthy(&args, "shell", src.as_bytes(), true));
        assert!(!python_kwarg_truthy(&args, "shell", src.as_bytes(), false));
    }

    #[test]
    fn python_kwarg_truthy_absent_is_false() {
        // Absent kwarg always returns false regardless of unknown_default —
        // the default semantic only kicks in when the kwarg is *present*
        // but its value is non-literal.
        let src = "f(timeout=5)\n";
        let tree = parse_python(src);
        let args = collect_py_call_args(&tree);
        assert!(!python_kwarg_truthy(&args, "shell", src.as_bytes(), true));
        assert!(!python_kwarg_truthy(&args, "shell", src.as_bytes(), false));
    }

    // ----- receiver_chain_label -----

    #[test]
    fn receiver_chain_label_simple_identifier() {
        // For a bare identifier, the label is just its lowercased text.
        let src = "x;\n";
        let tree = parse_js(src);
        let id = find_kind(tree.root_node(), "identifier").expect("id");
        assert_eq!(receiver_chain_label(id, src.as_bytes(), None), "x");
    }

    #[test]
    fn receiver_chain_label_member_chain() {
        // `a.b.c` — the outer member_expression's property is `c`.
        let src = "a.b.c;\n";
        let tree = parse_js(src);
        let mem = find_kind(tree.root_node(), "member_expression").expect("mem");
        // `find_kind` returns the first match found via the LIFO stack walk;
        // for `a.b.c`, that's the outermost expression with property `c`.
        let label = receiver_chain_label(mem, src.as_bytes(), None);
        assert_eq!(label, "c");
    }

    #[test]
    fn receiver_chain_label_python_attribute() {
        let src = "os.path.join\n";
        let tree = parse_python(src);
        let attr = find_kind(tree.root_node(), "attribute").expect("attr");
        let label = receiver_chain_label(attr, src.as_bytes(), None);
        assert_eq!(label, "join");
    }

    #[test]
    fn receiver_chain_label_call_with_resolver() {
        // `require('fs').readFile` — when the resolver matches the
        // `require('fs')` call_expression, it returns `"fs"` and that
        // wins over the raw text.
        let src = "require('fs');\n";
        let tree = parse_js(src);
        let call = find_kind(tree.root_node(), "call_expression").expect("call");
        let resolver = |n: Node<'_>, _src: &[u8]| -> Option<&'static str> {
            if n.kind() == "call_expression" {
                Some("fs")
            } else {
                None
            }
        };
        let label = receiver_chain_label(call, src.as_bytes(), Some(&resolver));
        assert_eq!(label, "fs");
        // Without the resolver, the raw call text falls through.
        let label_noresolve = receiver_chain_label(call, src.as_bytes(), None);
        assert_eq!(label_noresolve, "require('fs')");
    }

    // ----- receiver_chain_label_go -----

    #[test]
    fn receiver_chain_label_go_selector() {
        let src = "package m\nfunc f() { exec.Command(\"ls\") }\n";
        let tree = parse_go(src);
        let sel = find_kind(tree.root_node(), "selector_expression").expect("sel");
        let label = receiver_chain_label_go(sel, src.as_bytes());
        assert_eq!(label, "command");
    }
}