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
//! Path capability admission: trusted rules, review materialization, session
//! retention, symlink aliases, and the read-only and deny ceilings.

use crate::process_runner::tests::{permission_request, request_process_intent};
use crate::process_runner::{
    ProcessSessionPermissions, WorkspaceProcessRunner, WorkspaceProcessRunnerFactory,
};
use merry_core::ApprovalScope;
use merry_runtime::{
    PathAccess, PathAccessRule, PathAccessRuleSource, PermissionedProcessRunnerFactory,
};
use serde_json::json;
use std::path::PathBuf;

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

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

    let temp = tempfile::tempdir().expect("temporary path");
    let real = temp.path().join("real");
    let link = temp.path().join("link");
    std::fs::create_dir_all(&real).expect("real directory");
    symlink(&real, &link).expect("directory symlink");

    let factory = WorkspaceProcessRunnerFactory::new_at_workspace_root("/workspace/merry")
        .with_path_rules([PathAccessRule::new(
            real.clone(),
            PathAccess::ReadWrite,
            PathAccessRuleSource::TrustedGlobalConfig,
        )]);
    let request = permission_request(json!({
        "requested": {
            "paths": [{
                "path": link.to_str().expect("UTF-8 test path"),
                "access": "rw"
            }]
        },
        "for_action": { "command": "touch", "cwd": "." }
    }));

    assert!(
        factory
            .request_capabilities_are_satisfied(&request)
            .expect("path capability should be evaluated")
    );

    let denied_factory = WorkspaceProcessRunnerFactory::new_at_workspace_root("/workspace/merry")
        .with_path_rules([PathAccessRule::new(
            real,
            PathAccess::Deny,
            PathAccessRuleSource::TrustedGlobalConfig,
        )]);
    assert!(
        !denied_factory
            .request_capabilities_are_satisfied(&request)
            .expect("denied path capability should be evaluated")
    );
}

#[test]
fn permissioned_factory_preserves_trusted_path_rules() {
    let factory = WorkspaceProcessRunnerFactory::new_at_workspace_root("/workspace/merry")
        .with_path_rules([PathAccessRule::new(
            PathBuf::from("/var/log"),
            PathAccess::ReadOnly,
            PathAccessRuleSource::TrustedGlobalConfig,
        )]);
    let request = permission_request(json!({
        "requested": { "network": true },
        "for_action": { "command": "cargo test", "cwd": "." }
    }));

    let launch = factory
        .build_runner(&request)
        .plan_for(request_process_intent(&request))
        .expect("trusted path launch");

    let resolved_var_log = crate::resolve_host_path(std::path::Path::new("/var/log"));
    assert!(contains_path(
        launch.read_only(),
        resolved_var_log.to_str().expect("utf-8 path")
    ));
    assert!(launch.network());
}

#[test]
fn permissioned_factory_materializes_requested_path_rules() {
    let factory = WorkspaceProcessRunnerFactory::new_at_workspace_root("/workspace/merry");
    let request = permission_request(json!({
        "requested": {
            "paths": [{ "path": "deps/cache", "access": "rw" }]
        },
        "for_action": { "command": "cargo test", "cwd": "." }
    }));

    let launch = factory
        .build_runner(&request)
        .plan_for(request_process_intent(&request))
        .expect("requested path launch");

    assert!(contains_path(
        launch.read_write(),
        "/workspace/merry/deps/cache"
    ));
    assert!(!launch.network());
}

