merry-process 0.1.2

Sandboxed host-process execution (Landlock/seccomp, Seatbelt, Windows Job Objects) for Merry.
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
use super::{
    execution::{background_intent, process_alive, wait_until_dead},
    permission_request, request_process_intent,
};
use crate::process_runner::{
    WorkspaceProcessEnvironment, WorkspaceProcessRunner, WorkspaceProcessRunnerFactory,
};
use merry_runtime::{
    PathAccess, PathAccessRule, PathAccessRuleSource, PermissionedProcessRunnerFactory,
    ProcessActionIntent, ProcessEnvPolicy, ProcessExitStatus, ProcessRunner, ProcessRunnerContext,
    ProcessRunnerOutput,
};
use serde_json::json;
use std::path::{Path, PathBuf};
use tokio_util::sync::CancellationToken;

#[tokio::test]
async fn permissioned_factory_runner_for_invalid_request_fails_closed() {
    let factory = WorkspaceProcessRunnerFactory::new_at_workspace_root("/workspace/merry")
        .with_path_rules([PathAccessRule::new(
            PathBuf::from("/workspace/merry/secrets"),
            PathAccess::Deny,
            PathAccessRuleSource::TrustedGlobalConfig,
        )]);
    let request = permission_request(json!({
        "requested": {
            "paths": [{ "path": "secrets/token", "access": "ro" }]
        },
        "for_action": { "command": "cat secrets/token", "cwd": null }
    }));

    let runner = factory.runner_for(&request);
    let error = runner
        .run(
            request_process_intent(&request).clone(),
            ProcessRunnerContext::new(CancellationToken::new()),
        )
        .await
        .expect_err("invalid path request must not reach the process backend");
    assert!(
        error
            .to_string()
            .contains("denied by configured path policy")
    );
}

#[tokio::test]
async fn background_process_outlives_the_permissioned_runner() {
    let workspace = tempfile::tempdir().expect("workspace");
    let factory = WorkspaceProcessRunnerFactory::new_at_workspace_root(workspace.path());
    let request = permission_request(json!({
        "requested": { "network": true },
        "for_action": { "command": "sleep 30", "cwd": null }
    }));
    let runner = factory.runner_for(&request);
    let started = std::time::Instant::now();
    let output = runner
        .run(
            background_intent(vec!["/bin/sleep".to_owned(), "30".to_owned()]),
            ProcessRunnerContext::new(CancellationToken::new()),
        )
        .await
        .expect("sandboxed background sleep should be retained");

    assert!(started.elapsed() < std::time::Duration::from_secs(5));
    assert_eq!(output.status(), ProcessExitStatus::Running);
    let pid = output.running_pid().expect("sandboxed pid");
    assert!(process_alive(pid));
    drop(runner);
    assert!(
        process_alive(pid),
        "dropping the per-request runner must not kill a background process"
    );
    drop(factory);
    wait_until_dead(pid).await;
}

