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
//! `moat run` on macOS: the agent under `sandbox-exec` with the Seatbelt
//! profile generated for the session (`crate::sandbox::seatbelt`). Before
//! macOS 13 it refuses (exit 64): `sandbox-exec` there cannot read the profile.
//!
//! The Isolated tier here needs a Linux guest, since Seatbelt does not nest
//! and bubblewrap is Linux-only (ADR-018). ADR-023 picks Apple's
//! `containerization` toolchain for that; today `moat run --isolate` on macOS
//! is still a stub that refuses to run the agent (exit 64), reporting either
//! that `container` is missing or that the full implementation is still
//! coming. It never falls back to the Lightweight tier.

use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};

use anyhow::{Context as _, Result, bail};
use openmoat_core::boundary::{LaunchCheck, Mechanism, NetworkMode, Restriction};
use openmoat_core::{EvalContext, Policy};

use crate::cli::IsolatedArgs;
use crate::environment::find_in;
use crate::exit::Code;
use crate::os_version;
use crate::sandbox::{Grants, Report, seatbelt_profile};

/// Part of the base system; never one found on `PATH`. Apple has deprecated
/// it, but Codex, Claude Code and Chromium still start their sandboxes with it.
const SANDBOX_EXEC: &str = "/usr/bin/sandbox-exec";

/// The command the Isolated tier on macOS will drive once the implementation
/// lands (ADR-023): Apple's `containerization` CLI, which boots the Linux
/// guest and projects the virtiofs mounts.
const CONTAINER: &str = "container";

/// The agent, ready to start in its sandbox.
pub struct Confined {
    command: Command,
    report: Report,
}

pub fn confine(
    policy: &Policy,
    ctx: &EvalContext,
    grants: Grants,
    program: &Path,
    // Seatbelt denies inside a granted tree, so `kernel-self` keeps the state
    // directory wherever it is.
    _state: &Path,
) -> Result<Confined> {
    // Refused here with a plain reason rather than by `sandbox-exec` with
    // `unbound variable: TIOCSTI`; the profile keeps its deny either way.
    if let Some(reason) = os_version::run_floor(os_version::macos().as_deref()) {
        bail!("{}", refusal(&reason));
    }
    let generated = seatbelt_profile(policy, ctx, grants)?;
    let mut command = Command::new(SANDBOX_EXEC);
    command.arg("-p").arg(&generated.profile).arg(program);
    Ok(Confined {
        command,
        report: generated.report,
    })
}

/// The Isolated tier on macOS (ADR-023, #175): a stub until the Apple
/// Virtualization implementation lands. Refuses with a clear reason so no
/// one is surprised by half-work.
///
/// - `container` not on `PATH`: exit 64 with the install hint.
/// - `container` on `PATH`: exit 64 with "not yet implemented, see ADR-023".
///
/// Never a silent fallback to the Lightweight tier; the owner asked for the
/// Isolated boundary, so refusing is fail-closed.
pub fn isolate(_: &Policy, _: &EvalContext, _: Grants, _: &Path, _: &Path) -> Result<Confined> {
    bail!(
        "{}",
        stub_message(&crate::environment::absolute_search_path(), CONTAINER)
    )
}

pub fn inside(_: &IsolatedArgs) -> Result<Code> {
    bail!("only `openmoat run --isolate` on Linux starts this")
}

/// What macOS itself sets for a process, kept under `openmoat run`'s
/// environment allowlist (ADR-077).
pub const BASE_ENV: &[&str] = &[
    "__CF_USER_TEXT_ENCODING",
    "__CFBundleIdentifier",
    "COMMAND_MODE",
    "XPC_FLAGS",
    "XPC_SERVICE_NAME",
];

/// Why `moat run` cannot sandbox on this Mac; `None` when it can.
pub fn unavailable() -> Option<String> {
    os_version::run_floor(os_version::macos().as_deref()).map(|reason| refusal(&reason))
}

/// How macOS holds the network: the profile allows the proxy's address alone.
pub const NETWORK: NetworkMode = NetworkMode::Profile;

