openmoat 0.12.0

Policy checks for AI coding agents: decides allow, defer, ask or deny for every tool call from Claude Code, Codex, Cursor, OpenClaw, GitHub Copilot CLI, pi and Gemini CLI, 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
//! Human approvals that outlive one prompt.
//!
//! Two files under `~/.moat`, both pinned by the policy lock so an agent cannot
//! grant itself anything:
//! - `approvals.json`: session grants, an exact command or exact files for one host
//!   session, valid for [`GRANT_TTL_MS`] after they are written; a command only in
//!   the project it was approved in;
//! - `policy.d/approved.yaml`: permanent allow rules appended by `moat allow --always`,
//!   `--site` and `--dir`, merged into the user policy at load time so `policy.yaml` is never rewritten.

use std::fs;
use std::path::Path;

use anyhow::{Context as _, Result, bail};
use openmoat_core::{Action, RuleGroup};
use serde::{Deserialize, Serialize};

use crate::home::{Home, write_private};
use crate::time;

mod asked;
pub use asked::{approvable, describe, files};

/// Version 2 grants an [`Action`]; version 1 granted only a `command` string.
const GRANTS_VERSION: u32 = 2;
const OVERLAY_VERSION: u32 = 1;
pub const OVERLAY_PREFIX: &str = "approved-";
/// How long a session grant stays valid. Hosts do not tell OpenMoat when a session
/// ends, so a fixed lifetime is what bounds a grant.
pub const GRANT_TTL_MS: i64 = 24 * 60 * 60 * 1000;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Grant {
    pub host: String,
    pub session_id: String,
    /// What is approved, as [`approvable`] spells it.
    pub action: Action,
    /// Milliseconds since the epoch. A grant written without one reads as 0,
    /// long expired: a grant whose age is unknown must not stay valid forever.
    #[serde(default)]
    pub granted_at_ms: i64,
    /// The id of the newest audit event when the grant was written (0 for an
    /// empty log): it saw every event up to this one. Ids only grow, so this
    /// orders the grant against later calls even if the clock steps back. A
    /// grant written by an older build has none and is ordered by time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub audit_row: Option<i64>,
    /// Also answers every other session-taint ask of this host session that
    /// comes from untrusted content, until the session reads untrusted content
    /// again (`moat allow --last`, answer `s`). Never a secret taint. A build
    /// that does not know the field reads it as a grant for `action` alone.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub covers_taint: bool,
    /// The project the grant was approved in ([`project_of`]): a shell grant,
    /// and one that [`covers_taint`](Self::covers_taint), applies only to calls
    /// in it, since the same command means something else in another
    /// repository. A file grant names absolute paths and needs none. `None` for
    /// a grant an earlier release wrote: such a shell or taint grant applies
    /// nowhere ([`Grant::unbound`]) until a person approves it again.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    /// Where its files resolved when approved (empty: each was itself); it holds
    /// only while they still do, so a file swapped for a symlink is asked again.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub real: Vec<String>,
}

/// The project a call in `cwd` belongs to, as grants record it: the
/// repository root, else `cwd` itself ([`crate::project::root_of`]), with its
/// symlinks resolved when it exists so either spelling of it is the same
/// project. `home` is the person's home directory.
#[must_use]
pub fn project_of(cwd: &Path, home: &Path) -> String {
    let root = crate::project::root_of(cwd, home).unwrap_or_else(|| cwd.to_path_buf());
    let real = fs::canonicalize(&root).unwrap_or(root);
    crate::context::path_string(&real)
}

/// [`project_of`] the working directory of a call evaluated in `ctx`.
#[must_use]
pub fn project_in(ctx: &openmoat_core::EvalContext) -> String {
    project_of(Path::new(&ctx.cwd), Path::new(&ctx.home))
}

/// A version 1 grant: a shell command.
#[derive(Deserialize)]
struct GrantV1 {
    host: String,
    session_id: String,
    command: String,
    #[serde(default)]
    granted_at_ms: i64,
}

#[derive(Deserialize)]
struct GrantsV1 {
    entries: Vec<GrantV1>,
}

impl Grant {
    /// Valid for [`GRANT_TTL_MS`] from its creation. A creation time in the
    /// future (a clock set back, a hand edit) is not valid either.
    #[must_use]
    pub fn active(&self, now_ms: i64) -> bool {
        (0..GRANT_TTL_MS).contains(&now_ms.saturating_sub(self.granted_at_ms))
    }

    /// Whether it needs a project to apply and names none: written by an
    /// earlier release, so it applies nowhere and must be approved again.
    #[must_use]
    pub fn unbound(&self) -> bool {
        self.needs_project() && self.project.is_none()
    }

