use crate::cli::Output;
use crate::hook::{Decision, Request};
use crate::policy::Policy;
use std::path::Path;
pub(crate) fn guard(stdin: &str) -> Output {
let req = crate::hook::request(stdin);
let root = req.cwd.clone().unwrap_or_else(|| ".".to_owned());
match crate::policy::read(Path::new(&root)) {
Ok(p) => decide_or_refuse(&p, &req, Path::new(&root)),
Err(e) => Output::usage(format!("itok: {e}\n")),
}
}
fn decide_or_refuse(p: &Policy, req: &Request, root: &Path) -> Output {
let unhonored = crate::policy::unhonored(p);
if let Some(first) = unhonored.first() {
return Output::usage(format!("itok: {first}\n"));
}
let (d, why) = decide(p, req, root);
Output::ok(crate::hook::response(d, &why))
}
fn decide(p: &Policy, req: &Request, root: &Path) -> (Decision, String) {
if p.is_empty() {
return (Decision::Allow, String::new()); }
if let Some(path) = req.path.as_deref()
&& pinned(p, root, path)
{
return (Decision::Allow, String::new()); }
over_budget(p, req, root)
.map_or((Decision::Allow, String::new()), |m| (Decision::Deny, m))
}
fn pinned(p: &Policy, root: &Path, path: &str) -> bool {
let rel = relative(root, path);
p.pins.iter().any(|pin| crate::glob::matches(pin, &rel))
}
fn over_budget(p: &Policy, req: &Request, root: &Path) -> Option<String> {
let cost = req.path.as_deref().map(|f| cost_of(root, f))?;
let path = req.path.as_deref()?;
let rel = relative(root, path);
tool_breach(p, req, cost).or_else(|| glob_breach(p, &rel, cost))
}
fn tool_breach(p: &Policy, req: &Request, cost: u64) -> Option<String> {
let b = p.tools.iter().find(|b| b.what == req.tool)?;
(cost > b.tokens).then(|| {
format!(
"{} would add ~{cost} itok; tool `{}` is budgeted at {} (.context-policy). {ALTERNATIVE}",
req.path.as_deref().unwrap_or("this call"),
b.what,
b.tokens
)
})
}
fn glob_breach(p: &Policy, rel: &str, cost: u64) -> Option<String> {
let b = p
.budgets
.iter()
.find(|b| crate::glob::matches(&b.what, rel))?;
(cost > b.tokens).then(|| {
format!(
"{rel} is ~{cost} itok; `{}` is budgeted at {} (.context-policy). {ALTERNATIVE}",
b.what, b.tokens
)
})
}
const ALTERNATIVE: &str = "Read a line range, narrow with `rg -m`, or bundle under budget with \
`itok fit --window N`.";
fn cost_of(root: &Path, path: &str) -> u64 {
let full = root.join(path);
let target = if full.exists() {
full
} else {
root.join(relative(root, path))
};
crate::walk::bytes(&target).map_or(0, |b| b.saturating_div(4))
}
fn relative(root: &Path, path: &str) -> String {
Path::new(path)
.strip_prefix(root)
.map_or_else(|_| path.to_owned(), |p| p.display().to_string())
}
#[cfg(test)]
mod tests {
use super::*;
fn req(tool: &str, path: Option<&str>, cwd: &str) -> Request {
Request {
tool: tool.to_owned(),
path: path.map(str::to_owned),
cwd: Some(cwd.to_owned()),
}
}
fn quoted(p: &std::path::Path) -> String {
format!("\"{}\"", crate::json::escape(&p.display().to_string()))
}
fn read_payload(root: &std::path::Path, file: &str) -> String {
format!(
r#"{{"tool_name":"Read","cwd":{},"tool_input":{{"file_path":"{file}"}}}}"#,
quoted(root)
)
}
fn policy(text: &str) -> Policy {
match crate::policy::parse(text) {
Ok(p) => p,
Err(e) => unreachable!("test policy must parse: {e}"),
}
}
fn repo(name: &str, bytes: usize) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("itok-guard-{name}"));
let _ = std::fs::create_dir_all(dir.join("src"));
let _ = std::fs::write(dir.join("src/big.rs"), "x".repeat(bytes));
dir
}
#[test]
fn an_empty_policy_allows_in_silence() {
let root = repo("empty", 400);
let (d, why) = decide(
&Policy::default(),
&req("Read", Some("src/big.rs"), "."),
&root,
);
assert_eq!(d, Decision::Allow);
assert!(why.is_empty(), "nothing to say");
}
#[test]
fn a_crossed_glob_budget_denies_and_names_an_alternative() {
let root = repo("glob", 4_000); let p = policy("budget src/**/*.rs 100\n");
let (d, why) = decide(&p, &req("Read", Some("src/big.rs"), "."), &root);
assert_eq!(d, Decision::Deny, "{why}");
assert!(why.contains("itok fit"), "names a cheaper route: {why}");
assert!(why.contains("src/**/*.rs"), "names the rule: {why}");
}
#[test]
fn a_budget_that_is_not_crossed_allows() {
let root = repo("under", 40); let p = policy("budget src/**/*.rs 100\n");
let (d, why) = decide(&p, &req("Read", Some("src/big.rs"), "."), &root);
assert_eq!(d, Decision::Allow);
assert!(why.is_empty());
}
#[test]
fn a_pin_beats_a_budget_the_path_would_break() {
let root = repo("pin", 4_000);
let p = policy("budget src/**/*.rs 100\npin src/big.rs\n");
let (d, _) = decide(&p, &req("Read", Some("src/big.rs"), "."), &root);
assert_eq!(d, Decision::Allow, "a pin is absolute");
}
#[test]
fn a_tool_budget_matches_the_tool_by_name() {
let root = repo("tool", 4_000);
let p = policy("tool Read 100\n");
let (denied, _) =
decide(&p, &req("Read", Some("src/big.rs"), "."), &root);
assert_eq!(denied, Decision::Deny);
let (other, _) =
decide(&p, &req("Edit", Some("src/big.rs"), "."), &root);
assert_eq!(other, Decision::Allow, "a different tool is untouched");
}
#[test]
fn a_call_without_a_path_is_allowed() {
let root = repo("nopath", 4_000);
let p = policy("budget src/**/*.rs 100\n");
let (d, _) = decide(&p, &req("Bash", None, "."), &root);
assert_eq!(d, Decision::Allow);
}
#[test]
fn a_policy_with_unhonored_rules_refuses_to_decide() {
let out = decide_or_refuse(
&policy("fuse warn 70\n"),
&req("Read", None, "."),
Path::new("."),
);
assert_eq!(out.code, 2, "the adapter failed, it did not decide");
assert!(out.err.contains("T44"), "{}", out.err);
assert!(out.out.is_empty(), "no decision on stdout");
}
#[test]
fn a_malformed_policy_is_not_an_allow() {
let dir = std::env::temp_dir().join("itok-guard-bad");
let _ = std::fs::create_dir_all(&dir);
let _ = std::fs::write(dir.join(".context-policy"), "budget oops\n");
let payload =
format!(r#"{{"tool_name":"Read","cwd":{}}}"#, quoted(&dir));
let out = guard(&payload);
assert_eq!(out.code, 2, "{:?}", out.out);
assert!(out.err.contains(".context-policy:1:"), "{}", out.err);
}
#[test]
fn a_decision_is_json_on_stdout_at_exit_zero() {
let root = repo("json", 4_000);
let _ = std::fs::write(
root.join(".context-policy"),
"budget src/**/*.rs 100\n",
);
let out = guard(&read_payload(&root, "src/big.rs"));
assert_eq!(out.code, 0, "a denial is still a successful adapter run");
assert!(
out.out.contains("\"permissionDecision\":\"deny\""),
"{}",
out.out
);
assert!(out.err.is_empty(), "nothing on stderr");
}
}