harn-vm 0.10.169

Async bytecode virtual machine for the Harn programming language
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
//! Static execution facts for command strings. Unknown shell state is never
//! evidence that a program is missing.

use std::collections::BTreeMap;

use tree_sitter::Node;

/// The first statically named executable and the environment prefixes that
/// affect its lookup. `argv` is available only for a plain external command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandPlan {
    pub program: String,
    pub environment: BTreeMap<String, String>,
    pub argv: Option<Vec<String>>,
    /// Observed literal invocation, including env prefixes. This is evidence
    /// for inspection only; it never authorizes shell-to-direct conversion.
    pub literal_argv: Option<Vec<String>>,
    /// Shell lookup requires ruling out startup code and imported functions.
    pub requires_clean_shell_environment: bool,
}

/// Whether one effective environment entry makes POSIX shell startup or
/// imported command functions unknown. Callers inspect their resolved child
/// environment; this does not read the ambient process environment.
pub fn shell_startup_entry_may_change_lookup(name: &str, value: &str) -> bool {
    crate::security::environment_policy::environment_names_equal(name, "BASH_ENV")
        || crate::security::environment_policy::environment_names_equal(name, "ENV")
        || name.starts_with("BASH_FUNC_")
        || value.trim_start().starts_with("()")
}

/// Resolve the first program of an invocation, including a POSIX shell or
/// env wrapper. Other shell dialects retain their native execution behavior.
pub fn plan_invocation(program: &str, args: &[String]) -> Option<CommandPlan> {
    match super::shell_dialect_for_id(program) {
        Some(super::ShellDialect::Posix) => {
            // Login and interactive startup files can define functions or
            // change PATH, so pre-spawn filesystem evidence is insufficient.
            if args.first().map(String::as_str) != Some("-c") {
                return None;
            }
            // zsh reads startup files even for a noninteractive `-c` invocation.
            let name = program.rsplit(['/', '\\']).next()?.to_ascii_lowercase();
            if name.strip_suffix(".exe").unwrap_or(&name) == "zsh" {
                return None;
            }
            let mut plan = plan_posix_command(args.get(1)?)?;
            plan.requires_clean_shell_environment = true;
            Some(plan)
        }
        Some(_) => None,
        None => {
            let source = std::iter::once(program)
                .chain(args.iter().map(String::as_str))
                .map(shell_words::quote)
                .collect::<Vec<_>>()
                .join(" ");
            // An argv invocation may name an external executable with the
            // same name as a shell builtin.
            if program != "env" && !program.ends_with("/env") {
                return Some(CommandPlan {
                    program: program.to_string(),
                    environment: BTreeMap::new(),
                    argv: None,
                    literal_argv: Some(
                        std::iter::once(program.to_string())
                            .chain(args.iter().cloned())
                            .collect(),
                    ),
                    requires_clean_shell_environment: false,
                });
            }
            plan_posix_command(&source)
        }
    }
}