    fn needs_project(&self) -> bool {
        self.covers_taint || matches!(self.action, Action::Shell { .. })
    }

    /// Whether it applies to a call in `project` ([`project_of`]).
    fn applies_in(&self, project: &str) -> bool {
        !self.needs_project() || self.project.as_deref() == Some(project)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Grants {
    pub version: u32,
    pub entries: Vec<Grant>,
}

impl Default for Grants {
    fn default() -> Self {
        Self {
            version: GRANTS_VERSION,
            entries: Vec::new(),
        }
    }
}

impl Grants {
    /// Missing file means no grants; a malformed or newer file is an error.
    pub fn load(path: &Path) -> Result<Self> {
        if !path.exists() {
            return Ok(Self::default());
        }
        let text =
            fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
        Self::parse(&text, path)
    }

    /// [`Grants::load`] of `home`'s grants, from the bytes the lock check
    /// kept when it kept them ([`Home::load_state`]).
    pub fn load_in(home: &Home) -> Result<Self> {
        home.load_state(&home.grants_path(), Self::parse, Self::load)
    }

    /// The grants in `text`, read from `path` (named in errors).
    pub fn parse(text: &str, path: &Path) -> Result<Self> {
        let parse = || format!("parsing {}", path.display());
        let value: serde_json::Value = serde_json::from_str(text).with_context(parse)?;
        match value.get("version").and_then(serde_json::Value::as_u64) {
            Some(1) => {
                let old: GrantsV1 = serde_json::from_value(value).with_context(parse)?;
                let entries = old.entries.into_iter().map(|g| Grant {
                    host: g.host,
                    session_id: g.session_id,
                    action: Action::Shell {
                        command: g.command.trim().to_owned(),
                    },
                    granted_at_ms: g.granted_at_ms,
                    audit_row: None,
                    covers_taint: false,
                    project: None,
                    real: Vec::new(),
                });
                Ok(Self {
                    version: GRANTS_VERSION,
                    entries: entries.collect(),
                })
            }
            Some(2) => serde_json::from_value(value).with_context(parse),
            version => bail!(
                "{} has version {}; this build supports {GRANTS_VERSION}",
                path.display(),
                version.map_or_else(|| "none".to_owned(), |v| v.to_string())
            ),
        }
    }

    /// Write the file, dropping grants that expired by `now_ms` so it does not
    /// grow without bound.
    pub fn save(&mut self, path: &Path, now_ms: i64) -> Result<()> {
        self.entries.retain(|g| g.active(now_ms));
        write_private(
            path,
            (serde_json::to_string_pretty(self)? + "\n").as_bytes(),
        )
    }

    /// Grant `action` (spelled by [`approvable`]) to the host session in
    /// `project` ([`project_of`]) as of `now_ms`, having seen the audit log up
    /// to `audit_row`; granting it again restarts its lifetime and moves it to
    /// `project`.
    pub fn grant(
        &mut self,
        scope: Scope<'_>,
        action: &Action,
        now_ms: i64,
        audit_row: Option<i64>,
    ) {
        // The same grant made earlier in this project, or by an earlier
        // release in none, is replaced; one in another project stays.
        self.entries.retain(|g| {
            !(scope.owns(g)
                && g.action == *action
                && g.project.as_deref().is_none_or(|p| p == scope.project))
        });
        self.entries.push(Grant {
            host: scope.host.to_owned(),
            session_id: scope.session_id.to_owned(),
            action: action.clone(),
            granted_at_ms: now_ms,
            audit_row,
            covers_taint: false,
            project: Some(scope.project.to_owned()),
            // Unresolvable now: recorded as itself, but no lookup matches
            // while it stays unresolvable ([`Grants::newest`]).
            real: asked::real_files(action).unwrap_or_default(),
        });
    }

    /// Exact match of `action` (spelled by [`approvable`]) for this host session
    /// among grants still valid at `now_ms` that apply in the scope's project;
    /// no prefix or glob semantics. A call without a session id never
    /// matches: every such call shares the placeholder id, so a grant for it
    /// would hold in every session.
    #[must_use]
    pub fn matches(&self, scope: Scope<'_>, action: &Action, now_ms: i64) -> bool {
        self.granted_at(scope, action, now_ms).is_some()
    }

    /// When the grant [`Grants::matches`] finds was made, if there is one.
    #[must_use]
    pub fn granted_at(&self, scope: Scope<'_>, action: &Action, now_ms: i64) -> Option<i64> {
        self.newest(scope, action, now_ms).map(|g| g.granted_at_ms)
    }

    /// The newest grant [`Grants::matches`] finds whose files resolve as approved.
    #[must_use]
    pub fn newest(&self, scope: Scope<'_>, action: &Action, now_ms: i64) -> Option<&Grant> {
        if openmoat_hosts::is_unknown_session(scope.session_id) {
            return None;
        }
        let real = asked::real_files(action)?;
        self.active(now_ms)
            .filter(|g| scope.owns(g) && g.action == *action && g.applies_in(scope.project))
            .filter(|g| g.real == real)
            .max_by_key(|g| g.granted_at_ms)
    }

    /// Make the grant for `action` in this host session also answer the
    /// session's other taint asks from untrusted content ([`Grant::covers_taint`]).
    pub fn cover_taint(&mut self, scope: Scope<'_>, action: &Action) {
        for g in &mut self.entries {
            if scope.owns(g) && g.action == *action && g.project.as_deref() == Some(scope.project) {
                g.covers_taint = true;
            }
        }
    }

    /// The newest grant of this host session that answers its taint asks from
    /// untrusted content in the scope's project, if one is still valid at `now_ms`.
    #[must_use]
    pub fn covering_taint(&self, scope: Scope<'_>, now_ms: i64) -> Option<&Grant> {
        if openmoat_hosts::is_unknown_session(scope.session_id) {
            return None;
        }
        self.active(now_ms)
            .filter(|g| g.covers_taint && scope.owns(g) && g.applies_in(scope.project))
            .max_by_key(|g| g.granted_at_ms)
    }

    /// Grants still valid at `now_ms`.
    pub fn active(&self, now_ms: i64) -> impl Iterator<Item = &Grant> {
        self.entries.iter().filter(move |g| g.active(now_ms))
    }
}

/// Where a grant is made or looked up: a host session, and the project of the
/// call ([`project_of`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Scope<'a> {
    pub host: &'a str,
    pub session_id: &'a str,
    pub project: &'a str,
}

impl Scope<'_> {
    /// Whether `grant` belongs to this host session (in any project).
    fn owns(&self, grant: &Grant) -> bool {
        grant.host == self.host && grant.session_id == self.session_id
    }
}

