openmoat 0.27.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
//! Which inherited environment variables reach what `openmoat run` starts
//! (ADR-077, ADR-105). A scrubbed environment passes only an allowlist: a
//! base every program needs, the host's own names from its spec, the names the
//! person's policy adds and the names given with `--env`. It is scrubbed under
//! `require.run: full-boundary`, `sandbox.env: scrubbed` or `--scrub-env`
//! ([`Mode::choose`]). Otherwise everything still does, as before, and one line
//! says what looks like a credential. Either way a brokered secret's variable
//! holds its placeholder, never the value ([`brokered`]).
//!
//! Names only, everywhere in this file: a value is never read, kept or shown.

use std::collections::BTreeSet;
use std::ffi::{OsStr, OsString};

use openmoat_core::boundary::RunEnvironment;
use openmoat_core::{Policy, RunEnv, SecretSource};
use openmoat_hosts::Host;

use crate::render::clean;

/// Whether the run scrubs the environment, and what chose that.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mode {
    pub scrubbed: bool,
    /// In the words the run notice and the boundary record use.
    pub why: String,
}

impl Mode {
    /// The policy that requires the full boundary (`strict`, which scrubs
    /// whatever else says), then `--scrub-env` (`flag`, which only raises),
    /// then the person's `sandbox.env` (`choice`), then [`RunEnv::DEFAULT`].
    pub fn choose(choice: Option<RunEnv>, strict: Option<&str>, flag: bool) -> Self {
        let (scrubbed, why) = match (strict, flag, choice) {
            (Some(asks), _, _) => (
                true,
                format!("{asks} requires `require.run: full-boundary`"),
            ),
            (None, true, _) => (true, "`openmoat run --scrub-env`".to_owned()),
            (None, false, Some(env)) => (
                env == RunEnv::Scrubbed,
                format!("`sandbox.env: {}` in your policy", name(env)),
            ),
            (None, false, None) => (
                RunEnv::DEFAULT == RunEnv::Scrubbed,
                format!("the default (`sandbox.env: {}`)", name(RunEnv::DEFAULT)),
            ),
        };
        Self { scrubbed, why }
    }
}

fn name(env: RunEnv) -> &'static str {
    match env {
        RunEnv::Inherited => "inherited",
        RunEnv::Scrubbed => "scrubbed",
    }
}

/// Each variable a brokered secret of `policy` is read from (`source: env`)
/// and the placeholder the program gets in it instead (ADR-020): the run's
/// proxy reads the value from this process, and a tool that sends the
/// placeholder to the secret's host has it replaced there.
pub fn brokered(policy: &Policy) -> Vec<(String, String)> {
    let mut pairs: Vec<(String, String)> = policy
        .secrets
        .iter()
        .filter_map(|s| match &s.source {
            SecretSource::Env(name) => Some((name.clone(), s.placeholder())),
            _ => None,
        })
        .collect();
    pairs.sort();
    pairs.dedup_by(|a, b| a.0 == b.0);
    pairs
}

/// Once the run has set everything of its own on `command`: remove what a
/// scrubbed `mode` withholds of this process's environment, say so (and with
/// `verbose` name it), and return the boundary record's part. What `command`
/// already sets or removes is the run's own and never withheld.
pub fn apply(
    command: &mut std::process::Command,
    (allowed, mode, brokered): (&Allowed, &Mode, &[(String, String)]),
    verbose: bool,
) -> RunEnvironment {
    let set_by_run: Vec<OsString> = command
        .get_envs()
        .map(|(name, _)| name.to_owned())
        .collect();
    let inherited = || std::env::vars_os().map(|(name, _)| name);
    let withheld = withheld(inherited(), allowed, &|name| {
        set_by_run.iter().any(|set| same_name(set, name))
    });
    if mode.scrubbed {
        for name in &withheld {
            command.env_remove(name);
        }
    }
    if let Some(line) = notice(&withheld, mode.scrubbed) {
        eprintln!("{line}");
    }
    if verbose && let Some(line) = list(&withheld, mode.scrubbed) {
        eprintln!("{line}");
    }
    record(mode, inherited(), &withheld, brokered)
}

