openmoat 0.23.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.
//! The certificate authority the proxy terminates TLS with: `openmoat run`'s,
//! for secrets that say `tls: terminate` (ADR-043) and `requests:` hosts, and
//! the standalone `openmoat proxy`'s, for `requests:` hosts and the sessions
//! that received the trust files (ADR-062).
//!
//! - It lives in OpenMoat's state directory, `proxy-ca/`: `ca.pem` (the
//!   certificate, which clients in the run trust) and `key.pem` (the key,
//!   owner-only). No sandbox OpenMoat writes lets the agent read that
//!   directory, and the default policy's `kernel-self` denies reading it.
//! - Only `openmoat proxy ca init`, a person at a terminal, writes the files,
//!   and pins both in the policy lock. Other re-pins keep the pins and never
//!   add them, as for the signing files (`integrity::signing_files`).
//! - `openmoat run` uses the CA only while both files are pinned and intact,
//!   and only when it signs leaves that verify today for every terminated host.

mod trust;

use std::path::PathBuf;

use anyhow::{Context as _, Result, bail};
use openmoat_core::Policy;
use openmoat_proxy::{CA_VALID_DAYS, CaFiles, Roots, Tls};

pub use self::trust::Trust;
use crate::home::Home;
use crate::integrity::Lock;

/// Days before the CA expires that `openmoat run` starts saying so.
const EXPIRY_NOTICE_DAYS: i64 = 30;
const MS_PER_DAY: i64 = 86_400_000;

/// The CA's certificate.
pub fn cert_path(home: &Home) -> PathBuf {
    home.root().join("proxy-ca").join("ca.pem")
}

/// The CA's private key.
pub fn key_path(home: &Home) -> PathBuf {
    home.root().join("proxy-ca").join("key.pem")
}

/// The files `openmoat proxy ca init` pins.
pub fn files(home: &Home) -> Vec<PathBuf> {
    vec![cert_path(home), key_path(home)]
}

/// The hosts of `policy`'s secrets that say `tls: terminate`, and of its
/// `requests:` entries the proxy holds (not `hook_only`, ADR-062), sorted,
/// once each.
pub fn terminated_hosts(policy: &Policy) -> Vec<String> {
    let mut hosts: Vec<String> = policy
        .secrets
        .iter()
        .filter(|s| s.terminates())
        .map(|s| s.host.clone())
        .chain(request_hosts(policy))
        .collect();
    hosts.sort();
    hosts.dedup();
    hosts
}

/// The hosts of `policy`'s `requests:` entries the proxy holds.
pub fn request_hosts(policy: &Policy) -> Vec<String> {
    // The policy linted, so its entries compile.
    openmoat_core::RequestRules::for_proxy(&policy.requests)
        .map(|rules| rules.hosts())
        .unwrap_or_default()
}

/// The CA's certificate, when both files are pinned and present: what a
/// session's trust files hold (ADR-062 ยง2). Never the key.
pub fn pinned_cert(home: &Home) -> Option<String> {
    let lock = Lock::load(&home.lock_path()).ok()?;
    if !files(home).iter().all(|f| lock.pins(f) && f.is_file()) {
        return None;
    }
    std::fs::read_to_string(cert_path(home)).ok()
}

/// The name of the pack that has the proxy hold the default policy's
/// hook-only request rules (ADR-062, `policies/packs/exfil-endpoints.yaml`).
pub const EXFIL_PACK: &str = "exfil-endpoints";

/// What `openmoat doctor` and `openmoat status` say about request rules when
/// the host sandboxes send traffic to `openmoat proxy` (`(ok, text)`, a
/// `false` one a warning): a `requests:` host the pinned CA does not cover,
/// with `openmoat proxy ca init` as the fix, and a CA without the
/// `exfil-endpoints` pack, with the command that installs it.
pub fn status_lines(home: &Home, policy: &Policy) -> Vec<(bool, String)> {
    let Some(cert) = pinned_cert(home) else {
        return Vec::new();
    };
    let mut lines = Vec::new();
    let hosts = request_hosts(policy);
    if !hosts.is_empty() {
        let tls = crate::key_file::read(&key_path(home))
            .ok()
            .and_then(|key| Tls::new(&cert, &key, &Roots::System, &[]).ok());
        let uncovered: Vec<&str> = hosts
            .iter()
            .filter(|h| !tls.as_ref().is_some_and(|t| t.covers(h)))
            .map(String::as_str)
            .collect();
        if uncovered.is_empty() {
            lines.push((
                true,
                format!("request rules: the proxy CA covers {}", hosts.join(", ")),
            ));
        } else {
            lines.push((
                false,
                format!(
                    "request rules: the proxy CA does not cover {}, so the proxy refuses their \
                     connections (`requests_untrusted`); run `openmoat proxy ca init` in a \
                     terminal",
                    uncovered.join(", ")
                ),
            ));
        }
    }
    // The pack reaches the proxy only for hosts the person's own policy has
    // the proxy hold, so it is worth naming only then.
    let installed = crate::packs::Packs::load(&home.packs_path())
        .is_ok_and(|packs| packs.packs.contains_key(EXFIL_PACK));
    if !installed && !hosts.is_empty() {
        lines.push((
            false,
            format!(
                "request rules: a proxy CA exists, but the `{EXFIL_PACK}` pack is not installed, \
                 so the proxy holds none of its endpoint rules for {}; install it signed by \
                 whoever distributes it: `openmoat policy install {EXFIL_PACK}.yaml`",
                hosts.join(", ")
            ),
        ));
    }
    lines
}

