openmoat 0.23.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
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
use std::time::{Duration, Instant};

use openmoat_audit::{EventId, NewEvent, SessionWrite, Store};
use openmoat_core::rule_id::SESSION_TAINT;
use openmoat_core::{
    Action, CompiledPolicy, Decision, EvalContext, Policy, Taint, TaintSecret, Verdict,
};
use openmoat_hosts::{Host, Replacement};

use super::{
    CacheWrite, Call, Pass, Progress, SessionTaint, after_read, answered, behind, catch_up, digest,
    fold, of_session, provenance,
};
use crate::home::Home;
use crate::realpath::FsPathResolver;

#[test]
fn a_grant_is_ordered_against_the_read_by_row_whatever_the_clock_says() {
    // The clock stepped back after the read: the grant looks older by
    // time, but it saw the read's row, so it answers.
    assert!(after_read(1_000, Some(7), 2_000, Some(5)));
    assert!(after_read(1_000, Some(5), 2_000, Some(5)));
    // The clock stepped back before the read: the grant looks newer by
    // time, but the read came after every row it saw, so it does not.
    assert!(!after_read(3_000, Some(4), 2_000, Some(5)));
}

#[test]
fn a_grant_without_a_row_is_ordered_by_time() {
    assert!(after_read(3_000, None, 2_000, Some(5)));
    assert!(!after_read(2_000, None, 2_000, Some(5)));
    assert!(!after_read(1_000, None, 2_000, Some(5)));
}

const POLICY: &str = "version: 1\ndefaults: { \"*\": allow }\nreview:\n  - { id: secrets-paths, \
                      fs.read: [\"~/.ssh/**\"] }\n";
const CWDS: [&str; 2] = ["/p/a", "/p/b"];

fn ctx(cwd: &str) -> EvalContext {
    EvalContext {
        home: "/home/u".to_owned(),
        project: None,
        real_home: None,
        real_project: None,
        moved_dirs: Vec::new(),
        cwd: cwd.to_owned(),
        case_insensitive_paths: false,
    }
}

fn record(store: &Store, cwd: &str, action: &Action) {
    record_in(store, Some(cwd), action);
}

/// Record a call that ran in `cwd`, or, with `None`, one recorded without a
/// working directory, as some hosts' calls and older builds' rows are.
fn record_in(store: &Store, cwd: Option<&str>, action: &Action) {
    let decision = Decision::new(Verdict::Allow);
    store
        .record(&NewEvent {
            host: Host::ClaudeCode.id(),
            session_id: "s1",
            call_id: None,
            cwd,
            tool: "tool",
            action: Some(action),
            decision: &decision,
            latency_us: 0,
        })
        .unwrap();
}

fn read(path: String) -> Action {
    Action::FsRead { path }
}

fn far() -> Instant {
    Instant::now() + Duration::from_hours(1)
}

/// One guard call's taint lookup in `cwd`, writing the cache as the guard
/// does: what it folded to, and how many events it classified.
fn call(store: &Store, cwd: &str, deadline: Instant) -> anyhow::Result<(SessionTaint, usize)> {
    let policy = Policy::parse(POLICY).unwrap();
    let compiled = CompiledPolicy::compile(&policy, &ctx(cwd)).unwrap();
    let mut save = |write: &CacheWrite| write.write(store);
    let mut progress = Progress {
        deadline,
        save: &mut save,
        folded: 0,
    };
    let (taint, write) = of_session(store, Host::ClaudeCode, "s1", &compiled, cwd, &mut progress)?;
    if let Some(write) = write {
        write.write(store);
    }
    Ok((taint, progress.folded))
}

/// The session folded from its first event in one go, with no cache: what
/// every call answered before the cache existed.
fn reference(store: &Store, cwd: &str) -> SessionTaint {
    let policy = Policy::parse(POLICY).unwrap();
    let compiled = CompiledPolicy::compile(&policy, &ctx(cwd)).unwrap();
    let events = store.session_after("s1", EventId(0)).unwrap();
    let mut out = SessionTaint::default();
    let taken = fold(
        &mut out,
        &events,
        Host::ClaudeCode,
        &compiled,
        cwd,
        &mut Pass::default(),
    )
    .unwrap();
    assert_eq!(taken, events.len());
    out
}

