merry-process 0.1.3

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
use super::{
    LocalProcessBackend, ProcessBackend, ProcessBackendMode, ProcessBackendOptions,
    TokioProcessRunner,
};
use merry_runtime::{
    AcceptedLocalWorkspaceProcessAdmission, PermissionedProcessRunnerFactory, ProcessRunner,
    StaticPermissionedProcessRunnerFactory,
};
use std::sync::Arc;

#[test]
fn session_keeps_admission_with_runner_capabilities() {
    let runner: Arc<dyn ProcessRunner> = Arc::new(TokioProcessRunner::new());
    let factory: Arc<dyn PermissionedProcessRunnerFactory> = Arc::new(
        StaticPermissionedProcessRunnerFactory::new(Arc::clone(&runner)),
    );
    let admission = AcceptedLocalWorkspaceProcessAdmission::accept_host();
    let backend = LocalProcessBackend::from_parts(admission, runner, factory);

    assert_eq!(backend.new_session().admission(), admission);
}

#[test]
fn backend_mode_is_semantic_and_does_not_encode_a_platform() {
    assert_ne!(ProcessBackendMode::Host, ProcessBackendMode::Isolated);
}

#[test]
fn backend_options_default_to_no_host_overrides() {
    let options = ProcessBackendOptions::new();
    assert!(options.path_rules().is_empty());
    assert!(options.host_integrations().is_empty());
    assert!(options.environment_overrides().is_empty());
    assert!(options.workspace_writable);
}

#[test]
fn backend_options_attach_protected_and_writable_product_paths() {
    let home = if cfg!(windows) {
        std::path::PathBuf::from(r"C:\Users\alice")
    } else {
        std::path::PathBuf::from("/home/alice")
    };
    let state_dir = home.join(".local").join("state").join("merry");
    let providers_dir = home
        .join(".local")
        .join("share")
        .join("merry")
        .join("providers");
    let config_dir = home.join(".config").join("merry");
    let skills_dir = config_dir.join("skills");
    let memory_dir = home
        .join(".local")
        .join("share")
        .join("merry")
        .join("memory");

    let policy =
        merry_core::HostPathPolicy::from_merry_dirs(state_dir.clone(), providers_dir.clone())
            .extend_product_readonly([config_dir.clone()])
            .with_product_writable_config([skills_dir.clone()])
            .with_durable_memory_root(Some(memory_dir.clone()));
    let options = ProcessBackendOptions::new().with_host_path_policy(&policy);

    assert!(options.path_rules().iter().any(|rule| {
        rule.path() == state_dir
            && rule.access() == merry_runtime::PathAccess::ReadOnly
            && rule.source() == merry_runtime::PathAccessRuleSource::ProductReadOnly
    }));
    assert!(options.path_rules().iter().any(|rule| {
        rule.path() == config_dir
            && rule.access() == merry_runtime::PathAccess::ReadOnly
            && rule.source() == merry_runtime::PathAccessRuleSource::ProductReadOnly
    }));
    assert!(!options.path_rules().iter().any(|rule| {
        rule.path() == state_dir && rule.access() == merry_runtime::PathAccess::Deny
    }));
    assert!(options.path_rules().iter().any(|rule| {
        rule.path() == providers_dir
            && rule.access() == merry_runtime::PathAccess::Deny
            && rule.source() == merry_runtime::PathAccessRuleSource::ProductPrivate
    }));
    assert!(options.path_rules().iter().any(|rule| {
        rule.path() == skills_dir
            && rule.access() == merry_runtime::PathAccess::ReadWrite
            && rule.source() == merry_runtime::PathAccessRuleSource::ProductConfig
    }));
    assert!(options.path_rules().iter().any(|rule| {
        rule.path() == memory_dir
            && rule.access() == merry_runtime::PathAccess::ReadWrite
            && rule.source() == merry_runtime::PathAccessRuleSource::DurableMemory
    }));
}