/// The standalone proxy's termination for `policy`'s `requests:` hosts
/// (ADR-062): the CA, when one is pinned, intact and covers each of them, and
/// what to say at start-up. Without one, the proxy cannot terminate them and
/// `requests_untrusted` decides their connections.
pub fn load_for_requests(home: &Home, policy: &Policy) -> (Option<Tls>, Option<String>) {
    let hosts = request_hosts(policy);
    if hosts.is_empty() {
        return (None, None);
    }
    let untrusted = match policy.requests_untrusted() {
        openmoat_core::RequestsUntrusted::Refuse => "refused",
        openmoat_core::RequestsUntrusted::Relay => "relayed unread",
    };
    let pinned = Lock::load(&home.lock_path())
        .is_ok_and(|lock| files(home).iter().all(|f| lock.pins(f) && f.is_file()));
    let loaded = if pinned {
        std::fs::read_to_string(cert_path(home))
            .map_err(anyhow::Error::from)
            .and_then(|cert| Ok((cert, crate::key_file::read(&key_path(home))?)))
            .and_then(|(cert, key)| Ok(Tls::new(&cert, &key, &Roots::System, &hosts)?))
    } else {
        Err(anyhow::Error::msg("there is no pinned proxy CA yet"))
    };
    match loaded {
        Ok(tls) => (
            Some(tls),
            Some(format!(
                "moat proxy: note: {} have request rules: HTTPS there is read for the sessions \
                 that received the proxy CA (from their agent's session-start hook); the \
                 connections of other sessions are {untrusted} (`requests_untrusted`)",
                hosts.join(", ")
            )),
        ),
        Err(why) => (
            None,
            Some(format!(
                "moat proxy: WARNING: {} have request rules, but {why:#}: run `openmoat proxy ca \
                 init` in a terminal (again, when a host was added since); until then their \
                 connections are {untrusted} (`requests_untrusted`)",
                hosts.join(", ")
            )),
        ),
    }
}

/// `YYYY-MM-DD` of `ts_ms`, in UTC.
fn date(ts_ms: i64) -> String {
    crate::time::rfc3339(ts_ms)[..10].to_owned()
}

/// The text of `ca.pem`: what it is, for a person who opens it, then the
/// certificate. PEM readers skip text outside the block (RFC 7468 ยง2).
pub fn cert_text(ca: &CaFiles, hosts: &[String], now_ms: i64) -> String {
    format!(
        "# OpenMoat proxy CA, made by `openmoat proxy ca init` on {}\n\
         # valid until {}, and only for: {}\n\
         # trusted only by the commands `openmoat run` starts (ADR-043), and those of a \
         session given its per-session trust files (ADR-062)\n{}",
        date(now_ms),
        date(now_ms + CA_VALID_DAYS * MS_PER_DAY),
        hosts.join(", "),
        ca.cert_pem
    )
}

/// The `valid until` date `cert_text` wrote, if the file has one.
pub fn valid_until(text: &str) -> Option<&str> {
    text.lines()
        .find_map(|l| l.strip_prefix("# valid until "))
        .and_then(|rest| rest.get(..10))
}

/// The run's termination: the proxy's [`Tls`], and the certificate the
/// agent's clients trust.
pub struct Loaded {
    pub tls: Tls,
    pub cert_pem: String,
    /// Said on standard error before the agent starts: the CA expires soon.
    pub notice: Option<String>,
}

/// The CA for `policy`'s terminated hosts; `None` when no secret says
/// `tls: terminate`. Refused unless both files are pinned (the caller has
/// checked the lock for drift) and the CA covers every terminated host today.
pub fn load(home: &Home, policy: &Policy) -> Result<Option<Loaded>> {
    let hosts = terminated_hosts(policy);
    if hosts.is_empty() {
        return Ok(None);
    }
    let again = "run `openmoat proxy ca init` in a terminal";
    let lock = Lock::load(&home.lock_path())?;
    if !files(home).iter().all(|f| lock.pins(f) && f.is_file()) {
        bail!(
            "TLS to {} is terminated (`tls: terminate`, or `requests:` without `hook_only`), but \
             there is no pinned proxy CA yet: {again}",
            hosts.join(", ")
        );
    }
    let cert = std::fs::read_to_string(cert_path(home))
        .with_context(|| format!("reading {}", cert_path(home).display()))?;
    // Refused when others may read or replace it (`key_file::read`).
    let key = crate::key_file::read(&key_path(home))?;
    let tls = Tls::new(&cert, &key, &Roots::System, &hosts).with_context(|| {
        format!(
            "the proxy CA cannot be used for {} (a host added since it was made needs a new \
             one); {again}",
            hosts.join(", ")
        )
    })?;
    let now = crate::time::now_ms();
    let notice = valid_until(&cert)
        .filter(|until| *until <= date(now + EXPIRY_NOTICE_DAYS * MS_PER_DAY).as_str())
        .map(|until| {
            format!("moat run: the proxy CA expires on {until}; {again} to make a new one")
        });
    Ok(Some(Loaded {
        tls,
        cert_pem: cert,
        notice,
    }))
}

#[cfg(test)]
mod tests;