openmoat-core 0.18.0

Policy model and decision engine for OpenMoat. Pure: no I/O, no OS calls.
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
use super::*;
use crate::action::AtomicAction;
use crate::engine::EvalContext;
use crate::policy::Policy;

fn ctx() -> EvalContext {
    EvalContext {
        home: "/h".into(),
        project: Some("/p".into()),
        real_home: None,
        real_project: None,
        moved_dirs: Vec::new(),
        cwd: "/p".into(),
        case_insensitive_paths: false,
    }
}

fn lowered(yaml: &str) -> Enforcement {
    lower(&Policy::parse(yaml).expect("test policy must lint"), &ctx()).expect("must lower")
}

fn ids(rules: &[Rule]) -> Vec<&str> {
    rules.iter().map(|r| r.id.as_str()).collect()
}

fn read(path: &str) -> AtomicAction {
    AtomicAction::FsRead { path: path.into() }
}

#[test]
fn default_policy_lowers_paths_and_hosts() {
    let ir = lower(
        &Policy::parse(crate::DEFAULT_POLICY).unwrap(),
        &EvalContext {
            home: "/Users/me".into(),
            ..ctx()
        },
    )
    .unwrap();
    assert_eq!(ir.fs.read.default, Effect::Deny);
    // `kernel-self` also denies reads of OpenMoat's state beside the policy.
    assert_eq!(
        ids(&ir.fs.read.deny),
        ["secrets-paths", "agent-credentials", "kernel-self"]
    );
    assert!(
        ir.fs.read.deny[2]
            .patterns
            .contains(&"/Users/me/.moat/policy.lock".to_owned())
    );
    assert_eq!(ids(&ir.fs.read.allow), ["project-fs", "agent-temp"]);
    let secrets = &ir.fs.read.deny[0].patterns;
    assert!(secrets.contains(&"/Users/me/.ssh/**".to_owned()));
    assert!(
        secrets.contains(&"!**/.env.example".to_owned()),
        "exclusions kept"
    );
    assert_eq!(
        ir.fs.write.allow[0].patterns[..4],
        ["/p/**", "!/p/.git/**", "!/p/**/.git/**", "!/p/.moat/**"]
    );
    assert!(
        (ir.fs.write.allow[0].patterns.iter()).any(|p| p == "!/p/**/.github/workflows/**"),
        "what `runs-later` holds for review is left out"
    );
    assert_eq!(
        ids(&ir.fs.write.deny),
        [
            "secrets-paths",
            "agent-credentials",
            "destructive",
            "kernel-self",
            "shell-rc"
        ]
    );
    // the home directory and the root themselves, not their subtrees, and raw disks
    assert_eq!(
        ir.fs.write.deny[2].patterns[..3],
        ["/Users/me", "/", "/dev/disk*"]
    );
    assert_eq!(ir.egress.net.default, Effect::Deny);
    assert_eq!(
        ids(&ir.egress.net.deny),
        ["cloud-metadata", CLOUD_METADATA_RULE]
    );
    assert_eq!(ids(&ir.egress.net.allow), ["registries"]);
    assert_eq!(
        ir.egress.fetch.default,
        Effect::Deny,
        "fetch: review lowers to deny"
    );
    assert!(ir.secrets.is_empty() && ir.limits.is_empty());
    let kinds: Vec<&str> = ir.decide_only.iter().map(|d| d.kind.as_str()).collect();
    // `fs.read` and `fs.write`: the `hook_only` group `build-credentials`
    assert_eq!(
        kinds,
        ["shell", "env.read", "env.set", "mcp", "fs.read", "fs.write"]
    );
}

#[test]
fn every_deferred_kind_is_reported_as_a_loss() {
    let ir = lowered(crate::DEFAULT_POLICY);
    let losses: Vec<String> = ir.losses.iter().map(ToString::to_string).collect();
    let agent = "the hook leaves it to the agent";
    for expected in [
        format!("fs.read `default`: no rule matches: {agent}, OS layers deny"),
        format!("fs.write `default`: no rule matches: {agent}, OS layers deny"),
        format!("fetch `default.fetch`: no rule matches: {agent}, OS layers deny"),
        format!("net `local-net`: {agent}; OS layers deny unless an allow rule matches"),
        format!("fetch `local-net`: {agent}; OS layers deny unless an allow rule matches"),
        "fs.read `home-sweep`: the hook holds it for review; OS layers deny unless an allow rule matches".into(),
        "fs.write `git-internals`: the hook holds it for review; OS layers deny unless an allow rule matches"
            .into(),
        "fs.write `persistence`: the hook holds it for review; OS layers deny unless an allow rule matches".into(),
        "fs.write `runs-later`: the hook holds it for review; OS layers deny unless an allow rule matches".into(),
    ] {
        assert!(losses.contains(&expected), "{losses:#?}");
    }
    assert_eq!(losses.len(), 9, "{losses:#?}");
}