#[tokio::test]
async fn workspace_process_runner_reuses_tmp_and_writes_workspace() {
    let workspace = tempfile::tempdir().expect("workspace tempdir should be created");
    let marker = format!("merry-process-runner-{}", std::process::id());
    let runner = WorkspaceProcessRunner::new_at_workspace_root(workspace.path()).allow_network();

    let write_tmp = ProcessActionIntent::new(
        vec![
            "/bin/sh".to_owned(),
            "-c".to_owned(),
            format!("printf 'tmp-ok' > /tmp/{marker}"),
        ],
        None,
        ProcessEnvPolicy::empty(),
        None,
        1024,
        1024,
    )
    .expect("temporary write intent should be valid");
    let first = runner
        .run(
            write_tmp,
            ProcessRunnerContext::new(CancellationToken::new()),
        )
        .await
        .expect("first workspace action should run");
    assert!(first.ok(), "first workspace action failed: {first:?}");

    let read_tmp = ProcessActionIntent::new(
        vec![
            "/bin/sh".to_owned(),
            "-c".to_owned(),
            format!("cat /tmp/{marker}"),
        ],
        None,
        ProcessEnvPolicy::empty(),
        None,
        1024,
        1024,
    )
    .expect("temporary read intent should be valid");
    let second = runner
        .run(
            read_tmp,
            ProcessRunnerContext::new(CancellationToken::new()),
        )
        .await
        .expect("second workspace action should run");
    assert!(second.ok(), "second workspace action failed: {second:?}");
    assert_eq!(second.stdout_text(), "tmp-ok");

    let write_workspace = ProcessActionIntent::new(
        vec![
            "/bin/sh".to_owned(),
            "-c".to_owned(),
            "printf 'workspace-ok' > workspace-write.txt".to_owned(),
        ],
        None,
        ProcessEnvPolicy::empty(),
        None,
        1024,
        1024,
    )
    .expect("workspace write intent should be valid");
    let third = runner
        .run(
            write_workspace,
            ProcessRunnerContext::new(CancellationToken::new()),
        )
        .await
        .expect("workspace write action should run");
    assert!(third.ok(), "workspace write action failed: {third:?}");
    assert_eq!(
        std::fs::read_to_string(workspace.path().join("workspace-write.txt"))
            .expect("workspace write should persist"),
        "workspace-ok"
    );

    let _ = std::fs::remove_file(Path::new("/tmp").join(marker));
}

#[tokio::test]
async fn workspace_git_init_and_local_config_need_no_extra_grant() {
    let workspace = tempfile::tempdir().expect("workspace tempdir should be created");
    let runner = WorkspaceProcessRunner::new_at_workspace_root(workspace.path()).allow_network();
    let init_intent = ProcessActionIntent::new(
        vec!["git".to_owned(), "init".to_owned(), ".".to_owned()],
        None,
        ProcessEnvPolicy::empty(),
        None,
        4096,
        4096,
    )
    .expect("git init intent should be valid");

    let initialized = runner
        .run(
            init_intent,
            ProcessRunnerContext::new(CancellationToken::new()),
        )
        .await
        .expect("git init should return process output");
    assert!(initialized.ok(), "git init should succeed: {initialized:?}");
    assert!(workspace.path().join(".git").is_dir());

    let modify_intent = ProcessActionIntent::new(
        vec![
            "git".to_owned(),
            "config".to_owned(),
            "--local".to_owned(),
            "user.name".to_owned(),
            "Merry".to_owned(),
        ],
        None,
        ProcessEnvPolicy::empty(),
        None,
        4096,
        4096,
    )
    .expect("git config intent should be valid");
    let configured = runner
        .run(
            modify_intent,
            ProcessRunnerContext::new(CancellationToken::new()),
        )
        .await
        .expect("git config should return process output");
    assert!(
        configured.ok(),
        "workspace git metadata should stay writable: {configured:?}"
    );
}

#[tokio::test]
async fn read_only_workspace_can_read_and_cannot_write() {
    let workspace =
        tempfile::tempdir_in(fixture_root()).expect("workspace outside baseline writes");
    std::fs::write(workspace.path().join("note.txt"), "hello").expect("note");
    let runner =
        WorkspaceProcessRunner::new_at_workspace_root(workspace.path()).read_only_workspace();
    let context = ProcessRunnerContext::new(CancellationToken::new());

    let read = run_shell(&runner, "cat note.txt", &context).await;
    assert!(read.ok(), "read should succeed: {}", read.stderr_text());
    assert_eq!(read.stdout_text(), "hello");

    let write = run_shell(&runner, "touch denied.txt", &context).await;
    assert!(
        !write.ok(),
        "a read-only workspace must reject writes: {}",
        write.stderr_text()
    );
    assert!(!workspace.path().join("denied.txt").exists());

    let temporary = run_shell(
        &runner,
        "touch /tmp/merry-readonly-workspace-marker",
        &context,
    )
    .await;
    assert!(
        temporary.ok(),
        "/tmp stays writable: {}",
        temporary.stderr_text()
    );
    let _ = std::fs::remove_file("/tmp/merry-readonly-workspace-marker");
}

