harn-vm 0.10.155

Async bytecode virtual machine for the Harn programming language
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
/// The never-approvable command floor. A command that this module flags is
/// denied before the child spawns and is never routed to the consent gate.
///
/// The classifier is intentionally precision-over-recall and is NOT a complete
/// sandbox; it catches the obvious irreversible-destruction shapes (fork bomb,
/// `git reset --hard` / `git clean -fd` / force-push, `rm -rf` escaping the
/// workspace root or wiping it in place, `dd of=`, `mkfs`, `chmod -R 000`,
/// `truncate -s 0` of a tracked project file, and `>`/`>>` redirection onto a
/// tracked project file) through adversarial quoting, chained-command splitting, `bash -c`
/// recursion, and the `sudo`/`env`/`nice`/`nohup`/`time`/`timeout`/`command`/
/// `builtin`/`exec` wrapper family. Executable identity and nesting come from
/// the shared shell AST; the remaining text checks only inspect syntax that is
/// not an executable command (fork-bomb grammar and tracked-file redirects).
use std::path::Path;

mod project_delete;
mod semantic_shell;
mod shell;
mod tracked_writes;

use project_delete::argv_deletes_project;
pub(super) use semantic_shell::{
    analyze_argv, analyze_shell, analyze_shell_dialect, ShellAnalysis,
};
use shell::*;

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct ShellCommandStage {
    pub(super) text: String,
    pub(super) argv: Vec<String>,
    /// Expansion marker for each argv element.
    pub(super) dynamic: Vec<bool>,
}

/// Maximum `bash -c` recursion depth. Each level strips a shell wrapper, so
/// the string strictly shrinks; the cap is a defensive bound only.
const MAX_DEPTH: usize = 8;

const PROJECT_DELETE_REASON: &str = "destructive recursive deletion of the project root is blocked";

const FORK_BOMB_REASON: &str =
    "fork bomb (`:(){ :|:& };:`) is blocked: it would exhaust the machine";

/// Classify `command` against the floor. `workspace_roots` are the absolute
/// workspace roots (an `rm -rf` target is an escape unless it resolves
/// inside one of them); an empty slice means "no root context", under which
/// every absolute path is conservatively treated as an escape. Returns the
/// blocking reason.
pub(super) fn reason_at_with_analysis(
    analysis: &ShellAnalysis,
    workspace_roots: &[String],
    active_cwd: Option<&Path>,
) -> Option<String> {
    reason_from_analysis(analysis, workspace_roots, active_cwd, 0)
}

/// Classify already-resolved argv without interpreting ordinary arguments as
/// shell syntax. Only an actual POSIX shell `-c` payload re-enters `reason_at`.
pub(super) fn reason_argv(
    argv: &[String],
    workspace_roots: &[String],
    active_cwd: Option<&Path>,
) -> Option<String> {
    let analysis = analyze_argv(argv);
    reason_at_with_analysis(&analysis, workspace_roots, active_cwd)
}

pub(super) fn command_segments(command: &str) -> Vec<String> {
    command_segments_inner(command, 0)
}

/// Parse a shell command into chain groups and pipeline stages. This is the
/// shared shell boundary for policy written outside Rust; consumers receive
/// normalized argv while the original stage text remains available for
/// syntax-sensitive checks such as output redirection.
pub(super) fn shell_command_groups(command: &str) -> Vec<Vec<ShellCommandStage>> {
    split_chained_command(command)
        .into_iter()
        .filter_map(|group| {
            let stages = split_pipeline_command(&group)
                .into_iter()
                .filter_map(|text| {
                    let tokens = shell_words(&text);
                    let index = unwrapped_shell_command_index(&tokens, 0, tokens.len());
                    (index < tokens.len()).then(|| ShellCommandStage {
                        text: text.trim().to_string(),
                        argv: tokens[index..].to_vec(),
                        dynamic: vec![false; tokens.len() - index],
                    })
                })
                .collect::<Vec<_>>();
            (!stages.is_empty()).then_some(stages)
        })
        .collect()
}

fn command_segments_inner(command: &str, depth: usize) -> Vec<String> {
    if depth > MAX_DEPTH {
        return Vec::new();
    }
    let mut segments = Vec::new();
    for segment in split_chained_command(command) {
        push_unique(&mut segments, segment.trim());
        let tokens = shell_words(&segment);
        let mut start = 0;
        while start < tokens.len() {
            let end = next_pipeline_boundary(&tokens, start);
            if start < end {
                push_unique(&mut segments, &tokens[start..end].join(" "));
                let command_index = unwrapped_shell_command_index(&tokens, start, end);
                if command_index < end {
                    let command = command_basename(&tokens[command_index]);
                    if matches!(command, "bash" | "sh" | "zsh") {
                        if let Some(script) = shell_c_script(&tokens[(command_index + 1)..end]) {
                            for inner in command_segments_inner(script, depth + 1) {
                                push_unique(&mut segments, &inner);
                            }
                        }
                    }
                }
            }
            start = end + 1;
        }
    }
    segments
}