#[test]
fn review_under_an_allow_default_becomes_a_deny_rule() {
    let ir = lowered(
        "version: 1\ndefaults: allow\nallow:\n  - id: a\n    fs.read: ['/x/**']\n\
         review:\n  - id: q\n    fs.read: ['/x/secret']\n",
    );
    assert_eq!(ir.fs.read.default, Effect::Allow);
    assert_eq!(ids(&ir.fs.read.deny), ["q"]);
    let check = ir.checker().unwrap();
    assert_eq!(check.check(&read("/x/secret")), Some(Effect::Deny));
    assert_eq!(check.check(&read("/x/other")), Some(Effect::Allow));
    assert_eq!(ir.losses[0].rule, "q");
}

#[test]
fn net_rules_govern_fetch_with_their_own_exclusions() {
    let ir = lowered(
        "version: 1\ndefaults: deny\nallow:\n  - id: a\n    fetch: ['*.org', '!b.org']\n    net: ['b.org']\n",
    );
    assert_eq!(ir.egress.fetch.allow.len(), 2);
    let check = ir.checker().unwrap();
    let fetch = |host: &str| AtomicAction::Fetch { host: host.into() };
    assert_eq!(check.check(&fetch("B.org")), Some(Effect::Allow));
    assert_eq!(check.check(&fetch("a.org")), Some(Effect::Allow));
    let net = AtomicAction::Net {
        host: "a.org".into(),
    };
    assert_eq!(check.check(&net), Some(Effect::Deny));
}

#[test]
fn cloud_metadata_is_denied_even_when_allowed() {
    let ir = lowered("version: 1\ndefaults: allow\n");
    let check = ir.checker().unwrap();
    for host in ["169.254.169.254", "metadata.google.internal"] {
        for atom in [
            AtomicAction::Net { host: host.into() },
            AtomicAction::Fetch { host: host.into() },
        ] {
            assert_eq!(check.check(&atom), Some(Effect::Deny), "{atom:?}");
        }
    }
}

#[test]
fn builtin_metadata_hosts_match_the_default_policy() {
    let policy = Policy::parse(crate::DEFAULT_POLICY).unwrap();
    let group = policy.deny.iter().find(|g| g.id == "cloud-metadata");
    assert_eq!(
        group.map(|g| g.net.as_slice()),
        Some(&CLOUD_METADATA.map(String::from)[..])
    );
}

#[test]
fn project_rules_need_a_project_and_cover_every_spelling() {
    let yaml =
        "version: 1\nallow:\n  - id: p\n    fs.read: ['${project}/**', '!${project}/.git/**']\n";
    let policy = Policy::parse(yaml).unwrap();
    let none = lower(
        &policy,
        &EvalContext {
            project: None,
            ..ctx()
        },
    )
    .unwrap();
    assert_eq!(none.fs.read.allow, Vec::<Rule>::new());
    let linked = lower(
        &policy,
        &EvalContext {
            real_project: Some("/private/p".into()),
            ..ctx()
        },
    )
    .unwrap();
    assert_eq!(
        linked.fs.read.allow[0].patterns,
        [
            "/p/**",
            "/private/p/**",
            "!/p/.git/**",
            "!/private/p/.git/**"
        ]
    );
}

#[test]
fn decide_only_lists_rules_and_executables() {
    let ir = lowered(
        "version: 1\ndeny:\n  - id: s\n    shell: ['sudo *']\n    fs.read: ['/k']\n\
         executables:\n  git: ['/usr/bin/git']\n",
    );
    assert_eq!(
        ir.decide_only,
        [
            DecideOnly {
                kind: "shell".into(),
                rules: vec!["s".into()]
            },
            DecideOnly {
                kind: "executables".into(),
                rules: vec!["git".into()]
            },
        ]
    );
    assert_eq!(ir.checker().unwrap().check(&read("/k")), Some(Effect::Deny));
    let shell = AtomicAction::Shell {
        argv: vec!["sudo".into()],
    };
    assert_eq!(ir.checker().unwrap().check(&shell), None);
}

