merry-process 0.1.4

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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
use super::*;

#[test]
fn exclusion_inside_a_grant_fails_closed() {
    let rules = [PathAccessRule::new(
        PathBuf::from("/workspace/secret"),
        PathAccess::Deny,
        merry_runtime::PathAccessRuleSource::TrustedGlobalConfig,
    )];
    let error = ensure_exclusions_are_enforceable(
        Path::new("/workspace"),
        Path::new("/tmp"),
        &[],
        &[PathBuf::from("/workspace")],
        &rules,
        true,
    )
    .expect_err("deny inside a grant");
    let message = error.to_string();
    assert!(message.contains("deny_paths"), "{message}");
    assert!(message.contains("/workspace/secret"), "{message}");
    assert!(message.contains("writable workspace"), "{message}");
}

#[test]
fn exclusion_outside_a_grant_is_enforceable() {
    let rules = [PathAccessRule::new(
        PathBuf::from("/home/alice/.ssh"),
        PathAccess::Deny,
        merry_runtime::PathAccessRuleSource::TrustedGlobalConfig,
    )];
    ensure_exclusions_are_enforceable(
        Path::new("/workspace"),
        Path::new("/tmp"),
        &[PathBuf::from("/usr")],
        &[PathBuf::from("/workspace")],
        &rules,
        true,
    )
    .expect("secrets outside the allow list need no hole");
}

#[test]
fn read_only_workspace_names_the_read_only_grant() {
    let rules = [PathAccessRule::new(
        PathBuf::from("/workspace/secret"),
        PathAccess::Deny,
        merry_runtime::PathAccessRuleSource::TrustedGlobalConfig,
    )];
    let error = ensure_exclusions_are_enforceable(
        Path::new("/workspace"),
        Path::new("/tmp"),
        &[PathBuf::from("/workspace")],
        &[PathBuf::from("/tmp")],
        &rules,
        false,
    )
    .expect_err("deny inside a read-only workspace");
    let message = error.to_string();
    assert!(message.contains("read-only workspace"), "{message}");
    assert!(message.contains("granted read-only"), "{message}");
}

#[test]
fn git_user_files_include_the_xdg_trio_and_skip_credentials() {
    let home = Path::new("/home/alice");
    let xdg = Path::new("/srv/xdg");
    let paths = git_user_file_candidates(home, Some(xdg));
    assert!(paths.iter().any(|path| path == &home.join(".gitconfig")));
    for name in ["config", "ignore", "attributes"] {
        assert!(
            paths
                .iter()
                .any(|path| path == &home.join(".config/git").join(name))
        );
        assert!(paths.iter().any(|path| path == &xdg.join("git").join(name)));
    }
    assert!(paths.iter().all(|path| !path.ends_with("git-credentials")));
    assert!(paths.iter().all(|path| !path.ends_with("credentials")));
}

#[test]
fn relative_xdg_config_home_is_not_a_git_grant() {
    assert!(absolute_xdg_config_home(Some(Path::new("relative"))).is_none());
    assert!(absolute_xdg_config_home(None).is_none());
}

#[test]
fn read_only_workspace_is_readable_and_tmp_stays_writable() {
    let launch = sample_launch(false, false);
    let resolved_tmp = crate::resolve_host_path(Path::new("/tmp"));
    assert!(contains_path(launch.read_only(), "/workspace/merry"));
    assert!(!contains_path(launch.read_write(), "/workspace/merry"));
    assert!(contains_path(
        launch.read_write(),
        resolved_tmp.to_str().expect("tmp path is utf-8")
    ));
    assert!(!launch.network());
}

#[test]
fn seatbelt_profile_writes_the_workspace_and_can_deny_network() {
    let closed = super::seatbelt::profile(&sample_launch(false, true));
    assert!(closed.contains("(deny default)"));
    assert!(closed.contains("(deny network*)"));
    assert!(closed.contains("(allow file-read-data (literal \"/\"))"));
    assert!(closed.contains("(allow file-write* (subpath \"/workspace/merry\"))"));
    assert!(
        closed.contains("(allow network-bind (local unix-socket (subpath \"/workspace/merry\")))")
    );
    assert!(
        closed.contains(
            "(allow network-outbound (remote unix-socket (subpath \"/workspace/merry\")))"
        )
    );
    assert!(!closed.contains("(allow network*)"));

    let open = super::seatbelt::profile(&sample_launch(true, true));
    assert!(open.contains("(allow network*)"));
    assert!(!open.contains("(deny network*)"));
    assert!(!open.contains("unix-socket"));
}

