openmoat 0.29.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.
//! Hook decisions inside `moat run` (ADR-028).
//!
//! The agent's hooks run `moat guard` inside the run's sandbox, which gives
//! no access to OpenMoat's home: not the lock or the policy it must read, not
//! the audit log it must write. So `moat run` gives the agent
//! [`SOCKET_ENV`] (the loopback address of its proxy's port, the one port the
//! sandbox lets the agent reach) and [`TOKEN_ENV`] (a random token for this
//! run). A guard that has both sends the raw payload there ([`client`]) and
//! prints the answer; the `moat run` process, outside the sandbox, decides it
//! with its own access ([`service`]). Whatever goes wrong denies.

mod client;
mod inside;
mod service;
mod wire;

use std::fmt::Write as _;
use std::net::TcpStream;
use std::time::Duration;

use anyhow::{Context as _, Result};
use zeroize::Zeroizing;

pub use client::{Endpoint, configured};
pub use service::Service;
pub use wire::Reply;

/// What a guard does with the relay variables of its environment.
pub enum Relay {
    /// Neither is set: it decides by itself.
    Unset,
    /// It runs in `openmoat run`'s sandbox: it sends the call to the endpoint
    /// they name (an error when they name none it may use).
    Inside(Result<Endpoint>),
    /// They are set, but the guard can open its lock or is in no sandbox of
    /// `openmoat run`: it decides by itself and records that they were there.
    Outside,
}

/// [`Relay`] for an environment read by `var`, with the state directory
/// `home` names (`None` when none can be named).
pub fn relay(var: &dyn Fn(&str) -> Option<String>, home: Option<&crate::home::Home>) -> Relay {
    let Some(endpoint) = configured(var) else {
        return Relay::Unset;
    };
    let lock = home.map(crate::home::Home::lock_path);
    if inside::in_run_sandbox(lock.as_deref()) {
        Relay::Inside(endpoint)
    } else {
        Relay::Outside
    }
}

/// Where `moat run` answers hook calls: `127.0.0.1:<port>`.
pub const SOCKET_ENV: &str = "MOAT_GUARD_SOCKET";
/// The token `moat run` wants with each call.
pub const TOKEN_ENV: &str = "MOAT_GUARD_TOKEN";

/// The most one copy of a call's arguments may hold: `moat guard` reads that
/// much from standard input for each copy a host's payload carries
/// ([`payload_limit`]).
pub const MAX_PAYLOAD_BYTES: u64 = 1024 * 1024;

/// The most `host`'s payload may hold ([`openmoat_hosts::HostSpec::payload_copies`]).
pub fn payload_limit(host: openmoat_hosts::Host) -> u64 {
    MAX_PAYLOAD_BYTES * host.spec().payload_copies.max(1)
}

/// The most a payload the relay carries may hold: the largest of every
/// host's [`payload_limit`].
pub fn relayed_limit() -> u64 {
    openmoat_hosts::Host::EVERY
        .into_iter()
        .map(payload_limit)
        .max()
        .unwrap_or(MAX_PAYLOAD_BYTES)
}

/// A connection the relay reads and writes, with timeouts.
pub trait Stream: std::io::Read + std::io::Write {
    /// Let each read and write wait at most `limit`.
    fn set_timeouts(&self, limit: Duration) -> std::io::Result<()>;
}

impl Stream for &TcpStream {
    fn set_timeouts(&self, limit: Duration) -> std::io::Result<()> {
        self.set_read_timeout(Some(limit))?;
        self.set_write_timeout(Some(limit))
    }
}

impl Stream for TcpStream {
    fn set_timeouts(&self, limit: Duration) -> std::io::Result<()> {
        self.set_read_timeout(Some(limit))?;
        self.set_write_timeout(Some(limit))
    }
}

/// `bytes` random bytes from the system's random source, as hex.
pub fn random_hex(bytes: usize) -> Result<Zeroizing<String>> {
    let mut raw = Zeroizing::new(vec![0u8; bytes]);
    // The operating system's random source on every platform (Windows has no
    // `/dev/urandom`).
    getrandom::fill(raw.as_mut_slice())
        .map_err(|e| anyhow::Error::msg(e.to_string()))
        .context("reading random bytes")?;
    let mut out = Zeroizing::new(String::with_capacity(bytes * 2));
    for byte in raw.iter() {
        let _ = write!(out, "{byte:02x}");
    }
    Ok(out)
}

#[cfg(all(test, unix))]
mod tests;