#[test]
fn live_process_backend_host_mode_replaces_and_preserves_permission_view() {
    let workspace = tempfile::tempdir().expect("workspace");
    let backend = super::LiveProcessBackend::new(
        workspace.path(),
        ProcessBackendMode::Host,
        ProcessBackendOptions::new(),
    )
    .expect("host live backend should build on every platform");
    let initial = backend.new_session();
    assert_eq!(
        initial.admission().sandbox_profile(),
        merry_runtime::LocalWorkspaceProcessSandboxProfile::Host
    );
    assert!(
        initial.permission_view().is_some(),
        "host live backend should expose the shared session permission view"
    );

    let replaced = backend
        .replace(
            workspace.path(),
            ProcessBackendMode::Host,
            ProcessBackendOptions::new(),
        )
        .expect("host live backend replacement should succeed");
    assert_eq!(
        replaced.admission().sandbox_profile(),
        merry_runtime::LocalWorkspaceProcessSandboxProfile::Host
    );
    assert!(replaced.permission_view().is_some());

    let wrapped = super::LiveProcessBackend::from_session(replaced);
    assert_eq!(
        wrapped.new_session().admission().sandbox_profile(),
        merry_runtime::LocalWorkspaceProcessSandboxProfile::Host
    );
}

#[cfg(not(all(feature = "sandbox", any(target_os = "linux", target_os = "macos"))))]
mod unsupported_tests {
    use super::{
        super::ProcessBackendError, LocalProcessBackend, ProcessBackendMode, ProcessBackendOptions,
    };

    #[test]
    fn isolated_backend_reports_unavailable_platform() {
        let temp = tempfile::tempdir().expect("temporary workspace should be created");
        let Err(error) = LocalProcessBackend::new(
            temp.path(),
            ProcessBackendMode::Isolated,
            ProcessBackendOptions::new(),
        ) else {
            panic!("isolated backend should report unsupported platforms");
        };

        assert!(matches!(
            error,
            ProcessBackendError::UnsupportedIsolation { .. }
        ));
    }
}

#[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
mod sandbox_tests {
    use super::{LocalProcessBackend, ProcessBackend, ProcessBackendMode, ProcessBackendOptions};
    use std::path::PathBuf;

    #[test]
    fn backend_selection_binds_admission_to_the_selected_behavior() {
        let temp = tempfile::tempdir().expect("temporary workspace should be created");
        let host = LocalProcessBackend::new(
            temp.path(),
            ProcessBackendMode::Host,
            ProcessBackendOptions::new(),
        )
        .expect("host backend should build");
        assert_eq!(
            host.new_session().admission().sandbox_profile(),
            merry_runtime::LocalWorkspaceProcessSandboxProfile::Host
        );

        let isolated = LocalProcessBackend::new(
            temp.path(),
            ProcessBackendMode::Isolated,
            ProcessBackendOptions::new(),
        )
        .expect("isolated backend should build before process execution");
        assert_eq!(
            isolated.new_session().admission().sandbox_profile(),
            merry_runtime::LocalWorkspaceProcessSandboxProfile::LocalWorkspace
        );
    }