#[test]
fn seatbelt_profile_keeps_a_read_only_workspace_readable() {
    let profile = super::seatbelt::profile(&sample_launch(false, false));
    let resolved_tmp = crate::resolve_host_path(Path::new("/tmp"));
    assert!(profile.contains("(allow file-read* (subpath \"/workspace/merry\"))"));
    assert!(!profile.contains("file-write* (subpath \"/workspace/merry\")"));
    assert!(profile.contains(&format!(
        "(allow file-write* (subpath \"{}\"))",
        resolved_tmp.display()
    )));
}

#[test]
fn existing_git_user_files_are_readable_and_credentials_are_not() {
    let home = fixture_root();
    let home = tempfile::tempdir_in(home).expect("fixture home");
    let home_path = home.path();
    for name in ["config", "ignore", "attributes"] {
        let path = home_path.join(".config/git").join(name);
        std::fs::create_dir_all(path.parent().expect("git config dir")).expect("mkdir");
        std::fs::write(&path, "sample\n").expect("write git file");
    }
    std::fs::write(home_path.join(".gitconfig"), "[user]\n").expect("gitconfig");
    let credentials = home_path.join(".git-credentials");
    std::fs::write(&credentials, "secret\n").expect("credentials");

    let environment =
        WorkspaceProcessEnvironment::new("/usr/bin", home_path, "/tmp").expect("environment");
    let launch = prepare_launch(
        &sample_intent(),
        Path::new("/workspace/merry"),
        &environment,
        false,
        &[],
        &[],
        true,
    )
    .expect("launch");
    for name in ["config", "ignore", "attributes"] {
        let path = crate::resolve_host_path(&home_path.join(".config/git").join(name));
        assert!(
            contains_path(launch.read_only(), path.to_str().expect("utf-8")),
            "missing {path:?} in {:?}",
            launch.read_only()
        );
    }
    let gitconfig = crate::resolve_host_path(&home_path.join(".gitconfig"));
    assert!(contains_path(
        launch.read_only(),
        gitconfig.to_str().expect("utf-8")
    ));
    let credentials = crate::resolve_host_path(&credentials);
    assert!(!contains_path(
        launch.read_only(),
        credentials.to_str().expect("utf-8")
    ));

    let denied = PathAccessRule::new(
        home_path.join(".config/git/ignore"),
        PathAccess::Deny,
        merry_runtime::PathAccessRuleSource::TrustedGlobalConfig,
    );
    let blocked = prepare_launch(
        &sample_intent(),
        Path::new("/workspace/merry"),
        &environment,
        false,
        &[denied],
        &[],
        true,
    )
    .expect("a denied ignore file outside other grants still launches");
    let ignore = crate::resolve_host_path(&home_path.join(".config/git/ignore"));
    assert!(!contains_path(
        blocked.read_only(),
        ignore.to_str().expect("utf-8")
    ));
}

fn sample_launch(network: bool, workspace_writable: bool) -> SandboxLaunch {
    let environment =
        WorkspaceProcessEnvironment::new("/usr/bin", "/home/alice", "/tmp").expect("environment");
    prepare_launch(
        &sample_intent(),
        Path::new("/workspace/merry"),
        &environment,
        network,
        &[],
        &[],
        workspace_writable,
    )
    .expect("sample launch")
}

fn sample_intent() -> merry_runtime::ProcessActionIntent {
    merry_runtime::ProcessActionIntent::new(
        vec!["pwd".to_owned()],
        None,
        merry_runtime::ProcessEnvPolicy::empty(),
        None,
        1024,
        1024,
    )
    .expect("intent")
}