#[tokio::test]
async fn sandboxed_git_status_reads_the_user_ignore_file() {
    let root = tempfile::tempdir_in(fixture_root()).expect("fixture root");
    let home = root.path().join("home");
    let workspace = root.path().join("repo");
    std::fs::create_dir_all(home.join(".config/git")).expect("git config dir");
    std::fs::write(home.join(".config/git/ignore"), "*.log\n").expect("ignore");
    std::fs::write(home.join(".git-credentials"), "secret\n").expect("credentials");
    std::fs::create_dir_all(&workspace).expect("repo");
    let init = std::process::Command::new("git")
        .args(["init", "-q"])
        .current_dir(&workspace)
        .env("HOME", &home)
        .status()
        .expect("git init");
    assert!(init.success(), "host git init failed");

    let environment =
        WorkspaceProcessEnvironment::new("/usr/bin:/bin", &home, "/tmp").expect("environment");
    let runner =
        WorkspaceProcessRunner::new_at_workspace_root(&workspace).with_environment(environment);
    let context = ProcessRunnerContext::new(CancellationToken::new());
    let status = run_shell(&runner, "git status --short --branch", &context).await;
    assert!(
        status.ok(),
        "git status should read the user ignore file: {}",
        status.stderr_text()
    );

    let secret = run_shell(&runner, "cat \"$HOME/.git-credentials\"", &context).await;
    assert!(
        !secret.ok(),
        "git credentials stay unreadable: {}",
        secret.stdout_text()
    );
}

#[tokio::test]
async fn sandboxed_command_can_read_and_write_only_the_memory_tree() {
    let root = tempfile::tempdir_in(fixture_root()).expect("fixture root");
    let workspace = root.path().join("workspace");
    let memory = root.path().join("data/merry/memory");
    let secret = root.path().join("data/merry/secret.txt");
    std::fs::create_dir_all(&workspace).expect("workspace");
    std::fs::create_dir_all(memory.join("topics")).expect("memory topics");
    std::fs::write(memory.join("topics/hello.md"), "# 你好\n").expect("note");
    std::fs::write(&secret, "secret\n").expect("secret");

    let runner = WorkspaceProcessRunner::new_at_workspace_root(&workspace)
        .read_only_workspace()
        .with_path_rules([PathAccessRule::new(
            memory.clone(),
            PathAccess::ReadWrite,
            PathAccessRuleSource::DurableMemory,
        )]);
    let context = ProcessRunnerContext::new(CancellationToken::new());
    let memory_display = memory.display();
    let listed = run_shell(
        &runner,
        &format!("ls '{memory_display}/topics' && cat '{memory_display}/topics/hello.md'"),
        &context,
    )
    .await;
    assert!(
        listed.ok(),
        "memory should be readable: {}",
        listed.stderr_text()
    );
    assert!(listed.stdout_text().contains("你好"));

    let write = run_shell(
        &runner,
        &format!("printf 'x\\n' > '{memory_display}/topics/written.md'"),
        &context,
    )
    .await;
    assert!(
        write.ok(),
        "memory should be writable: {}",
        write.stderr_text()
    );
    assert_eq!(
        std::fs::read_to_string(memory.join("topics/written.md")).expect("written note"),
        "x\n"
    );

    let workspace_write = run_shell(&runner, "touch denied.txt", &context).await;
    assert!(
        !workspace_write.ok(),
        "a read-only workspace stays read-only"
    );

    let denied = run_shell(&runner, &format!("cat '{}'", secret.display()), &context).await;
    assert!(!denied.ok(), "a sibling outside memory stays unreadable");
    assert!(!denied.stdout_text().contains("secret"));
}

