O5: safety - allowlist guard, credential separation, audit log (#13)

This commit was merged in pull request #13.
This commit is contained in:
hermes committed 2026-11-13 00:09:31 +00:00
1 parent 06662a085f
commit bea07e82bb
9 files changed
+890 -29

No files matched your search

+108 -1
View File
@@ -2,6 +2,7 @@
use crate::adapter::Task;
use crate::lock;
use crate::policy::{self, Decision, Policy};
use crate::profile::Profile;
use crate::state::{Run, Status, gate_log_path, kill_group, log_path, now};
use anyhow::{Context, Result, bail};
@@ -79,6 +80,21 @@ fn fail(r: &mut Run, reason: impl Into<String>) -> Result<()> {
r.save()
}
/// Environment hx gets: a fixed base plus the profile's `env` patterns. `HX_HOME` only when the profile has no
/// own `home` (otherwise it would point back at another identity).
pub fn hx_env(vars: impl Iterator<Item = (String, String)>, p: &Profile) -> Vec<(String, String)> {
const BASE: &[&str] = &[
"PATH", "HOME", "USER", "LOGNAME", "SHELL", "TERM", "LANG", "LC_*", "TMPDIR", "CARGO_*",
"RUST*", "NIX_*",
];
vars.filter(|(k, _)| {
BASE.iter().any(|b| policy::glob(b, k))
|| p.env.iter().any(|b| policy::glob(b, k))
|| (k == "HX_HOME" && p.home.is_none())
})
.collect()
}
/// hx surfaces provider rejections as `api 429: ...`; also match the usual wording.
fn is_rate_limit(reason: &str) -> bool {
let r = reason.to_lowercase();
@@ -144,7 +160,20 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> {
r.status = Status::Running;
r.save()?;
writeln!(log, "\n--- attempt {}", r.attempts)?;
let reason = run_hx(r, p, &prompt, session.as_deref(), &mut log)?;
// rewritten before every attempt: an agent that tampered with it is healed
let pol = match p
.allow
.as_ref()
.map(|a| policy::install(&r.id, &r.worktree, a, &p.read_roots))
{
Some(Err(e)) => return fail(r, format!("setup: {e:#}")),
Some(Ok(pol)) => Some(pol),
None => None,
};
let reason = run_hx(r, p, &prompt, session.as_deref(), pol.as_ref(), &mut log)?;
if pol.is_some() {
policy::uninstall(&r.worktree);
}
if !git(&r.worktree, &["status", "--porcelain"])?
.trim()
.is_empty()
@@ -158,6 +187,13 @@ pub fn execute(r: &mut Run, p: &Profile, task: &Task) -> Result<()> {
lock::pause(&account, until)?; // every full window pauses the account, even after a clean run
}
if let Some(reason) = reason {
if reason.starts_with("policy:") {
// the agent wanted something the profile does not allow: a human decides
r.status = Status::NeedsHuman;
r.reason = Some(reason);
r.ended = Some(now());
return r.save();
}
if r.quota_until.is_some() || is_rate_limit(&reason) {
// provider said no: not the task's fault. Pause the account and hand the task back.
lock::pause(&account, r.quota_until.unwrap_or(now() + 900))?;
@@ -204,6 +240,7 @@ fn run_hx(
p: &Profile,
body: &str,
session: Option<&str>,
pol: Option<&Policy>,
log: &mut std::fs::File,
) -> Result<Option<String>> {
let mut parts = p.hx.split_whitespace();
@@ -221,6 +258,8 @@ fn run_hx(
if let Some(prov) = &p.provider {
cmd.args(["--provider", prov]);
}
// cleared environment: orch's own secrets and another profile's HX_HOME never reach the agent
cmd.env_clear().envs(hx_env(std::env::vars(), p));
if let Some(h) = &p.home {
cmd.env("HOME", h);
}
@@ -264,6 +303,29 @@ fn run_hx(
killed = Some("budget:turns".to_string());
}
}
Some("tool_call") if pol.is_some() => {
// second line of defence: hx treats a dead or slow guard as "continue"
let name = ev["name"].as_str().unwrap_or_default();
if let Decision::Deny(why) = pol.unwrap().decide(name, &ev["args"]) {
// the guard may not have logged yet (we read the event first): log it here too
policy::audit(
&policy::audit_path(),
&r.id,
"tool",
serde_json::json!({"tool": name, "decision": "deny", "why": why, "args": ev["args"], "by": "orch"}),
);
killed = Some(format!("policy: {why}"));
}
}
Some("tool_result")
if pol.is_some()
&& ev["is_error"] == true
&& ev["content"].to_string().contains(policy::PREFIX) =>
{
let c = ev["content"].as_str().unwrap_or_default();
let why = c.split_once(policy::PREFIX).map_or(c, |(_, w)| w.trim());
killed = Some(format!("policy: {why}"));
}
Some("stream") if ev["event"]["type"] == "quota" => {
let full: Vec<&Value> = ev["event"]["windows"]
.as_array()
@@ -326,3 +388,48 @@ fn run_hx(
_ => None,
})
}
#[cfg(test)]
mod env_tests {
use super::*;
fn vars(names: &[&str]) -> Vec<(String, String)> {
names.iter().map(|n| (n.to_string(), "v".into())).collect()
}
fn keys(p: &str, names: &[&str]) -> Vec<String> {
let p = Profile::parse(p).unwrap();
hx_env(vars(names).into_iter(), &p)
.into_iter()
.map(|(k, _)| k)
.collect()
}
#[test]
fn env_is_filtered() {
let all = [
"PATH",
"LC_ALL",
"CARGO_HOME",
"AWS_SECRET_ACCESS_KEY",
"GITEA_TOKEN",
"HX_HOME",
"HX_BASE_URL",
"ORCH_STATE_DIR",
];
assert_eq!(
keys("", &all),
["PATH", "LC_ALL", "CARGO_HOME", "HX_HOME"],
"HX_HOME passes without own home"
);
assert_eq!(
keys("home = \"/h\"", &all),
["PATH", "LC_ALL", "CARGO_HOME"],
"own home drops HX_HOME"
);
assert_eq!(
keys("env = [\"HX_BASE_URL\", \"GITEA_*\"]\nhome = \"/h\"", &all),
["PATH", "LC_ALL", "CARGO_HOME", "GITEA_TOKEN", "HX_BASE_URL"]
);
}
}