/// Allow rules appended by `moat allow --always`, `--site` and `--dir`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Overlay {
    pub version: u32,
    #[serde(default)]
    pub allow: Vec<RuleGroup>,
}

impl Default for Overlay {
    fn default() -> Self {
        Self {
            version: OVERLAY_VERSION,
            allow: Vec::new(),
        }
    }
}

impl Overlay {
    pub fn load(path: &Path) -> Result<Self> {
        if !path.exists() {
            return Ok(Self::default());
        }
        let text =
            fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
        Self::parse(&text, path)
    }

    /// [`Overlay::load`] of `home`'s overlay, from the bytes the lock check
    /// kept when it kept them ([`Home::load_state`]).
    pub fn load_in(home: &Home) -> Result<Self> {
        home.load_state(&home.overlay_path(), Self::parse, Self::load)
    }

    /// The overlay in `text`, read from `path` (named in errors).
    pub fn parse(text: &str, path: &Path) -> Result<Self> {
        let overlay: Self = openmoat_core::yaml::from_str(text)
            .with_context(|| format!("parsing {}", path.display()))?;
        if overlay.version != OVERLAY_VERSION {
            bail!(
                "{} has version {}; this build supports {OVERLAY_VERSION}",
                path.display(),
                overlay.version
            );
        }
        if let Some(bad) = overlay
            .allow
            .iter()
            .find(|g| !g.id.starts_with(OVERLAY_PREFIX))
        {
            bail!(
                "{}: rule `{}` must have an id starting with `{OVERLAY_PREFIX}`",
                path.display(),
                bad.id
            );
        }
        Ok(overlay)
    }

    pub fn save(&self, path: &Path) -> Result<()> {
        let text = format!(
            "# Permanent allow rules added with `openmoat allow`. Remove one with\n\
             # `openmoat allow --remove <id>`, or edit freely, then run `openmoat doctor --accept`.\n{}",
            openmoat_core::yaml::to_string(self)?
        );
        write_private(path, text.as_bytes())
    }

    /// Append an allow rule for one shell command, matched literally: glob
    /// characters in the command are not wildcards in the rule. Shell rules are
    /// prefixes, so extra arguments after the approved command are accepted.
    /// An install of a name close to a popular package also gets its
    /// `@package-near-miss` atom, which `package-near-miss` asks for on its
    /// own: approving the command answers that ask too.
    pub fn allow_command(&mut self, command: &str) -> Result<&RuleGroup> {
        let mut patterns = Vec::new();
        for line in
            std::iter::once(command.to_owned()).chain(openmoat_core::package_near_misses(command))
        {
            let pattern = openmoat_core::literal_shell_pattern(&line)
                .with_context(|| format!("cannot approve `{line}`"))?;
            patterns.push(pattern);
        }
        Ok(self.push("openmoat allow --always", |g| g.shell = patterns))
    }