fn contains_path(paths: &[String], expected: &str) -> bool {
    paths.iter().any(|path| path == expected)
}

fn fixture_root() -> PathBuf {
    for candidate in [env::var_os("XDG_RUNTIME_DIR"), env::var_os("HOME")] {
        let Some(value) = candidate else {
            continue;
        };
        let path = PathBuf::from(value);
        if path.is_dir() && !is_baseline_write(&path) {
            return path;
        }
    }
    panic!("need a directory outside /tmp, /var/tmp, and /dev");
}

fn is_baseline_write(path: &Path) -> bool {
    [
        "/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))
}

#[test]
fn helper_resolution_handles_cargo_test_layouts_and_fails_closed_without_recursion() {
    let temp = tempfile::tempdir().expect("tempdir");
    let profile = temp.path().join("target/debug");
    let deps_bin = profile.join("deps/merry_process-123456");
    let build_bin = profile.join("build/merry-process/abcdef01/out/merry_process-abcdef01");
    fs::create_dir_all(deps_bin.parent().expect("deps dir")).expect("create deps dir");
    fs::create_dir_all(build_bin.parent().expect("out dir")).expect("create out dir");

    assert_eq!(cargo_test_profile_dir(&deps_bin), Some(profile.as_path()));
    assert_eq!(cargo_test_profile_dir(&build_bin), Some(profile.as_path()));
    assert_eq!(cargo_test_profile_dir(&profile.join("merry")), None);

    // Missing helper in both Cargo test layouts must fail closed rather than
    // falling back to `/proc/self/exe` (which would recursively re-run libtest).
    for test_bin in [&deps_bin, &build_bin] {
        let error = resolve_helper_program(None, Some(test_bin), true, true)
            .expect_err("missing test helper must fail closed");
        let message = error.to_string();
        assert!(message.contains("merry-sandbox-helper"), "{message}");
        assert!(
            message.contains("refusing to re-exec test binary"),
            "{message}"
        );
    }

    // An explicit helper path still overrides Cargo test layout discovery.
    let explicit = temp.path().join("custom-helper");
    assert_eq!(
        resolve_helper_program(Some(explicit.clone()), Some(&deps_bin), false, true)
            .expect("explicit helper succeeds"),
        explicit
    );

    // Once merry-sandbox-helper exists, both Cargo test layouts resolve to it.
    let helper = profile.join("merry-sandbox-helper");
    fs::write(&helper, b"").expect("create helper stub");
    assert_eq!(
        resolve_helper_program(None, Some(&deps_bin), false, true)
            .expect("deps test resolves helper"),
        helper
    );
    assert_eq!(
        resolve_helper_program(None, Some(&build_bin), false, true)
            .expect("build out test resolves helper"),
        helper
    );

    // Non-test executables that never called `sandbox_helper_requested()` in
    // `main()` (e.g. Python/Rust SDK hosts) must also fail closed.
    let host_bin = temp.path().join("python3");
    let unregistered = resolve_helper_program(None, Some(&host_bin), false, true)
        .expect_err("unregistered host executable must fail closed");
    assert!(
        unregistered
            .to_string()
            .contains("sandbox_helper_requested"),
        "{unregistered}"
    );

    // A registered `merry` binary resolves to `/proc/self/exe` on Linux (when
    // available) or `current_exe` otherwise.
    let merry_bin = profile.join("merry");
    let resolved =
        resolve_helper_program(None, Some(&merry_bin), true, true).expect("registered binary");
    if cfg!(target_os = "linux") {
        assert_eq!(resolved, PathBuf::from("/proc/self/exe"));
    } else {
        assert_eq!(resolved, merry_bin);
    }
    assert_eq!(
        resolve_helper_program(None, Some(&merry_bin), true, false)
            .expect("registered binary without /proc/self/exe"),
        merry_bin
    );
}

#[test]
fn seatbelt_command_args_invokes_sandbox_exec_directly_with_profile_and_target() {
    let launch = sample_launch(false, true);
    let args = super::seatbelt::command_args(&launch);
    assert_eq!(args[0], "-p");
    assert_eq!(args[1], super::seatbelt::profile(&launch));
    assert_eq!(args[2], "--");
    assert_eq!(args[3], "pwd");
    assert_eq!(args.len(), 4);
}

#[test]
fn seatbelt_profile_emits_deny_rules_after_allows_for_product_private() {
    let environment =
        WorkspaceProcessEnvironment::new("/usr/bin", "/home/alice", "/tmp").expect("environment");
    let rules = [
        PathAccessRule::new(
            PathBuf::from("/home/alice/.local/share"),
            PathAccess::ReadWrite,
            PathAccessRuleSource::TrustedGlobalConfig,
        ),
        PathAccessRule::new(
            PathBuf::from("/home/alice/.local/share/merry/providers"),
            PathAccess::Deny,
            PathAccessRuleSource::ProductPrivate,
        ),
    ];
    let launch = prepare_launch(
        &sample_intent(),
        Path::new("/workspace/merry"),
        &environment,
        false,
        &rules,
        &[],
        true,
    )
    .expect("user grant covering ProductPrivate should still prepare a launch");
    let profile = super::seatbelt::profile(&launch);
    let allow_idx = profile
        .find("(allow file-write* (subpath \"/home/alice/.local/share\"))")
        .expect("allow rule for parent grant");
    let deny_read_idx = profile
        .find("(deny file-read* (subpath \"/home/alice/.local/share/merry/providers\"))")
        .expect("deny read rule for ProductPrivate");
    let deny_write_idx = profile
        .find("(deny file-write* (subpath \"/home/alice/.local/share/merry/providers\"))")
        .expect("deny write rule for ProductPrivate");
    assert!(deny_read_idx > allow_idx);
    assert!(deny_write_idx > allow_idx);
}

#[test]
fn seatbelt_and_launch_keep_state_dir_readonly_while_honoring_deeper_memory_and_denied_secrets() {
    let environment =
        WorkspaceProcessEnvironment::new("/usr/bin", "/home/alice", "/tmp").expect("environment");
    let home = PathBuf::from("/home/alice");
    let state_dir = home.join(".local/state/merry");
    let nested_memory = state_dir.join("memory");
    let nested_providers = state_dir.join("providers");
    let nested_secret = state_dir.join("external.key");
    let rules = [
        PathAccessRule::new(
            home.clone(),
            PathAccess::ReadWrite,
            PathAccessRuleSource::TrustedGlobalConfig,
        ),
        PathAccessRule::new(
            state_dir.clone(),
            PathAccess::ReadOnly,
            PathAccessRuleSource::ProductReadOnly,
        ),
        PathAccessRule::new(
            nested_memory.clone(),
            PathAccess::ReadWrite,
            PathAccessRuleSource::DurableMemory,
        ),
        PathAccessRule::new(
            nested_providers.clone(),
            PathAccess::Deny,
            PathAccessRuleSource::ProductPrivate,
        ),
        PathAccessRule::new(
            nested_secret.clone(),
            PathAccess::Deny,
            PathAccessRuleSource::ProductPrivate,
        ),
    ];
    let launch = prepare_launch(
        &sample_intent(),
        Path::new("/workspace/merry"),
        &environment,
        false,
        &rules,
        &[],
        true,
    )
    .expect("read-only state_dir with nested memory and denied secrets should prepare cleanly");

    let state_str = state_dir.to_string_lossy().into_owned();
    let memory_str = nested_memory.to_string_lossy().into_owned();
    assert!(launch.read_only().contains(&state_str));
    assert!(!launch.read_write().contains(&state_str));
    assert!(launch.read_write().contains(&memory_str));

    let profile = super::seatbelt::profile(&launch);
    let allow_home_write_idx = profile
        .find("(allow file-write* (subpath \"/home/alice\"))")
        .expect("broad home write grant");
    let allow_state_read_idx = profile
        .rfind("(allow file-read* (subpath \"/home/alice/.local/state/merry\"))")
        .expect("state dir read allow override");
    let deny_state_write_idx = profile
        .rfind("(deny file-write* (subpath \"/home/alice/.local/state/merry\"))")
        .expect("state dir write deny");
    let allow_memory_write_idx = profile
        .rfind("(allow file-write* (subpath \"/home/alice/.local/state/merry/memory\"))")
        .expect("nested durable memory write allow");
    let deny_providers_read_idx = profile
        .rfind("(deny file-read* (subpath \"/home/alice/.local/state/merry/providers\"))")
        .expect("nested providers under state_dir must be re-denied last");
    let deny_nested_secret_idx = profile
        .rfind("(deny file-read* (subpath \"/home/alice/.local/state/merry/external.key\"))")
        .expect("nested secret under state_dir must be re-denied last");
    assert!(deny_state_write_idx > allow_home_write_idx);
    assert!(allow_state_read_idx > allow_home_write_idx);
    assert!(allow_memory_write_idx > deny_state_write_idx);
    assert!(deny_providers_read_idx > allow_memory_write_idx);
    assert!(deny_nested_secret_idx > allow_memory_write_idx);
}

#[cfg(target_os = "linux")]
#[test]
fn proc_self_exe_remains_executable_after_unlinking_running_binary() {
    let temp = tempfile::tempdir().expect("tempdir");
    let sh_source = fs::canonicalize("/bin/sh").expect("canonical /bin/sh");
    let sh_copy = temp.path().join("ephemeral-sh");
    fs::copy(&sh_source, &sh_copy).expect("copy sh binary");

    // In a multi-threaded `cargo test` binary, another test thread can `fork()`
    // while `fs::copy` holds a writable fd to `sh_copy`, leaving that fd open
    // in the child until its `execve()` closes `O_CLOEXEC` descriptors. Retry
    // briefly on Linux's transient `ETXTBSY` (`ExecutableFileBusy`).
    let mut attempts = 0_u8;
    let output = loop {
        match Command::new(&sh_copy)
            .arg("-c")
            .arg("rm -f \"$1\" && exec /proc/self/exe -c 'printf still-alive'")
            .arg("ephemeral-sh")
            .arg(&sh_copy)
            .output()
        {
            Ok(output) => break output,
            Err(error)
                if error.kind() == std::io::ErrorKind::ExecutableFileBusy && attempts < 50 =>
            {
                attempts += 1;
                std::thread::sleep(std::time::Duration::from_millis(5));
            }
            Err(error) => panic!("spawn copied shell: {error}"),
        }
    };

    assert!(
        output.status.success(),
        "re-exec via /proc/self/exe should survive binary unlink: stderr={}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(String::from_utf8_lossy(&output.stdout), "still-alive");
    assert!(
        !sh_copy.exists(),
        "copied binary should have been unlinked before re-exec"
    );
}

#[cfg(unix)]
#[test]
fn cwd_symlink_escaping_workspace_root_is_rejected() {
    use std::os::unix::fs::symlink;

    let root = tempfile::tempdir_in(fixture_root()).expect("fixture root");
    let workspace = root.path().join("workspace");
    let outside = root.path().join("outside-secrets");
    fs::create_dir_all(&workspace).expect("workspace");
    fs::create_dir_all(&outside).expect("outside");
    symlink(&outside, workspace.join("escape")).expect("symlink escape");

    let environment =
        WorkspaceProcessEnvironment::new("/usr/bin", root.path(), "/tmp").expect("environment");
    let intent = merry_runtime::ProcessActionIntent::new(
        vec!["pwd".to_owned()],
        Some("escape".to_owned()),
        merry_runtime::ProcessEnvPolicy::empty(),
        None,
        1024,
        1024,
    )
    .expect("intent");

    for writable in [true, false] {
        let error = prepare_launch(&intent, &workspace, &environment, false, &[], &[], writable)
            .expect_err("cwd symlink pointing outside workspace must be rejected");
        assert!(
            error
                .to_string()
                .contains("resolves outside the workspace root"),
            "{error}"
        );
    }
}

#[cfg(unix)]
#[test]
fn gpg_agent_grants_only_validated_native_socket_never_auxiliary_sockets() {
    use std::os::unix::net::UnixListener;

    let root = tempfile::tempdir_in(fixture_root()).expect("fixture root");
    let gpg_home = root.path().join("gnupg");
    fs::create_dir_all(&gpg_home).expect("gpg home");
    let native = gpg_home.join("S.gpg-agent");
    let ssh_aux = gpg_home.join("S.gpg-agent.ssh");
    let extra_aux = gpg_home.join("S.gpg-agent.extra");
    let keyboxd_aux = gpg_home.join("S.keyboxd");
    let _listeners = [
        UnixListener::bind(&native).expect("bind native"),
        UnixListener::bind(&ssh_aux).expect("bind ssh aux"),
        UnixListener::bind(&extra_aux).expect("bind extra aux"),
        UnixListener::bind(&keyboxd_aux).expect("bind keyboxd aux"),
    ];

    let sockets = crate::GpgAgentSockets::new(&gpg_home, &native)
        .expect("gpg sockets")
        .with_auxiliary_sockets([ssh_aux.clone(), extra_aux.clone(), keyboxd_aux.clone()])
        .expect("auxiliary sockets");
    let environment = WorkspaceProcessEnvironment::new("/usr/bin", root.path(), "/tmp")
        .expect("environment")
        .with_gpg_agent_sockets(sockets)
        .with_host_integrations([HostIntegration::GpgAgent]);

    let launch = prepare_launch(
        &sample_intent(),
        Path::new("/workspace/merry"),
        &environment,
        false,
        &[],
        &[],
        true,
    )
    .expect("launch with gpg_agent");

    let resolved_native = resolve_host_path(&native);
    assert!(contains_path(
        launch.read_write(),
        resolved_native.to_str().expect("utf-8 native socket")
    ));
    for aux in [ssh_aux, extra_aux, keyboxd_aux] {
        let resolved_aux = resolve_host_path(&aux);
        assert!(
            !contains_path(
                launch.read_write(),
                resolved_aux.to_str().expect("utf-8 aux socket")
            ),
            "auxiliary socket `{}` must never be granted by gpg_agent integration",
            resolved_aux.display()
        );
    }
}

#[test]
fn seatbelt_profile_allows_direct_approved_write_on_product_readonly() {
    let environment =
        WorkspaceProcessEnvironment::new("/usr/bin", "/home/alice", "/tmp").expect("environment");
    let config_dir = PathBuf::from("/home/alice/.config/merry");
    let providers_dir = config_dir.join("providers");
    let rules = [
        PathAccessRule::new(
            config_dir.clone(),
            PathAccess::ReadOnly,
            PathAccessRuleSource::ProductReadOnly,
        ),
        PathAccessRule::new(
            config_dir.clone(),
            PathAccess::ReadWrite,
            PathAccessRuleSource::PermissionReview,
        ),
        PathAccessRule::new(
            providers_dir.clone(),
            PathAccess::Deny,
            PathAccessRuleSource::ProductPrivate,
        ),
    ];
    let launch = prepare_launch(
        &sample_intent(),
        Path::new("/workspace/merry"),
        &environment,
        false,
        &rules,
        &[],
        true,
    )
    .expect("direct approved write on ProductReadOnly");

    let profile = super::seatbelt::profile(&launch);
    let deny_config_write = profile
        .find("(deny file-write* (subpath \"/home/alice/.config/merry\"))")
        .expect("ProductReadOnly write deny");
    let allow_config_write = profile
        .rfind("(allow file-write* (subpath \"/home/alice/.config/merry\"))")
        .expect("approved write re-allow");
    let deny_providers = profile
        .rfind("(deny file-write* (subpath \"/home/alice/.config/merry/providers\"))")
        .expect("providers re-denied last");
    assert!(allow_config_write > deny_config_write);
    assert!(deny_providers > allow_config_write);
}

#[test]
fn seatbelt_profile_reallows_explicitly_approved_child_inside_product_private() {
    let environment =
        WorkspaceProcessEnvironment::new("/usr/bin", "/home/alice", "/tmp").expect("environment");
    let providers_dir = PathBuf::from("/home/alice/.local/share/merry/providers");
    let providers_toml = providers_dir.join("providers.toml");
    let rules = [
        PathAccessRule::new(
            providers_dir,
            PathAccess::Deny,
            PathAccessRuleSource::ProductPrivate,
        ),
        PathAccessRule::new(
            providers_toml,
            PathAccess::ReadOnly,
            PathAccessRuleSource::PermissionReview,
        ),
    ];
    let launch = prepare_launch(
        &sample_intent(),
        Path::new("/workspace/merry"),
        &environment,
        false,
        &rules,
        &[],
        true,
    )
    .expect("approved child inside ProductPrivate should prepare cleanly");

    let profile = super::seatbelt::profile(&launch);
    let deny_providers = profile
        .rfind("(deny file-read* (subpath \"/home/alice/.local/share/merry/providers\"))")
        .expect("providers dir stays denied");
    let allow_child = profile
        .rfind("(allow file-read* (subpath \"/home/alice/.local/share/merry/providers/providers.toml\"))")
        .expect("approved child re-allowed after providers deny");
    assert!(allow_child > deny_providers);
    assert!(
        !profile.contains("(allow file-write* (subpath \"/home/alice/.local/share/merry/providers/providers.toml\"))"),
        "read-only approval must not grant write access"
    );
}

#[test]
fn path_to_string_rejects_control_characters() {
    let error = path_to_string(Path::new("/tmp/bad\npath"), "sandbox path")
        .expect_err("control characters in sandbox paths must fail closed");
    assert!(error.to_string().contains("control characters"), "{error}");
}

#[test]
fn prepare_launch_never_creates_directories_and_skips_missing_baseline_paths() {
    let root = tempfile::tempdir_in(fixture_root()).expect("fixture root");
    let home = root.path().join("home");
    let workspace = root.path().join("workspace");
    fs::create_dir_all(&workspace).expect("workspace");
    let existing_cache = home.join(".cache/pip");
    let missing_cache = home.join(".cache/go-build");
    let missing_cargo = home.join(".cargo/registry");
    let missing_skills = home.join(".config/merry/skills");
    let missing_memory = home.join(".local/share/merry/memory");
    fs::create_dir_all(&existing_cache).expect("existing pip cache");

    let environment =
        WorkspaceProcessEnvironment::new("/usr/bin", &home, "/tmp").expect("environment");
    let rules = [
        PathAccessRule::new(
            existing_cache.clone(),
            PathAccess::ReadWrite,
            PathAccessRuleSource::DefaultDevelopmentBaseline,
        ),
        PathAccessRule::new(
            missing_cache.clone(),
            PathAccess::ReadWrite,
            PathAccessRuleSource::DefaultDevelopmentBaseline,
        ),
        PathAccessRule::new(
            missing_cargo.clone(),
            PathAccess::ReadWrite,
            PathAccessRuleSource::DefaultDevelopmentBaseline,
        ),
        PathAccessRule::new(
            missing_skills.clone(),
            PathAccess::ReadWrite,
            PathAccessRuleSource::ProductConfig,
        ),
        PathAccessRule::new(
            missing_memory.clone(),
            PathAccess::ReadWrite,
            PathAccessRuleSource::DurableMemory,
        ),
    ];

    let launch = prepare_launch(
        &sample_intent(),
        &workspace,
        &environment,
        false,
        &rules,
        &[],
        true,
    )
    .expect("prepare_launch should succeed without mutating host fs");

    let resolved_existing = resolve_host_path(&existing_cache);
    assert!(contains_path(
        launch.read_write(),
        resolved_existing.to_str().expect("utf-8 existing cache")
    ));
    for missing in [&missing_cache, &missing_cargo] {
        let resolved = resolve_host_path(missing);
        assert!(
            !contains_path(launch.read_write(), resolved.to_str().expect("utf-8")),
            "non-existent baseline path `{}` must not be mounted",
            resolved.display()
        );
        assert!(
            !missing.exists(),
            "prepare_launch must never create `{}`",
            missing.display()
        );
    }
    assert!(
        !missing_skills.exists() && !missing_memory.exists(),
        "prepare_launch must never pre-create missing product directories"
    );
}