harn-vm 0.10.180

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
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
//! A command under a `read` external root (harn#9622).
//!
//! The approval boundary admits a command-running call whose declared path is
//! under a `read` root only when the OS sandbox its child runs under refuses
//! every write there. Each test pairs that admission with the real spawn path,
//! so a disposition that claimed more than the kernel enforces would show up
//! as a write that landed.

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

use crate::orchestration::{
    pop_execution_policy, push_execution_policy, CapabilityPolicy, ExternalRoot, SandboxProfile,
    ToolApprovalPolicy,
};
use crate::stdlib::sandbox::child_write::{child_write_disposition, ChildWriteDisposition};
use crate::tool_annotations::{SideEffectLevel, ToolAnnotations, ToolArgSchema, ToolKind};

/// A confined-run policy: `workspace` writable, `read_only` readable, the
/// `run` tool annotated as executing.
fn confined_policy(
    profile: SandboxProfile,
    workspace: &Path,
    read_only: &[&Path],
) -> CapabilityPolicy {
    let mut annotations = BTreeMap::new();
    annotations.insert(
        "run".to_string(),
        ToolAnnotations {
            kind: ToolKind::Execute,
            side_effect_level: SideEffectLevel::ProcessExec,
            arg_schema: ToolArgSchema {
                path_params: vec!["path".to_string()],
                ..Default::default()
            },
            ..Default::default()
        },
    );
    CapabilityPolicy {
        // The child may write its workspace, as an agent's `run` may; without
        // that every path would be read-only and nothing here would be tested.
        capabilities: BTreeMap::from([
            ("process".to_string(), vec!["run".to_string()]),
            (
                "workspace".to_string(),
                ["read_text", "write_text", "list", "exists"]
                    .map(str::to_string)
                    .to_vec(),
            ),
        ]),
        workspace_roots: vec![workspace.display().to_string()],
        read_only_roots: read_only
            .iter()
            .map(|root| root.display().to_string())
            .collect(),
        side_effect_level: Some("process_exec".to_string()),
        tool_annotations: annotations,
        sandbox_profile: profile,
        ..Default::default()
    }
}

/// The boundary's answer for `run` naming `path`, under `policy` and a `read`
/// external root at `root`.
fn run_admitted(policy: &CapabilityPolicy, root: &Path, path: &Path) -> bool {
    crate::stdlib::sandbox::child_write::install_child_write_probe();
    let approval = ToolApprovalPolicy {
        external_roots: vec![ExternalRoot::read(root.display().to_string())],
        ..Default::default()
    };
    push_execution_policy(policy.clone());
    let decision = approval.evaluate_detailed(
        "run",
        &serde_json::json!({ "path": path.display().to_string() }),
    );
    pop_execution_policy();
    decision.is_allow()
}

/// Run `script` through the confined spawn path under `policy`: the same
/// `std_command_for` a process capability builds its child with. Returns
/// whether the shell exited zero; a refused spawn is a refused write.
#[cfg(any(target_os = "macos", target_os = "linux"))]
fn shell_succeeds(policy: &CapabilityPolicy, script: &str) -> bool {
    push_execution_policy(policy.clone());
    let output =
        crate::stdlib::sandbox::std_command_for("/bin/sh", &["-c".to_string(), script.to_string()])
            .and_then(|mut command| {
                command
                    .output()
                    .map_err(|error| crate::value::VmError::Runtime(error.to_string()))
            });
    pop_execution_policy();
    output.is_ok_and(|output| output.status.success())
}

fn canonical(path: &Path) -> PathBuf {
    std::fs::canonicalize(path).unwrap()
}

/// Directories the default presets do not grant: the workspace under the
/// test's working directory and the external root under `HOME`, never under a
/// shared temp dir a preset might make writable.
fn workspace_and_outside() -> Option<(tempfile::TempDir, tempfile::TempDir)> {
    let cwd = std::env::current_dir().ok()?;
    let home = std::env::var_os("HOME").map(PathBuf::from)?;
    if !home.is_dir() || home.starts_with("/tmp") || home.starts_with("/private/tmp") {
        return None;
    }
    Some((
        tempfile::tempdir_in(&cwd).ok()?,
        tempfile::tempdir_in(home).ok()?,
    ))
}

