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
//! What a change touches that the policy protects (ADR-050).
//!
//! Every path a change writes (added, edited, deleted, renamed from or to) is
//! decided by the core engine as an `fs.write` inside a project, with session
//! taint set as after reading untrusted content: a pull request is content
//! nobody on this machine wrote. So the default policy's `deny` rules
//! (`kernel-self`, `secrets-paths`) give `deny`, and its `review` rules and the
//! files session taint protects (CI, hooks, build and package files, agent
//! settings) give `review`. No path list lives here.
//!
//! On top of the engine, what only a diff shows: a path that leaves the
//! repository, a symbolic link and where it points, a submodule, a change to
//! the policy files the check itself read, and added lines holding a known
//! token shape (`openmoat_audit::token_shape`, the push check's scanner).
//!
//! And what the added lines do (ADR-055, `content.rs`): the core's content
//! checks, at the levels the policy's `check_diff.levels` sets.

use anyhow::Result;
use openmoat_core::diffscan::Settings;
use openmoat_core::rule_id::{
    DIFF_LINK, DIFF_PATH, DIFF_POLICY, DIFF_SECRET, DIFF_SUBMODULE, DIFF_UNCHECKED, DIFF_WIDENS,
    SESSION_TAINT,
};
use openmoat_core::{
    Action, CompiledPolicy, Decision, EvalContext, NoResolver, Policy, Taint, Verdict,
};
use serde::Serialize;

use super::parse::FileChange;

mod content;

/// Where the repository is placed for the engine. Not a real directory: no
/// file is read, and it is outside any home so no `~/` rule meets it.
const ROOT: &str = "/openmoat-diff/repo";
const HOME: &str = "/openmoat-diff/home";

/// What the untrusted content of every change is, in the engine's taint.
const UNTRUSTED: &str = "the change under review";

/// git's modes for a symbolic link and a submodule.
const LINK_MODE: &str = "120000";
const SUBMODULE_MODE: &str = "160000";

/// How much a finding holds up a merge.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Level {
    /// A person should look before it is merged: the policy holds it for review.
    Review,
    /// The policy denies it.
    Deny,
}

impl Level {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Review => "review",
            Self::Deny => "deny",
        }
    }

    fn of(verdict: Verdict) -> Option<Self> {
        match verdict {
            Verdict::Deny => Some(Self::Deny),
            Verdict::Review => Some(Self::Review),
            _ => None,
        }
    }
}

/// One thing a change does that the policy protects.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Finding {
    pub level: Level,
    /// The path in the repository, `/`-separated, as the diff names it.
    pub path: String,
    /// The line in the new file, for an added line.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<usize>,
    pub rules: Vec<String>,
    pub reasons: Vec<String>,
}

impl Finding {
    fn new(level: Level, path: &str, rule: &str, reason: String) -> Self {
        Self {
            level,
            path: path.to_owned(),
            line: None,
            rules: vec![rule.to_owned()],
            reasons: vec![reason],
        }
    }

    /// Add `other`, about the same path: the stricter level, every rule and reason.
    fn absorb(&mut self, other: Self) {
        self.level = self.level.max(other.level);
        for rule in other.rules {
            if !self.rules.contains(&rule) {
                self.rules.push(rule);
            }
        }
        for reason in other.reasons {
            if !self.reasons.contains(&reason) {
                self.reasons.push(reason);
            }
        }
    }
}

/// Where a path of the diff lands.
#[derive(Debug, PartialEq, Eq)]
enum Placed {
    /// Inside the repository, `/`-separated with `.` and `..` collapsed.
    Inside(String),
    /// Absolute, or above the repository root.
    Outside,
}

/// `raw` taken from the directory `dir` of the repository (`""` for the
/// root). `\` counts as a separator too, as on Windows.
fn place(raw: &str, dir: &str) -> Placed {
    let unified = raw.replace('\\', "/");
    let drive = unified.as_bytes().get(1) == Some(&b':');
    if unified.starts_with('/') || drive {
        return Placed::Outside;
    }
    let mut segments: Vec<&str> = dir.split('/').filter(|s| !s.is_empty()).collect();
    for segment in unified.split('/') {
        match segment {
            "" | "." => {}
            ".." => {
                if segments.pop().is_none() {
                    return Placed::Outside;
                }
            }
            name => segments.push(name),
        }
    }
    Placed::Inside(segments.join("/"))
}

/// `path` as Windows opens it: each name without trailing dots and spaces,
/// which NTFS drops (`.github./workflows` is `.github/workflows`).
fn windows_spelling(path: &str) -> String {
    path.split('/')
        .map(|s| s.trim_end_matches(['.', ' ']))
        .map(|s| if s.is_empty() { "_" } else { s })
        .collect::<Vec<_>>()
        .join("/")
}

