openmoat 0.28.0

Policy checks for AI coding agents: decides allow, defer, review or deny for each tool call the hook of Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot CLI and seven more agents reports, configures Claude Code's, Codex's and Cursor's own OS sandboxes from the same policy, and keeps a local audit log.
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
use std::path::Path;

use openmoat_core::{DEFAULT_POLICY, EvalContext, Policy};

use super::*;

fn generated(home: &Path) -> Generated {
    let home = home.to_string_lossy().into_owned();
    let project = format!("{home}/proj");
    let ctx = EvalContext {
        home: home.clone(),
        project: Some(project.clone()),
        real_home: None,
        real_project: None,
        moved_dirs: Vec::new(),
        cwd: project.clone(),
        case_insensitive_paths: false,
    };
    let grants = Grants {
        proxy_port: Some(18080),
        // The home is in the temp directory, which the session gets empty.
        tmpdir: Path::new(&home)
            .parent()
            .map(|t| t.to_string_lossy().into_owned()),
        program: Some("/usr/bin/agent".into()),
        writes: vec![format!("{home}/.claude"), format!("{home}/.cargo")],
        terminals: Vec::new(),
        trust: None,
        tool_shell: None,
        helpers: None,
        listen: None,
    };
    let mut policy = Policy::parse(DEFAULT_POLICY).expect("default policy");
    // No read roots: the temp directory holding the test home is one.
    policy.sandbox = None;
    let ir = openmoat_core::ir::lower(&policy, &ctx).expect("lowers");
    generate(&ir, &grants, &[project]).expect("generates")
}

fn tree(home: &Path) {
    for dir in [
        "proj/src",
        "proj/.env.d",
        "proj/.git/hooks",
        "proj/vendor/lib/.git/hooks",
        "proj/sub",
        "proj/.claude/worktrees",
        ".claude",
        ".cargo",
    ] {
        std::fs::create_dir_all(home.join(dir)).unwrap();
    }
    for file in [
        "proj/.env",
        "proj/.env.example",
        "proj/src/.env.local",
        "proj/src/main.rs",
        "proj/sub/.git",
        "proj/.env.d/inner",
        "proj/.claude/settings.json",
        ".claude/settings.json",
        ".cargo/credentials.toml",
    ] {
        std::fs::write(home.join(file), "x").unwrap();
    }
}

