milo-guards-code 0.1.3

Reads Python and JavaScript code and says what it is certain to do to files and what it runs, or that it does not understand it.
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! The one gate in front of the inline readers: whether a piece of code is
//! read whole, so that a line with nothing found in it is safe.
//!
//! The readers find the calls that delete, write, move and run, and the paths
//! they name. What they find is kept whatever the code looks like. But a line
//! whose code they find nothing in is only safe when the code is nothing else
//! than a few plain statements the guard reads in full: an allow-list of what
//! the grammar may hold, not a list of what is known to be dangerous. Code
//! that has anything else in it (a function, a class, a loop, an import off
//! the list, a call off the list, a name nothing bound) is `unknown`, because
//! the reader has no row for what it does.
//!
//! The subset, for Python and for JavaScript alike:
//!
//! - it parses, and holds at least one statement;
//! - its statements are expression statements, assignments to a plain name
//!   and `if`/`else`, so the code runs straight through;
//! - its calls are on a short list that only computes (`print`, `len`, `str`,
//!   `time.time`, `console.log`, `Math.max`, the methods of a string or a
//!   list), or `open` in Python, which the reader judges by its path and mode;
//! - its imports are the modules built into the interpreter binary (`sys`,
//!   `errno`, `itertools`, `time`) in Python 3, and `sys` and `errno` alone in
//!   Python 2, which no file in the folder the code runs in can stand in for,
//!   and it has no import, `require` or `eval` in JavaScript;
//! - it names nothing that is not a name it set, a call on the list or a
//!   module on the list that it imported (JavaScript's are always there), and
//!   sets none of those;
//! - it reaches into nothing: no attribute that starts with an underscore, and
//!   in JavaScript no member other than `length` and the methods on the list.

use std::collections::HashSet;

use tree_sitter::Node;

use super::{walk, Ancestor, Language};
use crate::unit::MAX_TREE_DEPTH;

/// Whether `code` is read whole: nothing in it is outside the subset above.
/// `None` when it is not; when it is, `Some(true)` if it may load a module,
/// which looks in the folder the code runs in first (all Python code does,
/// with or without an `import`).
pub(super) fn reads_whole(language: Language, code: &str) -> Option<bool> {
    if has_odd_character(code) {
        return None;
    }
    match language {
        Language::Python => python(code, false),
        Language::JavaScript => javascript(code).then_some(false),
    }
}

/// [`reads_whole`] for Python 2, which has fewer modules built in.
pub(super) fn reads_whole_python2(code: &str) -> Option<bool> {
    if has_odd_character(code) {
        return None;
    }
    python(code, true)
}

/// Whether a node with `above` over it is within [`MAX_TREE_DEPTH`]: the
/// readers stop walking past it (`deep`), so the acts of code nested deeper
/// are not all found, and such code is never read whole.
fn shallow(above: &[Ancestor<'_>]) -> bool {
    above.len() <= MAX_TREE_DEPTH
}

/// Whether `code` holds a control character other than a newline or a tab,
/// or a line separator the grammars and the interpreters read differently.
fn has_odd_character(code: &str) -> bool {
    code.chars().any(|c| {
        (c.is_control() && !matches!(c, '\n' | '\t')) || matches!(c, '\u{2028}' | '\u{2029}')
    })
}

/// The calls of a name alone that compute and touch nothing, and `open`,
/// whose path and mode the reader judges.
const PYTHON_CALLS: [&str; 40] = [
    "print",
    "len",
    "str",
    "int",
    "float",
    "bool",
    "repr",
    "abs",
    "min",
    "max",
    "sum",
    "round",
    "sorted",
    "reversed",
    "list",
    "tuple",
    "dict",
    "set",
    "frozenset",
    "range",
    "enumerate",
    "zip",
    "any",
    "all",
    "ord",
    "chr",
    "hex",
    "bin",
    "oct",
    "divmod",
    "pow",
    "bytes",
    "bytearray",
    "format",
    "ascii",
    "iter",
    "next",
    "open",
    "complex",
    "slice",
];

/// The modules an import may name in Python 3, and the names the code may not
/// set: the ones the `Modules/Setup.bootstrap` of `CPython` compiles into the
/// interpreter binary (`errno`, `itertools`, `time`) and `sys`, which is the
/// interpreter itself. The import system tries the built-in finder before it
/// looks at the import path, so no file in the folder the code runs in can
/// stand in for one of them, and importing one reads nothing from disk. Every
/// other module (`json`, `re`, `math`, which is a file on many builds, and the
/// modules each of them loads in turn) is looked up in that folder first, and
/// an import of one makes the code not read whole. `builtins` is not on the
/// list: it is `__builtin__` in Python 2, so a planted `./builtins.py` would
/// run there, and code may use none of its members anyway.
const PYTHON_MODULES: [&str; 4] = ["errno", "itertools", "sys", "time"];

/// The modules an import may name in Python 2, where only `sys` and `errno`
/// are built into the binary: `time` and `itertools` are shared files of
/// `lib-dynload`, which the import path reaches after the folder the code
/// runs in.
const PYTHON2_MODULES: [&str; 2] = ["errno", "sys"];

/// The modules an import may name, for Python 2 or Python 3.
fn python_modules(python2: bool) -> &'static [&'static str] {
    if python2 {
        &PYTHON2_MODULES
    } else {
        &PYTHON_MODULES
    }
}