    #[test]
    fn sandboxed_backend_allows_user_grant_covering_product_private_directory() {
        use merry_runtime::{PathAccess, PathAccessRule, PathAccessRuleSource};

        let workspace = tempfile::tempdir().expect("workspace");
        let parent = PathBuf::from("/var/merry-path-check");
        let private = parent.join("merry/providers");
        let options = ProcessBackendOptions::new().with_path_rules([
            PathAccessRule::new(
                parent,
                PathAccess::ReadOnly,
                PathAccessRuleSource::TrustedGlobalConfig,
            ),
            PathAccessRule::new(
                private,
                PathAccess::Deny,
                PathAccessRuleSource::ProductPrivate,
            ),
        ]);

        LocalProcessBackend::sandboxed(workspace.path(), options)
            .expect("explicit user grant covering a ProductPrivate path must not block startup");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn new_session_with_read_only_workspace_and_inherited_permissions_stays_isolated() {
        use crate::{
            ProcessSessionRequest,
            process_runner::tests::{fixture_root, permission_request},
        };
        use merry_runtime::{
            ProcessActionIntent, ProcessEnvPolicy, ProcessExitStatus, ProcessRunnerContext,
        };
        use serde_json::json;

        let root = tempfile::tempdir_in(fixture_root()).expect("fixture root outside /tmp");
        let workspace = root.path().join("workspace");
        let extra = root.path().join("extra");
        std::fs::create_dir_all(&workspace).expect("workspace dir");
        std::fs::create_dir_all(&extra).expect("extra dir");
        std::fs::write(workspace.join("hello.txt"), "hi\n").expect("seed workspace");
        std::fs::write(extra.join("shared.txt"), "from-extra\n").expect("seed extra");

        let backend = LocalProcessBackend::sandboxed(&workspace, ProcessBackendOptions::new())
            .expect("isolated backend should build");
        let parent_session = backend.new_session();
        let parent_view = parent_session
            .permission_view()
            .expect("sandboxed session should expose a permission view");

        // Grant the parent session read access to `extra` via an approved request.
        let grant_request = permission_request(json!({
            "requested": {
                "paths": [{
                    "path": extra.display().to_string(),
                    "access": "ro"
                }]
            },
            "for_action": { "command": "true", "cwd": "." }
        }));
        let _ = parent_session
            .permissioned_factory()
            .runner_for_decision(&grant_request, merry_core::ApprovalScope::Session);

        let child_session = backend
            .new_session_with(
                ProcessSessionRequest::new()
                    .read_only_workspace()
                    .with_inherited_permissions(parent_view.clone()),
            )
            .expect("read-only child session should build");
        let child_view = child_session
            .permission_view()
            .expect("child session should expose its own permission view");
        assert_eq!(
            child_view
                .snapshot()
                .expect("child snapshot")
                .path_rules()
                .len(),
            parent_view
                .snapshot()
                .expect("parent snapshot")
                .path_rules()
                .len(),
            "child should inherit parent's approved ordinary path grants"
        );

        // Child can read inside workspace & inherited extra dir, and cannot write workspace.
        let read_intent = ProcessActionIntent::new(
            vec![
                "sh".to_owned(),
                "-c".to_owned(),
                format!("cat hello.txt && cat {}/shared.txt", extra.display()),
            ],
            None,
            ProcessEnvPolicy::empty(),
            None,
            4096,
            4096,
        )
        .expect("valid read intent");
        let read_out = child_session
            .runner()
            .run(
                read_intent,
                ProcessRunnerContext::new(tokio_util::sync::CancellationToken::new()),
            )
            .await
            .expect("read command should run in read-only sandbox");
        assert_eq!(
            read_out.status(),
            ProcessExitStatus::Exited(0),
            "stderr: {}",
            read_out.stderr_text()
        );
        assert!(read_out.stdout_text().contains("hi"));
        assert!(read_out.stdout_text().contains("from-extra"));

        let write_intent = ProcessActionIntent::new(
            vec![
                "sh".to_owned(),
                "-c".to_owned(),
                "touch should-fail.txt".to_owned(),
            ],
            None,
            ProcessEnvPolicy::empty(),
            None,
            4096,
            4096,
        )
        .expect("valid write intent");
        let write_out = child_session
            .runner()
            .run(
                write_intent,
                ProcessRunnerContext::new(tokio_util::sync::CancellationToken::new()),
            )
            .await
            .expect("write command should execute and be refused by OS sandbox");
        assert_ne!(write_out.status(), ProcessExitStatus::Exited(0));
        assert!(!workspace.join("should-fail.txt").exists());

        // Child's extra grant must not leak back to parent.
        let child_only_dir = root.path().join("child-only");
        std::fs::create_dir_all(&child_only_dir).expect("child only dir");
        let child_grant_request = permission_request(json!({
            "requested": {
                "paths": [{
                    "path": child_only_dir.display().to_string(),
                    "access": "ro"
                }]
            },
            "for_action": { "command": "true", "cwd": "." }
        }));
        let _ = child_session
            .permissioned_factory()
            .runner_for_decision(&child_grant_request, merry_core::ApprovalScope::Session);
        assert_eq!(
            parent_view
                .snapshot()
                .expect("parent snapshot")
                .path_rules()
                .len(),
            1,
            "child-only grants must not mutate parent session permissions"
        );
    }

    #[tokio::test]
    async fn live_process_backend_replace_switches_modes_preserves_background_and_resets_permissions()
     {
        use crate::process_runner::tests::permission_request;
        use serde_json::json;

        let workspace = tempfile::tempdir().expect("workspace");
        let extra = tempfile::tempdir().expect("extra dir");
        let backend = crate::LiveProcessBackend::new(
            workspace.path(),
            ProcessBackendMode::Isolated,
            ProcessBackendOptions::new(),
        )
        .expect("live isolated backend");
        let initial_session = backend.new_session();
        assert_eq!(
            initial_session.admission().sandbox_profile(),
            merry_runtime::LocalWorkspaceProcessSandboxProfile::LocalWorkspace
        );
        let shared_permission_view = initial_session
            .permission_view()
            .expect("live backend exposes shared permission view");
        let initial_control = initial_session
            .runner()
            .background_control()
            .expect("background control");

        // Record a session-scoped grant before replacing the backend.
        let pre_reload_grant = permission_request(json!({
            "requested": {
                "paths": [{
                    "path": extra.path().display().to_string(),
                    "access": "ro"
                }]
            },
            "for_action": { "command": "true", "cwd": "." }
        }));
        let _ = initial_session
            .permissioned_factory()
            .runner_for_decision(&pre_reload_grant, merry_core::ApprovalScope::Session);
        assert_eq!(
            shared_permission_view
                .snapshot()
                .expect("snapshot")
                .path_rules()
                .len(),
            1
        );

        let intent = merry_runtime::ProcessActionIntent::new(
            vec!["/bin/sleep".to_owned(), "30".to_owned()],
            None,
            merry_runtime::ProcessEnvPolicy::empty(),
            None,
            1024,
            1024,
        )
        .expect("sleep intent")
        .with_background(true)
        .with_display_name(Some("live-swap-bg".to_owned()));
        let bg_output = initial_session
            .runner()
            .run(
                intent,
                merry_runtime::ProcessRunnerContext::new(Default::default()),
            )
            .await
            .expect("background sleep should start");
        let bg_id = bg_output
            .background_process_id()
            .expect("background id")
            .clone();
        assert_eq!(initial_control.list().len(), 1);
        let live_access_policy = initial_session.live_policy_handle(workspace.path(), true);
        assert!(
            live_access_policy.is_restricted(),
            "isolated backend starts with an active WorkspaceAccessPolicy"
        );

        let host_session = backend
            .replace(
                workspace.path(),
                ProcessBackendMode::Host,
                ProcessBackendOptions::new(),
            )
            .expect("live replace to host should succeed");
        assert!(
            !live_access_policy.is_restricted(),
            "live swap to Host must disable WorkspaceAccessPolicy on the shared handle"
        );
        assert_eq!(
            host_session.admission().sandbox_profile(),
            merry_runtime::LocalWorkspaceProcessSandboxProfile::Host
        );
        assert!(
            shared_permission_view
                .snapshot()
                .expect("snapshot after replace")
                .path_rules()
                .is_empty(),
            "replacing sandbox settings must clear stale pre-reload session grants on the shared view"
        );
        let child_after_swap = backend
            .new_session_with(crate::ProcessSessionRequest::new())
            .expect("subagent session after swap");
        assert_eq!(
            child_after_swap.admission().sandbox_profile(),
            merry_runtime::LocalWorkspaceProcessSandboxProfile::Host
        );

        let host_control = host_session
            .runner()
            .background_control()
            .expect("host background control");
        assert!(
            host_control.list().iter().any(|item| item.id() == &bg_id),
            "background process started before live swap must stay visible"
        );
        host_control
            .stop(&bg_id)
            .expect("background process should stop cleanly through swapped session");

        let restored_session = backend
            .replace(
                workspace.path(),
                ProcessBackendMode::Isolated,
                ProcessBackendOptions::new(),
            )
            .expect("live replace back to isolated should succeed");
        assert!(
            live_access_policy.is_restricted(),
            "live swap back to Isolated must re-enable WorkspaceAccessPolicy on the shared handle"
        );
        assert_eq!(
            restored_session.admission().sandbox_profile(),
            merry_runtime::LocalWorkspaceProcessSandboxProfile::LocalWorkspace
        );

        // Grants recorded after reload flow through the same view held by child factories.
        let _ = restored_session
            .permissioned_factory()
            .runner_for_decision(&pre_reload_grant, merry_core::ApprovalScope::Session);
        let child_after_restore = backend
            .new_session_with(
                crate::ProcessSessionRequest::new()
                    .with_inherited_permissions(shared_permission_view.clone()),
            )
            .expect("child after restore");
        assert_eq!(
            child_after_restore
                .permission_view()
                .expect("child view")
                .snapshot()
                .expect("child snapshot")
                .path_rules()
                .len(),
            1,
            "post-reload parent grants must remain visible to subsequent subagents"
        );
    }
}