/// The boundary record's part for this run (ADR-105): `inherited` names what
/// this process has, `withheld` what the run removes, `brokered` the
/// variables that hold a placeholder.
pub fn record(
    mode: &Mode,
    inherited: impl IntoIterator<Item = OsString>,
    withheld: &[OsString],
    brokered: &[(String, String)],
) -> RunEnvironment {
    let text = |names: &[OsString]| shown(names);
    let passed = if mode.scrubbed {
        let mut names: Vec<OsString> = inherited
            .into_iter()
            .filter(|n| !withheld.contains(n) && !brokered.iter().any(|(b, _)| n == b.as_str()))
            .collect();
        names.sort();
        names.dedup();
        text(&names)
    } else {
        Vec::new()
    };
    RunEnvironment {
        scrubbed: mode.scrubbed,
        why: mode.why.clone(),
        passed,
        withheld: if mode.scrubbed {
            text(withheld)
        } else {
            Vec::new()
        },
        brokered: brokered.iter().map(|(name, _)| name.clone()).collect(),
    }
}

/// What every program needs, on every platform. A value `openmoat run` sets
/// itself (the proxy, the temp directory, the CA files) is kept without being
/// listed here, because the run's own settings are never withheld.
const BASE: &[&str] = &[
    "PATH",
    "HOME",
    "USER",
    "LOGNAME",
    "SHELL",
    "PWD",
    "OLDPWD",
    "SHLVL",
    "_",
    "TERM",
    "TERM_PROGRAM",
    "TERM_PROGRAM_VERSION",
    "COLORTERM",
    "COLUMNS",
    "LINES",
    "NO_COLOR",
    "FORCE_COLOR",
    "CLICOLOR",
    "LANG",
    "LANGUAGE",
    "LC_ALL",
    "LC_ADDRESS",
    "LC_COLLATE",
    "LC_CTYPE",
    "LC_IDENTIFICATION",
    "LC_MEASUREMENT",
    "LC_MESSAGES",
    "LC_MONETARY",
    "LC_NAME",
    "LC_NUMERIC",
    "LC_PAPER",
    "LC_TELEPHONE",
    "LC_TIME",
    "TZ",
    "TMPDIR",
    "TEMP",
    "TMP",
    "EDITOR",
    "VISUAL",
    "PAGER",
    "XDG_CACHE_HOME",
    "XDG_CONFIG_DIRS",
    "XDG_CONFIG_HOME",
    "XDG_DATA_DIRS",
    "XDG_DATA_HOME",
    "XDG_RUNTIME_DIR",
    "XDG_STATE_HOME",
    // Where common toolchains are, which a build reads and nothing secret is
    // in (ADR-105): without them a scrubbed run would break normal builds.
    "JAVA_HOME",
    "GOPATH",
    "GOROOT",
    "GOBIN",
    "CARGO_HOME",
    "RUSTUP_HOME",
    "RUSTUP_TOOLCHAIN",
    "NVM_DIR",
    "NVM_BIN",
    "PYENV_ROOT",
    "VIRTUAL_ENV",
    "CONDA_PREFIX",
    "CONDA_DEFAULT_ENV",
    "HOMEBREW_PREFIX",
    "HOMEBREW_CELLAR",
    "HOMEBREW_REPOSITORY",
    "MANPATH",
    "INFOPATH",
    "LESS",
    "GPG_TTY",
    // Where OpenMoat's own state is: the hook is told the same on its command line.
    crate::home::ENV,
];

/// How many credential-looking names the warning spells out.
const SHOWN: usize = 3;

/// Words that, as a whole `_`-separated part of a name, mean it probably holds
/// a credential. Whole parts, so `KEYBOARD_LAYOUT` and `MONKEY` are not one.
const CREDENTIAL_WORDS: &[&str] = &[
    "APIKEY",
    "AUTH",
    "COOKIE",
    "CREDENTIAL",
    "CREDENTIALS",
    "KEY",
    "PASS",
    "PASSPHRASE",
    "PASSWD",
    "PASSWORD",
    "PAT",
    "PRIVATE",
    "SECRET",
    "SECRETS",
    "TOKEN",
];

/// Whether `name` looks like it holds a credential, for the warning only:
/// whether a variable is withheld never depends on this.
fn looks_like_credential(name: &str) -> bool {
    let upper = name.to_ascii_uppercase();
    upper.starts_with("AWS_")
        || upper
            .split('_')
            .any(|part| CREDENTIAL_WORDS.contains(&part))
}

/// The names that may reach what the run starts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Allowed(BTreeSet<String>);

impl Allowed {
    /// The base, this `platform`'s own, `host`'s facts, the person's policy
    /// (`sandbox.env_allow`) and `flags` (`--env`).
    pub fn new(platform: &[&str], host: Option<Host>, policy: &Policy, flags: &[String]) -> Self {
        let mut names: BTreeSet<String> = BASE
            .iter()
            .chain(platform)
            .map(|n| (*n).to_owned())
            .collect();
        names.extend(policy.sandbox.iter().flat_map(|s| s.env_allow.clone()));
        names.extend(flags.iter().cloned());
        let mut allowed = Self(names);
        if let Some(host) = host {
            allowed.add_host(host);
        }
        allowed
    }