/// The policy compiled for checking changes, and the repository paths of the
/// policy files the check read, whose change it reports.
pub struct Gate<'p> {
    policy: CompiledPolicy<'p>,
    policy_files: Vec<String>,
    /// The policy's `check_diff:` section.
    settings: Option<&'p Settings>,
}

impl<'p> Gate<'p> {
    /// File paths compare without letter case: a change merged here may be
    /// checked out on macOS or Windows, where `.Claude/Settings.json` is
    /// `.claude/settings.json`.
    pub fn new(policy: &'p Policy, policy_files: &[String]) -> Result<Self> {
        let ctx = EvalContext {
            home: HOME.to_owned(),
            project: Some(ROOT.to_owned()),
            real_home: None,
            real_project: None,
            moved_dirs: Vec::new(),
            cwd: ROOT.to_owned(),
            case_insensitive_paths: true,
        };
        let policy_files = policy_files
            .iter()
            .filter_map(|p| match place(p, "") {
                Placed::Inside(p) => Some(p.to_lowercase()),
                Placed::Outside => None,
            })
            .collect();
        Ok(Self {
            policy: CompiledPolicy::compile(policy, &ctx)?,
            policy_files,
            settings: policy.check_diff.as_ref(),
        })
    }

    /// Every finding of `files`, one per path and one per added line a check
    /// finds something on, in the order of the diff; new hosts last.
    pub fn check(&self, files: &[FileChange]) -> Vec<Finding> {
        let mut findings: Vec<Finding> = Vec::new();
        let mut add = |finding: Finding| match findings
            .iter_mut()
            .find(|f| f.path == finding.path && f.line == finding.line)
        {
            Some(found) => found.absorb(finding),
            None => findings.push(finding),
        };
        for file in files {
            for path in file.paths() {
                self.path_findings(path).into_iter().for_each(&mut add);
            }
            self.mode_findings(file).into_iter().for_each(&mut add);
            secret_findings(file).into_iter().for_each(&mut add);
            content::findings(self.settings, file)
                .into_iter()
                .for_each(&mut add);
        }
        content::host_findings(&self.policy, self.settings, files)
            .into_iter()
            .for_each(&mut add);
        findings
    }

    fn path_findings(&self, raw: &str) -> Vec<Finding> {
        let path = match place(raw, "") {
            Placed::Inside(path) if !path.is_empty() && !path.contains('\0') => path,
            _ => {
                return vec![Finding::new(
                    Level::Deny,
                    raw,
                    DIFF_PATH,
                    "the path leaves the repository or is not a file name git checks out"
                        .to_owned(),
                )];
            }
        };
        let mut findings = Vec::new();
        if let Some(finding) = self.decided(raw, &path, None) {
            findings.push(finding);
        }
        if self.policy_files.contains(&path.to_lowercase()) {
            findings.push(Finding::new(
                Level::Review,
                raw,
                DIFF_POLICY,
                "changes a policy file this check reads; checked from git, the check reads \
                 the base revision's copy, so the change applies only once it is merged"
                    .to_owned(),
            ));
        }
        findings
    }

    /// The engine's decision for writing `path` (and its Windows spelling), as
    /// a finding on `shown`; `via` names the link it is reached through.
    fn decided(&self, shown: &str, path: &str, via: Option<&str>) -> Option<Finding> {
        let mut decision = self.write(path);
        let windows = windows_spelling(path);
        if windows != path {
            let other = self.write(&windows);
            if other.verdict > decision.verdict {
                decision = other;
            }
        }
        let level = Level::of(decision.verdict)?;
        // Session taint's reason speaks of a session; for a change, say what it means.
        let tainted = decision.rules.iter().any(|r| r == SESSION_TAINT);
        let reasons = decision
            .reasons
            .iter()
            .map(|reason| {
                let reason = if tainted && reason.contains(UNTRUSTED) {
                    "CI, a build or test tool, a commit hook or an AI agent runs or reads this \
                     file later"
                        .to_owned()
                } else {
                    reason.replace(&format!("{ROOT}/"), "")
                };
                match via {
                    Some(target) => format!("through the link to {target}: {reason}"),
                    None => reason,
                }
            })
            .collect();
        Some(Finding {
            level,
            path: shown.to_owned(),
            line: None,
            rules: decision.rules,
            reasons,
        })
    }

    fn write(&self, path: &str) -> Decision {
        let action = Action::FsWrite {
            path: format!("{ROOT}/{path}"),
        };
        let taint = Taint {
            secrets: Vec::new(),
            untrusted: Some(UNTRUSTED.to_owned()),
            ..Taint::default()
        };
        let decision = self.policy.decide(&action);
        self.policy
            .with_taint(decision, &action, &NoResolver, &taint)
    }