/// Calls that alternate between two directories each read on from their own
/// cache row: over many calls each event is classified about once per
/// directory, not once per call (before, every call folded the whole
/// session again).
#[test]
fn alternating_directories_fold_each_event_a_bounded_number_of_times() {
    const EVENTS: usize = 2_000;
    const CALLS: usize = 20;
    let store = Store::open_in_memory().unwrap();
    for i in 0..EVENTS {
        let cwd = CWDS[i % 2];
        record(&store, cwd, &read(format!("{cwd}/f{i}.rs")));
    }
    let mut total = 0;
    for n in 0..CALLS {
        let cwd = CWDS[n % 2];
        let (_, folded) = call(&store, cwd, far()).unwrap();
        total += folded;
        record(&store, cwd, &read(format!("{cwd}/x{n}.rs")));
    }
    // A full fold per directory, then only the calls recorded since.
    assert!(
        total <= CWDS.len() * (EVENTS + CALLS),
        "{total} events folded over {CALLS} calls"
    );
}

/// A directory change reads on from the row every directory shares, as long
/// as no call of the session was recorded without a directory: the first call
/// in the new directory folds only what came since, and answers what a full
/// fold there would.
#[test]
fn a_directory_change_reads_on_from_the_shared_row() {
    const EVENTS: usize = 2_000;
    let store = Store::open_in_memory().unwrap();
    for i in 0..EVENTS {
        record(&store, CWDS[0], &read(format!("/p/a/f{i}.rs")));
    }
    let (_, folded) = call(&store, CWDS[0], far()).unwrap();
    assert_eq!(folded, EVENTS);
    record(&store, CWDS[0], &read("/p/a/next.rs".to_owned()));
    let (taint, folded) = call(&store, CWDS[1], far()).unwrap();
    assert_eq!(folded, 1, "the call in the new directory read on");
    assert_eq!(taint, reference(&store, CWDS[1]));
    assert!(!taint.cwdless);
}

/// A call recorded without a directory is taken to have run where the call
/// being decided runs, so once the session has one, a directory reads on only
/// from its own row: the first call in another directory folds the session
/// from its first event, and the shared row is never moved on with it.
#[test]
fn a_call_without_a_directory_keeps_each_directory_to_its_own_row() {
    let store = Store::open_in_memory().unwrap();
    for i in 0..10 {
        record(&store, CWDS[0], &read(format!("/p/a/f{i}.rs")));
    }
    record_in(&store, None, &read("rel.rs".to_owned()));
    let (taint, folded) = call(&store, CWDS[0], far()).unwrap();
    assert_eq!(folded, 11);
    assert!(taint.cwdless);
    let (taint, folded) = call(&store, CWDS[1], far()).unwrap();
    assert_eq!(folded, 11, "another directory folds from the first event");
    assert_eq!(taint, reference(&store, CWDS[1]));
    record(&store, CWDS[1], &read("/p/b/next.rs".to_owned()));
    for cwd in CWDS {
        let (taint, folded) = call(&store, cwd, far()).unwrap();
        assert_eq!(folded, 1, "{cwd} read on from its own row");
        assert_eq!(taint, reference(&store, cwd));
    }
}

