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.
use super::*;
use crate::approvals::Grant;

fn write(dir: &Path, name: &str, contents: &str) -> PathBuf {
    let path = dir.join(name);
    fs::write(&path, contents).unwrap();
    path
}

#[test]
fn pin_verify_and_detect_drift() {
    let dir = tempfile::tempdir().unwrap();
    let policy = write(dir.path(), "policy.yaml", "version: 1\n");
    let hook = write(dir.path(), "settings.json", "{}");
    let absent = dir.path().join("never-written.json");

    let lock = Lock::pin(
        Path::new("/x/moat"),
        &[policy.clone(), hook.clone(), absent],
    )
    .unwrap();
    assert_eq!(lock.entries.len(), 2, "absent files are not pinned");
    assert!(lock.entries.keys().any(|k| k.ends_with("policy.yaml")));
    assert_eq!(lock.verify(), Vec::<Drift>::new());

    fs::write(&policy, "version: 1\nallow: []\n").unwrap();
    fs::remove_file(&hook).unwrap();
    let drift = lock.verify();
    assert_eq!(drift.len(), 2);
    assert!(
        drift
            .iter()
            .any(|d| matches!(d, Drift::Modified(p) if p.ends_with("policy.yaml")))
    );
    assert!(
        drift
            .iter()
            .any(|d| matches!(d, Drift::Missing(p) if p.ends_with("settings.json")))
    );
}

#[cfg(unix)]
#[test]
fn replacing_a_pinned_file_with_a_symlink_is_drift() {
    let dir = tempfile::tempdir().unwrap();
    let policy = write(dir.path(), "policy.yaml", "version: 1\n");
    let other = write(dir.path(), "other.yaml", "version: 1\n");
    let lock = Lock::pin(Path::new("/x/moat"), std::slice::from_ref(&policy)).unwrap();

    fs::remove_file(&policy).unwrap();
    std::os::unix::fs::symlink(&other, &policy).unwrap();
    assert!(lock.pins(&policy), "a symlinked leaf keeps its identity");
    assert!(
        matches!(lock.verify_one(&policy), Some(Drift::Modified(p)) if p.ends_with("policy.yaml")),
        "same bytes through a link must still count as modified"
    );

    fs::remove_file(&policy).unwrap();
    assert!(matches!(lock.verify_one(&policy), Some(Drift::Missing(_))));
}

#[test]
fn round_trips_through_disk_and_rejects_other_versions() {
    let dir = tempfile::tempdir().unwrap();
    let policy = write(dir.path(), "policy.yaml", "version: 1\n");
    let lock_path = dir.path().join("policy.lock");
    let lock = Lock::pin(Path::new("/x/moat"), &[policy]).unwrap();
    lock.save(&lock_path).unwrap();
    assert_eq!(Lock::load(&lock_path).unwrap(), lock);

    fs::write(
        &lock_path,
        r#"{"version":9,"pinned_at_ms":0,"binary":"","entries":{}}"#,
    )
    .unwrap();
    assert!(
        Lock::load(&lock_path)
            .unwrap_err()
            .to_string()
            .contains("version 9")
    );
}

#[test]
fn the_policy_bytes_checked_are_the_bytes_parsed() {
    let dir = tempfile::tempdir().unwrap();
    let pinned = openmoat_core::DEFAULT_POLICY;
    let policy = write(dir.path(), "policy.yaml", pinned);
    let lock = Lock::pin(Path::new("/x/moat"), std::slice::from_ref(&policy)).unwrap();
    let (drift, kept) = lock.verify_keeping(std::slice::from_ref(&policy), &[]);
    assert_eq!(drift, Vec::<Drift>::new());
    let kept = kept
        .get(&policy)
        .expect("an intact pinned file keeps the bytes it was checked by")
        .to_vec();
    // The file changes after the check: what is parsed is still what matched the pin.
    fs::write(&policy, "version: 1\n").unwrap();
    assert_eq!(kept, pinned.as_bytes());
    let parsed = crate::context::parse_policy(kept, &policy).unwrap();
    assert_eq!(parsed, openmoat_core::Policy::parse(pinned).unwrap());
    // Drifted bytes are never kept.
    let (drift, kept) = lock.verify_keeping(std::slice::from_ref(&policy), &[]);
    assert_eq!(drift.len(), 1);
    assert_eq!(kept.get(&policy), None);
}