    /// Append an `fs.read` and `fs.write` allow for exactly these paths. A path
    /// holding glob characters is refused: the rule would read them as wildcards.
    pub fn allow_files(&mut self, reads: &[String], writes: &[String]) -> Result<&RuleGroup> {
        if let Some(bad) = reads
            .iter()
            .chain(writes)
            .find(|p| p.contains(['*', '?', '[', ']', '{', '}', '\\']))
        {
            bail!(
                "{bad} contains glob characters; write it in the policy with `openmoat edit` instead"
            );
        }
        Ok(self.push("openmoat allow --always", |g| {
            g.fs_read = reads.to_vec();
            g.fs_write = writes.to_vec();
        }))
    }

    /// Whether a rule here already allows `action` (spelled by [`approvable`]).
    #[must_use]
    pub fn covers(&self, action: &Action) -> bool {
        if let Action::Shell { command } = action {
            let pattern = openmoat_core::literal_shell_pattern(command).ok();
            return self
                .allow
                .iter()
                .any(|g| pattern.as_ref().is_some_and(|p| g.shell.contains(p)));
        }
        let (reads, writes) = files(action);
        !(reads.is_empty() && writes.is_empty())
            && self.allow.iter().any(|g| {
                reads.iter().all(|p| g.fs_read.contains(p))
                    && writes.iter().all(|p| g.fs_write.contains(p))
            })
    }

    /// Append a `net` allow for one host name, which also covers web fetches.
    /// Only a plain name or address is accepted: a wildcard, scheme or port would
    /// widen the rule beyond what the person typed.
    pub fn allow_site(&mut self, host: &str) -> Result<&RuleGroup> {
        let host = host.trim().trim_end_matches('.').to_ascii_lowercase();
        let plain = host.split('.').all(|label| {
            !label.is_empty() && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
        });
        if !plain {
            bail!(
                "`{host}` is not a host name such as docs.rs; wildcards, URLs and ports \
                 are not accepted here (write those in the policy with `openmoat edit`)"
            );
        }
        Ok(self.push("openmoat allow --site", |g| g.net = vec![host]))
    }

    /// Append an `fs.read` and `fs.write` allow for each spelling of a directory
    /// and everything below it. Writes into a `.git` there are left out, as
    /// `project-fs` leaves out the project's: git runs what its hooks and config
    /// name later, outside any sandbox, so such a write is not allowed by this rule.
    /// So are the files CI, a commit-hook manager or the editor runs later
    /// ([`RUNS_LATER`](crate::sandbox::RUNS_LATER)), which `runs-later` asks for.
    pub fn allow_dir(&mut self, spellings: &[String]) -> &RuleGroup {
        let patterns: Vec<String> = spellings
            .iter()
            .flat_map(|dir| [dir.clone(), format!("{dir}/**")])
            .collect();
        let git: Vec<String> = spellings
            .iter()
            .flat_map(|dir| {
                [format!("!{dir}/.git/**"), format!("!{dir}/**/.git/**")]
                    .into_iter()
                    .chain(
                        crate::sandbox::RUNS_LATER
                            .iter()
                            .map(move |f| format!("!{dir}/{f}")),
                    )
            })
            .collect();
        self.push("openmoat allow --dir", |g| {
            g.fs_read.clone_from(&patterns);
            g.fs_write = patterns.into_iter().chain(git).collect();
        })
    }

    /// Remove the rule with this id, returning it.
    pub fn remove(&mut self, id: &str) -> Option<RuleGroup> {
        let index = self.allow.iter().position(|g| g.id == id)?;
        Some(self.allow.remove(index))
    }

    fn push(&mut self, how: &str, fill: impl FnOnce(&mut RuleGroup)) -> &RuleGroup {
        // One past the highest existing number: ids stay unique after a person
        // deletes an earlier rule, and a duplicate id would fail the policy lint.
        let n = self
            .allow
            .iter()
            .filter_map(|g| g.id.strip_prefix(OVERLAY_PREFIX)?.parse::<u64>().ok())
            .max()
            .unwrap_or(0)
            + 1;
        let mut rule = RuleGroup {
            id: format!("{OVERLAY_PREFIX}{n}"),
            reason: Some(format!(
                "approved with `{how}` on {}",
                time::timestamp(time::now_ms())
            )),
            ..RuleGroup::default()
        };
        fill(&mut rule);
        self.allow.push(rule);
        &self.allow[self.allow.len() - 1]
    }
}

#[cfg(test)]
mod tests;