#[test]
fn permissioned_factory_keeps_approved_paths_for_later_actions() {
    let session_permissions = ProcessSessionPermissions::new();
    let factory = WorkspaceProcessRunnerFactory::new_at_workspace_root("/workspace/merry")
        .with_session_permissions(session_permissions.clone());
    let base_runner = WorkspaceProcessRunner::new_at_workspace_root("/workspace/merry")
        .with_session_permissions(session_permissions);
    let first_request = permission_request(json!({
        "requested": {
            "paths": [
                { "path": "/var/lib/merry-demo.txt", "access": "ro" }
            ]
        },
        "for_action": { "command": "touch /var/lib/merry-demo.txt", "cwd": null }
    }));
    let later_request = permission_request(json!({
        "requested": { "network": true },
        "for_action": { "command": "cat /var/lib/merry-demo.txt", "cwd": null }
    }));

    // `runner_for` / ApprovalScope::Once must NOT silently retain path grants.
    let _ = factory.runner_for(&first_request);
    let after_once = base_runner
        .plan_for(request_process_intent(&later_request))
        .expect("later ordinary process plan after once should build");
    let resolved_demo = crate::resolve_host_path(std::path::Path::new("/var/lib/merry-demo.txt"));
    assert!(
        !contains_path(
            after_once.read_only(),
            resolved_demo.to_str().expect("utf-8 path")
        ),
        "ApprovalScope::Once must not leak path grants to later actions"
    );

    // Explicit ApprovalScope::Session retains the path grant for later actions.
    let _ = factory.runner_for_decision(&first_request, ApprovalScope::Session);
    let launch = base_runner
        .plan_for(request_process_intent(&later_request))
        .expect("later ordinary process plan should build");

    let resolved_tmp = crate::resolve_host_path(std::path::Path::new("/tmp"));
    let resolved_var_tmp = crate::resolve_host_path(std::path::Path::new("/var/tmp"));
    assert!(contains_path(
        launch.read_only(),
        resolved_demo.to_str().expect("utf-8 path")
    ));
    assert!(!launch.network());
    assert!(contains_path(
        launch.read_write(),
        resolved_tmp.to_str().expect("utf-8 path")
    ));
    assert!(contains_path(
        launch.read_write(),
        resolved_var_tmp.to_str().expect("utf-8 path")
    ));
}

#[test]
fn permissioned_factory_reuses_parent_path_grants_for_descendants() {
    let session_permissions = ProcessSessionPermissions::new();
    let factory = WorkspaceProcessRunnerFactory::new_at_workspace_root("/workspace/merry")
        .with_session_permissions(session_permissions);
    let parent_request = permission_request(json!({
        "requested": {
            "paths": [{ "path": "/var/merry-parent", "access": "rw" }]
        },
        "for_action": { "command": "mkdir -p /var/merry-parent", "cwd": null }
    }));
    let descendant_read_write_request = permission_request(json!({
        "requested": {
            "paths": [{ "path": "/var/merry-parent/hello.txt", "access": "rw" }]
        },
        "for_action": { "command": "cat /var/merry-parent/hello.txt", "cwd": null }
    }));
    let descendant_read_only_request = permission_request(json!({
        "requested": {
            "paths": [{ "path": "/var/merry-parent/hello.txt", "access": "ro" }]
        },
        "for_action": { "command": "cat /var/merry-parent/hello.txt", "cwd": null }
    }));
    let network_request = permission_request(json!({
        "requested": { "network": true },
        "for_action": { "command": "curl https://example.invalid", "cwd": null }
    }));

    let _ = factory.runner_for_decision(&parent_request, ApprovalScope::Session);
    assert!(
        factory
            .request_capabilities_are_satisfied(&descendant_read_write_request)
            .expect("descendant write capability query should succeed")
    );
    assert!(
        factory
            .request_capabilities_are_satisfied(&descendant_read_only_request)
            .expect("descendant read capability query should succeed")
    );
    assert!(
        !factory
            .request_capabilities_are_satisfied(&network_request)
            .expect("network capability query should succeed")
    );

    let read_only_factory =
        WorkspaceProcessRunnerFactory::new_at_workspace_root("/workspace/merry")
            .with_session_permissions(ProcessSessionPermissions::new());
    let read_only_parent_request = permission_request(json!({
        "requested": {
            "paths": [{ "path": "/var/merry-parent", "access": "ro" }]
        },
        "for_action": { "command": "cat /var/merry-parent/hello.txt", "cwd": null }
    }));

    let _ =
        read_only_factory.runner_for_decision(&read_only_parent_request, ApprovalScope::Session);
    assert!(
        read_only_factory
            .request_capabilities_are_satisfied(&descendant_read_only_request)
            .expect("read-only descendant capability query should succeed")
    );
    assert!(
        !read_only_factory
            .request_capabilities_are_satisfied(&descendant_read_write_request)
            .expect("read-write upgrade capability query should succeed")
    );
}

