727 lines
25 KiB
Rust
727 lines
25 KiB
Rust
//! Tool policy for headless runs. hx in `-p` mode never prompts (no permission hook = every tool call is
|
|
//! allowed), so the allowlist is enforced here, twice: `orch guard` runs as an hx extension and blocks a call
|
|
//! before it executes; orch re-checks every `tool_call` event in the NDJSON stream and kills the run, which
|
|
//! also catches a dead guard (hx treats a dead or slow extension as "continue").
|
|
//!
|
|
//! Allowlist entries: `TOOL` (any call of that tool; `*` = every tool) or `bash:PATTERN` (glob, `*` only).
|
|
//! A PATTERN matches only simple commands (no `; & | < > $ ( ) { } \` newline backslash), whose path-like words
|
|
//! must stay inside the worktree or `read_roots`. Hard rules apply to every allowed call: no `git push`
|
|
//! (publishing is the sink's job), no secret-looking paths, file tools stay in the worktree (reads may also
|
|
//! use `read_roots`), writes never touch `.git` or `.hx` (guard config).
|
|
//! Not enforceable with hx' `claude_cli` provider: the `claude` binary runs its own tools, invisible to hx' event
|
|
//! bus. `run::execute` refuses such a run up front (see `report::provider_mode`) instead of running it unguarded.
|
|
//! ponytail: plain `bash` is not confined (a shell cannot be parsed reliably); use `sandbox = true` for that.
|
|
|
|
use anyhow::{Result, bail};
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::{Value, json};
|
|
use std::io::{BufRead, Write};
|
|
use std::path::{Component, Path, PathBuf};
|
|
|
|
pub const MARK: &str = "# orch-guard (generated, do not edit)";
|
|
pub const PREFIX: &str = "orch-guard:";
|
|
/// Block reason of a soft deny under `on_deny = "continue"`: the run goes on, orch only counts it.
|
|
pub const SOFT_PREFIX: &str = "orch-guard-soft:";
|
|
|
|
#[derive(Serialize, Deserialize, Clone, Debug)]
|
|
pub struct Policy {
|
|
pub run: String,
|
|
pub allow: Vec<String>,
|
|
/// Canonical path of the run's worktree.
|
|
pub worktree: PathBuf,
|
|
pub read_roots: Vec<PathBuf>,
|
|
pub audit: PathBuf,
|
|
/// `on_deny = "continue"`: soft denies are answered to the agent instead of ending the run.
|
|
#[serde(default)]
|
|
pub soft_continue: bool,
|
|
}
|
|
|
|
#[derive(Debug, PartialEq)]
|
|
pub enum Decision {
|
|
Allow(String),
|
|
/// Not in the allowlist: with `on_deny = "continue"` the agent gets the reason and works on.
|
|
Deny(String),
|
|
/// Never negotiable: credentials, outside the worktree, `git push`, `.git`/`.hx`. Ends the run.
|
|
Hard(String),
|
|
}
|
|
|
|
impl Decision {
|
|
pub fn deny_reason(&self) -> Option<&str> {
|
|
match self {
|
|
Decision::Deny(w) | Decision::Hard(w) => Some(w),
|
|
Decision::Allow(_) => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// `*` matches any run of characters (including none); everything else is literal.
|
|
pub fn glob(pat: &str, s: &str) -> bool {
|
|
let (p, s): (Vec<char>, Vec<char>) = (pat.chars().collect(), s.chars().collect());
|
|
let (mut i, mut j, mut star, mut mark) = (0, 0, None, 0);
|
|
while j < s.len() {
|
|
if i < p.len() && p[i] == '*' {
|
|
star = Some(i);
|
|
mark = j;
|
|
i += 1;
|
|
} else if i < p.len() && p[i] == s[j] {
|
|
i += 1;
|
|
j += 1;
|
|
} else if let Some(st) = star {
|
|
i = st + 1;
|
|
mark += 1;
|
|
j = mark;
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
p[i..].iter().all(|&c| c == '*')
|
|
}
|
|
|
|
/// Validates one profile entry.
|
|
pub fn check_entry(e: &str) -> Result<()> {
|
|
let (tool, pat) = match e.split_once(':') {
|
|
Some((t, p)) => (t, Some(p)),
|
|
None => (e, None),
|
|
};
|
|
if tool.is_empty() || tool.contains(char::is_whitespace) {
|
|
bail!("bad allow entry {e:?}");
|
|
}
|
|
if pat.is_some_and(|p| p.is_empty()) || (pat.is_some() && !tool.eq_ignore_ascii_case("bash")) {
|
|
bail!("allow entry {e:?}: only `bash:PATTERN` takes a pattern");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Credentials by name: reading them is never part of a coding task.
|
|
pub fn secret(path: &str) -> bool {
|
|
let comps: Vec<&str> = path.trim_matches(['"', '\'']).split('/').collect();
|
|
let name = comps.last().copied().unwrap_or_default();
|
|
comps
|
|
.iter()
|
|
.any(|c| matches!(*c, ".ssh" | ".aws" | ".gnupg"))
|
|
|| name.starts_with(".env")
|
|
|| name.starts_with("id_rsa")
|
|
|| name.starts_with("id_ed25519")
|
|
|| name.starts_with("credentials")
|
|
|| matches!(
|
|
name,
|
|
".netrc" | ".git-credentials" | "auth.json" | "mcp-auth.json"
|
|
)
|
|
|| name.ends_with(".pem")
|
|
|| name.ends_with(".key")
|
|
}
|
|
|
|
/// Lexical normalization plus symlink resolution of the deepest existing ancestor.
|
|
fn resolve(base: &Path, p: &str) -> PathBuf {
|
|
let mut out = if Path::new(p).is_absolute() {
|
|
PathBuf::new()
|
|
} else {
|
|
base.to_path_buf()
|
|
};
|
|
for c in Path::new(p).components() {
|
|
match c {
|
|
Component::ParentDir => {
|
|
out.pop();
|
|
}
|
|
Component::CurDir => {}
|
|
c => out.push(c.as_os_str()),
|
|
}
|
|
}
|
|
let (mut cur, mut tail) = (out.clone(), vec![]);
|
|
loop {
|
|
if let Ok(mut c) = cur.canonicalize() {
|
|
c.extend(tail.iter().rev());
|
|
return c;
|
|
}
|
|
match cur.file_name().map(|n| n.to_owned()) {
|
|
Some(n) => {
|
|
tail.push(n);
|
|
cur.pop();
|
|
}
|
|
None => return out,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Allowlist entry `readonly`: bash commands that only look. Spelled out in code instead of glob patterns because
|
|
/// the dangerous part is the flags (`find -exec`, `rg --pre`, `sort -o`, `fd -x`), which a pattern cannot see.
|
|
pub const READONLY: &str = "readonly";
|
|
const READONLY_CMDS: &[&str] = &[
|
|
"ls", "cat", "head", "tail", "wc", "grep", "rg", "fd", "find", "pwd", "echo", "stat", "file",
|
|
"du", "df", "which", "tree", "diff", "sort", "cut", "nl", "tr", "jq", "basename", "dirname",
|
|
];
|
|
const READONLY_GIT: &[&str] = &[
|
|
"status",
|
|
"diff",
|
|
"log",
|
|
"show",
|
|
"blame",
|
|
"ls-files",
|
|
"rev-parse",
|
|
];
|
|
/// Flags that run a program or write a file, per command (`*` = any command).
|
|
const RUN_OR_WRITE_FLAGS: &[(&str, &[&str])] = &[
|
|
(
|
|
"find",
|
|
&[
|
|
"-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf",
|
|
"-fls",
|
|
],
|
|
),
|
|
("fd", &["-x", "-X", "--exec", "--exec-batch"]),
|
|
("rg", &["--pre", "--pre-glob"]),
|
|
("sort", &["-o", "--output", "--compress-program"]),
|
|
("tree", &["-o"]),
|
|
(
|
|
"git",
|
|
&[
|
|
"--output",
|
|
"--ext-diff",
|
|
"--textconv",
|
|
"-O",
|
|
"--open-files-in-pager",
|
|
],
|
|
),
|
|
];
|
|
|
|
/// Ok when `cmd` is one simple command from the read-only set without a flag that runs or writes anything.
|
|
pub fn readonly_cmd(cmd: &str) -> Result<(), String> {
|
|
if !simple(cmd) {
|
|
return Err("not a simple command".into());
|
|
}
|
|
let words: Vec<&str> = cmd.split_whitespace().collect();
|
|
let Some(first) = words.first().copied() else {
|
|
return Err("empty".into());
|
|
};
|
|
let ok = if first == "git" {
|
|
words.get(1).is_some_and(|s| READONLY_GIT.contains(s))
|
|
} else {
|
|
READONLY_CMDS.contains(&first)
|
|
};
|
|
if !ok {
|
|
return Err(format!("`{first}` is not a read-only command"));
|
|
}
|
|
let bad = RUN_OR_WRITE_FLAGS
|
|
.iter()
|
|
.filter(|(c, _)| *c == first)
|
|
.flat_map(|(_, f)| f.iter());
|
|
for w in &words[1..] {
|
|
let flag = w.split_once('=').map_or(*w, |(f, _)| f);
|
|
if bad
|
|
.clone()
|
|
.any(|f| *f == flag || (f.len() > 2 && f.starts_with("--") && flag == *f))
|
|
{
|
|
return Err(format!("flag `{flag}` runs or writes"));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn simple(cmd: &str) -> bool {
|
|
!cmd.contains([
|
|
'\n', ';', '&', '|', '`', '$', '<', '>', '(', ')', '{', '}', '\\',
|
|
])
|
|
}
|
|
|
|
fn mentions_git_push(cmd: &str) -> bool {
|
|
let words: Vec<&str> = cmd
|
|
.split(|c: char| c.is_whitespace() || ";&|()`".contains(c))
|
|
.filter(|w| !w.is_empty())
|
|
.collect();
|
|
words.iter().any(|w| w.rsplit('/').next() == Some("git")) && words.contains(&"push")
|
|
}
|
|
|
|
impl Policy {
|
|
fn inside(&self, p: &Path, roots: &[&Path]) -> bool {
|
|
roots.iter().any(|r| p.starts_with(r))
|
|
}
|
|
|
|
fn roots(&self) -> Vec<&Path> {
|
|
std::iter::once(self.worktree.as_path())
|
|
.chain(self.read_roots.iter().map(|r| r.as_path()))
|
|
.collect()
|
|
}
|
|
|
|
pub fn decide(&self, tool: &str, args: &Value) -> Decision {
|
|
use Decision::*;
|
|
let t = tool.to_lowercase();
|
|
let s = |k: &str| args[k].as_str().unwrap_or_default();
|
|
let mut why = None;
|
|
if t == "bash" {
|
|
let cmd = if s("command").is_empty() {
|
|
s("cmd")
|
|
} else {
|
|
s("command")
|
|
};
|
|
if mentions_git_push(cmd) {
|
|
return Hard("git push is done by the sink, not the agent".into());
|
|
}
|
|
if cmd.split_whitespace().any(secret) {
|
|
return Hard("command touches a secret-looking path".into());
|
|
}
|
|
let free = self
|
|
.allow
|
|
.iter()
|
|
.any(|a| a == "*" || a.eq_ignore_ascii_case("bash"));
|
|
if free {
|
|
why = Some("bash".to_string());
|
|
} else {
|
|
let hit = self
|
|
.allow
|
|
.iter()
|
|
.find_map(|a| {
|
|
let (tl, pat) = a.split_once(':')?;
|
|
(tl.eq_ignore_ascii_case("bash") && simple(cmd) && glob(pat, cmd.trim()))
|
|
.then(|| a.clone())
|
|
})
|
|
.or_else(|| {
|
|
let on = self.allow.iter().any(|a| a.eq_ignore_ascii_case(READONLY));
|
|
(on && readonly_cmd(cmd).is_ok()).then(|| READONLY.to_string())
|
|
});
|
|
let Some(hit) = hit else {
|
|
return Deny(format!("bash `{}` is not in the allowlist", short(cmd)));
|
|
};
|
|
for w in cmd.split_whitespace() {
|
|
let w = w.trim_matches(['"', '\'']);
|
|
let w = w.split_once('=').map_or(w, |(_, v)| v);
|
|
if w.starts_with('/') || w.starts_with('~') || w.contains("..") {
|
|
let ok = !w.starts_with('~')
|
|
&& self.inside(&resolve(&self.worktree, w), &self.roots());
|
|
if !ok {
|
|
return Hard(format!("path `{w}` is outside the worktree"));
|
|
}
|
|
}
|
|
}
|
|
why = Some(hit);
|
|
}
|
|
} else if let Some(path) = ["path", "file_path"]
|
|
.iter()
|
|
.map(|k| s(k))
|
|
.find(|p| !p.is_empty())
|
|
{
|
|
let write = matches!(t.as_str(), "write" | "edit");
|
|
let r = resolve(&self.worktree, path);
|
|
if secret(&r.to_string_lossy()) {
|
|
return Hard(format!("`{path}` looks like a credential file"));
|
|
}
|
|
if write {
|
|
let rel = r.strip_prefix(&self.worktree);
|
|
if rel.is_err() {
|
|
return Hard(format!("write outside the worktree: `{path}`"));
|
|
}
|
|
if rel.is_ok_and(|x| {
|
|
x.components()
|
|
.any(|c| matches!(c.as_os_str().to_str(), Some(".git" | ".hx")))
|
|
}) {
|
|
return Hard(format!("`{path}` is guard/git metadata"));
|
|
}
|
|
} else if !self.inside(&r, &self.roots()) {
|
|
return Hard(format!("read outside the worktree: `{path}`"));
|
|
}
|
|
}
|
|
if why.is_none() {
|
|
why = self
|
|
.allow
|
|
.iter()
|
|
.find(|a| a.as_str() == "*" || a.eq_ignore_ascii_case(&t))
|
|
.cloned();
|
|
}
|
|
match why {
|
|
Some(w) => Allow(w),
|
|
None => Deny(format!("tool `{tool}` is not in the allowlist")),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn short(s: &str) -> String {
|
|
s.chars().take(80).collect()
|
|
}
|
|
|
|
/// Append-only JSONL audit trail (O_APPEND; lines stay under PIPE_BUF so concurrent writers do not interleave).
|
|
pub fn audit(path: &Path, run: &str, ev: &str, detail: Value) {
|
|
let mut line =
|
|
json!({"ts": crate::state::now(), "run": run, "ev": ev, "detail": detail}).to_string();
|
|
line.truncate(3900);
|
|
line.push('\n');
|
|
if let Some(d) = path.parent() {
|
|
let _ = std::fs::create_dir_all(d);
|
|
}
|
|
if let Ok(mut f) = std::fs::OpenOptions::new()
|
|
.create(true)
|
|
.append(true)
|
|
.open(path)
|
|
{
|
|
let _ = f.write_all(line.as_bytes());
|
|
}
|
|
}
|
|
|
|
pub fn audit_path() -> PathBuf {
|
|
crate::state_dir().join("audit.log")
|
|
}
|
|
|
|
fn policy_path(run: &str) -> PathBuf {
|
|
crate::state_dir()
|
|
.join("policies")
|
|
.join(format!("{run}.json"))
|
|
}
|
|
|
|
/// Writes the policy and the worktree's `.hx/config.toml` that starts the guard. Rewritten before every
|
|
/// attempt, so an agent that edited it is healed. Refuses to touch a config that is not ours.
|
|
pub fn install(
|
|
run: &str,
|
|
wt: &Path,
|
|
allow: &[String],
|
|
read_roots: &[PathBuf],
|
|
soft_continue: bool,
|
|
) -> Result<Policy> {
|
|
let pol = Policy {
|
|
run: run.into(),
|
|
allow: allow.to_vec(),
|
|
worktree: wt.canonicalize()?,
|
|
read_roots: read_roots
|
|
.iter()
|
|
.map(|r| resolve(Path::new("/"), &r.to_string_lossy()))
|
|
.collect(),
|
|
audit: audit_path(),
|
|
soft_continue,
|
|
};
|
|
let pp = policy_path(run);
|
|
std::fs::create_dir_all(pp.parent().unwrap())?;
|
|
std::fs::write(&pp, serde_json::to_vec(&pol)?)?;
|
|
let cfg = wt.join(".hx/config.toml");
|
|
if let Ok(old) = std::fs::read_to_string(&cfg)
|
|
&& !old.starts_with(MARK)
|
|
{
|
|
bail!(
|
|
"{} exists in the repo; orch cannot install its guard next to it",
|
|
cfg.display()
|
|
);
|
|
}
|
|
std::fs::create_dir_all(cfg.parent().unwrap())?;
|
|
let exe = std::env::current_exe()?.to_string_lossy().into_owned();
|
|
// `permissions = "extensions-only"` (hx#182): in claude_cli mode a question is allowed only while a LIVE
|
|
// `tool_call` extension guards it, so a dead or slow guard denies instead of "continue". hx ignores the value
|
|
// for the direct provider's `-p` path, where orch's stream check is the second line of defence.
|
|
let ext = toml::to_string(&json!({"permissions": "extensions-only", "extensions": [{
|
|
"command": [exe, "guard", pp.to_string_lossy()], "timeout_secs": 10}]}))?;
|
|
std::fs::write(cfg, format!("{MARK}\n{ext}"))?;
|
|
Ok(pol)
|
|
}
|
|
|
|
/// Removes the guard config after an attempt (it must never end up in the commit).
|
|
pub fn uninstall(wt: &Path) {
|
|
let cfg = wt.join(".hx/config.toml");
|
|
if std::fs::read_to_string(&cfg).is_ok_and(|s| s.starts_with(MARK)) {
|
|
let _ = std::fs::remove_file(&cfg);
|
|
let _ = std::fs::remove_dir(wt.join(".hx")); // only if empty
|
|
}
|
|
}
|
|
|
|
/// `orch guard POLICY.json`: hx extension, JSON-RPC over stdio (see hx README, "Extensions").
|
|
pub fn guard(policy_file: &Path) -> Result<()> {
|
|
let pol: Policy = serde_json::from_slice(&std::fs::read(policy_file)?)?;
|
|
let mut out = std::io::stdout().lock();
|
|
for line in std::io::stdin().lock().lines() {
|
|
let m: Value = serde_json::from_str(&line?)?;
|
|
let Some(id) = m.get("id") else { continue };
|
|
let result = match m["method"].as_str() {
|
|
Some("initialize") => Ok(json!({"subscribe": ["tool_call"], "tools": []})),
|
|
Some("event") => {
|
|
let e = &m["params"]["event"];
|
|
let tool = e["name"].as_str().unwrap_or_default();
|
|
let d = pol.decide(tool, &e["args"]);
|
|
let (act, why, extra) = match &d {
|
|
Decision::Allow(w) => ("allow", w.clone(), json!({"action": "continue"})),
|
|
Decision::Deny(w) => (
|
|
"deny",
|
|
w.clone(),
|
|
// soft: the agent reads the reason and picks another way (orch does not kill the run)
|
|
json!({"action": "block", "reason": if pol.soft_continue {
|
|
format!("{SOFT_PREFIX} {w}. Use another way (allowed: read-only commands, project tests).")
|
|
} else {
|
|
format!("{PREFIX} {w}")
|
|
}}),
|
|
),
|
|
Decision::Hard(w) => (
|
|
"deny",
|
|
w.clone(),
|
|
json!({"action": "block", "reason": format!("{PREFIX} {w}")}),
|
|
),
|
|
};
|
|
audit(
|
|
&pol.audit,
|
|
&pol.run,
|
|
"tool",
|
|
json!({"tool": tool, "decision": act, "why": why, "args": e["args"],
|
|
"hard": matches!(d, Decision::Hard(_))}),
|
|
);
|
|
Ok(extra)
|
|
}
|
|
_ => Err("unknown method"),
|
|
};
|
|
let msg = match result {
|
|
Ok(r) => json!({"jsonrpc": "2.0", "id": id, "result": r}),
|
|
Err(e) => json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601, "message": e}}),
|
|
};
|
|
writeln!(out, "{msg}")?;
|
|
out.flush()?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use Decision::*;
|
|
|
|
/// Denied, soft or hard.
|
|
fn denied(d: Decision) -> bool {
|
|
d.deny_reason().is_some()
|
|
}
|
|
|
|
fn pol(allow: &[&str]) -> Policy {
|
|
let d = std::env::temp_dir().join(format!("orch-pol-{}", std::process::id()));
|
|
std::fs::create_dir_all(d.join("wt/sub")).unwrap();
|
|
Policy {
|
|
run: "r".into(),
|
|
allow: allow.iter().map(|s| s.to_string()).collect(),
|
|
worktree: d.join("wt").canonicalize().unwrap(),
|
|
read_roots: vec![],
|
|
audit: d.join("audit"),
|
|
soft_continue: false,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn globbing() {
|
|
assert!(glob("cargo test*", "cargo test -p x"));
|
|
assert!(glob("*", ""));
|
|
assert!(glob("a*c*e", "abcde") && !glob("a*c*e", "abcdf"));
|
|
assert!(!glob("cargo test", "cargo test -p x"));
|
|
}
|
|
|
|
#[test]
|
|
fn entries() {
|
|
assert!(check_entry("read").is_ok() && check_entry("bash:cargo *").is_ok());
|
|
assert!(check_entry("readonly").is_ok() && check_entry("readonly:x").is_err());
|
|
assert!(
|
|
check_entry("").is_err()
|
|
&& check_entry("read:x").is_err()
|
|
&& check_entry("bash:").is_err()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn tools_and_allowlist() {
|
|
let p = pol(&["read", "Edit"]);
|
|
assert!(matches!(
|
|
p.decide("Read", &json!({"path": "a.rs"})),
|
|
Allow(_)
|
|
));
|
|
assert!(matches!(
|
|
p.decide("edit", &json!({"path": "sub/a.rs"})),
|
|
Allow(_)
|
|
));
|
|
assert!(
|
|
denied(p.decide("write", &json!({"path": "a.rs"}))),
|
|
"not in allowlist"
|
|
);
|
|
assert!(denied(p.decide("bash", &json!({"command": "ls"}))));
|
|
assert!(matches!(
|
|
pol(&["*"]).decide("anything", &json!({})),
|
|
Allow(_)
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn paths_and_secrets() {
|
|
let p = pol(&["*"]);
|
|
let w = p.worktree.to_string_lossy().to_string();
|
|
for bad in [
|
|
"../x",
|
|
"/etc/passwd",
|
|
"sub/../../x",
|
|
".env",
|
|
"sub/auth.json",
|
|
] {
|
|
assert!(denied(p.decide("write", &json!({"path": bad}))), "{bad}");
|
|
}
|
|
for bad in [
|
|
"/etc/passwd",
|
|
"../x",
|
|
"/home/other/.hx/auth.json",
|
|
".ssh/id_rsa",
|
|
] {
|
|
assert!(denied(p.decide("read", &json!({"path": bad}))), "{bad}");
|
|
}
|
|
for bad in [
|
|
".git/hooks/pre-commit",
|
|
".hx/config.toml",
|
|
"sub/../.hx/config.toml",
|
|
] {
|
|
assert!(denied(p.decide("edit", &json!({"path": bad}))), "{bad}");
|
|
}
|
|
assert!(matches!(
|
|
p.decide("read", &json!({"path": format!("{w}/a")})),
|
|
Allow(_)
|
|
));
|
|
// symlink out of the worktree is resolved
|
|
std::os::unix::fs::symlink("/etc", p.worktree.join("lnk")).ok();
|
|
assert!(denied(p.decide("read", &json!({"path": "lnk/passwd"}))));
|
|
}
|
|
|
|
#[test]
|
|
fn hard_and_soft_denies() {
|
|
let p = pol(&["read", "bash:cargo *"]);
|
|
let d = |t: &str, a: Value| p.decide(t, &a);
|
|
// soft: simply not allowed, the agent may try something else
|
|
assert!(matches!(d("bash", json!({"command": "ls"})), Deny(_)));
|
|
assert!(matches!(
|
|
d("bash", json!({"command": "python3 -c 'print(1)'"})),
|
|
Deny(_)
|
|
));
|
|
assert!(matches!(d("write", json!({"path": "a.rs"})), Deny(_)));
|
|
assert!(matches!(d("Foo", json!({})), Deny(_)));
|
|
// hard: never negotiable
|
|
assert!(matches!(d("read", json!({"path": ".env"})), Hard(_)));
|
|
assert!(matches!(d("read", json!({"path": "/etc/passwd"})), Hard(_)));
|
|
assert!(matches!(
|
|
d("bash", json!({"command": "git push origin main"})),
|
|
Hard(_)
|
|
));
|
|
assert!(matches!(d("bash", json!({"command": "cat .env"})), Hard(_)));
|
|
assert!(matches!(
|
|
d("bash", json!({"command": "cargo run ../../x"})),
|
|
Hard(_)
|
|
));
|
|
let w = pol(&["*"]);
|
|
assert!(matches!(
|
|
w.decide("edit", &json!({"path": ".hx/config.toml"})),
|
|
Hard(_)
|
|
));
|
|
assert!(matches!(
|
|
w.decide("write", &json!({"path": "../x"})),
|
|
Hard(_)
|
|
));
|
|
assert!(
|
|
Deny("x".into()).deny_reason().is_some() && Allow("x".into()).deny_reason().is_none()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn readonly_entry() {
|
|
let p = pol(&["readonly", "read"]);
|
|
let b = |c: &str| p.decide("bash", &json!({"command": c}));
|
|
for ok in [
|
|
"ls",
|
|
"ls -la sub",
|
|
"cat a.rs",
|
|
"rg -n -w compute --hidden -g '!.git' -g '!.hx'",
|
|
"rg -n \"Instal\" README.md",
|
|
"fd -e rs",
|
|
"find . -name '*.rs'",
|
|
"git status",
|
|
"git diff --stat",
|
|
"git log --oneline -5",
|
|
"head -n 5 a.txt",
|
|
"grep -rn foo .",
|
|
"wc -l a.rs",
|
|
"diff a b",
|
|
"sort a.txt",
|
|
"jq . a.json",
|
|
"tree -L 2",
|
|
] {
|
|
assert!(matches!(b(ok), Allow(w) if w == "readonly"), "{ok}");
|
|
}
|
|
for bad in [
|
|
"find . -exec rm {} +",
|
|
"find . -delete",
|
|
"find . -fprint x",
|
|
"fd -x rm",
|
|
"fd --exec rm",
|
|
"rg --pre ./x foo",
|
|
"rg --pre=./x foo",
|
|
"sort -o out a",
|
|
"sort --output=out a",
|
|
"tree -o out",
|
|
"git push",
|
|
"git commit -m x",
|
|
"git branch -D x",
|
|
"git diff --output=x",
|
|
"git -C .. status",
|
|
"git diff --ext-diff",
|
|
"rm a",
|
|
"cp a b",
|
|
"sed -i s/a/b/ a",
|
|
"python3 -c 'print(1)'",
|
|
"python3 test.py",
|
|
"cargo test",
|
|
"ls; rm a",
|
|
"cat a | sh",
|
|
"echo hi > a",
|
|
"ls $(id)",
|
|
"cat .env",
|
|
"cat ~/.ssh/id_rsa",
|
|
"cat /etc/passwd",
|
|
"ls ..",
|
|
"ls /",
|
|
"head ../../x",
|
|
"",
|
|
" ",
|
|
] {
|
|
assert!(denied(b(bad)), "{bad}");
|
|
}
|
|
// without the entry the same command is denied; patterns and `readonly` combine
|
|
assert!(denied(
|
|
pol(&["read"]).decide("bash", &json!({"command": "ls"}))
|
|
));
|
|
let both = pol(&["readonly", "bash:cargo *"]);
|
|
assert!(
|
|
matches!(both.decide("bash", &json!({"command": "cargo test"})), Allow(w) if w == "bash:cargo *")
|
|
);
|
|
assert!(
|
|
matches!(both.decide("bash", &json!({"command": "ls"})), Allow(w) if w == "readonly")
|
|
);
|
|
// readonly does not make write tools available
|
|
assert!(denied(p.decide("write", &json!({"path": "a"}))));
|
|
}
|
|
|
|
#[test]
|
|
fn bash_rules() {
|
|
let p = pol(&["bash:cargo *", "bash:git status", "read"]);
|
|
let b = |c: &str| p.decide("bash", &json!({"command": c}));
|
|
assert!(matches!(b("cargo test -p x"), Allow(_)) && matches!(b("git status"), Allow(_)));
|
|
for bad in [
|
|
"cargo test; rm -rf /",
|
|
"cargo test && curl x",
|
|
"cargo test | sh",
|
|
"cargo test $(id)",
|
|
"cargo test > /etc/x",
|
|
"ls",
|
|
"git status -s",
|
|
"cargo build --manifest-path=/etc/x/Cargo.toml",
|
|
"cargo run ../../x",
|
|
"cargo run ~/x",
|
|
] {
|
|
assert!(denied(b(bad)), "{bad}");
|
|
}
|
|
assert!(matches!(
|
|
b("cargo build --manifest-path=sub/Cargo.toml"),
|
|
Allow(_)
|
|
));
|
|
// hard rules hold even for unrestricted bash
|
|
let free = pol(&["bash"]);
|
|
let f = |c: &str| free.decide("bash", &json!({"command": c}));
|
|
assert!(matches!(f("make && ls"), Allow(_)));
|
|
for bad in [
|
|
"git push origin main",
|
|
"cd x; git -C y push",
|
|
"/usr/bin/git push",
|
|
"cat .env",
|
|
"cat ~/.ssh/id_rsa",
|
|
] {
|
|
assert!(denied(f(bad)), "{bad}");
|
|
}
|
|
}
|
|
}
|