/// Whether `module.name` is a member the code may use, as a call or not.
fn python_member(module: &str, name: &str, call: bool) -> bool {
    match module {
        "errno" => !call,
        "sys" => !call && matches!(name, "stdin" | "argv" | "version"),
        "time" => {
            call && matches!(
                name,
                "time" | "time_ns" | "monotonic" | "monotonic_ns" | "perf_counter"
            )
        }
        // `itertools` builds lazy iterators: importing it is read whole and
        // using it is not.
        _ => false,
    }
}

/// Whether a name is plain ASCII letters, digits, `_` and `$`: Python reads a
/// name in its NFKC form (a full-width `__class__` is `__class__`) and
/// JavaScript reads an escape in one (`console`), so a name written any
/// other way is not the name the checks above see.
fn plain_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$'))
}

fn text<'a>(node: Node<'_>, code: &'a str) -> &'a str {
    code.get(node.byte_range()).unwrap_or_default()
}

/// Whether the tree holds a statement that is not a comment.
fn has_statement(root: Node<'_>) -> bool {
    let mut cursor = root.walk();
    let found = root
        .named_children(&mut cursor)
        .any(|child| child.kind() != "comment");
    found
}

/// Python code that is read whole, and whether it imports a module.
fn python(code: &str, python2: bool) -> Option<bool> {
    let mut parser = tree_sitter::Parser::new();
    let tree = parser
        .set_language(&tree_sitter_python::LANGUAGE.into())
        .ok()
        .and_then(|()| parser.parse(code, None))?;
    let root = tree.root_node();
    if root.has_error() || !has_statement(root) {
        return None;
    }
    // The names the code sets, none of which may be a name the reader gives a
    // meaning to, and the modules it imports: a member of a module is only
    // read once the code has named the module.
    let mut assigned = HashSet::new();
    let mut imported = HashSet::new();
    let mut clean = true;
    walk(root, |node, _, _| {
        if node.kind() == "import_statement" {
            let mut cursor = node.walk();
            for name in node.named_children(&mut cursor) {
                imported.insert(text(name, code).to_string());
            }
        }
        let left = match node.kind() {
            "assignment" | "augmented_assignment" => node.child_by_field_name("left"),
            _ => None,
        };
        if let Some(left) = left {
            walk(left, |name, _, _| {
                if name.kind() == "identifier" {
                    let name = text(name, code);
                    clean &= plain_name(name)
                        && !name.starts_with('_')
                        && !PYTHON_CALLS.contains(&name)
                        && !PYTHON_MODULES.contains(&name)
                        // Names of modules that were once importable.
                        && !matches!(name, "json" | "math" | "re");
                    assigned.insert(name.to_string());
                }
                true
            });
        }
        clean
    });
    if !clean {
        return None;
    }
    let mut whole = true;
    walk(root, |node, field, above| {
        whole =
            shallow(above) && python_node(node, field, above, code, &assigned, &imported, python2);
        whole
    });
    // Python loads modules from the folder it runs in without an import
    // statement: an uncaught exception imports `traceback`, the `idna` codec
    // imports `stringprep` and `unicodedata`. So any Python code read whole
    // counts as importing.
    whole.then_some(true)
}