#[test]
fn permissioned_factory_caps_requested_write_to_trusted_read_only_rule() {
    let factory = WorkspaceProcessRunnerFactory::new_at_workspace_root("/workspace/merry")
        .with_path_rules([PathAccessRule::new(
            PathBuf::from("/opt/merry-readonly"),
            PathAccess::ReadOnly,
            PathAccessRuleSource::TrustedGlobalConfig,
        )]);
    let request = permission_request(json!({
        "requested": {
            "paths": [{ "path": "/opt/merry-readonly", "access": "rw" }]
        },
        "for_action": { "command": "cargo test", "cwd": "." }
    }));

    factory
        .validate_request(&request)
        .expect("read-only policy should cap rather than reject a write request");
    let launch = factory
        .build_runner(&request)
        .plan_for(request_process_intent(&request))
        .expect("capped path launch");

    assert!(contains_path(launch.read_only(), "/opt/merry-readonly"));
    assert!(!contains_path(launch.read_write(), "/opt/merry-readonly"));
}

#[test]
fn permissioned_factory_rejects_requested_path_under_configured_deny() {
    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 error = factory
        .validate_request(&request)
        .expect_err("configured deny must be a hard policy boundary");
    assert!(
        error
            .to_string()
            .contains("denied by configured path policy")
    );
}