/// Why `openmoat run --listen` is refused on macOS (ADR-108 §7, ADR-122):
/// Seatbelt's `local ip "localhost:PORT"` filter lets a bind to every address
/// (`0.0.0.0`) on the port through too, as the end-to-end test found on macOS
/// 15, so the port could be reachable from the network, not only from this
/// machine. No other filter form names that address, and guard sockets held
/// by `openmoat run` would end with it while a process the agent left behind
/// keeps the sandbox (ADR-122).
#[expect(
    clippy::unnecessary_wraps,
    reason = "one signature on every platform: Linux's lets `--listen` through"
)]
pub fn listen_refused_here(port: u16) -> Option<String> {
    Some(format!(
        "`openmoat run --listen {port}` is refused on macOS: its sandbox cannot keep a \
         listening port to this machine (a bind to every address on port {port} would go \
         through too), so the port could be reachable from the network. Start the agent \
         without `openmoat run`, under its hook, with the same command after `--`; \
         docs/SANDBOX.md#openclaw-under-openmoat-run and ADR-122 say why"
    ))
}

/// None: the tool-shell wrapper (ADR-075) works here.
pub const TOOL_SHELL_GAP: Option<&str> = None;

/// `openmoat mcp wrap` starts servers under `openmoat run` by default here.
pub const MCP_SANDBOX_BY_DEFAULT: bool = true;

/// The restriction a macOS run plans (ADR-089): the Seatbelt profile.
/// `sandbox-exec` reports nothing back and there is no `/proc`, so it is
/// never marked applied or tested; the profile is what `openmoat sandbox
/// show` prints.
pub fn restrictions(
    _isolated: bool,
    _port_only: bool,
    _kernel: Option<&crate::sandbox::landlock::abi::Kernel>,
    _agent_account: crate::agent_account::RunAs,
) -> Vec<Restriction> {
    vec![Restriction::planned(Mechanism::Seatbelt, true, true)]
}

/// The person's own user: the agent account is Windows' (ADR-129).
pub fn agent_account(_state: &Path) -> crate::agent_account::RunAs {
    crate::agent_account::RunAs::Person
}

/// None: the proxy takes any free loopback port; only the Windows agent
/// account's network filters fix a range (ADR-129).
pub fn proxy_ports(_state: &Path) -> Option<[u16; 2]> {
    None
}

/// None: Landlock is Linux's (ADR-082).
pub fn landlock() -> Option<crate::sandbox::landlock::abi::Kernel> {
    None
}

/// None: Seatbelt names the proxy's address, not only its port.
pub fn port_only_network() -> Option<String> {
    None
}

/// None: Seatbelt holds the network without a namespace.
pub fn no_network_namespace() -> Option<String> {
    None
}

/// No Isolated tier to start by default until ADR-023's lands: Seatbelt
/// denies paths inside the project already, and `--isolate` refuses here.
pub fn isolation() -> super::isolation::Offered {
    super::isolation::Offered::Not
}

/// None: Seatbelt denies paths inside the project, so plain `moat run` has
/// no Linux-only gap to name (`tier.rs`).
pub fn bubblewrap() -> Option<bool> {
    None
}

/// None: no agent sandbox here uses user namespaces.
pub fn bubblewrap_userns() -> Option<std::result::Result<(), String>> {
    None
}

/// None: Seatbelt denies inside the project what the policy denies, so
/// nothing there stays open for `moat doctor` to name.
pub fn project_open(_: &Policy, _: &EvalContext) -> Option<String> {
    None
}