/// The cached fold answers what a fold of the whole session from its first
/// event answers, in every directory, at every call: over a session whose
/// calls ran in several directories, some recorded without one, read files by
/// a path relative to their directory (a secret only from one of them) and
/// fetched untrusted content, decided from directories in turn, with calls
/// stopped by their deadline and `PostToolUse` catch-ups between them.
#[test]
fn the_cached_fold_is_a_full_fold_in_every_directory() {
    const DIRS: [&str; 3] = ["/p/a", "/p/b", "/home/u/work"];
    let store = Store::open_in_memory().unwrap();
    let policy = Policy::parse(POLICY).unwrap();
    // a fixed pseudo-random sequence, so a failure replays
    let mut seed: u64 = 0x5eed;
    let mut next = |n: usize| {
        seed = seed
            .wrapping_mul(6_364_136_223_846_793_005)
            .wrapping_add(1_442_695_040_888_963_407);
        usize::try_from(seed >> 33).unwrap() % n
    };
    let mut differed = false;
    // Each step folds the whole session again as the reference, so the cost
    // grows with the square of the steps: 200 keep it to seconds on the
    // slowest CI runner while still crossing many cache rows and deadlines.
    for step in 0..200 {
        let recorded = match next(5) {
            4 => None,
            d => Some(DIRS[d % DIRS.len()]),
        };
        let action = match next(20) {
            0 => Action::Fetch {
                url: format!("https://example.com/{step}"),
            },
            1..=3 => read("../.ssh/id_rsa".to_owned()),
            4..=6 => read(format!("f{step}.rs")),
            _ => read(format!("/p/a/f{step}.rs")),
        };
        // Untrusted content late, so most of the session is folded clean.
        if step > 40 || !matches!(action, Action::Fetch { .. }) {
            record_in(&store, recorded, &action);
        }
        let cwd = DIRS[next(DIRS.len())];
        match next(6) {
            0 => assert!(call(&store, cwd, Instant::now()).is_err(), "step {step}"),
            1 => {
                let compiled = CompiledPolicy::compile(&policy, &ctx(cwd)).unwrap();
                catch_up(&store, Host::ClaudeCode, "s1", &compiled, cwd, far());
            }
            _ => {
                let (taint, _) = call(&store, cwd, far()).unwrap();
                assert_eq!(taint, reference(&store, cwd), "step {step} in {cwd}");
            }
        }
        // Whether the directory changed the answer at all: three more full
        // folds, so asked every 25 steps, not at each.
        if step % 25 == 24 {
            let folds: Vec<SessionTaint> = DIRS.iter().map(|d| reference(&store, d)).collect();
            differed |= folds.iter().any(|f| f.taint != folds[0].taint);
        }
    }
    assert!(differed, "no step's fold depended on the directory");
}

/// A session that read untrusted content in one directory is tainted for a
/// protected write in another, with or without the cache, at every call.
#[test]
fn verdicts_are_those_of_a_full_fold_in_every_directory() {
    let store = Store::open_in_memory().unwrap();
    let policy = Policy::parse(POLICY).unwrap();
    let write = Action::FsWrite {
        path: "/p/b/.github/workflows/ci.yml".to_owned(),
    };
    for n in 0..12 {
        let cwd = CWDS[n % 2];
        match n {
            3 => record(
                &store,
                CWDS[0],
                &Action::Fetch {
                    url: "https://example.com/page".to_owned(),
                },
            ),
            _ => record(&store, cwd, &read(format!("{cwd}/f{n}.rs"))),
        }
        for cwd in CWDS {
            let (taint, _) = call(&store, cwd, far()).unwrap();
            assert_eq!(taint, reference(&store, cwd), "call {n} in {cwd}");
            assert_eq!(taint.taint.untrusted.is_some(), n >= 3, "call {n} in {cwd}");
            let compiled = CompiledPolicy::compile(&policy, &ctx(CWDS[1])).unwrap();
            let decision = compiled.with_taint(
                Decision::new(Verdict::Allow),
                &write,
                &FsPathResolver,
                &taint.taint,
            );
            let expected = if n >= 3 {
                Verdict::Review
            } else {
                Verdict::Allow
            };
            assert_eq!(decision.verdict, expected, "call {n} in {cwd}");
        }
    }
}