/// Analyze a POSIX command without evaluating expansions or executing it.
pub fn plan_posix_command(source: &str) -> Option<CommandPlan> {
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&tree_sitter_bash::LANGUAGE.into())
        .ok()?;
    let tree = parser.parse(source, None)?;
    let root = tree.root_node();
    if root.has_error() {
        return None;
    }
    let mut command = root.named_child(0)?;
    let single = root.child_count() == 1 && command.kind() == "command";
    while matches!(command.kind(), "list" | "pipeline" | "redirected_statement") {
        command = command.named_child(0)?;
    }
    if command.kind() != "command" {
        return None;
    }
    let name = command.child_by_field_name("name")?;
    let mut argv = vec![literal(name, source)?];
    let mut environment = BTreeMap::new();
    let mut cursor = command.walk();
    for child in command.named_children(&mut cursor) {
        if child.kind() == "variable_assignment" {
            let text = child.utf8_text(source.as_bytes()).ok()?;
            let (key, value) = text.split_once('=')?;
            // Assignment expansion can change PATH. Decline the whole probe
            // instead of searching a guessed environment.
            if dynamic(child) || value.contains(['$', '~', '{', '}']) {
                return None;
            }
            let words = shell_words::split(value).ok()?;
            let value = match words.as_slice() {
                [] => String::new(),
                [value] => value.clone(),
                _ => return None,
            };
            environment.insert(key.to_string(), value);
        }
    }
    let mut cursor = command.walk();
    let mut all_literal = true;
    for arg in command.children_by_field_name("argument", &mut cursor) {
        if let Some(value) = literal(arg, source) {
            argv.push(value);
        } else {
            all_literal = false;
            break;
        }
    }
    let mut cursor = command.walk();
    let only_words = command.named_children(&mut cursor).all(|child| {
        child == name
            || command
                .children_by_field_name("argument", &mut command.walk())
                .any(|arg| arg == child)
    });
    let plain = single && environment.is_empty() && all_literal && only_words;
    let mut index = 0;
    if argv.len() > 1 && (argv[0] == "env" || argv[0].ends_with("/env")) {
        // Do not interpret unknown env options (notably -S or -i) using a
        // partial argv or the enclosing shell's environment.
        if !all_literal {
            return None;
        }
        index = 1;
        while let Some(word) = argv.get(index) {
            if let Some((key, value)) = word.split_once('=') {
                if key.is_empty() || key.starts_with('-') {
                    return None;
                }
                environment.insert(key.to_string(), value.to_string());
                index += 1;
            } else if word == "--" {
                index += 1;
                break;
            } else {
                break;
            }
        }
    }
    let program = argv.get(index)?.clone();
    if program.starts_with('-') || (index == 0 && shell_builtin(&program)) {
        return None;
    }
    Some(CommandPlan {
        requires_clean_shell_environment: false,
        program,
        environment,
        literal_argv: (single && all_literal).then(|| argv[index..].to_vec()),
        argv: (plain && index == 0).then_some(argv),
    })
}

fn literal(node: Node<'_>, source: &str) -> Option<String> {
    if dynamic(node) {
        return None;
    }
    let raw = node.utf8_text(source.as_bytes()).ok()?;
    if raw.contains(['*', '?', '[', '{', '~', '$', '(', ')']) || raw.starts_with('=') {
        return None;
    }
    let words = shell_words::split(raw).ok()?;
    (words.len() == 1).then(|| words[0].clone())
}

fn dynamic(node: Node<'_>) -> bool {
    if matches!(
        node.kind(),
        "expansion"
            | "simple_expansion"
            | "command_substitution"
            | "arithmetic_expansion"
            | "process_substitution"
    ) {
        return true;
    }
    let mut cursor = node.walk();
    let found = node.named_children(&mut cursor).any(dynamic);
    found
}