#[test]
fn hook_only_deny_groups_are_left_to_the_hook() {
    let ir = lowered(
        "version: 1\ndefaults: allow\ndeny:\n  - id: s\n    fs.read: ['/s/**']\n\
         \x20 - id: b\n    hook_only: true\n    fs.read: ['/h/.m2/settings.xml']\n\
         \x20   fs.write: ['/h/.m2/settings.xml']\n",
    );
    assert_eq!(ids(&ir.fs.read.deny), ["s"]);
    assert_eq!(ir.fs.write.deny, Vec::<Rule>::new());
    let check = ir.checker().unwrap();
    assert_eq!(
        check.check_os(&read("/h/.m2/settings.xml")),
        Some(Effect::Allow)
    );
    assert_eq!(check.check_os(&read("/s/key")), Some(Effect::Deny));
    let kinds: Vec<(&str, &[String])> = ir
        .decide_only
        .iter()
        .map(|d| (d.kind.as_str(), d.rules.as_slice()))
        .collect();
    let b = ["b".to_owned()];
    assert_eq!(kinds, [("fs.read", &b[..]), ("fs.write", &b[..])]);
    // The hook still denies them.
    let policy =
        Policy::parse("version: 1\ndeny:\n  - id: b\n    hook_only: true\n    fs.read: ['/h/x']\n")
            .unwrap();
    let engine = crate::CompiledPolicy::compile(&policy, &ctx()).unwrap();
    let decision = engine.evaluate_atomic(&read("/h/x")).unwrap();
    assert_eq!(decision.verdict, crate::Verdict::Deny);
}

#[test]
fn the_default_policy_leaves_build_credentials_out_of_os_layers() {
    let ir = lowered(crate::DEFAULT_POLICY);
    let json = serde_json::to_string(&ir.fs).unwrap();
    // `mvn` and `gradle` run inside the sandboxes read their settings.
    for file in [
        ".m2/settings.xml",
        ".m2/settings-security.xml",
        "gradle.properties",
    ] {
        assert!(!json.contains(file), "{file} reaches OS layers: {json}");
    }
    let hook_only = |rule: &str| {
        ir.decide_only
            .iter()
            .any(|d| d.kind == "fs.read" && d.rules.iter().any(|r| r == rule))
    };
    assert!(hook_only("build-credentials"));
    assert!(!hook_only("agent-credentials"));
}

/// ADR-054: every agent's login is an OS-layer deny, each file of a brace
/// group a pattern of its own, so a command an agent runs cannot read another
/// agent's token through any backend.
#[test]
fn the_default_policy_denies_agent_logins_in_os_layers() {
    let ir = lowered(crate::DEFAULT_POLICY);
    let check = ir.checker().unwrap();
    for file in [
        "/h/.claude/.credentials.json",
        "/h/.config/anthropic/default.json",
        "/h/.codex/auth.json",
        "/h/.codex/.credentials.json",
        "/h/.local/share/opencode/auth.json",
        "/h/.hermes/auth.json",
        "/h/.gemini/oauth_creds.json",
        "/h/.pi/agent/auth.json",
        "/h/.config/goose/secrets.yaml",
    ] {
        assert_eq!(check.check_os(&read(file)), Some(Effect::Deny), "{file}");
        let write = AtomicAction::FsWrite { path: file.into() };
        assert_eq!(check.check_os(&write), Some(Effect::Deny), "{file}");
    }
    let rule = ir
        .fs
        .read
        .deny
        .iter()
        .find(|r| r.id == "agent-credentials")
        .unwrap();
    assert!(rule.patterns.iter().all(|p| !p.contains('{')), "{rule:?}");
    assert!(
        rule.patterns
            .contains(&"/h/.codex/.credentials.json".to_owned()),
        "{rule:?}"
    );
}

#[test]
fn brace_groups_in_file_patterns_become_one_pattern_each() {
    let ir = lowered(
        "version: 1\ndefaults: allow\ndeny:\n  - id: k\n    fs.read: ['/h/{a,b/**}', '!/h/b/{ok,fine}']\n\
         \x20   net: ['{x,y}.example']\n",
    );
    assert_eq!(
        ir.fs.read.deny[0].patterns,
        ["/h/a", "/h/b/**", "!/h/b/ok", "!/h/b/fine"]
    );
    let check = ir.checker().unwrap();
    assert_eq!(check.check(&read("/h/b/c")), Some(Effect::Deny));
    assert_eq!(check.check(&read("/h/b/ok")), Some(Effect::Allow));
    // Host patterns stay as written: no backend lists a host path by path.
    let net = ir.egress.net.deny.iter().find(|r| r.id == "k").unwrap();
    assert_eq!(net.patterns, ["{x,y}.example"]);
}