/// The disjoint case on a platform with a mechanism: the root is read-only
/// for the child, the boundary admits the command, and every write spelling
/// the issue names is refused by the kernel with nothing written.
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[test]
fn a_command_under_an_enforced_read_only_root_is_admitted_and_cannot_write() {
    if !crate::stdlib::sandbox::active_backend_filesystem_available() {
        return;
    }
    let Some((workspace, outside)) = workspace_and_outside() else {
        return;
    };
    let root = canonical(outside.path());
    std::fs::create_dir_all(root.join("sub")).unwrap();
    std::fs::write(root.join("data.txt"), "reference").unwrap();
    let ws = canonical(workspace.path());
    std::os::unix::fs::symlink(&root, ws.join("link")).unwrap();
    let policy = confined_policy(SandboxProfile::OsHardened, &ws, &[root.as_path()]);

    let file = root.join("data.txt");
    assert_eq!(
        child_write_disposition(&policy, &file),
        ChildWriteDisposition::EnforcedReadOnly
    );
    assert!(
        run_admitted(&policy, &root, &file),
        "the boundary must admit the read"
    );
    assert!(
        shell_succeeds(&policy, &format!("cat '{}'", file.display())),
        "control: the child can read the root"
    );

    for (label, target) in [
        ("direct", root.join("f")),
        ("dot-dot", root.join("sub").join("..").join("f")),
        ("workspace symlink", ws.join("link").join("f")),
    ] {
        assert!(
            !shell_succeeds(&policy, &format!("echo x > '{}'", target.display())),
            "{label}: the kernel must refuse a write into the read-only root"
        );
        assert!(!root.join("f").exists(), "{label}: nothing may be written");
    }
    assert_eq!(std::fs::read_to_string(&file).unwrap(), "reference");
    // Control: the same policy writes the workspace, so the refusals above are
    // the root's mode and not a child that cannot write anything.
    assert!(shell_succeeds(
        &policy,
        &format!("echo x > '{}'", ws.join("ok.txt").display())
    ));
}

/// A read-only root nested in the writable workspace: the oracle must agree
/// with the kernel on both OSes. macOS re-denies it, so it is read-only;
/// Landlock cannot, so it is `Writable`, and the write really lands. (The
/// boundary never consults the oracle here: a workspace path is not under an
/// external root.)
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[test]
fn a_read_only_root_nested_in_the_workspace_is_judged_by_its_backend() {
    if !crate::stdlib::sandbox::active_backend_filesystem_available() {
        return;
    }
    let Some((workspace, _outside)) = workspace_and_outside() else {
        return;
    };
    let ws = canonical(workspace.path());
    let nested = ws.join("vendor");
    std::fs::create_dir_all(&nested).unwrap();
    let policy = confined_policy(SandboxProfile::OsHardened, &ws, &[nested.as_path()]);
    let target = nested.join("f");
    let write = format!("echo x > '{}'", target.display());

    #[cfg(target_os = "macos")]
    {
        assert_eq!(
            child_write_disposition(&policy, &target),
            ChildWriteDisposition::EnforcedReadOnly
        );
        assert!(!shell_succeeds(&policy, &write));
        assert!(!target.exists());
    }
    #[cfg(target_os = "linux")]
    {
        assert_eq!(
            child_write_disposition(&policy, &target),
            ChildWriteDisposition::Writable
        );
        assert!(
            shell_succeeds(&policy, &write) && target.exists(),
            "the oracle said writable, so the write must really land"
        );
    }
}