fn python_node(
    node: Node<'_>,
    field: Option<&str>,
    above: &[Ancestor<'_>],
    code: &str,
    assigned: &HashSet<String>,
    imported: &HashSet<String>,
    python2: bool,
) -> bool {
    // A token (`(`, `,`, an operator) is the business of the node it is in.
    if !node.is_named() {
        return true;
    }
    let modules = python_modules(python2);
    let parent = above.last().map(|ancestor| ancestor.node.kind());
    match node.kind() {
        "module"
        | "comment"
        | "expression_statement"
        | "if_statement"
        | "elif_clause"
        | "else_clause"
        | "integer"
        | "float"
        | "true"
        | "false"
        | "none"
        | "string"
        | "string_start"
        | "string_content"
        | "string_end"
        | "escape_sequence"
        | "escape_interpolation"
        | "interpolation"
        | "type_conversion"
        | "format_specifier"
        | "format_expression"
        | "concatenated_string"
        | "list"
        | "tuple"
        | "dictionary"
        | "set"
        | "pair"
        | "binary_operator"
        | "unary_operator"
        | "boolean_operator"
        | "comparison_operator"
        | "not_operator"
        | "parenthesized_expression"
        | "subscript"
        | "slice"
        | "conditional_expression"
        | "argument_list"
        | "keyword_argument"
        | "expression_list"
        | "pattern_list"
        | "tuple_pattern"
        | "list_pattern" => true,
        // A block holds a statement: the grammar lets `if 1:` end the code.
        "block" => {
            let mut cursor = node.walk();
            let filled = node
                .named_children(&mut cursor)
                .any(|child| child.kind() != "comment");
            filled
        }
        "assignment" => {
            node.child_by_field_name("type").is_none()
                && node.child_by_field_name("right").is_some()
                && node.child_by_field_name("left").is_some_and(|left| {
                    matches!(
                        left.kind(),
                        "identifier" | "pattern_list" | "tuple_pattern" | "list_pattern"
                    )
                })
        }
        "augmented_assignment" => node
            .child_by_field_name("left")
            .is_some_and(|left| left.kind() == "identifier"),
        "import_statement" => {
            let mut cursor = node.walk();
            let all = node
                .named_children(&mut cursor)
                .all(|name| name.kind() == "dotted_name" && modules.contains(&text(name, code)));
            all
        }
        "dotted_name" => parent == Some("import_statement"),
        "identifier" => {
            let name = text(node, code);
            plain_name(name)
                && match (parent, field) {
                    (Some("dotted_name"), _) => true,
                    (Some("call"), Some("function")) => {
                        PYTHON_CALLS.contains(&name) && !assigned.contains(name)
                    }
                    // A module is a name once the code imports it.
                    (Some("attribute"), Some("object")) => {
                        imported.contains(name) || assigned.contains(name)
                    }
                    (Some("attribute"), Some("attribute")) => !name.starts_with('_'),
                    (Some("keyword_argument"), Some("name")) => true,
                    _ => assigned.contains(name),
                }
        }
        "attribute" => {
            let (Some(object), Some(attribute)) = (
                node.child_by_field_name("object"),
                node.child_by_field_name("attribute"),
            ) else {
                return false;
            };
            let name = text(attribute, code);
            let call = parent == Some("call") && field == Some("function");
            if name.starts_with('_') {
                return false;
            }
            if object.kind() == "identifier" && modules.contains(&text(object, code)) {
                return python_member(text(object, code), name, call);
            }
            true
        }
        "call" => node
            .child_by_field_name("function")
            .is_some_and(|function| matches!(function.kind(), "identifier" | "attribute")),
        _ => false,
    }
}

/// The calls of a name alone that only compute.
const JAVASCRIPT_CALLS: [&str; 7] = [
    "parseInt",
    "parseFloat",
    "String",
    "Number",
    "Boolean",
    "isNaN",
    "isFinite",
];

/// The objects whose members the code may use, and the names it may not set.
const JAVASCRIPT_MODULES: [&str; 3] = ["console", "JSON", "Math"];

/// The methods of a string, a list or a regular expression the code may call.
const JAVASCRIPT_METHODS: [&str; 33] = [
    "toString",
    "toUpperCase",
    "toLowerCase",
    "trim",
    "trimStart",
    "trimEnd",
    "split",
    "join",
    "slice",
    "substring",
    "indexOf",
    "lastIndexOf",
    "includes",
    "startsWith",
    "endsWith",
    "replace",
    "replaceAll",
    "repeat",
    "padStart",
    "padEnd",
    "concat",
    "charAt",
    "charCodeAt",
    "push",
    "pop",
    "shift",
    "unshift",
    "reverse",
    "sort",
    "at",
    "toFixed",
    "test",
    "match",
];

/// Whether `object.name` is a member of `console`, `JSON` or `Math` the code
/// may use.
fn javascript_member(object: &str, name: &str, call: bool) -> bool {
    match object {
        "console" => call && matches!(name, "log" | "error" | "warn" | "info" | "debug"),
        "JSON" => call && matches!(name, "stringify" | "parse"),
        "Math" => matches!(
            name,
            "abs"
                | "ceil"
                | "floor"
                | "round"
                | "max"
                | "min"
                | "pow"
                | "sqrt"
                | "trunc"
                | "sign"
                | "cbrt"
                | "hypot"
                | "log"
                | "log2"
                | "log10"
                | "exp"
                | "sin"
                | "cos"
                | "tan"
                | "atan"
                | "atan2"
                | "random"
                | "PI"
                | "E"
        ),
        _ => false,
    }
}

fn javascript(code: &str) -> bool {
    let mut parser = tree_sitter::Parser::new();
    let Some(tree) = parser
        .set_language(&tree_sitter_javascript::LANGUAGE.into())
        .ok()
        .and_then(|()| parser.parse(code, None))
    else {
        return false;
    };
    let root = tree.root_node();
    if root.has_error() || !has_statement(root) {
        return false;
    }
    let mut assigned = HashSet::new();
    let mut clean = true;
    walk(root, |node, _, _| {
        let name = match node.kind() {
            "variable_declarator" => node.child_by_field_name("name"),
            "assignment_expression" | "augmented_assignment_expression" => {
                node.child_by_field_name("left")
            }
            "update_expression" => node.child_by_field_name("argument"),
            _ => None,
        };
        if let Some(name) = name.filter(|name| name.kind() == "identifier") {
            let name = text(name, code);
            clean &= plain_name(name)
                && !name.starts_with('_')
                && !JAVASCRIPT_CALLS.contains(&name)
                && !JAVASCRIPT_MODULES.contains(&name);
            assigned.insert(name.to_string());
        }
        clean
    });
    if !clean {
        return false;
    }
    let mut whole = true;
    walk(root, |node, field, above| {
        whole = shallow(above) && javascript_node(node, field, above, code, &assigned);
        whole
    });
    whole
}

fn javascript_node(
    node: Node<'_>,
    field: Option<&str>,
    above: &[Ancestor<'_>],
    code: &str,
    assigned: &HashSet<String>,
) -> bool {
    // A token (`(`, `,`, an operator) is the business of the node it is in.
    if !node.is_named() {
        return true;
    }
    let parent = above.last().map(|ancestor| ancestor.node.kind());
    match node.kind() {
        "program"
        | "comment"
        | "expression_statement"
        | "lexical_declaration"
        | "variable_declaration"
        | "if_statement"
        | "else_clause"
        | "parenthesized_expression"
        | "sequence_expression"
        | "ternary_expression"
        | "binary_expression"
        | "number"
        | "string"
        | "string_fragment"
        | "escape_sequence"
        | "template_string"
        | "template_substitution"
        | "regex"
        | "regex_pattern"
        | "regex_flags"
        | "true"
        | "false"
        | "null"
        | "undefined"
        | "array"
        | "object"
        | "pair"
        | "arguments"
        | "optional_chain" => true,
        "statement_block" => {
            let mut cursor = node.walk();
            let filled = node
                .named_children(&mut cursor)
                .any(|child| child.kind() != "comment");
            filled && matches!(parent, Some("if_statement" | "else_clause"))
        }
        "variable_declarator" => node
            .child_by_field_name("name")
            .is_some_and(|name| name.kind() == "identifier"),
        "assignment_expression" | "augmented_assignment_expression" => node
            .child_by_field_name("left")
            .is_some_and(|left| left.kind() == "identifier"),
        "update_expression" => node
            .child_by_field_name("argument")
            .is_some_and(|argument| argument.kind() == "identifier"),
        "unary_expression" => node
            .child_by_field_name("operator")
            .is_some_and(|operator| {
                matches!(text(operator, code), "!" | "-" | "+" | "~" | "typeof")
            }),
        "property_identifier" => {
            let name = text(node, code);
            plain_name(name)
                && match (parent, field) {
                    (Some("member_expression"), Some("property")) => true,
                    (Some("pair"), Some("key")) => {
                        !name.starts_with('_') && !matches!(name, "constructor" | "prototype")
                    }
                    _ => false,
                }
        }
        "shorthand_property_identifier" => {
            let name = text(node, code);
            plain_name(name) && assigned.contains(name)
        }
        "identifier" => {
            let name = text(node, code);
            plain_name(name)
                && match (parent, field) {
                    (Some("call_expression"), Some("function")) => {
                        JAVASCRIPT_CALLS.contains(&name) && !assigned.contains(name)
                    }
                    (Some("member_expression"), Some("object")) => {
                        JAVASCRIPT_MODULES.contains(&name) || assigned.contains(name)
                    }
                    (Some("variable_declarator"), Some("name")) => true,
                    _ => assigned.contains(name),
                }
        }
        "member_expression" => {
            let (Some(object), Some(property)) = (
                node.child_by_field_name("object"),
                node.child_by_field_name("property"),
            ) else {
                return false;
            };
            let name = text(property, code);
            let call = parent == Some("call_expression") && field == Some("function");
            if property.kind() != "property_identifier" || name.starts_with('_') {
                return false;
            }
            if object.kind() == "identifier" && JAVASCRIPT_MODULES.contains(&text(object, code)) {
                return javascript_member(text(object, code), name, call);
            }
            if call {
                JAVASCRIPT_METHODS.contains(&name)
            } else {
                name == "length"
            }
        }
        "subscript_expression" => node
            .child_by_field_name("index")
            .is_some_and(|index| index.kind() == "number"),
        "call_expression" => node
            .child_by_field_name("function")
            .is_some_and(|function| matches!(function.kind(), "identifier" | "member_expression")),
        _ => false,
    }
}