#[tokio::test]
async fn network_denied_sandbox_allows_granted_unix_sockets_and_blocks_inet_and_ungranted_sockets()
{
    let root = tempfile::tempdir_in(fixture_root()).expect("fixture root");
    let workspace = root.path().join("workspace");
    let granted_dir = root.path().join("granted");
    let denied_dir = root.path().join("denied");
    std::fs::create_dir_all(&workspace).expect("workspace");
    std::fs::create_dir_all(&granted_dir).expect("granted");
    std::fs::create_dir_all(&denied_dir).expect("denied");

    let granted_sock = granted_dir.join("agent.sock");
    let denied_sock = denied_dir.join("secret.sock");
    let _granted_listener = std::os::unix::net::UnixListener::bind(&granted_sock)
        .expect("granted unix listener should bind");
    let _denied_listener = std::os::unix::net::UnixListener::bind(&denied_sock)
        .expect("denied unix listener should bind");

    let runner = WorkspaceProcessRunner::new_at_workspace_root(&workspace).with_path_rules([
        PathAccessRule::new(
            granted_sock.clone(),
            PathAccess::ReadWrite,
            PathAccessRuleSource::PermissionReview,
        ),
    ]);
    let context = ProcessRunnerContext::new(CancellationToken::new());
    let script = format!(
        r#"python3 -c '
import os, socket, sys

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("127.0.0.1", 0))
    s.close()
    print("INET=ALLOWED")
except OSError:
    print("INET=DENIED")

local = os.path.join(sys.argv[1], "local.sock")
srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
srv.bind(local)
srv.listen(1)
cli = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
cli.connect(local)
cli.close()
srv.close()
print("LOCAL_UNIX=ALLOWED")

cli = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
cli.connect(sys.argv[2])
cli.close()
print("GRANTED_UNIX=ALLOWED")

try:
    srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    srv.bind(os.path.join(os.path.dirname(sys.argv[3]), "ungranted-bind.sock"))
    srv.close()
    print("DENIED_BIND=ALLOWED")
except OSError:
    print("DENIED_BIND=DENIED")

try:
    cli = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    cli.connect(sys.argv[3])
    cli.close()
    print("DENIED_UNIX=ALLOWED")
except OSError:
    print("DENIED_UNIX=DENIED")
' '{}' '{}' '{}'"#,
        workspace.display(),
        granted_sock.display(),
        denied_sock.display(),
    );

    let output = run_shell(&runner, &script, &context).await;
    assert!(
        output.ok(),
        "unix socket sandbox probe failed: stderr={}",
        output.stderr_text()
    );
    let stdout = output.stdout_text();
    assert!(stdout.contains("INET=DENIED"), "{stdout}");
    assert!(stdout.contains("LOCAL_UNIX=ALLOWED"), "{stdout}");
    assert!(stdout.contains("GRANTED_UNIX=ALLOWED"), "{stdout}");
    assert!(stdout.contains("DENIED_BIND=DENIED"), "{stdout}");
    // macOS Seatbelt scopes `remote unix-socket` to granted writable paths and
    // blocks connecting to ungranted sockets; Linux Landlock AccessFs mediates
    // socket creation (`MakeSock`, checked via DENIED_BIND above) rather than
    // `connect()` on already-bound pathname sockets.
    #[cfg(target_os = "macos")]
    assert!(stdout.contains("DENIED_UNIX=DENIED"), "{stdout}");
}