    /// Allow `host`'s own names too.
    pub fn add_host(&mut self, host: Host) {
        self.0
            .extend(host_names(host).into_iter().map(str::to_owned));
    }

    fn holds(&self, name: &OsStr) -> bool {
        name.to_str().is_some_and(|n| {
            self.0.contains(n) || self.0.iter().any(|a| same_name(OsStr::new(a), name))
        })
    }
}

/// Whether two variable names are one: Windows compares them without case
/// (`Path` is `PATH`), so a scrubbed run there must too, or it would withhold
/// `Path` and remove what the run itself set under another case.
pub fn same_name(a: &OsStr, b: &OsStr) -> bool {
    if cfg!(windows) {
        a.eq_ignore_ascii_case(b)
    } else {
        a == b
    }
}

/// `host`'s own names: its spec's facts and the variable that moves its
/// configuration directory.
pub fn host_names(host: Host) -> Vec<&'static str> {
    let spec = host.spec();
    let dir = spec
        .install
        .as_ref()
        .map(|i| i.dir_variable)
        .into_iter()
        .chain(spec.detect.as_ref().map(|d| d.dir_variable));
    spec.run_env
        .iter()
        .copied()
        .chain(dir)
        .filter(|n| !n.is_empty())
        .collect()
}

/// The names in `inherited` that are not `allowed`, sorted. `set_by_run` tells
/// the names the run sets or removes itself, which are never reported: its
/// own values reach the agent, and a brokered secret is already gone.
pub fn withheld(
    inherited: impl IntoIterator<Item = OsString>,
    allowed: &Allowed,
    set_by_run: &dyn Fn(&OsStr) -> bool,
) -> Vec<OsString> {
    let mut names: Vec<OsString> = inherited
        .into_iter()
        .filter(|name| !allowed.holds(name) && !set_by_run(name))
        .collect();
    names.sort();
    names.dedup();
    names
}

/// The names as a person reads them, control characters taken out.
fn shown(names: &[OsString]) -> Vec<String> {
    names
        .iter()
        .map(|n| clean(&n.to_string_lossy()).to_string())
        .collect()
}

/// The one line `openmoat run` prints about `names`: what it withheld from a
/// `scrubbed` environment, or else what looks like a credential and still
/// reaches the agent; `None` when there is nothing to say.
pub fn notice(names: &[OsString], scrubbed: bool) -> Option<String> {
    if scrubbed {
        return (!names.is_empty()).then(|| {
            format!(
                "moat run: {} inherited variables withheld from the agent (--verbose names them; \
                 `--env NAME` or `sandbox.env_allow` in your policy passes one on)",
                names.len()
            )
        });
    }
    let credentials: Vec<String> = shown(names)
        .into_iter()
        .filter(|n| looks_like_credential(n))
        .collect();
    let first = credentials.first()?;
    let more = credentials.len().saturating_sub(SHOWN);
    let listed = credentials
        .get(1..SHOWN.min(credentials.len()))
        .unwrap_or_default()
        .iter()
        .fold(first.clone(), |all, n| format!("{all}, {n}"));
    let tail = if more > 0 {
        format!(" and {more} more")
    } else {
        String::new()
    };
    Some(format!(
        "moat run: {} inherited variables that look like credentials reach the agent \
         ({listed}{tail}); `sandbox.env: scrubbed` in your policy or `--scrub-env` withholds them",
        credentials.len()
    ))
}

/// `openmoat doctor`'s row: the names the run withholds from a `scrubbed`
/// environment, or would.
pub fn doctor_line(names: &[OsString], scrubbed: bool) -> String {
    let what = if scrubbed {
        "withholds from the agent"
    } else {
        "would withhold with `sandbox.env: scrubbed`"
    };
    if names.is_empty() {
        return format!("run environment  `openmoat run` {what}: nothing here");
    }
    format!(
        "run environment  `openmoat run` {what} (names only, each agent's own excepted): {}",
        shown(names).join(", ")
    )
}

/// `--verbose`'s line naming every withheld variable; `None` when none is.
pub fn list(names: &[OsString], scrubbed: bool) -> Option<String> {
    let verb = if scrubbed {
        "withheld"
    } else {
        "would be withheld"
    };
    (!names.is_empty()).then(|| format!("  {verb} (names only): {}", shown(names).join(", ")))
}

#[cfg(test)]
mod tests;