/// The terminals (`/dev/ttys*`) this process's standard input, output and
/// error are on. macOS has no `/proc` to name an open file, so each stream's
/// device number is looked up among the terminals in `/dev`.
pub fn terminals() -> Vec<String> {
    use std::os::fd::{AsFd as _, BorrowedFd};
    use std::os::unix::fs::{FileTypeExt as _, MetadataExt as _};

    let stat = |fd: BorrowedFd<'_>| {
        let file = std::fs::File::from(fd.try_clone_to_owned().ok()?);
        file.metadata().ok()
    };
    let (stdin, stdout, stderr) = (std::io::stdin(), std::io::stdout(), std::io::stderr());
    let streams = [stdin.as_fd(), stdout.as_fd(), stderr.as_fd()];
    let devices: Vec<u64> = streams
        .into_iter()
        .filter_map(stat)
        .filter(|m| m.file_type().is_char_device())
        .map(|m| m.rdev())
        .collect();
    if devices.is_empty() {
        return Vec::new();
    }
    let Ok(entries) = std::fs::read_dir("/dev") else {
        return Vec::new();
    };
    let mut found: Vec<String> = entries
        .flatten()
        .filter(|e| e.file_name().to_string_lossy().starts_with("ttys"))
        .filter_map(|e| {
            let meta = std::fs::symlink_metadata(e.path()).ok()?;
            let terminal = meta.file_type().is_char_device() && devices.contains(&meta.rdev());
            terminal.then(|| crate::context::path_string(&e.path()))
        })
        .collect();
    found.sort();
    found
}

impl Confined {
    pub fn command(&mut self) -> &mut Command {
        &mut self.command
    }

    pub fn report(&self) -> &Report {
        &self.report
    }

    pub fn report_mut(&mut self) -> &mut Report {
        &mut self.report
    }

    /// None: the profile allows only `localhost:<port>`.
    #[expect(
        clippy::unused_self,
        reason = "the method every platform's `Confined` has; Linux's reads itself"
    )]
    pub fn warning(&self) -> Option<&str> {
        None
    }

    /// None: Seatbelt denies inside the project what the policy denies,
    /// matches created later included, so there is nothing to name.
    #[expect(
        clippy::unused_self,
        reason = "the method every platform's `Confined` has; Linux's reads itself"
    )]
    pub fn project_notice(&self) -> Option<&str> {
        None
    }

    /// False: Seatbelt denies by path, so `sandbox.project_top` changes
    /// nothing here (ADR-090).
    #[expect(
        clippy::unused_self,
        reason = "the method every platform's `Confined` has; Linux's reads itself"
    )]
    pub fn project_top_open(&self) -> bool {
        false
    }

    /// The person's own user: the agent account is Windows' (ADR-129).
    #[expect(
        clippy::unused_self,
        reason = "the method every platform's `Confined` has; Windows' reads itself"
    )]
    pub fn agent_account(&self) -> crate::agent_account::RunAs {
        crate::agent_account::RunAs::Person
    }

    /// Start the agent under `sandbox-exec`, tell `on_launch` it started
    /// (with no check to give: no `/proc` here), and wait for it.
    pub fn status(
        mut self,
        on_launch: impl FnOnce(Option<LaunchCheck>) -> Result<()>,
    ) -> Result<ExitStatus> {
        // Seatbelt does not check a file opened before the profile applies.
        super::inherited::close_on_exec()?;
        let mut child = self.command.spawn().context("starting sandbox-exec")?;
        if let Err(error) = on_launch(None) {
            let _ = child.kill();
            let _ = child.wait();
            return Err(error);
        }
        Ok(child.wait()?)
    }
}

/// Link the wrapper of a tool shell (`tool_shell.rs`) to this binary.
pub fn link_tool_shell(moat: &Path, link: &Path) -> std::io::Result<()> {
    std::os::unix::fs::symlink(moat, link)
}

/// Nothing to do here: Seatbelt keeps the agent's environment from every
/// process in the profile (`kern.procargs`), the wrapper's sandbox included.
#[expect(
    clippy::unnecessary_wraps,
    reason = "one signature on every platform: Linux's adds a Landlock layer, which can fail"
)]
pub fn seal_tool_shell() -> Result<()> {
    Ok(())
}

/// Replace this process with `command`, returning only if that failed.
pub fn exec_tool_shell(command: &mut Command) -> std::io::Error {
    std::os::unix::process::CommandExt::exec(command)
}

/// What `moat run` says on a macOS too old for its profile (exit 64).
fn refusal(reason: &str) -> String {
    format!(
        "`openmoat run` {reason}. The agent was not started. The agent hooks still apply the \
         policy to each tool call: start the agent without `openmoat run`"
    )
}