#[cfg(target_os = "linux")]
#[tokio::test]
async fn permission_review_never_creates_placeholder_directory_and_deleted_grant_does_not_brick_session()
 {
    use crate::process_runner::ProcessSessionPermissions;

    let root = tempfile::tempdir_in(fixture_root()).expect("fixture root outside /tmp");
    let workspace = root.path().join("workspace");
    let outside_dir = root.path().join("outside");
    std::fs::create_dir_all(&workspace).expect("workspace");
    std::fs::create_dir_all(&outside_dir).expect("outside dir");
    let nonexistent_file = outside_dir.join("merry-test.txt");
    let existing_file = outside_dir.join("existing.txt");
    let sibling_file = outside_dir.join("sibling.txt");
    std::fs::write(&existing_file, "before\n").expect("seed existing file");
    std::fs::write(&sibling_file, "untouched\n").expect("seed sibling file");

    let session_permissions = ProcessSessionPermissions::new();
    let ordinary_runner = WorkspaceProcessRunner::new_at_workspace_root(&workspace)
        .with_session_permissions(session_permissions.clone());
    let factory = WorkspaceProcessRunnerFactory::new_at_workspace_root(&workspace)
        .with_session_permissions(session_permissions);
    let context = ProcessRunnerContext::new(CancellationToken::new());

    // 1. Non-existent PermissionReview file path must NEVER be turned into a
    //    stray placeholder directory on disk and must fail with a clear Landlock error.
    let nonexistent_request = permission_request(json!({
        "requested": { "paths": [{ "path": nonexistent_file, "access": "rw" }] },
        "for_action": { "command": format!("printf 'hello' > '{}'", nonexistent_file.display()), "cwd": null }
    }));
    let err = factory
        .runner_for(&nonexistent_request)
        .run(
            request_process_intent(&nonexistent_request).clone(),
            context.clone(),
        )
        .await
        .expect_err("non-existent Landlock PermissionReview path must fail cleanly");
    assert!(
        err.to_string().contains("non-existent path"),
        "expected actionable Landlock error, got: {err}"
    );
    assert!(
        !nonexistent_file.exists(),
        "sandbox setup must never create a placeholder directory at `{}`",
        nonexistent_file.display()
    );

    // 2. Existing PermissionReview file path grants write access to that exact
    //    file inode without exposing sibling files, and is retained in session.
    let existing_request = permission_request(json!({
        "requested": { "paths": [{ "path": existing_file, "access": "rw" }] },
        "for_action": { "command": format!("printf 'after\\n' > '{}'", existing_file.display()), "cwd": null }
    }));
    let write_existing = factory
        .runner_for(&existing_request)
        .run(
            request_process_intent(&existing_request).clone(),
            context.clone(),
        )
        .await
        .expect("approved existing file write should run");
    assert_eq!(
        write_existing.status(),
        ProcessExitStatus::Exited(0),
        "stderr={}",
        write_existing.stderr_text()
    );
    assert_eq!(
        std::fs::read_to_string(&existing_file).expect("read updated file"),
        "after\n"
    );

    let touch_sibling = run_shell(
        &ordinary_runner,
        &format!("printf 'bad\\n' > '{}'", sibling_file.display()),
        &context,
    )
    .await;
    assert_ne!(touch_sibling.status(), ProcessExitStatus::Exited(0));
    assert_eq!(
        std::fs::read_to_string(&sibling_file).expect("sibling must stay untouched"),
        "untouched\n"
    );

    // 3. Deleting a previously approved file must NEVER brick subsequent
    //    unrelated commands in the same session, while explicitly re-requesting
    //    that deleted path still reports the actionable Landlock error.
    std::fs::remove_file(&existing_file).expect("delete previously approved file");
    let unrelated = run_shell(&ordinary_runner, "printf 'still-alive'", &context).await;
    assert_eq!(unrelated.status(), ProcessExitStatus::Exited(0));
    assert_eq!(unrelated.stdout_text(), "still-alive");

    let stale_err = factory
        .runner_for(&existing_request)
        .run(request_process_intent(&existing_request).clone(), context)
        .await
        .expect_err("explicitly re-requesting a deleted path must fail cleanly");
    assert!(
        stale_err.to_string().contains("non-existent path"),
        "{stale_err}"
    );
    assert!(!existing_file.exists());
}