#[test]
fn permissioned_factory_blocks_parent_bypasses_and_keeps_product_readonly_writes_action_scoped() {
    let state_dir = PathBuf::from("/home/alice/.local/state/merry");
    let providers_dir = PathBuf::from("/home/alice/.local/share/merry/providers");
    let session = ProcessSessionPermissions::new();
    let session_view = session.view();
    let base_rules = [
        PathAccessRule::new(
            state_dir.clone(),
            PathAccess::ReadOnly,
            PathAccessRuleSource::ProductReadOnly,
        ),
        PathAccessRule::new(
            providers_dir.clone(),
            PathAccess::Deny,
            PathAccessRuleSource::ProductPrivate,
        ),
    ];
    let factory = WorkspaceProcessRunnerFactory::new_at_workspace_root("/workspace/merry")
        .with_path_rules(base_rules.clone())
        .with_session_permissions(session.clone());
    let base_runner = WorkspaceProcessRunner::new_at_workspace_root("/workspace/merry")
        .with_path_rules(base_rules)
        .with_session_permissions(session);

    // Reading inside ProductReadOnly is already satisfied without review.
    let read_state = permission_request(json!({
        "requested": {
            "paths": [{ "path": "/home/alice/.local/state/merry/sessions", "access": "ro" }]
        },
        "for_action": { "command": "ls /home/alice/.local/state/merry/sessions", "cwd": "." }
    }));
    assert!(
        factory
            .request_capabilities_are_satisfied(&read_state)
            .expect("read-only state query should succeed")
    );

    // Parent-directory write request covering ProductReadOnly must be rejected.
    let parent_state_write = permission_request(json!({
        "requested": {
            "paths": [{ "path": "/home/alice/.local/state", "access": "rw" }]
        },
        "for_action": { "command": "touch /home/alice/.local/state/merry/x", "cwd": "." }
    }));
    let parent_ro_err = factory
        .validate_request(&parent_state_write)
        .expect_err("parent rw request covering ProductReadOnly must be rejected");
    assert!(
        parent_ro_err
            .to_string()
            .contains("covers Merry protected read-only path"),
        "{parent_ro_err}"
    );

    // Parent-directory read or write request covering ProductPrivate (providers/) must be rejected.
    for (parent, access) in [
        ("/home/alice/.local/share", "ro"),
        ("/home/alice/.local/share", "rw"),
        ("/home/alice", "ro"),
        ("/home/alice", "rw"),
    ] {
        let req = permission_request(json!({
            "requested": {
                "paths": [{ "path": parent, "access": access }]
            },
            "for_action": { "command": "ls", "cwd": "." }
        }));
        let err = factory
            .validate_request(&req)
            .expect_err("ancestor of ProductPrivate deny must be rejected");
        assert!(
            err.to_string().contains("covers denied path"),
            "parent={parent} access={access}: {err}"
        );
    }

    // Direct write on ProductReadOnly requires review, works for that ONE action,
    // and is never retained in session permissions.
    let write_logs = permission_request(json!({
        "requested": {
            "paths": [{ "path": "/home/alice/.local/state/merry/logs", "access": "rw" }]
        },
        "for_action": { "command": "touch /home/alice/.local/state/merry/logs/note", "cwd": "." }
    }));
    assert!(
        !factory
            .request_capabilities_are_satisfied(&write_logs)
            .expect("write query on ProductReadOnly must require review")
    );
    factory
        .validate_request(&write_logs)
        .expect("direct write on ProductReadOnly should be reviewable");
    let approved_runner = factory.runner_for(&write_logs);
    let _ = approved_runner;
    assert!(
        session_view
            .snapshot()
            .expect("session snapshot")
            .path_rules()
            .is_empty(),
        "approved write on ProductReadOnly must stay action-scoped and never persist in session"
    );
    assert!(
        !factory
            .request_capabilities_are_satisfied(&write_logs)
            .expect("subsequent write on ProductReadOnly must still require review")
    );
    let follow_up_launch = base_runner
        .plan_for(request_process_intent(&write_logs))
        .expect("subsequent base launch");
    assert!(contains_path(
        follow_up_launch.read_only(),
        "/home/alice/.local/state/merry"
    ));
    assert!(!contains_path(
        follow_up_launch.read_write(),
        "/home/alice/.local/state/merry"
    ));
    assert!(!contains_path(
        follow_up_launch.read_write(),
        "/home/alice/.local/state/merry/logs"
    ));

    // Verify the one-shot runner itself actually receives read_write for the approved target.
    let raw_factory = WorkspaceProcessRunnerFactory::new_at_workspace_root("/workspace/merry")
        .with_path_rules([PathAccessRule::new(
            state_dir.clone(),
            PathAccess::ReadOnly,
            PathAccessRuleSource::ProductReadOnly,
        )]);
    let direct_state_write = permission_request(json!({
        "requested": {
            "paths": [{ "path": "/home/alice/.local/state/merry", "access": "rw" }]
        },
        "for_action": { "command": "touch /home/alice/.local/state/merry/note", "cwd": "." }
    }));
    let approved_launch = raw_factory
        .build_runner(&direct_state_write)
        .plan_for(request_process_intent(&direct_state_write))
        .expect("approved direct write launch");
    assert!(contains_path(
        approved_launch.read_write(),
        "/home/alice/.local/state/merry"
    ));

    // Nested built-in ProductPrivate secret inside ProductReadOnly:
    // - Direct request is allowed to enter permission review (built-in rules never hard-deny),
    //   and is tagged ProtectedMetadata so it is never retained in session permissions.
    // - Broad parent write covering the secret is still rejected before review.
    let nested_secret = state_dir.join("external.key");
    let nested_session_permissions = ProcessSessionPermissions::new();
    let nested_factory = WorkspaceProcessRunnerFactory::new_at_workspace_root("/workspace/merry")
        .with_path_rules([
            PathAccessRule::new(
                state_dir.clone(),
                PathAccess::ReadOnly,
                PathAccessRuleSource::ProductReadOnly,
            ),
            PathAccessRule::new(
                nested_secret,
                PathAccess::Deny,
                PathAccessRuleSource::ProductPrivate,
            ),
        ])
        .with_session_permissions(nested_session_permissions.clone());
    let read_nested_secret = permission_request(json!({
        "requested": {
            "paths": [{ "path": "/home/alice/.local/state/merry/external.key", "access": "ro" }]
        },
        "for_action": { "command": "cat /home/alice/.local/state/merry/external.key", "cwd": "." }
    }));
    nested_factory
        .validate_request(&read_nested_secret)
        .expect("direct request on built-in ProductPrivate must be reviewable, not hard-denied");
    let _ = nested_factory.runner_for_decision(&read_nested_secret, ApprovalScope::Session);
    assert!(
        nested_session_permissions
            .view()
            .snapshot()
            .expect("snapshot")
            .path_rules()
            .is_empty(),
        "approved built-in ProductPrivate grant must never persist into session permissions"
    );
    let state_write_covering_secret = nested_factory
        .validate_request(&direct_state_write)
        .expect_err("writing state_dir when it contains a protected secret must be rejected");
    assert!(
        state_write_covering_secret
            .to_string()
            .contains("covers denied path")
    );

    // Explicit user config.toml `readwrite_paths` overrides default ProductReadOnly.
    let user_rw_factory = WorkspaceProcessRunnerFactory::new_at_workspace_root("/workspace/merry")
        .with_path_rules([
            PathAccessRule::new(
                state_dir.clone(),
                PathAccess::ReadOnly,
                PathAccessRuleSource::ProductReadOnly,
            ),
            PathAccessRule::new(
                state_dir,
                PathAccess::ReadWrite,
                PathAccessRuleSource::TrustedGlobalConfig,
            ),
        ]);
    assert!(
        user_rw_factory
            .request_capabilities_are_satisfied(&direct_state_write)
            .expect("explicit config.toml readwrite_paths should override default ProductReadOnly")
    );
}