/// A fold that runs out of time is never an answer: the call fails (the
/// guard denies) whether or not a cache row exists, and the row stays as it
/// was. A fold saved part way, as a stopped fold saves it, reads on to the
/// full fold's verdict, untrusted read included.
#[test]
fn an_interrupted_fold_never_answers_cleaner() {
    let store = Store::open_in_memory().unwrap();
    for n in 0..10 {
        record(&store, CWDS[0], &read(format!("/p/a/f{n}.rs")));
    }
    let past = Instant::now();
    assert!(call(&store, CWDS[0], past).is_err());
    let (clean, _) = call(&store, CWDS[0], far()).unwrap();
    assert_eq!(clean.taint.untrusted, None);
    record(
        &store,
        CWDS[0],
        &Action::Fetch {
            url: "https://example.com/page".to_owned(),
        },
    );
    // The clean row is there, but a stopped fold does not answer from it.
    assert!(call(&store, CWDS[0], past).is_err());
    let (tainted, folded) = call(&store, CWDS[0], far()).unwrap();
    assert_eq!(folded, 1, "read on from the clean row");
    assert!(tainted.taint.untrusted.is_some());
    assert_eq!(tainted, reference(&store, CWDS[0]));

    // A row saved part way through a fold, read on from another directory
    // (the same session in a log where no call was decided yet).
    let store = Store::open_in_memory().unwrap();
    for n in 0..10 {
        record(&store, CWDS[0], &read(format!("/p/a/f{n}.rs")));
    }
    record(
        &store,
        CWDS[0],
        &Action::Fetch {
            url: "https://example.com/page".to_owned(),
        },
    );
    let policy = Policy::parse(POLICY).unwrap();
    let compiled = CompiledPolicy::compile(&policy, &ctx(CWDS[0])).unwrap();
    let events = store.session_after("s1", EventId(0)).unwrap();
    let (head, _) = events.split_at(5);
    let mut partial = SessionTaint::default();
    fold(
        &mut partial,
        head,
        Host::ClaudeCode,
        &compiled,
        CWDS[0],
        &mut Pass::default(),
    )
    .unwrap();
    assert_eq!(partial.taint.untrusted, None);
    CacheWrite {
        session: "s1".to_owned(),
        host: Host::ClaudeCode,
        cached: openmoat_audit::Cached {
            digest: digest(Host::ClaudeCode, &compiled).unwrap(),
            upto: head[4].id,
            state: serde_json::to_string(&partial).unwrap(),
        },
    }
    .write(&store);
    let (resumed, folded) = call(&store, CWDS[1], far()).unwrap();
    assert_eq!(folded, events.len() - 5);
    assert_eq!(resumed, reference(&store, CWDS[1]));
    assert!(resumed.taint.untrusted.is_some());
}

/// A real project directory (the covering check reads the file), an audit log
/// and an empty state directory for `answered` (ADR-048).
struct Covering {
    _dir: tempfile::TempDir,
    proj: String,
    store: Store,
    home: Home,
    compiled: CompiledPolicy<'static>,
}

const UNTRUSTED: &str = "fetch evil.example";

impl Covering {
    fn new() -> Self {
        let dir = tempfile::tempdir().unwrap();
        let proj = crate::context::path_string(&dir.path().canonicalize().unwrap());
        let home = Home::at(dir.path().join("state"));
        let policy: &'static Policy = Box::leak(Box::new(Policy::parse(POLICY).unwrap()));
        let compiled = CompiledPolicy::compile(policy, &ctx(&proj)).unwrap();
        Self {
            _dir: dir,
            proj,
            store: Store::open_in_memory().unwrap(),
            home,
            compiled,
        }
    }

    fn write_of(&self, file: &str) -> Action {
        Action::FsWrite {
            path: format!("{}/{file}", self.proj),
        }
    }

    /// Record a call of `session` as the guard does, with `verdict`.
    fn record(&self, session: &str, action: &Action, verdict: Verdict) -> EventId {
        let decision = Decision::new(verdict);
        self.store
            .record(&NewEvent {
                host: Host::ClaudeCode.id(),
                session_id: session,
                call_id: None,
                cwd: Some(&self.proj),
                tool: "Write",
                action: Some(action),
                decision: &decision,
                latency_us: 0,
            })
            .unwrap()
    }

    /// Record a `Write` of `content` by `session` that was held for review and
    /// may have run,
    /// with the file as it was (`before`), as `guard` records one.
    fn held_write(&self, session: &str, action: &Action, content: &str, before: &str) -> EventId {
        let event = self.record(session, action, Verdict::Review);
        let writes: Vec<SessionWrite> = provenance::Files::of(&self.compiled, action)
            .writes
            .iter()
            .map(|path| SessionWrite {
                path: provenance::key(path, false),
                sha256: Some(provenance::content_hash(content.as_bytes())),
                before: Some(if before.is_empty() {
                    String::new()
                } else {
                    provenance::content_hash(before.as_bytes())
                }),
            })
            .collect();
        self.store
            .add_session_writes(event, Host::ClaudeCode.id(), session, &writes)
            .unwrap();
        event
    }