#[test]
fn denied_paths_in_the_project_and_the_grants_are_masked() {
    let dir = tempfile::tempdir().unwrap();
    let home = std::fs::canonicalize(dir.path()).unwrap();
    tree(&home);
    let out = generated(&home);
    let p = |rel: &str| format!("{}/{rel}", home.display());
    let hide = |rel: &str| Mount::Hide {
        path: p(rel),
        dir: false,
    };
    for expected in [
        hide("proj/.env"),
        hide("proj/src/.env.local"),
        Mount::Hide {
            path: p("proj/.env.d"),
            dir: true,
        },
        hide("proj/.envrc"),
        hide("proj/.moat"),
        Mount::ReadOnly(p("proj/.git")),
        // a nested repository's `.git`, directory or `gitdir:` file, is git's too
        Mount::ReadOnly(p("proj/vendor/lib/.git")),
        Mount::ReadOnly(p("proj/sub/.git")),
        Mount::ReadOnly(p("proj/.claude/settings.json")),
        // The node is pinned; Claude Code may still write its worktrees.
        Mount::ReadWrite(p("proj/.claude")),
        Mount::ReadWrite(p(".claude")),
        Mount::ReadOnly(p(".claude/settings.json")),
        hide(".cargo/credentials.toml"),
    ] {
        assert!(
            out.mounts.contains(&expected),
            "{expected:?}: {:#?}",
            out.mounts
        );
    }
    assert!(!out.mounts.contains(&hide("proj/.env.example")));
    assert!(
        !out.mounts.contains(&hide("proj/.env.d/inner")),
        "a hidden directory is not entered"
    );
    assert!(
        !out.mounts
            .contains(&Mount::ReadOnly(p("proj/.claude/worktrees")))
    );
    let made: Vec<&str> = out.placeholders.iter().map(|x| x.path.as_str()).collect();
    let (envrc, moat) = (p("proj/.envrc"), p("proj/.moat"));
    assert_eq!(made[..2], [envrc.as_str(), moat.as_str()]);
    // and the hook settings the project lacks
    let local = p("proj/.claude/settings.local.json");
    assert!(made.contains(&local.as_str()), "{made:?}");
    assert!(!made.contains(&p("proj/.claude/settings.json").as_str()));
    // Trees first, outermost first; the home itself is never mounted.
    let first_mask = out
        .mounts
        .iter()
        .position(|m| matches!(m, Mount::Hide { .. }));
    let project = out
        .mounts
        .iter()
        .position(|m| m == &Mount::ReadWrite(p("proj")));
    assert!(
        project.is_some() && project < first_mask,
        "{:#?}",
        out.mounts
    );
    assert!(out.rules.write.contains(&p("proj")), "{:?}", out.rules);
    let tmp = home.parent().unwrap().to_string_lossy().into_owned();
    assert!(
        out.mounts.contains(&Mount::Tmpfs(tmp.clone())),
        "{:#?}",
        out.mounts
    );
    assert!(!out.mounts.contains(&Mount::ReadOnly(tmp)));
    let home_path = home.to_string_lossy().into_owned();
    assert!(!out.mounts.iter().any(|m| path_of(m) == home_path));
    let rules = out
        .report
        .allowances
        .iter()
        .map(|a| a.rule.as_str())
        .collect::<Vec<_>>();
    assert!(rules.contains(&"bwrap.created-later"), "{rules:?}");
    assert!(!rules.contains(&"landlock.inside-grants") && !rules.contains(&"landlock.tcp-port"));
}

#[test]
fn masks_repeat_under_every_spelling_of_the_project() {
    let mut masks = vec![
        Mount::Hide {
            path: "/real/p/.env".into(),
            dir: false,
        },
        Mount::ReadOnly("/real/p/.git/hooks".into()),
    ];
    let all = respelled(&masks, &["/real/p".into(), "/link/p".into()]);
    masks.extend([
        Mount::Hide {
            path: "/link/p/.env".into(),
            dir: false,
        },
        Mount::ReadOnly("/link/p/.git/hooks".into()),
    ]);
    assert_eq!(all, masks);
}

#[test]
fn args_bind_the_placeholders_over_hidden_paths() {
    let mounts = [
        Mount::ReadOnly("/usr".into()),
        Mount::ReadWrite("/p".into()),
        Mount::Tmpfs("/tmp".into()),
        Mount::Hide {
            path: "/p/.env".into(),
            dir: false,
        },
        Mount::Hide {
            path: "/p/secrets".into(),
            dir: true,
        },
    ];
    let args = args(&mounts, "/b/file", "/b/dir").join(" ");
    assert_eq!(
        args,
        "--ro-bind-try /usr /usr --bind-try /p /p --tmpfs /tmp --ro-bind /b/file /p/.env \
         --ro-bind /b/dir /p/secrets"
    );
}