fn push_unique(values: &mut Vec<String>, value: &str) {
    let value = value.trim();
    if !value.is_empty() && !values.iter().any(|existing| existing == value) {
        values.push(value.to_string());
    }
}

fn reason_inner(
    command: &str,
    roots: &[String],
    active_cwd: Option<&Path>,
    depth: usize,
) -> Option<String> {
    let analysis = analyze_shell(command);
    reason_from_analysis(&analysis, roots, active_cwd, depth)
}

fn reason_from_analysis(
    analysis: &ShellAnalysis,
    roots: &[String],
    active_cwd: Option<&Path>,
    depth: usize,
) -> Option<String> {
    if depth > MAX_DEPTH {
        return None;
    }
    // Fork bomb is checked on the WHOLE command first: splitting on `;`/`&`
    // would tear `:(){ :|:& };:` apart before it can be recognized.
    if analysis.fork_bomb {
        return Some(FORK_BOMB_REASON.to_string());
    }
    for redirect in &analysis.redirects {
        if redirect.writes_file() && !redirect.dynamic {
            if let Some(destination) = redirect.destination.as_deref() {
                if let Some(reason) = tracked_writes::redirect_target_over_tracked_reason(
                    destination,
                    active_cwd,
                    roots,
                ) {
                    return Some(reason);
                }
            }
        }
    }
    for stage in &analysis.stages {
        if argv_deletes_project(&stage.argv) {
            return Some(PROJECT_DELETE_REASON.to_string());
        }
        if let Some(hit) =
            invocation_catastrophe(&stage.argv, 0, stage.argv.len(), roots, active_cwd, depth)
        {
            return Some(hit);
        }
    }
    None
}

fn invocation_catastrophe(
    tokens: &[String],
    start: usize,
    end: usize,
    roots: &[String],
    active_cwd: Option<&Path>,
    depth: usize,
) -> Option<String> {
    let command_index = unwrapped_command_index(tokens, start, end);
    if command_index >= end {
        return None;
    }
    let argv = &tokens[command_index..end];
    let command = command_basename(&argv[0]);
    let args = &argv[1..];

    // bash/sh/zsh -c '<script>' → recurse into the inner script (category
    // inherited from the inner classification).
    if matches!(command, "bash" | "sh" | "zsh") {
        if let Some(script) = shell_c_script(args) {
            if let Some(hit) = reason_inner(script, roots, active_cwd, depth + 1) {
                return Some(hit);
            }
        }
    }

    match command {
        "git" => git_catastrophe(args),
        "rm" => rm_escape_catastrophe(args, roots),
        "dd" => dd_catastrophe(args),
        "mkfs" | "mke2fs" => Some(format!(
            "`{command}` (filesystem format) is blocked: it would destroy a device"
        )),
        _ if command.starts_with("mkfs.") => Some(format!(
            "`{command}` (filesystem format) is blocked: it would destroy a device"
        )),
        "chmod" => chmod_catastrophe(args),
        "truncate" => tracked_writes::truncate_catastrophe(args, active_cwd, roots),
        _ => None,
    }
}

// -c detection: skip `--`, scan short-flag clusters for 'c', return the NEXT
// token as the script.
fn shell_c_script(args: &[String]) -> Option<&str> {
    let mut index = 0;
    while index < args.len() {
        let token = &args[index];
        if token == "--" {
            index += 1;
            continue;
        }
        if token.starts_with('-') && token != "-" {
            if token.chars().skip(1).any(|flag| flag == 'c') {
                return args.get(index + 1).map(String::as_str);
            }
            index += 1;
            continue;
        }
        return None;
    }
    None
}

/// Split git's argv (after the `git` word) into its subcommand and that
/// subcommand's arguments, skipping global options. Value-taking global options
/// consume the next token.
fn git_subcommand(args: &[String]) -> Option<(&str, &[String])> {
    let mut index = 0;
    while index < args.len() {
        let token = &args[index];
        match token.as_str() {
            "-C" | "-c" | "--git-dir" | "--work-tree" | "--namespace" | "--config-env" => {
                index += 2;
                continue;
            }
            _ if token.starts_with('-') => {
                index += 1;
                continue;
            }
            _ => break,
        }
    }
    let subcommand = args.get(index)?.as_str();
    Some((subcommand, &args[(index + 1).min(args.len())..]))
}