/// Without `os_hardened` nothing is measured: `worktree` may run unconfined
/// on a host without the mechanism, and `unrestricted` never confines.
#[test]
fn only_os_hardened_can_admit() {
    let Some((workspace, outside)) = workspace_and_outside() else {
        return;
    };
    let root = canonical(outside.path());
    let file = root.join("data.txt");
    std::fs::write(&file, "reference").unwrap();
    let ws = canonical(workspace.path());
    for profile in [SandboxProfile::Unrestricted, SandboxProfile::Worktree] {
        let policy = confined_policy(profile, &ws, &[root.as_path()]);
        assert_eq!(
            child_write_disposition(&policy, &file),
            ChildWriteDisposition::Unknown,
            "{profile:?}"
        );
        assert!(!run_admitted(&policy, &root, &file), "{profile:?}");
    }
}

/// No active policy means no measured fact: the boundary keeps refusing.
#[test]
fn a_command_with_no_active_policy_is_refused() {
    let Some((_workspace, outside)) = workspace_and_outside() else {
        return;
    };
    let root = canonical(outside.path());
    let file = root.join("data.txt");
    let approval = ToolApprovalPolicy {
        external_roots: vec![ExternalRoot::read(root.display().to_string())],
        ..Default::default()
    };
    let decision = approval.evaluate_detailed(
        "run",
        &serde_json::json!({ "path": file.display().to_string() }),
    );
    assert!(!decision.is_allow(), "{}", decision.reason);
}

/// Windows has no OS mechanism, so even `os_hardened` measures nothing.
#[cfg(windows)]
#[test]
fn windows_never_admits() {
    let workspace = tempfile::tempdir().unwrap();
    let outside = tempfile::tempdir().unwrap();
    let root = canonical(outside.path());
    let file = root.join("data.txt");
    std::fs::write(&file, "reference").unwrap();
    let policy = confined_policy(
        SandboxProfile::OsHardened,
        &canonical(workspace.path()),
        &[root.as_path()],
    );
    assert_eq!(
        child_write_disposition(&policy, &file),
        ChildWriteDisposition::Unknown
    );
    assert!(!run_admitted(&policy, &root, &file));
}

/// A mount made on the session after the policy was built reaches the next
/// child's OS profile: `read_only` reads and cannot write, `extend` writes, and
/// an unmounted sibling reads nothing. The policy names neither root.
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[test]
fn a_session_mount_reaches_the_child_profile_by_its_mode() {
    use crate::workspace_anchor::{MountMode, WorkspaceAnchor};
    if !crate::stdlib::sandbox::active_backend_filesystem_available() {
        eprintln!("MOUNT-TEST-SKIPPED: no filesystem confinement backend");
        return;
    }
    // Every directory is made under HOME by absolute path, so no other test's
    // working-directory change can reach this one.
    let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else {
        return;
    };
    let (Ok(workspace), Ok(outside), Ok(sibling)) = (
        tempfile::tempdir_in(&home),
        tempfile::tempdir_in(&home),
        tempfile::tempdir_in(&home),
    ) else {
        eprintln!("MOUNT-TEST-SKIPPED: no writable home directory");
        return;
    };
    crate::reset_thread_local_state();
    let ws = canonical(workspace.path());
    let root = canonical(outside.path());
    let other = canonical(sibling.path());
    std::fs::write(root.join("data.txt"), "reference").unwrap();
    std::fs::write(other.join("data.txt"), "other").unwrap();
    let mut policy = confined_policy(SandboxProfile::OsHardened, &ws, &[]);
    policy.workspace_roots = vec![ws.display().to_string()];

    let session = crate::agent_sessions::open_or_create_for_test(Some("mount-child".to_string()));
    let _current = crate::agent_sessions::enter_current_session(session.clone());
    let anchor = WorkspaceAnchor {
        primary: ws,
        additional_roots: Vec::new(),
        anchored_at: "0".to_string(),
    };
    crate::agent_sessions::set_workspace_anchor(&session, Some(anchor)).unwrap();
    let read = format!("cat '{}'", root.join("data.txt").display());
    let write = format!("echo x > '{}'", root.join("f").display());

    assert!(!shell_succeeds(&policy, &read), "unmounted: not readable");

    let root_text = root.display().to_string();
    crate::stdlib::add_workspace_root(&session, &root_text, Some(MountMode::ReadOnly), None, None)
        .unwrap();
    assert!(shell_succeeds(&policy, &read), "read_only mount reads");
    assert!(
        !shell_succeeds(&policy, &write),
        "read_only mount never writes"
    );
    assert!(!root.join("f").exists());
    assert!(
        !shell_succeeds(
            &policy,
            &format!("cat '{}'", other.join("data.txt").display())
        ),
        "a different outside path stays unreadable"
    );

    crate::stdlib::add_workspace_root(&session, &root_text, Some(MountMode::Extend), None, None)
        .unwrap();
    assert!(shell_succeeds(&policy, &write), "extend mount writes");
    assert!(root.join("f").exists());
    assert!(
        !shell_succeeds(
            &policy,
            &format!("echo x > '{}'", other.join("f").display())
        ),
        "a write outside the mount stays refused"
    );
    eprintln!("MOUNT-TEST-RAN");
}