/// `moat run`'s network namespace binds the whole root, where Landlock alone
/// cannot deny inside a grant: `--write ~/.agent` left the agent's denied
/// `settings.json` writable, and a read root `~/.tools` its denied token
/// readable, to every command.
#[test]
fn the_network_namespace_masks_denied_paths_inside_its_grants() {
    let dir = tempfile::tempdir().unwrap();
    let home = std::fs::canonicalize(dir.path()).unwrap();
    let p = |rel: &str| format!("{}/{rel}", home.display());
    for d in ["proj", ".agent", ".tools"] {
        std::fs::create_dir_all(p(d)).unwrap();
    }
    for f in ["proj/token", ".agent/settings.json", ".tools/token"] {
        std::fs::write(p(f), "x").unwrap();
    }
    let ctx = EvalContext {
        home: home.to_string_lossy().into_owned(),
        project: Some(p("proj")),
        real_home: None,
        real_project: None,
        moved_dirs: Vec::new(),
        cwd: p("proj"),
        case_insensitive_paths: false,
    };
    let policy = Policy::parse(
        r#"
version: 1
defaults: { "*": deny }
deny:
  - id: own
    fs.read: ["~/.tools/token", "${project}/token"]
    fs.write: ["~/.agent", "~/.agent/settings.json"]
allow:
  - id: work
    fs.write: ["${project}/**"]
"#,
    )
    .expect("test policy");
    let ir = openmoat_core::ir::lower(&policy, &ctx).expect("lowers");
    let rules = Rules {
        read: vec![p(".tools"), "/dev/null".into()],
        write: vec![p("proj"), p(".agent")],
        list: Vec::new(),
        connect_port: Some(18080),
        bind_port: None,
    };
    let masks = grant_masks(&ir, &rules, &[p("proj")]).unwrap();
    assert_eq!(
        masks,
        [
            // outermost first: the directory node pinned before the file
            // inside it is made read-only
            Mount::ReadWrite(p(".agent")),
            Mount::Hide {
                path: p(".tools/token"),
                dir: false,
            },
            Mount::ReadOnly(p(".agent/settings.json")),
        ],
        "the project stays the hook's and Landlock's, as without a namespace"
    );
}

/// The default policy lowered for a session in `project`.
fn session_ir(project: &str) -> Enforcement {
    let ctx = EvalContext {
        home: "/nowhere/home".into(),
        project: Some(project.to_owned()),
        real_home: None,
        real_project: None,
        moved_dirs: Vec::new(),
        cwd: project.to_owned(),
        case_insensitive_paths: false,
    };
    let policy = Policy::parse(DEFAULT_POLICY).expect("default policy");
    openmoat_core::ir::lower(&policy, &ctx).expect("lowers")
}

/// In the network namespace the agent configuration and the agents' hook
/// settings directly in the project are bound read-only where they exist, and
/// the folders holding them are bound onto themselves so they cannot be
/// renamed away and back, outermost first and under each spelling of the
/// project; CI and commit-hook managers' files stay writable.
#[test]
fn the_network_namespace_keeps_the_projects_agent_configuration_read_only() {
    let dir = tempfile::tempdir().unwrap();
    let real = std::fs::canonicalize(dir.path()).unwrap();
    let p = |rel: &str| format!("{}/{rel}", real.display());
    for d in [
        ".github/hooks",
        ".github/workflows",
        ".github/copilot",
        ".pi",
        ".husky",
        ".claude",
        ".copilot/hooks",
    ] {
        std::fs::create_dir_all(p(d)).unwrap();
    }
    for f in [
        ".mcp.json",
        ".pi/settings.json",
        ".claude/settings.json",
        ".github/copilot/settings.json",
    ] {
        std::fs::write(p(f), "{}").unwrap();
    }
    let project = real.display().to_string();
    let ir = session_ir(&project);
    let all = project_masks(&ir, &[project.clone(), "/other/spelling".into()]).unwrap();
    // the missing hook settings planned for the session are another test's
    let made: Vec<String> = all.placeholders.iter().map(|x| x.path.clone()).collect();
    let masks: Vec<Mount> = all
        .mounts
        .into_iter()
        .filter(|m| {
            let at = path_of(m);
            !made
                .iter()
                .any(|x| x == at || x.replacen(&project, "/other/spelling", 1) == at)
        })
        .collect();
    let expected = [
        Mount::ReadWrite(p(".github")),
        Mount::ReadWrite(p(".pi")),
        Mount::ReadWrite(p(".claude")),
        Mount::ReadWrite(p(".copilot")),
        Mount::ReadOnly(p(".mcp.json")),
        Mount::ReadOnly(p(".github/hooks")),
        Mount::ReadOnly(p(".pi/settings.json")),
        Mount::ReadOnly(p(".claude/settings.json")),
        Mount::ReadOnly(p(".copilot/hooks")),
        Mount::ReadOnly(p(".github/copilot/settings.json")),
    ];
    for mount in &expected {
        assert!(masks.contains(mount), "{mount:?}: {masks:?}");
    }
    let at = |m: &Mount| masks.iter().position(|x| x == m).unwrap_or(usize::MAX);
    assert!(
        at(&expected[0]) < at(&expected[5]),
        "outermost first: {masks:?}"
    );
    assert!(
        at(&expected[2]) < at(&expected[7]),
        "outermost first: {masks:?}"
    );
    let here = masks
        .iter()
        .filter(|m| path_of(m).starts_with(&project))
        .count();
    assert_eq!(here, expected.len(), "{masks:?}");
    assert_eq!(
        masks.len(),
        2 * expected.len(),
        "each again under the other spelling: {masks:?}"
    );
    assert!(masks.contains(&Mount::ReadOnly("/other/spelling/.mcp.json".into())));
    assert!(masks.contains(&Mount::ReadWrite("/other/spelling/.github".into())));
    for writable in [".github/workflows", ".husky"] {
        assert!(
            !masks.iter().any(|m| path_of(m) == p(writable)),
            "{writable}"
        );
    }
    let none = project_masks(&ir, &[]).unwrap();
    assert!(none.mounts.is_empty() && none.placeholders.is_empty());
}