#[test]
fn only_the_named_files_are_kept() {
    let dir = tempfile::tempdir().unwrap();
    let policy = write(dir.path(), "policy.yaml", "version: 1\n");
    let other = dir.path().join("policy.lock");
    let lock = Lock::pin(Path::new("/x/moat"), std::slice::from_ref(&policy)).unwrap();
    assert_eq!(lock.verify_keeping(&[], &[]), (Vec::new(), Kept::default()));
    assert_eq!(
        lock.verify_keeping(std::slice::from_ref(&other), &[]),
        (Vec::new(), Kept::default()),
        "a file the lock does not pin is read from disk as before"
    );
}

#[test]
fn the_files_of_a_named_directory_are_kept_under_its_path() {
    let dir = tempfile::tempdir().unwrap();
    let packs = dir.path().join("packs");
    fs::create_dir(&packs).unwrap();
    let pack = write(&packs, "team.yaml", "version: 1\n");
    let elsewhere = write(dir.path(), "team.yaml", "version: 1\n");
    let lock = Lock::pin(Path::new("/x/moat"), &[pack.clone(), elsewhere.clone()]).unwrap();
    let (drift, kept) = lock.verify_keeping(&[], std::slice::from_ref(&packs));
    assert_eq!(drift, Vec::<Drift>::new());
    fs::write(&pack, "version: 1\ndeny: []\n").unwrap();
    assert_eq!(kept.get(&pack), Some(b"version: 1\n".as_slice()));
    assert_eq!(
        kept.get(&elsewhere),
        None,
        "only files directly in the directory"
    );
}