    /// Record an `Edit` (or `MultiEdit`) of the file by `session` that was held for review and
    /// may have run, with the content it leaves worked out from the file as it
    /// is, as `guard` records one through `provenance::observe`.
    fn held_edit(&self, session: &str, action: &Action, edits: &[(&str, &str, bool)]) -> EventId {
        let event = self.record(session, action, Verdict::Review);
        let edits: Vec<Replacement> = edits
            .iter()
            .map(|(old, new, all)| Replacement {
                old: (*old).to_owned(),
                new: (*new).to_owned(),
                all: *all,
            })
            .collect();
        let seen = provenance::observe(
            &self.store,
            &self.compiled,
            &provenance::Call {
                session,
                action,
                content: None,
                edits: &edits,
                untrusted: Some(UNTRUSTED),
            },
        )
        .unwrap();
        seen.write(&self.store, event, Host::ClaudeCode.id(), session)
            .unwrap();
        event
    }

    /// The session's taint after an untrusted read recorded in `read_row`.
    fn tainted_since(read_row: EventId) -> SessionTaint {
        SessionTaint {
            taint: Taint {
                secrets: Vec::new(),
                untrusted: Some(UNTRUSTED.to_owned()),
            },
            untrusted_last_ms: Some(1_000),
            untrusted_last_row: Some(read_row.0),
            ..SessionTaint::default()
        }
    }

    /// `action` in `session`, decided as the guard decides it: allowed by the
    /// policy, tightened by `taint`, then answered.
    fn decide(&self, session: &str, action: &Action, taint: &SessionTaint) -> Decision {
        let untainted = Decision::new(Verdict::Allow);
        let tainted =
            self.compiled
                .with_taint(untainted.clone(), action, &FsPathResolver, &taint.taint);
        assert_eq!(tainted.verdict, Verdict::Review, "{tainted:?}");
        assert!(
            tainted.rules.iter().any(|r| r == SESSION_TAINT),
            "{tainted:?}"
        );
        let call = Call {
            home: &self.home,
            store: &self.store,
            host: Host::ClaudeCode,
            session,
            action,
            cwd: &self.proj,
            user_home: "/home/u",
        };
        answered(&call, &self.compiled, taint, untainted, tainted, 2_000).unwrap()
    }

    fn put(&self, file: &str, content: &str) {
        let path = std::path::Path::new(&self.proj).join(file);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, content).unwrap();
    }
}

const WORKFLOW: &str = ".github/workflows/ci.yml";

/// A long session whose cache is far behind: a call's own fold may run out of
/// time and is denied (fail closed), with a message that says the next call
/// reads on. Once a `PostToolUse` caught the session up, the next call is
/// decided, folding only what came after, well within its budget, and it
/// answers what a full fold would.
#[test]
fn a_long_backlog_caught_up_after_a_call_lets_the_next_call_be_decided() {
    const EVENTS: usize = 3_000;
    let store = Store::open_in_memory().unwrap();
    for i in 0..EVENTS {
        record(&store, CWDS[0], &read(format!("/p/a/f{i}.rs")));
    }
    record(
        &store,
        CWDS[0],
        &Action::Fetch {
            url: "https://example.com/page".to_owned(),
        },
    );
    let stopped = call(&store, CWDS[0], Instant::now())
        .unwrap_err()
        .to_string();
    assert!(stopped.contains("run it again"), "{stopped}");
    assert!(stopped.contains("not judged"), "{stopped}");

    let policy = Policy::parse(POLICY).unwrap();
    let compiled = CompiledPolicy::compile(&policy, &ctx(CWDS[0])).unwrap();
    catch_up(&store, Host::ClaudeCode, "s1", &compiled, CWDS[0], far());
    record(&store, CWDS[0], &read("/p/a/next.rs".to_owned()));
    let started = Instant::now();
    let (taint, folded) = call(&store, CWDS[0], started + Duration::from_secs(5)).unwrap();
    assert!(folded <= 2, "the next call folded {folded} events");
    assert_eq!(taint, reference(&store, CWDS[0]));
    assert!(
        taint.taint.untrusted.is_some(),
        "the fetch before the catch-up counts"
    );
}

#[test]
fn the_behind_message_says_the_call_was_not_judged_and_to_run_it_again() {
    let message = behind(512);
    assert!(message.contains("512 more"), "{message}");
    assert!(message.contains("the next call reads on"), "{message}");
}

mod approved_writes;
mod long_session;