    /// A symbolic link (and what it points to) or a submodule the change adds or changes.
    fn mode_findings(&self, file: &FileChange) -> Vec<Finding> {
        let mut findings = Vec::new();
        let Some(shown) = file.new.as_deref().or(file.old.as_deref()) else {
            return findings;
        };
        let modes = [file.old_mode.as_deref(), file.new_mode.as_deref()];
        if modes.contains(&Some(SUBMODULE_MODE)) {
            findings.push(Finding::new(
                Level::Review,
                shown,
                DIFF_SUBMODULE,
                "changes a submodule: the commit it points to is not in this diff, and its \
                 code was not checked"
                    .to_owned(),
            ));
        }
        let Some(new) = file.new.as_deref() else {
            return findings;
        };
        if file.new_mode.as_deref() != Some(LINK_MODE) {
            return findings;
        }
        let Some((_, target)) = file.added.first() else {
            findings.push(Finding::new(
                Level::Review,
                new,
                DIFF_LINK,
                "makes a symbolic link whose target the diff does not show".to_owned(),
            ));
            return findings;
        };
        let dir = new.rsplit_once('/').map_or("", |(dir, _)| dir);
        let reason = match place(target, dir) {
            Placed::Inside(inside) => {
                findings.extend(self.decided(new, &inside, Some(target)));
                format!(
                    "makes a symbolic link to {target}: what later reads or writes {new} \
                     reaches that file instead"
                )
            }
            Placed::Outside => format!(
                "makes a symbolic link to {target}, outside the repository: what later reads \
                 or writes {new} reaches a file of the machine it is checked out on"
            ),
        };
        findings.push(Finding::new(Level::Review, new, DIFF_LINK, reason));
        findings
    }
}

/// Each added line of `file` that holds a known token shape. The value is never named.
fn secret_findings(file: &FileChange) -> Vec<Finding> {
    let Some(path) = file.new.as_deref() else {
        return Vec::new();
    };
    file.added
        .iter()
        .filter_map(|(line, text)| {
            let shape = openmoat_audit::token_shape(text)?;
            Some(Finding {
                line: Some(*line),
                ..Finding::new(
                    Level::Deny,
                    path,
                    DIFF_SECRET,
                    format!(
                        "adds {shape}; the change already published it to whoever can read it, \
                         so revoke it and remove it from the commits"
                    ),
                )
            })
        })
        .collect()
}

/// The finding for a diff that was not read in full.
pub fn unchecked(why: String) -> Finding {
    Finding::new(Level::Review, "", DIFF_UNCHECKED, why)
}

/// Most widenings listed as findings of their own; the rest are counted.
const WIDENINGS_LISTED: usize = 20;

/// What a change to the policy files at `path` widens (ADR-111): a `deny`
/// finding per case that moves toward allow and per setting that widens, a
/// `review` one per setting changed in a way the check does not rank.
pub fn widenings(path: &str, report: &openmoat_core::widen::Report) -> Vec<Finding> {
    use openmoat_core::widen::Effect;
    let rules = |r: &[String]| {
        if r.is_empty() {
            String::new()
        } else {
            format!(" ({})", r.join(", "))
        }
    };
    let mut out: Vec<Finding> = report
        .widenings
        .iter()
        .take(WIDENINGS_LISTED)
        .map(|w| {
            let why = format!(
                "the changed policy widens {}: {}{} → {}{}",
                w.case,
                w.before.as_str(),
                rules(&w.before_rules),
                w.after.as_str(),
                rules(&w.after_rules)
            );
            Finding::new(Level::Deny, path, DIFF_WIDENS, why)
        })
        .collect();
    if let Some(more) = report
        .widenings
        .len()
        .checked_sub(WIDENINGS_LISTED)
        .filter(|n| *n > 0)
    {
        let why = format!(
            "the changed policy widens {more} more cases; `openmoat policy diff OLD NEW --widen` \
             lists them"
        );
        out.push(Finding::new(Level::Deny, path, DIFF_WIDENS, why));
    }
    for change in &report.settings {
        let level = match change.effect {
            Effect::Widens => Level::Deny,
            Effect::Unchecked => Level::Review,
            Effect::Narrows => continue,
        };
        let why = format!(
            "the changed policy changes {}: {}",
            change.setting, change.what
        );
        out.push(Finding::new(level, path, DIFF_WIDENS, why));
    }
    out
}

#[cfg(test)]
pub(super) fn placed_inside(raw: &str, dir: &str) -> Option<String> {
    match place(raw, dir) {
        Placed::Inside(p) => Some(p),
        Placed::Outside => None,
    }
}