/// A `read_only` session mount nested in the writable workspace, through the
/// real spawn path: the child's profile must agree with what the backend
/// reports. macOS re-denies the nested root; Landlock cannot subtract from the
/// workspace grant, so it reports `Writable` and the write really lands. The
/// host must not mount a read-only root there on such a backend.
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[test]
fn a_read_only_mount_nested_in_the_workspace_matches_its_backend() {
    use crate::workspace_anchor::{MountMode, WorkspaceAnchor};
    if !crate::stdlib::sandbox::active_backend_filesystem_available() {
        eprintln!("NESTED-MOUNT-TEST-SKIPPED: no filesystem confinement backend");
        return;
    }
    let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else {
        return;
    };
    let Ok(workspace) = tempfile::tempdir_in(&home) else {
        return;
    };
    crate::reset_thread_local_state();
    let ws = canonical(workspace.path());
    let nested = ws.join("vendor");
    std::fs::create_dir_all(&nested).unwrap();
    let policy = confined_policy(SandboxProfile::OsHardened, &ws, &[]);
    let session = crate::agent_sessions::open_or_create_for_test(Some("nested-child".to_string()));
    let _current = crate::agent_sessions::enter_current_session(session.clone());
    let anchor = WorkspaceAnchor {
        primary: ws.clone(),
        additional_roots: Vec::new(),
        anchored_at: "0".to_string(),
    };
    crate::agent_sessions::set_workspace_anchor(&session, Some(anchor)).unwrap();
    let beside = format!("echo x > '{}'", ws.join("ok.txt").display());
    let inside = format!("echo x > '{}'", nested.join("f").display());

    assert!(
        shell_succeeds(&policy, &inside),
        "control: writable before the mount"
    );
    std::fs::remove_file(nested.join("f")).unwrap();
    // No current execution policy and no current session: an idle session's
    // host supplies the policy its children will run under.
    let mounted = crate::stdlib::add_workspace_root(
        &session,
        &nested.to_string_lossy(),
        Some(MountMode::ReadOnly),
        None,
        Some(&policy),
    );
    assert!(
        shell_succeeds(&policy, &beside),
        "the rest of the workspace stays writable"
    );
    let landed = shell_succeeds(&policy, &inside) && nested.join("f").exists();
    #[cfg(target_os = "macos")]
    {
        mounted.unwrap();
        assert!(
            !landed,
            "macOS must refuse a write into the nested read-only mount"
        );
    }
    #[cfg(target_os = "linux")]
    {
        // Landlock cannot subtract the workspace grant, so the mount is
        // refused rather than reported read-only while a child could write it.
        assert!(
            mounted.is_err_and(|error| error.contains("cannot subtract write access")),
            "an unenforceable nested read-only mount must be refused"
        );
        assert!(
            child_write_disposition(&policy, &nested.join("f")) == ChildWriteDisposition::Writable,
            "the refusal rests on a measured Writable disposition"
        );
        assert!(
            landed,
            "control: the child really could write the nested path"
        );
    }
    eprintln!("NESTED-MOUNT-TEST-RAN landed={landed}");
}