#[test]
fn lowering_is_deterministic_and_serialises_kinds_by_name() {
    let a = lowered(crate::DEFAULT_POLICY);
    assert_eq!(a, lowered(crate::DEFAULT_POLICY));
    let json = serde_json::to_string(&a).unwrap();
    assert!(json.contains(r#""list":"fs.read""#), "{json}");
    assert!(json.contains(r#""default":"deny""#), "{json}");
    assert!(json.contains(r#""secrets":[]"#), "{json}");
}

#[test]
fn read_roots_are_an_allowance_that_deny_rules_still_beat() {
    let ir = lower(
        &Policy::parse(crate::DEFAULT_POLICY).unwrap(),
        &EvalContext {
            home: "/Users/me".into(),
            ..ctx()
        },
    )
    .unwrap();
    assert_eq!(ir.allowances.len(), 1);
    let roots = &ir.allowances[0];
    assert_eq!(
        (roots.kind, roots.rule.as_str()),
        (Kind::FsRead, READ_ROOTS_RULE)
    );
    for expected in ["/usr", "/usr/**", "/Users/me/.cargo", "/Users/me/.cargo/**"] {
        assert!(roots.patterns.contains(&expected.to_owned()), "{expected}");
    }
    assert!(
        !ids(&ir.fs.read.allow).contains(&READ_ROOTS_RULE),
        "the IR's own read verdicts stay the hook's"
    );
    let check = ir.checker().unwrap();
    let os = |path: &str| check.check_os(&read(path));
    let cargo = read("/Users/me/.cargo/registry/x");
    assert_eq!(check.check(&cargo), Some(Effect::Deny));
    assert_eq!(check.check_os(&cargo), Some(Effect::Allow));
    assert_eq!(os("/usr/bin/git"), Some(Effect::Allow));
    assert_eq!(os("/Users/me/.cargo/credentials.toml"), Some(Effect::Deny));
    assert_eq!(os("/Users/me/.cargo/registry/.env"), Some(Effect::Deny));
    assert_eq!(os("/Users/me/Documents/x"), Some(Effect::Deny));
    assert_eq!(os("/p/src/main.rs"), Some(Effect::Allow), "the project");
    let write = AtomicAction::FsWrite {
        path: "/usr/local/bin/x".into(),
    };
    assert_eq!(
        check.check_os(&write),
        Some(Effect::Deny),
        "writes stay out"
    );
}

#[test]
fn a_policy_without_read_roots_has_no_allowance() {
    assert_eq!(
        lowered("version: 1\nsandbox: {}\n").allowances,
        Vec::<Allowance>::new()
    );
    assert_eq!(lowered("version: 1\n").allowances, Vec::<Allowance>::new());
}

/// #167: the policy's `secrets:` list lowers into `ir.secrets` field-for-field,
/// so OS backends (Claude Code's broker, `moat proxy`) read one source of truth.
#[test]
fn policy_secrets_lower_into_ir_secrets() {
    let ir = lowered(
        "version: 1\n\
         allow:\n  - id: a\n    net: ['api.github.com', 'registry.npmjs.org']\n\
         secrets:\n  \
         - id: gh\n    host: api.github.com\n    header: Authorization\n    source: { env: GITHUB_TOKEN }\n  \
         - id: npm\n    host: registry.npmjs.org\n    header: Authorization\n    source: { file: ~/.config/moat/npm }\n    plain_http: true\n",
    );
    assert_eq!(ir.secrets.len(), 2);
    assert_eq!(ir.secrets[0].id, "gh");
    assert_eq!(ir.secrets[0].host, "api.github.com");
    assert_eq!(ir.secrets[0].header, "Authorization");
    assert!(matches!(
        &ir.secrets[0].source,
        crate::SecretSource::Env(name) if name == "GITHUB_TOKEN"
    ));
    assert!(!ir.secrets[0].plain_http);
    assert_eq!(ir.secrets[1].id, "npm");
    assert!(matches!(
        &ir.secrets[1].source,
        crate::SecretSource::File(path) if path == "~/.config/moat/npm"
    ));
    assert!(ir.secrets[1].plain_http);
    assert!(
        lowered("version: 1\n").secrets.is_empty(),
        "no `secrets:` key means no entries"
    );
}