/// Under `--isolate` the folders above an agent's configuration directly in
/// the project are bound onto themselves too: renaming `.github` away and
/// back would carry a hook written under the other name past the read-only
/// `.github/hooks`. A package's own `.github` deeper down stays as it is.
#[test]
fn isolate_pins_the_folders_holding_agent_configuration() {
    let dir = tempfile::tempdir().unwrap();
    let home = std::fs::canonicalize(dir.path()).unwrap();
    tree(&home);
    for d in [
        "proj/.github/hooks",
        "proj/.pi",
        "proj/.openclaw",
        "proj/.github2",
        "proj/node_modules/qs/.github",
    ] {
        std::fs::create_dir_all(home.join(d)).unwrap();
    }
    let out = generated(&home);
    let p = |rel: &str| format!("{}/{rel}", home.display());
    for pinned in ["proj/.github", "proj/.pi", "proj/.openclaw"] {
        assert!(
            out.mounts.contains(&Mount::ReadWrite(p(pinned))),
            "{pinned}: {:?}",
            out.mounts
        );
    }
    let github = out
        .mounts
        .iter()
        .position(|m| m == &Mount::ReadWrite(p("proj/.github")));
    let hooks = out
        .mounts
        .iter()
        .position(|m| m == &Mount::ReadOnly(p("proj/.github/hooks")));
    assert!(github.is_some() && github < hooks, "{:?}", out.mounts);
    for open in ["proj/.github2", "proj/node_modules/qs/.github"] {
        assert!(
            !out.mounts.iter().any(|m| path_of(m) == p(open)),
            "{open}: {:?}",
            out.mounts
        );
    }
}