/// A read-only mount of a directory that holds the writable workspace: the
/// most specific root wins on every layer. The workspace stays writable, the
/// rest of the mount refuses writes, and its files stay readable. macOS
/// re-asserts the narrower write grant after the broad deny; Landlock grants
/// the parent read and the child write additively; the file builtins resolve
/// by the deepest matching root.
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[test]
fn a_read_only_parent_of_a_writable_root_leaves_that_root_writable() {
    use crate::workspace_anchor::{MountMode, WorkspaceAnchor};
    if !crate::stdlib::sandbox::active_backend_filesystem_available() {
        eprintln!("PARENT-MOUNT-TEST-SKIPPED: no filesystem confinement backend");
        return;
    }
    let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else {
        return;
    };
    let Ok(parent_dir) = tempfile::tempdir_in(&home) else {
        return;
    };
    crate::reset_thread_local_state();
    let parent = canonical(parent_dir.path());
    let ws = parent.join("ws");
    let work = parent.join("work");
    std::fs::create_dir_all(&ws).unwrap();
    std::fs::create_dir_all(&work).unwrap();
    std::fs::write(parent.join("data.txt"), "reference").unwrap();
    let policy = confined_policy(SandboxProfile::OsHardened, &ws, &[]);
    let session = crate::agent_sessions::open_or_create_for_test(Some("parent-mount".to_string()));
    let _current = crate::agent_sessions::enter_current_session(session.clone());
    let anchor = WorkspaceAnchor {
        primary: ws.clone(),
        additional_roots: Vec::new(),
        anchored_at: "0".to_string(),
    };
    crate::agent_sessions::set_workspace_anchor(&session, Some(anchor)).unwrap();

    crate::stdlib::add_workspace_root(
        &session,
        &parent.to_string_lossy(),
        Some(MountMode::ReadOnly),
        None,
        Some(&policy),
    )
    .expect("a read-only parent of the writable workspace mounts");
    crate::stdlib::add_workspace_root(
        &session,
        &work.to_string_lossy(),
        Some(MountMode::Extend),
        None,
        Some(&policy),
    )
    .expect("a writable mount inside a read-only one mounts");

    let in_ws = format!("echo x > '{}'", ws.join("f").display());
    let in_work = format!("echo x > '{}'", work.join("f").display());
    let in_parent = format!("echo x > '{}'", parent.join("f").display());
    let read_parent = format!("cat '{}'", parent.join("data.txt").display());
    assert!(
        shell_succeeds(&policy, &in_ws),
        "the workspace stays writable"
    );
    assert!(
        shell_succeeds(&policy, &in_work),
        "a writable mount inside stays writable"
    );
    assert!(
        !shell_succeeds(&policy, &in_parent) && !parent.join("f").exists(),
        "a write in the read-only parent outside both is refused"
    );
    assert!(
        shell_succeeds(&policy, &read_parent),
        "the parent stays readable"
    );

    // The file builtins agree, by the deepest matching root.
    use crate::stdlib::sandbox::{check_fs_path_scope, FsAccess};
    push_execution_policy(policy);
    let writable = check_fs_path_scope(&ws.join("g"), FsAccess::Write).is_ok()
        && check_fs_path_scope(&work.join("g"), FsAccess::Write).is_ok();
    let refused = check_fs_path_scope(&parent.join("g"), FsAccess::Write).is_err();
    let readable = check_fs_path_scope(&parent.join("data.txt"), FsAccess::Read).is_ok();
    pop_execution_policy();
    assert!(writable, "file builtins write the deeper writable roots");
    assert!(
        refused,
        "file builtins refuse a write in the read-only parent"
    );
    assert!(readable, "file builtins read the read-only parent");
}