#[cfg(target_os = "linux")]
#[tokio::test]
async fn linux_landlock_blocks_ungranted_elf_execution_cwd_escape_and_hides_policy_stdin() {
    use std::os::unix::fs::symlink;

    if crate::probe_workspace_sandbox().is_err() {
        return;
    }

    let root = tempfile::tempdir_in(fixture_root()).expect("fixture root");
    let workspace = root.path().join("workspace");
    let outside = root.path().join("outside");
    std::fs::create_dir_all(&workspace).expect("workspace");
    std::fs::create_dir_all(&outside).expect("outside");
    std::fs::write(outside.join("secret.txt"), "top-secret\n").expect("secret");
    symlink(&outside, workspace.join("escape")).expect("symlink escape");

    let sh_source = std::fs::canonicalize("/bin/sh").expect("canonical /bin/sh");
    let outside_bin = outside.join("ungranted-sh");
    std::fs::copy(&sh_source, &outside_bin).expect("copy sh outside workspace");

    let runner = WorkspaceProcessRunner::new_at_workspace_root(&workspace);
    let context = ProcessRunnerContext::new(CancellationToken::new());

    // 1. Stdin policy pipe must be replaced with /dev/null before exec, so the
    //    sandboxed command never observes the serialized SandboxLaunch JSON.
    let stdin_check = run_shell(&runner, "cat", &context).await;
    assert_eq!(stdin_check.status(), ProcessExitStatus::Exited(0));
    assert!(
        stdin_check.stdout_text().is_empty(),
        "sandboxed command stdin must be /dev/null, got: {}",
        stdin_check.stdout_text()
    );

    // 2. Executing an ELF binary outside allowed directories must be denied by
    //    Landlock (proving `/` no longer carries `AccessFs::Execute`).
    let exec_outside = run_shell(
        &runner,
        &format!("'{}' -c 'echo escaped'", outside_bin.display()),
        &context,
    )
    .await;
    assert_ne!(
        exec_outside.status(),
        ProcessExitStatus::Exited(0),
        "ungranted ELF binary must not be executable: stdout={:?} stderr={:?}",
        exec_outside.stdout_text(),
        exec_outside.stderr_text()
    );
    assert!(!exec_outside.stdout_text().contains("escaped"));

    // 3. A symlink inside the workspace used as `cwd` must be rejected before
    //    launch instead of granting its target directory outside the workspace.
    let escape_intent = ProcessActionIntent::new(
        vec![
            "/bin/sh".to_owned(),
            "-c".to_owned(),
            "cat secret.txt".to_owned(),
        ],
        Some("escape".to_owned()),
        ProcessEnvPolicy::empty(),
        None,
        4096,
        4096,
    )
    .expect("escape intent");
    let escape_error = runner
        .run(escape_intent, context)
        .await
        .expect_err("cwd symlink escape must fail closed");
    assert!(
        escape_error
            .to_string()
            .contains("resolves outside the workspace root"),
        "{escape_error}"
    );
}

async fn run_shell(
    runner: &WorkspaceProcessRunner,
    command: &str,
    context: &ProcessRunnerContext,
) -> ProcessRunnerOutput {
    let intent = ProcessActionIntent::new(
        vec!["/bin/sh".to_owned(), "-c".to_owned(), command.to_owned()],
        None,
        ProcessEnvPolicy::empty(),
        None,
        4096,
        4096,
    )
    .expect("shell intent");
    runner
        .run(intent, context.clone())
        .await
        .expect("sandboxed command should return output")
}

pub(crate) fn fixture_root() -> PathBuf {
    for candidate in [
        std::env::var_os("XDG_RUNTIME_DIR"),
        std::env::var_os("HOME"),
    ] {
        let Some(value) = candidate else {
            continue;
        };
        let path = PathBuf::from(value);
        let baseline = [
            "/tmp",
            "/private/tmp",
            "/var/tmp",
            "/private/var/tmp",
            "/var/folders",
            "/private/var/folders",
            "/dev",
            "/dev/shm",
            "/dev/pts",
        ]
        .iter()
        .any(|root| path == Path::new(root) || path.starts_with(root));
        if path.is_dir() && !baseline {
            return path;
        }
    }
    panic!("need a directory outside /tmp, /var/tmp, and /dev");
}