/// With `~/.claude` a link, `--write ~/.claude` grants the directory it points
/// to (`openmoat run` resolves its grants), and the deny of
/// `~/.claude/settings.json` is masked there: compared as text, it lay below
/// no grant and stayed writable to every command. Linux, where bubblewrap
/// runs: on macOS the temp directory itself resolves elsewhere
/// (`/var` → `/private/var`), which no grant written here does.
#[cfg(target_os = "linux")]
#[test]
fn a_linked_agent_folder_keeps_its_hook_settings_read_only() {
    let dir = tempfile::tempdir().unwrap();
    let home = std::fs::canonicalize(dir.path()).unwrap();
    let p = |rel: &str| format!("{}/{rel}", home.display());
    for d in ["proj", "real-claude"] {
        std::fs::create_dir_all(p(d)).unwrap();
    }
    std::fs::write(p("real-claude/settings.json"), "{}").unwrap();
    std::os::unix::fs::symlink(p("real-claude"), p(".claude")).unwrap();
    let ctx = EvalContext {
        home: home.to_string_lossy().into_owned(),
        project: Some(p("proj")),
        real_home: None,
        real_project: None,
        moved_dirs: Vec::new(),
        cwd: p("proj"),
        case_insensitive_paths: false,
    };
    let policy = Policy::parse(DEFAULT_POLICY).expect("default policy");
    let ir = openmoat_core::ir::lower(&policy, &ctx).expect("lowers");
    let rules = Rules {
        read: Vec::new(),
        write: vec![p("proj"), p("real-claude")],
        list: Vec::new(),
        connect_port: Some(18080),
        bind_port: None,
    };
    let masks = grant_masks(&ir, &rules, &[p("proj")]).unwrap();
    assert!(
        masks.contains(&Mount::ReadOnly(p("real-claude/settings.json"))),
        "{masks:?}"
    );
    // the link's own spelling is no mount of its own: bubblewrap follows it
    assert!(
        !masks.iter().any(|m| path_of(m).starts_with(&p(".claude/"))),
        "{masks:?}"
    );
    // and Landlock reports the deny as one it cannot enforce in that grant
    let grants = Grants {
        writes: vec![p("real-claude")],
        ..Grants::default()
    };
    let report = landlock::generate(&ir, &grants).expect("generates").report;
    let inside: Vec<String> = report
        .allowances
        .iter()
        .filter(|a| a.rule == INSIDE_GRANTS_ALLOWANCE && a.kind == Kind::FsWrite)
        .flat_map(|a| a.patterns.clone())
        .collect();
    assert!(inside.contains(&p(".claude/settings.json")), "{inside:?}");
}

/// The network namespace hides the Kerberos ticket caches in a read root
/// (`/tmp/krb5cc_*`): Landlock grants `/tmp` whole. Other files there stay
/// readable, and a policy's default never masks an entry, only a deny rule.
#[test]
fn ticket_caches_in_a_read_root_are_hidden_and_nothing_else() {
    let dir = tempfile::tempdir().unwrap();
    let root = std::fs::canonicalize(dir.path()).unwrap();
    let p = |rel: &str| format!("{}/{rel}", root.display());
    for d in ["proj", "tmp/krb5cc_1000_dir"] {
        std::fs::create_dir_all(p(d)).unwrap();
    }
    for f in ["tmp/krb5cc_1000", "tmp/build.log", "tmp/my-krb5cc_1000"] {
        std::fs::write(p(f), "x").unwrap();
    }
    let ctx = EvalContext {
        home: "/nowhere/home".into(),
        project: Some(p("proj")),
        real_home: None,
        real_project: None,
        moved_dirs: Vec::new(),
        cwd: p("proj"),
        case_insensitive_paths: false,
    };
    let tmp = p("tmp");
    let policy = Policy::parse(&format!(
        r#"
version: 1
defaults: {{ "*": deny }}
deny:
  - id: secrets-paths
    fs.read: ["{tmp}/krb5cc_*", "{tmp}/krb5cc_*/**"]
allow:
  - id: work
    fs.write: ["${{project}}/**"]
"#
    ))
    .expect("test policy");
    let ir = openmoat_core::ir::lower(&policy, &ctx).expect("lowers");
    let rules = Rules {
        read: vec![tmp.clone()],
        write: vec![p("proj")],
        list: Vec::new(),
        connect_port: Some(18080),
        bind_port: None,
    };
    let mut masks = grant_masks(&ir, &rules, &[p("proj")]).unwrap();
    masks.sort_by(|a, b| path_of(a).cmp(path_of(b)));
    assert_eq!(
        masks,
        [
            Mount::Hide {
                path: p("tmp/krb5cc_1000"),
                dir: false,
            },
            Mount::Hide {
                path: p("tmp/krb5cc_1000_dir"),
                dir: true,
            },
        ]
    );
}

/// The agents' hook settings a project lacks when the session starts.
mod hook_settings;