/// What `moat run --isolate` tells the user on macOS today, with `#175` in
/// it so hosts and tests can match on it as they did before.
fn stub_message(path: &[PathBuf], program: &str) -> String {
    let found = find_in(path, &[], program);
    if found.is_some() {
        format!(
            "`openmoat run --isolate` on macOS: not yet implemented, see ADR-023 (#175). `{program}` \
             is installed; the virtualization work ships in follow-up PRs. For now the Isolated \
             tier is Linux-only; `openmoat run` without --isolate is the Lightweight tier"
        )
    } else {
        format!(
            "`openmoat run --isolate` on macOS needs Apple's `containerization` toolchain (ADR-023, \
             #175): `{program}` is not on PATH. Install it with `brew install --cask container` \
             or from https://github.com/apple/container/releases, then re-run. Refusing rather \
             than starting the agent in a weaker tier"
        )
    }
}

#[cfg(test)]
mod tests {
    use std::fs::{self, File};
    use std::os::unix::fs::PermissionsExt as _;
    use std::path::PathBuf;

    use super::*;

    /// A directory with one executable called `name`, as `PATH` would list it.
    fn with_executable(dir: &Path, name: &str) -> PathBuf {
        let bin = dir.join(name);
        File::create(&bin).expect("creating a fake `container` binary");
        fs::set_permissions(&bin, fs::Permissions::from_mode(0o755))
            .expect("marking it executable");
        dir.to_path_buf()
    }

    /// The stub never exits 0 or 2: hosts rely on these exit codes
    /// (ADR-004), and the owner picked exit 64 for refusing to start.
    #[test]
    fn exit_code_contract_is_64_whichever_branch_the_stub_takes() {
        // The CLI maps `Err(_)` from `isolate()` to `Code::Usage` (64) in
        // `main.rs`; this test asserts the mapping stays in that enum.
        assert_eq!(Code::Usage as u8, 64);
    }

    #[test]
    fn an_old_macos_is_refused_with_a_plain_reason() {
        let reason = os_version::run_floor(Some("12.7")).unwrap();
        let message = refusal(&reason);
        assert!(
            message.starts_with("`openmoat run` needs macOS 13 or later"),
            "{message}"
        );
        assert!(
            message.contains("hooks still apply the policy"),
            "{message}"
        );
        assert!(!message.contains("unbound variable"), "{message}");
    }

    /// Only terminal devices, never `/dev/tty` or another device; under
    /// `cargo test` the streams are usually pipes, so often none.
    #[test]
    fn the_terminals_are_the_streams_own_ttys() {
        for terminal in terminals() {
            assert!(terminal.starts_with("/dev/ttys"), "{terminal}");
        }
    }

    #[test]
    fn missing_container_points_at_the_install_command() {
        let dir = tempfile::tempdir().expect("a scratch dir");
        let path = vec![dir.path().to_path_buf()];
        let message = stub_message(&path, "container-not-here");
        assert!(message.contains("ADR-023"), "{message}");
        assert!(message.contains("#175"), "{message}");
        assert!(
            message.contains("brew install --cask container"),
            "{message}"
        );
        assert!(
            !message.contains("not yet implemented"),
            "missing is a different branch: {message}"
        );
    }

    #[test]
    fn present_container_says_not_yet_implemented() {
        let dir = tempfile::tempdir().expect("a scratch dir");
        let path = vec![with_executable(dir.path(), "container")];
        let message = stub_message(&path, "container");
        assert!(message.contains("ADR-023"), "{message}");
        assert!(message.contains("#175"), "{message}");
        assert!(message.contains("not yet implemented"), "{message}");
        assert!(
            !message.contains("brew install"),
            "present is a different branch: {message}"
        );
    }

    #[test]
    fn stub_message_never_promises_a_lightweight_fallback() {
        // Fail-closed (ADR-018): the Isolated tier never silently downgrades.
        let dir = tempfile::tempdir().expect("a scratch dir");
        let missing = stub_message(&[dir.path().to_path_buf()], "nope");
        let present = stub_message(&[with_executable(dir.path(), "container")], "container");
        for message in [missing, present] {
            let lowered = message.to_lowercase();
            assert!(!lowered.contains("falls back"), "{message}");
            assert!(!lowered.contains("falling back"), "{message}");
        }
    }
}