/// How a `git push` can change remote refs beyond a fast-forward.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RemoteRefRewrite {
    /// `--delete`/`-d`, `--prune`, or a `:dst` refspec removes a remote ref.
    Delete,
    /// `--force`/`-f`, `--force-with-lease`, `--mirror`, or a `+src:dst`
    /// refspec can overwrite a remote ref with unrelated history.
    Force,
}

/// Classify `git push <args>` from its argv. This is the one owner of the
/// judgment: the never-approvable floor blocks [`RemoteRefRewrite::Force`] and
/// the `git_force_push` label covers both kinds, so the two cannot disagree.
///
/// Long options may be abbreviated to any prefix, as git's option parser
/// accepts unambiguous ones; an ambiguous prefix fails in git, so classifying
/// it costs nothing. Refspecs come from argv only: a configured
/// `remote.<name>.push` or `push.default` is not visible here.
fn git_push_rewrite(args: &[String]) -> Option<RemoteRefRewrite> {
    fn abbreviates(name: &str, option: &str) -> bool {
        name.len() > 2 && option.starts_with(name)
    }

    let mut rewrite = None;
    let mut options = true;
    let mut index = 0;
    while index < args.len() {
        let arg = args[index].as_str();
        index += 1;
        if options && arg == "--" {
            options = false;
            continue;
        }
        if options && arg.starts_with("--") {
            let (name, value) = match arg.split_once('=') {
                Some((name, value)) => (name, Some(value)),
                None => (arg, None),
            };
            if ["--force", "--force-with-lease", "--mirror"]
                .iter()
                .any(|option| abbreviates(name, option))
            {
                return Some(RemoteRefRewrite::Force);
            }
            if ["--delete", "--prune"]
                .iter()
                .any(|option| abbreviates(name, option))
            {
                rewrite = Some(RemoteRefRewrite::Delete);
            } else if value.is_none()
                && [
                    "--push-option",
                    "--repo",
                    "--receive-pack",
                    "--exec",
                    "--recurse-submodules",
                ]
                .iter()
                .filter(|option| abbreviates(name, option))
                .count()
                    == 1
            {
                index += 1;
            }
            continue;
        }
        if options && arg.starts_with('-') && arg.len() > 1 {
            for (offset, flag) in arg.char_indices().skip(1) {
                match flag {
                    'f' => return Some(RemoteRefRewrite::Force),
                    'd' => rewrite = Some(RemoteRefRewrite::Delete),
                    // `-o` takes the rest of the cluster, or the next token.
                    'o' => {
                        if offset + 1 == arg.len() {
                            index += 1;
                        }
                        break;
                    }
                    _ => {}
                }
            }
            continue;
        }
        if arg.starts_with('+') {
            return Some(RemoteRefRewrite::Force);
        }
        // A bare `:` pushes matching branches without forcing.
        if arg.starts_with(':') && arg != ":" {
            rewrite = Some(RemoteRefRewrite::Delete);
        }
    }
    rewrite
}

/// Whether any command in `analysis`, including one nested in a `bash -c`
/// payload or behind a wrapper such as `env` or `sudo`, is a `git push` that
/// can overwrite or delete a remote ref.
pub(super) fn analysis_rewrites_remote_refs(analysis: &ShellAnalysis) -> bool {
    analysis_rewrites_remote_refs_at(analysis, 0)
}

fn analysis_rewrites_remote_refs_at(analysis: &ShellAnalysis, depth: usize) -> bool {
    if depth > MAX_DEPTH {
        return false;
    }
    analysis.stages.iter().any(|stage| {
        let tokens = &stage.argv;
        let command_index = unwrapped_command_index(tokens, 0, tokens.len());
        let Some(command) = tokens.get(command_index) else {
            return false;
        };
        let args = &tokens[command_index + 1..];
        match command_basename(command) {
            "git" => git_subcommand(args)
                .is_some_and(|(sub, rest)| sub == "push" && git_push_rewrite(rest).is_some()),
            "bash" | "sh" | "zsh" => shell_c_script(args).is_some_and(|script| {
                analysis_rewrites_remote_refs_at(&analyze_shell(script), depth + 1)
            }),
            _ => false,
        }
    })
}