fn shell_builtin(program: &str) -> bool {
    matches!(
        program,
        ":" | "."
            | "["
            | "alias"
            | "bg"
            | "bind"
            | "break"
            | "builtin"
            | "cd"
            | "command"
            | "caller"
            | "compgen"
            | "complete"
            | "compopt"
            | "coproc"
            | "continue"
            | "declare"
            | "dirs"
            | "disown"
            | "echo"
            | "enable"
            | "eval"
            | "exec"
            | "exit"
            | "export"
            | "false"
            | "fc"
            | "fg"
            | "getopts"
            | "hash"
            | "help"
            | "history"
            | "jobs"
            | "kill"
            | "let"
            | "local"
            | "logout"
            | "mapfile"
            | "popd"
            | "printf"
            | "pushd"
            | "pwd"
            | "read"
            | "readarray"
            | "readonly"
            | "return"
            | "set"
            | "shift"
            | "shopt"
            | "source"
            | "test"
            | "times"
            | "time"
            | "trap"
            | "true"
            | "type"
            | "typeset"
            | "ulimit"
            | "umask"
            | "unalias"
            | "unset"
            | "wait"
            | "autoload"
            | "bindkey"
            | "bye"
            | "chdir"
            | "compadd"
            | "comparguments"
            | "compcall"
            | "compctl"
            | "compdescribe"
            | "compfiles"
            | "compgroups"
            | "compquote"
            | "compset"
            | "comptags"
            | "comptry"
            | "compvalues"
            | "disable"
            | "echotc"
            | "echoti"
            | "emulate"
            | "float"
            | "functions"
            | "getln"
            | "integer"
            | "limit"
            | "log"
            | "noglob"
            | "nocorrect"
            | "print"
            | "private"
            | "pushln"
            | "r"
            | "rehash"
            | "sched"
            | "setopt"
            | "suspend"
            | "ttyctl"
            | "unfunction"
            | "unhash"
            | "unlimit"
            | "unsetopt"
            | "vared"
            | "whence"
            | "where"
            | "which"
            | "zcompile"
            | "zformat"
            | "zle"
            | "zmodload"
            | "zparseopts"
            | "zregexparse"
            | "zstyle"
    )
}

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

    #[test]
    fn command_plan_preserves_shell_semantics() {
        let plain = plan_posix_command("cargo test 'a b'").unwrap();
        assert_eq!(plain.argv.unwrap(), ["cargo", "test", "a b"]);
        for source in [
            "cargo test && true",
            "cargo test | cat",
            "cargo test > out",
            "> out cargo test",
            "cargo test <<< input",
            "X=1 cargo test",
            "cargo *.rs",
            "cargo test &",
            "cargo $'quoted\\nargument'",
        ] {
            let plan = plan_posix_command(source).unwrap();
            assert_eq!(plan.program, "cargo");
            assert!(plan.argv.is_none(), "{source}");
        }
        for source in [
            "$PROGRAM test",
            "PATH=$OTHER cargo test",
            "PATH=~/tools cargo test",
            "f() { absent; }; f",
            "echo hi",
            "exit 127",
            "print hello",
            "$'cargo' test",
        ] {
            assert!(plan_posix_command(source).is_none(), "{source}");
        }
        let env = plan_posix_command("env VAR=1 PATH=/tools ./relative/prog").unwrap();
        assert_eq!(env.program, "./relative/prog");
        assert_eq!(env.environment["PATH"], "/tools");
        assert!(env.argv.is_none());
    }

    #[test]
    fn shell_invocation_records_startup_uncertainty() {
        let args = vec!["-c".to_string(), "absent_8932".to_string()];
        assert!(plan_invocation("/bin/zsh", &args).is_none());
        assert!(
            plan_invocation("/bin/bash", &args)
                .unwrap()
                .requires_clean_shell_environment
        );
        assert!(
            !plan_invocation("absent_8932", &[])
                .unwrap()
                .requires_clean_shell_environment
        );
    }

    #[test]
    fn literal_loader_inspection_does_not_authorize_shell_conversion() {
        for source in [
            "PYTHONPATH=/workspace python -m pytest test_calc.py",
            "env PYTHONPATH=/workspace python -m pytest test_calc.py",
        ] {
            let plan = plan_posix_command(source).unwrap();
            assert_eq!(plan.program, "python");
            assert_eq!(plan.environment["PYTHONPATH"], "/workspace");
            assert_eq!(
                plan.literal_argv.as_deref(),
                Some(
                    ["python", "-m", "pytest", "test_calc.py"]
                        .map(String::from)
                        .as_slice()
                ),
            );
            assert!(
                plan.argv.is_none(),
                "inspection cannot authorize conversion: {source}"
            );
        }
        for source in ["python -m pytest > output", "python -m $MODULE"] {
            let plan = plan_posix_command(source).unwrap();
            assert!(
                plan.literal_argv.is_none(),
                "ambiguous loader invocation: {source}"
            );
            assert!(plan.argv.is_none());
        }
    }
}