/// A person who re-pins over a deleted state file (`openmoat doctor --accept`
/// over "approvals.json is missing") pins its absence: a file planted there
/// later is drift, not trusted unpinned from disk.
#[test]
fn a_state_file_missing_at_a_re_pin_cannot_be_planted_later() {
    let dir = tempfile::tempdir().unwrap();
    let home = Home::at(dir.path().join("state"));
    write_private(&home.policy_path(), b"version: 1\n").unwrap();
    let binary = Path::new("/x/moat");
    Lock::pin(binary, &[home.policy_path()])
        .unwrap()
        .save(&home.lock_path())
        .unwrap();
    let lock = repin(&home, binary, HookPins::Keep).unwrap();
    assert!(lock.verify().is_empty(), "{:?}", lock.verify());
    let planted = [
        (home.grants_path(), r#"{"version":2,"entries":[]}"#),
        (home.overlay_path(), "version: 1\nallow: []\n"),
        (home.hosts_path(), r#"{"version":1,"dirs":{}}"#),
        (
            home.environment_path(),
            r#"{"version":1,"captured_at_ms":1,"path":["/x"],"programs":{}}"#,
        ),
    ];
    for (path, text) in planted {
        write_private(&path, text.as_bytes()).unwrap();
        assert!(
            lock.verify()
                .iter()
                .any(|d| matches!(d, Drift::Modified(p) if p.ends_with(path.file_name().unwrap()))),
            "{} was planted after the re-pin",
            path.display()
        );
        fs::remove_file(&path).unwrap();
    }
    // Missing as pinned is no drift (`policy.d`, created above, stays).
    fs::remove_dir(home.overlay_path().parent().unwrap()).unwrap();
    let (drift, kept) = verify_state(&home, &lock);
    assert!(drift.is_empty(), "{drift:?}");
    assert_eq!(
        crate::approvals::Grants::load_in(&kept).unwrap().entries,
        Vec::<Grant>::new()
    );
}

/// The guidance for a hook file pinned elsewhere names every host's
/// directory variable, not only the first hosts'.
#[test]
fn a_hook_pinned_elsewhere_names_every_hosts_variable() {
    let moved = HookPinGap::moved_by();
    for variable in [
        "CLAUDE_CONFIG_DIR",
        "CODEX_HOME",
        "CURSOR_CONFIG_DIR",
        "COPILOT_HOME",
        "PI_CODING_AGENT_DIR",
        "GEMINI_CLI_HOME",
    ] {
        assert!(moved.contains(variable), "{moved}");
    }
}

/// A Codex `config.toml` is pinned by the part OpenMoat owns, never whole as
/// well: a whole pin would deny every call after Codex's next edit of it.
#[test]
fn a_file_is_never_pinned_whole_and_by_its_codex_profile() {
    let dir = tempfile::tempdir().unwrap();
    let policy = write(dir.path(), "policy.yaml", "version: 1\n");
    let config = write(dir.path(), "config.toml", "model = \"x\"\n");
    let mut lock = Lock::pin(Path::new("/x/moat"), std::slice::from_ref(&policy)).unwrap();
    lock.codex_profiles.insert(key(&config), "00".to_owned());
    assert_eq!(lock.pinned_twice(), None);
    lock.save(&dir.path().join("policy.lock")).unwrap();

    lock.entries.insert(key(&config), "00".to_owned());
    assert_eq!(lock.pinned_twice(), Some(key(&config).as_str()));
}

#[cfg(debug_assertions)]
#[test]
#[should_panic(expected = "pinned whole and by the part of it OpenMoat owns")]
fn saving_a_lock_that_pins_a_file_twice_is_a_bug() {
    let dir = tempfile::tempdir().unwrap();
    let config = write(dir.path(), "config.toml", "model = \"x\"\n");
    let mut lock = Lock::pin(Path::new("/x/moat"), std::slice::from_ref(&config)).unwrap();
    lock.codex_profiles.insert(key(&config), "00".to_owned());
    let _ = lock.save(&dir.path().join("policy.lock"));
}

/// A state directory whose record puts every host's configuration in its own
/// temp directory, with OpenMoat's hook installed for Claude Code and Codex.
fn two_agents_installed() -> (tempfile::TempDir, Home, PathBuf) {
    let dir = tempfile::tempdir().unwrap();
    let home = Home::at(dir.path().join("state"));
    let binary = dir.path().join("bin/guard");
    fs::create_dir_all(binary.parent().unwrap()).unwrap();
    fs::write(&binary, "#!/bin/sh\n").unwrap();
    let mut recorded = crate::install::Recorded::default();
    for host in Host::ALL {
        let cfg = dir.path().join("agents").join(host.id());
        fs::create_dir_all(&cfg).unwrap();
        recorded.dirs.insert(host.id().to_owned(), cfg);
    }
    recorded.save(&home).unwrap();
    for host in [Host::ClaudeCode, Host::Codex] {
        HostConfig::for_host(&home, host)
            .unwrap()
            .install(&home, &binary, false)
            .unwrap();
    }
    (dir, home, binary)
}

fn pins_hook_of(lock: &Lock, home: &Home, host: Host) -> bool {
    let hook = HostConfig::for_host(home, host).unwrap().settings_path;
    lock.entries.contains_key(&key(&hook))
}

/// `init --hooks-only` writes the chosen agents' hooks; without a lock to keep,
/// or with one that cannot be read, it still pins every installed hook, so
/// another agent's hook file cannot change unseen.
#[test]
fn a_selected_re_pin_without_a_readable_lock_pins_every_installed_hook() {
    let (_dir, home, binary) = two_agents_installed();
    let codex = [Host::Codex];

    let lock = repin(&home, &binary, HookPins::Selected(&codex)).unwrap();
    assert!(pins_hook_of(&lock, &home, Host::Codex));
    assert!(pins_hook_of(&lock, &home, Host::ClaudeCode), "no lock yet");

    fs::write(home.lock_path(), "not a lock").unwrap();
    let lock = repin(&home, &binary, HookPins::Selected(&codex)).unwrap();
    assert!(
        pins_hook_of(&lock, &home, Host::ClaudeCode),
        "unreadable lock"
    );
}

/// Over a readable lock, a selected re-pin keeps what the lock pinned and adds
/// only the chosen agents' hooks.
#[test]
fn a_selected_re_pin_over_a_lock_adds_only_the_chosen_hooks() {
    let (_dir, home, binary) = two_agents_installed();
    Lock::pin(&binary, &[home.policy_path()])
        .unwrap()
        .save(&home.lock_path())
        .unwrap();
    let lock = repin(&home, &binary, HookPins::Selected(&[Host::Codex])).unwrap();
    assert!(pins_hook_of(&lock, &home, Host::Codex));
    assert!(!pins_hook_of(&lock, &home, Host::ClaudeCode));
}