fn git_catastrophe(args: &[String]) -> Option<String> {
    let (subcommand, rest) = git_subcommand(args)?;
    match subcommand {
        "reset" => rest.iter().any(|a| a == "--hard").then(|| {
            "`git reset --hard` is blocked: it discards all uncommitted work. Commit or stash first, then reset on a feature branch.".to_string()
        }),
        "clean" => {
            let mut force = false;
            let mut dirs = false;
            for arg in rest {
                if arg == "--force" {
                    force = true;
                } else if arg == "-d" || arg == "--directory" {
                    dirs = true;
                } else if arg.starts_with('-') && !arg.starts_with("--") {
                    for flag in arg.chars().skip(1) {
                        match flag {
                            'f' => force = true,
                            'd' => dirs = true,
                            _ => {}
                        }
                    }
                }
            }
            (force && dirs).then(|| {
                "`git clean -fd`/`-fdx` is blocked: it permanently deletes untracked files and directories. Inspect with `git clean -nd` first, or remove specific paths.".to_string()
            })
        }
        "push" => (git_push_rewrite(rest) == Some(RemoteRefRewrite::Force)).then(|| {
            "force-push (`--force` / `-f` / `--force-with-lease` / `--mirror` / a `+ref` refspec) is blocked: it can rewrite shared history. Push without forcing, or perform the force-push yourself after review.".to_string()
        }),
        _ => None,
    }
}

fn rm_escape_catastrophe(args: &[String], roots: &[String]) -> Option<String> {
    let mut force = false;
    let mut recursive = false;
    let mut targets: Vec<&str> = Vec::new();
    let mut parsing_options = true;
    for arg in args {
        if parsing_options && arg == "--" {
            parsing_options = false;
            continue;
        }
        if parsing_options && arg.starts_with("--") {
            force = force || arg == "--force";
            recursive = recursive || arg == "--recursive";
            continue;
        }
        if parsing_options && arg.starts_with('-') && arg != "-" {
            for flag in arg.chars().skip(1) {
                force = force || flag == 'f';
                recursive = recursive || flag == 'r' || flag == 'R';
            }
            continue;
        }
        parsing_options = false;
        targets.push(arg);
    }
    if !(force && recursive) {
        return None;
    }
    for target in targets {
        if path_escapes_root(target, roots) {
            return Some(format!(
                "`rm -rf` of `{target}` is blocked: it targets an absolute path or escapes the project root. Delete only paths inside the workspace, and prefer a scoped removal."
            ));
        }
    }
    None
}

fn dd_catastrophe(args: &[String]) -> Option<String> {
    args.iter().any(|a| a.starts_with("of=")).then(|| {
        "`dd of=…` is blocked: a raw block-device/file overwrite is irreversible.".to_string()
    })
}

fn chmod_catastrophe(args: &[String]) -> Option<String> {
    let recursive = args.iter().any(|a| {
        a == "-R"
            || a == "--recursive"
            || (a.starts_with('-') && !a.starts_with("--") && a.contains('R'))
    });
    let strips_all = args.iter().any(|a| a == "000" || a == "0000");
    (recursive && strips_all).then(|| {
        "`chmod -R 000` is blocked: recursively stripping all permissions can lock you out of the tree.".to_string()
    })
}

fn path_escapes_root(target: &str, roots: &[String]) -> bool {
    let cleaned = strip_trailing_slashes(target);
    if cleaned.is_empty() {
        return false;
    }
    // Home / root / device targets always escape regardless of root.
    if cleaned == "~"
        || cleaned.starts_with("~/")
        || cleaned == "/"
        || cleaned == "/*"
        || cleaned.starts_with("$HOME")
        || cleaned.starts_with("${HOME}")
    {
        return true;
    }
    if cleaned.starts_with('/') {
        // Absolute: escapes UNLESS it resolves inside one of the roots. No
        // root context → conservatively treat as an escape.
        if roots.is_empty() {
            return true;
        }
        return !roots.iter().any(|root| {
            let root = strip_trailing_slashes(root);
            cleaned == root || cleaned.starts_with(&format!("{root}/"))
        });
    }
    relative_path_escapes(cleaned)
}

fn relative_path_escapes(path: &str) -> bool {
    let mut depth: i32 = 0;
    for part in path.split('/') {
        match part {
            "" | "." => {}
            ".." => {
                depth -= 1;
                if depth < 0 {
                    return true;
                }
            }
            _ => depth += 1,
        }
    }
    false
}

#[expect(
    clippy::string_slice,
    reason = "end sits before an ASCII '/' byte or at value.len()"
)]
fn strip_trailing_slashes(value: &str) -> &str {
    let mut end = value.len();
    while end > 1 && value.as_bytes()[end - 1] == b'/' {
        end -= 1;
    }
    &value[..end]
}