diff --git a/.claude/agent-guard.toml b/.claude/agent-guard.toml deleted file mode 100644 index d951121..0000000 --- a/.claude/agent-guard.toml +++ /dev/null @@ -1,146 +0,0 @@ -# Agent Guard Configuration -# Schema Version: 1.0 -# Location: .claude/agent-guard.toml (project) or ~/.claude/agent-guard.toml (user) -# -# This file configures which destructive command patterns are detected by the -# agent guard system. Each pattern can be enabled/disabled and have custom -# denial messages. -# -# Configuration hierarchy: -# 1. ./.claude/agent-guard.toml (project-level overrides) -# 2. ~/.claude/agent-guard.toml (user-level defaults) -# 3. Embedded defaults (built into binary) - -schema_version = "1.0" - -[metadata] -source = "meta" -version = "0.1.0" -description = "Default agent guard patterns for meta CLI" - -# Pattern Definitions -# Each pattern uses a namespaced ID (source.category.name) for forward compatibility -# with multi-tool pattern registration. - -[[patterns]] -id = "meta.git.force_push" -priority = 100 -enabled = true -matcher = { type = "regex", pattern = 'git\s+push.*(--force|-f)\b' } -validator = { type = "not_contains", value = "--force-with-lease" } -message = """ -git push --force in a multi-repo workspace can overwrite history across \ -multiple repos. Safer alternatives: -- git push --force-with-lease (checks for upstream changes) -- meta --include exec -- git push --force (target one repo) -- git fetch, then git branch backup/ origin/ to keep the remote tip -""" - -[[patterns]] -id = "meta.git.reset_hard" -priority = 100 -enabled = true -matcher = { type = "regex", pattern = 'git\s+reset.*--hard\b' } -message = """ -git reset --hard destroys uncommitted work. In a multi-repo workspace, \ -this can silently discard changes across repos. Safer alternatives: -- Commit, or git stash push -u -m , to keep the work first -- git reflog to find and go back to an earlier commit (commits only) -- Target a specific repo: cd && git reset --hard -""" - -[[patterns]] -id = "meta.git.clean_force" -priority = 100 -enabled = true -matcher = { type = "regex", pattern = 'git\s+clean' } -validator = { type = "flags_present", command = "clean", flags = ["f", "d"] } -message = """ -git clean -fd removes untracked files and directories permanently. \ -In a multi-repo workspace, this affects all repos. Safer alternatives: -- git clean -nd (dry run — preview what would be removed) -- meta --include exec -- git clean -fd (target specific repos) -- git stash push -u -m to keep untracked files instead -""" - -[[patterns]] -id = "meta.git.checkout_dot" -priority = 100 -enabled = true -# Matches "git checkout ." or "git checkout -- ." -matcher = { type = "regex", pattern = 'git\s+checkout\s+(--\s+)?\.(\s|$)' } -message = """ -git checkout . reverts all modified files. In a multi-repo workspace, \ -ensure you are in the correct repo directory. Safer alternatives: -- git checkout -- (target specific files) -- meta --include exec -- git checkout . (target one repo) -- git stash push -m to keep the changes instead -""" - -[[patterns]] -id = "meta.git.branch_force_delete" -priority = 100 -enabled = true -matcher = { type = "regex", pattern = 'git\s+branch.*\s+-D\b' } -message = """ -git branch -D force-deletes branches, potentially losing unmerged work. \ -In a multi-repo workspace, this can affect coordination between repos. Safer alternatives: -- git branch -d (safe delete — only works if merged) -- git branch -v to check merge status first -- git branch backup/ first to keep its commits -- meta --include exec -- git branch -D (target specific repos) -""" - -[[patterns]] -id = "meta.git.stash_drop" -priority = 100 -enabled = true -matcher = { type = "regex", pattern = 'git\s+stash\s+drop\b' } -message = """ -git stash drop permanently removes a stash entry. \ -For AI agents working across repos, this could discard important work. Safer alternatives: -- git stash list to review what will be dropped -- git stash show to inspect contents first -- git stash apply instead of pop (preserves the stash) -""" - -[[patterns]] -id = "meta.git.stash_clear" -priority = 100 -enabled = true -matcher = { type = "regex", pattern = 'git\s+stash\s+clear\b' } -message = """ -git stash clear removes ALL stash entries permanently. \ -In a multi-repo workspace, this could discard important work across repos. Safer alternatives: -- git stash list to review what will be cleared -- git stash drop to remove specific entries one at a time -- meta --include exec -- git stash clear (target specific repos) -""" - -[[patterns]] -id = "meta.rm.dangerous_paths" -priority = 100 -enabled = true -matcher = { type = "regex", pattern = 'rm\s+' } -validator = { type = "all_of", validators = [{ type = "flags_present", command = "rm", flags = ["r", "f"] }, { type = "args_match_any", command = "rm", values = [".", "..", "/", "~", "$HOME", ".meta", ".meta.yaml", ".meta.yml", "*", "./*", "../*", "./"] }] } -message = """ -rm -rf on dangerous paths could destroy repo roots or workspace data. \ -In a multi-repo workspace, this is especially dangerous. Safer alternatives: -- Remove specific files instead of entire directories -- meta --dry-run exec -- to preview operations -- Commit and push work you want to keep first -""" - -# Examples: Project-specific overrides -# -# Disable a pattern: -# [[patterns]] -# id = "meta.git.checkout_dot" -# enabled = false -# -# Custom message: -# [[patterns]] -# id = "meta.git.force_push" -# enabled = true -# matcher = { type = "regex", pattern = 'git\s+push.*\s+(--force|-f)\b(?!-with-lease)' } -# message = "Our team policy: never force push to shared branches!" diff --git a/README.md b/README.md index abaa0f2..f9f92f0 100644 --- a/README.md +++ b/README.md @@ -52,17 +52,21 @@ echo '{"tool_input":{"command":"git status"}}' | agent guard } ``` -**Blocked patterns** (configurable via `.claude/agent-guard.toml`): +**What it refuses.** The guard splits the command line the way a shell does (quotes, `;`, `&&`, `|`, `&`, newlines, `$(…)`, backticks, heredocs, `((…))` and `$((…))` as opaque arithmetic, `case` outside `$(…)`, function bodies), unwraps `sudo`, `doas`, `env` (and the words of `env -S`), `nohup`, `nice`, `time`, `timeout`, `setsid`, `stdbuf`, `command`, `exec`, `sh -c` (also `bash`, `zsh`, `dash`, `ksh`), `eval`, `find -exec`, `meta [options] exec` and `meta [options] git`, skips git's global options (`git -C dir`, `-c k=v`, `--git-dir`), and reads options the way git and getopt do: `-Df` is `-D -f`, an option's value is not read as flags (`-ekeep`, `-o x`), and any unique prefix of a long option counts (`--ha` is `--hard`). An option that makes a command safe (`--dry-run`, `--staged`) counts only spelled in full or as its letter, and not after its `--no-…`. When a shell, `eval` or `source` appears anywhere in a command, or it runs `.`, every heredoc and here-string in it is judged as a script, wherever it is piped. So every spelling of these is refused: -| Pattern | What it blocks | Safe alternative | +| Rule id | What it blocks | Safe alternative | |---------|----------------|------------------| -| `git push --force` | Force push | `--force-with-lease` | -| `git reset --hard` | Hard reset | `git stash` or commit first; `git reflog` | -| `git clean -fd` | Clean force | `git clean -nd` (dry run) | -| `git checkout .` | Checkout all | Specific files | -| `git branch -D` | Force delete branch | `git branch -d` | -| `git stash drop/clear` | Drop stashes | `git stash list` first | -| `rm -rf .` / `*` / `.meta` | Dangerous rm | Specific paths | +| `meta.git.force_push` | `git push` with `-f`/`--force` (even next to `--force-with-lease`), a `+refspec`, `--mirror`, `--delete` or `:branch` | `--force-with-lease` on its own | +| `meta.git.reset_hard` | `git reset --hard` | `git stash` or commit first; `git reflog` | +| `meta.git.clean_force` | `git clean` with both `-f` and `-d` | `git clean -nd` (dry run) | +| `meta.git.checkout_dot` | `git checkout .` (any pathspec meaning everything), `checkout -f`, `restore .` (except `--staged` alone), `switch -f` | Specific files | +| `meta.git.branch_force_delete` | `git branch -D`, or `-d` with `-f` | `git branch -d` | +| `meta.git.stash_drop`, `meta.git.stash_clear` | `git stash drop` / `clear` | `git stash list` first | +| `meta.rm.dangerous_paths` | `rm -r` (with or without `-f`) of `.`, `..`, `/`, `~`, `$HOME`, `*`, `.*`; of `.meta`, `.meta.yaml` or `.meta.yml`; of a path with a `.git` part (`.git/*`), where a dot-glob such as `.*` or `.g*` counts as both; of a folder holding `.git`, looked up on disk from the hook's `cwd` and from every folder a `cd` or `pushd` anywhere in the command names (from the `cwd` or from another such folder; relative paths are not looked up when the payload has no `cwd`); any `rm -r` in a command whose `cd` names a folder it can't know (`cd "$DIR"`, `cd $(…)`, `cd -`, a glob); `find` with any argument that has a `.git` part, in any case (`find .git`, `-iname .GIT`), and `-delete` or `-exec rm -r {}` | Specific paths | + +Text that only mentions a command (`echo "git push --force"`, a commit message) is not refused. Hook input it cannot read, a Bash call without a command string, a broken policy file and `git -c alias.…` are refused. So is a command it does not model exactly, with "cannot parse this command": an unclosed quote or heredoc; substitutions, `sh -c` or `find -exec` nested deeper than 4 levels; `case` inside `$(…)`; a quote, backslash, backtick, `$(`, `<<` or newline inside `((…))` or `$((…))` (so `$((1<<2))` too); an option it does not know for one of the wrappers above, or a lone `-` (`env - cmd`); an `env -S` string with a quote, a backslash or a leading `-`, or a second `-S`; a shell option starting with `+` (`bash +o posix -c …`). Because a heredoc is judged as a script whenever a shell appears, one that is not valid shell (prose with an apostrophe) is refused in such a command. + +**What it can't see.** It judges the text of the command, so it is a safety net, not a sandbox. It does not see: values of variables (`$cmd`, `git reset $flag`, `CDPATH`) or strings `eval` builds at run time; other interpreters (`python -c`, `node -e`) and scripts; git aliases stored in config or set through `GIT_CONFIG_*`; `xargs`, `git submodule foreach`, and `find -delete` on anything but `.git`; `.git` deeper than one level below an `rm -r` target (`rm -rf services` with `services/api/.git`); brace expansion in an `rm` path (`rm -rf {.git,x}`); symlinks (`rm -rf link`); a folder changed by `env -C`, `sudo -D`/`-R` or `git -C` before an `rm`; stdin that is not a heredoc or here-string (`printf … | sh`); and the Write, Edit and MCP tools. If the hook's stdout is closed, the deny it writes is lost and the call goes ahead (Rust's standard library treats writing to a closed stdout as success, and the crate forbids `unsafe`); Claude Code always connects a pipe. ### `agent score` @@ -90,30 +94,27 @@ agent score --json ## Configuration -### Guard patterns +### Guard rules -Create `.claude/agent-guard.toml` in your project to customize patterns: +The built-in rules are in the binary. `~/.claude/agent-guard.toml` and then the project's `.claude/agent-guard.toml` change them by id; they never replace them. This file turns one built-in off and adds one rule: ```toml -schema_version = "1.0" - -[[patterns]] -id = "custom.my_pattern" -priority = 100 -enabled = true -matcher = { type = "regex", pattern = 'dangerous-command' } -message = "This command is blocked because..." +schema_version = "2" + +[[rules]] # turn a built-in off +id = "meta.git.checkout_dot" +enabled = false + +[[rules]] # add one +id = "custom.no_tf_destroy" +deny = '^terraform destroy\b' +message = "Run terraform destroy yourself." ``` -**Pattern options:** -- `id`: Unique identifier (namespaced recommended) -- `priority`: Higher = checked first (default: 100) -- `enabled`: Toggle pattern on/off -- `matcher`: Currently only `regex` type supported -- `validator`: Optional additional checks (`not_contains`, `flags_present`, `args_match_any`, `all_of`, `any_of`, `not`) -- `message`: Shown to Claude when command is blocked +- A built-in id may set only `enabled` and `message`. +- A new id needs `deny`, a regex matched against each command's words after unwrapping (`sudo git -C x push` is matched as `git push`), and `message`. -The guard reads the project file, else `~/.claude/agent-guard.toml`, else its built-in defaults. A file that exists but cannot be read or parsed denies every Bash command, with a reason naming the file, until it is fixed or removed. +A file that exists but cannot be read, is not `schema_version = "2"` (a schema 1.0 `[[patterns]]` file must be rewritten as above), has an unknown key, a bad regex, a `deny` on a built-in id, a repeated id, or a new id without `deny` and `message` denies every Bash command, with a reason naming the file, until it is fixed or removed. ## Development diff --git a/src/guard.rs b/src/guard.rs index 1355227..1e176d8 100644 --- a/src/guard.rs +++ b/src/guard.rs @@ -2,395 +2,216 @@ //! Claude Code PreToolUse hooks. //! //! Reads hook JSON from stdin, evaluates the tool input, and returns structured -//! JSON to block or allow execution. No LLM evaluation — pure pattern matching -//! in Rust. +//! JSON to block or allow execution. No LLM evaluation: the command is lexed +//! (`crate::shell`) and judged by its arguments, in Rust. //! //! Two modes: -//! - **Bash guard**: Evaluates Bash commands for destructive patterns (always active). +//! - **Bash guard**: Evaluates Bash commands for destructive operations (always active). //! - **File path sandbox**: When `AGENT_ALLOWED_PATHS` is set, restricts Edit/Write/Read/ //! NotebookEdit tools to allowed directory prefixes. Inactive in interactive mode. //! -//! Configuration is loaded from `.claude/agent-guard.toml` (project-level) or -//! `~/.claude/agent-guard.toml` (user-level), with embedded defaults as fallback. +//! The built-in rules live in this file. `~/.claude/agent-guard.toml` and then +//! `.claude/agent-guard.toml` can turn them off, reword them, or add regex +//! rules, by id. Anything the guard cannot read or parse denies the command. -use anyhow::{Context, Result}; +use anyhow::{bail, Context, Result}; use regex::Regex; -use serde::{Deserialize, Serialize}; -use std::io::Read; -use std::path::Path; -use std::sync::OnceLock; - -// ── Configuration ─────────────────────────────────────── - -/// Default agent guard configuration embedded in the binary. -const DEFAULT_CONFIG: &str = include_str!("../.claude/agent-guard.toml"); - -/// Compiled patterns loaded once per process, or the load error that denies -/// every command while the policy file is broken. -static CACHED_PATTERNS: OnceLock, String>> = OnceLock::new(); - -/// Agent guard configuration structure (versioned schema). -/// Fields `schema_version` and `metadata` are deserialized for forward compat -/// and future schema migration; only `patterns` is actively used today. -#[derive(Debug, Clone, Deserialize)] -#[allow(dead_code)] -pub struct GuardConfig { - #[serde(default = "default_schema_version")] - pub schema_version: String, - #[serde(default)] - pub metadata: Option, - #[serde(default)] - pub patterns: Vec, -} - -/// Metadata about the configuration file (reserved for future tooling). -#[derive(Debug, Clone, Deserialize)] -#[allow(dead_code)] -pub struct ConfigMetadata { - pub source: String, - pub version: String, - pub description: Option, -} - -/// Pattern definition from configuration. -#[derive(Debug, Clone, Deserialize)] -pub struct PatternDefinition { - pub id: String, - #[serde(default = "default_priority")] - pub priority: u32, - #[serde(default = "default_enabled")] - pub enabled: bool, - pub matcher: MatcherConfig, - #[serde(default)] - pub validator: Option, - pub message: String, -} - -/// Matcher configuration (currently only regex, extensible for future types). -#[derive(Debug, Clone, Deserialize)] -#[serde(tag = "type")] -pub enum MatcherConfig { - #[serde(rename = "regex")] - Regex { pattern: String }, -} - -/// Validator configuration for additional pattern checks. -/// Validators are composable and can express complex logic without hardcoding. -#[derive(Debug, Clone, Deserialize)] -#[serde(tag = "type")] -pub enum ValidatorConfig { - /// Reject if segment contains a specific substring - #[serde(rename = "not_contains")] - NotContains { value: String }, - - /// Ensure all specified flags are present after a command - #[serde(rename = "flags_present")] - FlagsPresent { command: String, flags: Vec }, - - /// Check if any command arguments match values in a list - #[serde(rename = "args_match_any")] - ArgsMatchAny { - command: String, - values: Vec, - }, - - /// All sub-validators must pass - #[serde(rename = "all_of")] - AllOf { validators: Vec }, - - /// At least one sub-validator must pass - #[serde(rename = "any_of")] - AnyOf { validators: Vec }, - - /// Negate the result of a sub-validator - #[serde(rename = "not")] - Not { validator: Box }, -} - -/// Compiled pattern ready for evaluation. -/// Regex is compiled once during initialization and cached for the process lifetime. -struct CompiledPattern { +use serde::Deserialize; +use serde_json::Value; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; + +// ── Policy ────────────────────────────────────────────── + +/// The built-in rules: id, and the reason shown when it denies. +const BUILTINS: [(&str, &str); 8] = [ + ("meta.git.force_push", "git push with --force, -f, a +refspec, --mirror, --delete or :branch rewrites or deletes remote branches; commits it drops may exist nowhere else. Safer alternatives:\n- git push --force-with-lease (on its own, without --force) refuses if the remote moved\n- git fetch, then git branch backup/ origin/ to keep the remote tip"), + ("meta.git.reset_hard", "git reset --hard destroys uncommitted work. Safer alternatives:\n- Commit, or git stash push -u -m , to keep the work first\n- git reflog to find and go back to an earlier commit (commits only)"), + ("meta.git.clean_force", "git clean -fd removes untracked files and directories permanently. Safer alternatives:\n- git clean -nd (dry run: preview what would be removed)\n- git stash push -u -m to keep untracked files instead"), + ("meta.git.checkout_dot", "git checkout ., checkout -f, restore . and switch -f throw away every uncommitted change. Safer alternatives:\n- git checkout -- (target specific files)\n- git stash push -m to keep the changes instead"), + ("meta.git.branch_force_delete", "git branch -D force-deletes a branch, losing commits that are merged nowhere. Safer alternatives:\n- git branch -d (safe delete: only works if merged)\n- git branch -v to check merge status first\n- git branch backup/ first to keep its commits"), + ("meta.git.stash_drop", "git stash drop permanently removes a stash entry. Safer alternatives:\n- git stash list to review what will be dropped\n- git stash show to inspect contents first\n- git stash apply instead of pop (preserves the stash)"), + ("meta.git.stash_clear", "git stash clear removes ALL stash entries permanently. Safer alternatives:\n- git stash list to review what will be cleared\n- git stash drop to remove specific entries one at a time"), + ("meta.rm.dangerous_paths", "rm -r on ., .., /, ~, $HOME, *, .meta, a .git folder or a folder holding one destroys repos and the work in them. Safer alternatives:\n- Remove specific files or build folders instead\n- Commit and push work you want to keep first"), +]; + +/// How to write a policy file, for the error a bad one gives. +const POLICY_HELP: &str = "the guard reads schema_version = \"2\" with [[rules]] entries: \ +a built-in id (such as meta.git.checkout_dot) may set only enabled and message; a new id \ +needs deny = '' (matched against each command's words) and message. A schema 1.0 \ +[[patterns]] file must be rewritten that way (see the agent README)"; + +/// A rule in force: a built-in (no `deny`) or a policy file's regex rule. +struct Rule { id: String, - priority: u32, - regex: Regex, + enabled: bool, message: String, - validator: Option, -} - -fn default_schema_version() -> String { - "1.0".to_string() -} - -fn default_priority() -> u32 { - 100 + deny: Option, } -fn default_enabled() -> bool { - true +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PolicyFile { + #[serde(default)] + rules: Vec, } -// ── Validator Implementation ──────────────────────────── - -/// Execute a validator configuration against a command segment. -fn execute_validator(segment: &str, validator: &ValidatorConfig) -> bool { - match validator { - ValidatorConfig::NotContains { value } => !segment.contains(value.as_str()), - - ValidatorConfig::FlagsPresent { command, flags } => { - validate_flags_present(segment, command, flags) - } - - ValidatorConfig::ArgsMatchAny { command, values } => { - validate_args_match_any(segment, command, values) - } - - ValidatorConfig::AllOf { validators } => { - validators.iter().all(|v| execute_validator(segment, v)) - } - - ValidatorConfig::AnyOf { validators } => { - validators.iter().any(|v| execute_validator(segment, v)) - } - - ValidatorConfig::Not { validator } => !execute_validator(segment, validator), - } +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RuleEntry { + id: String, + enabled: Option, + message: Option, + deny: Option, } -/// Check if all specified flags are present after a command. -fn validate_flags_present(segment: &str, command: &str, required_flags: &[String]) -> bool { - let words: Vec<&str> = segment.split_whitespace().collect(); - let cmd_pos = match words.iter().position(|w| *w == command) { - Some(pos) => pos, - None => return false, - }; - - // Collect all flag characters after the command - let mut flag_chars = String::new(); - for word in &words[cmd_pos + 1..] { - if word.starts_with('-') && !word.starts_with("--") { - flag_chars.push_str(&word[1..]); // Strip leading '-' - } - } - - // Check that all required flags are present - required_flags +fn builtin_rules() -> Vec { + BUILTINS .iter() - .all(|flag| flag.chars().all(|c| flag_chars.contains(c))) + .map(|(id, message)| Rule { + id: id.to_string(), + enabled: true, + message: message.to_string(), + deny: None, + }) + .collect() } -/// Check if any arguments after a command match values in a list. -fn validate_args_match_any(segment: &str, command: &str, values: &[String]) -> bool { - let words: Vec<&str> = segment.split_whitespace().collect(); - let cmd_pos = match words.iter().position(|w| *w == command) { - Some(pos) => pos, - None => return false, - }; - - // Check arguments after the command (skip flags) - for word in &words[cmd_pos + 1..] { - if word.starts_with('-') { - continue; // Skip flags - } - - // Normalize path for comparison - let normalized = word.trim_end_matches('/'); - let normalized = if normalized.is_empty() { - word // Keep original if it becomes empty (like "/") - } else { - normalized +/// The built-ins, overridden by id by each of `paths` that exists, in order. +/// A file that exists but cannot be read or used is an error naming it. +fn load_policy(paths: &[PathBuf]) -> Result> { + let mut rules = builtin_rules(); + for path in paths { + let text = match std::fs::read_to_string(path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, + read => read.with_context(|| format!("cannot read guard policy {}", path.display()))?, }; - - if values.iter().any(|v| v == normalized || v == word) { - return true; - } + merge(&mut rules, &text) + .with_context(|| format!("invalid guard policy {}", path.display()))?; } - - false + Ok(rules) } -impl GuardConfig { - /// Load configuration from the hierarchy: project → user → embedded defaults. - /// - /// A missing file falls through to the next level; a file that exists but - /// cannot be read or parsed is an error naming its path. - pub fn load() -> Result { - if let Some(config) = Self::load_from_file(Path::new(".claude/agent-guard.toml"))? { - return Ok(config); +fn merge(rules: &mut Vec, text: &str) -> Result<()> { + let mut table: toml::Table = toml::from_str(text)?; + let version = table.remove("schema_version"); + if version.as_ref().and_then(toml::Value::as_str) != Some("2") { + bail!("{POLICY_HELP}"); + } + let file: PolicyFile = toml::Value::Table(table).try_into()?; + let mut seen = std::collections::HashSet::new(); + for entry in file.rules { + let id = entry.id; + if !seen.insert(id.clone()) { + bail!("rule {id} appears twice"); } - // No home directory means there is no user-level policy to read. - if let Some(home) = dirs::home_dir() { - if let Some(config) = Self::load_from_file(&home.join(".claude/agent-guard.toml"))? { - return Ok(config); + let deny = entry.deny.as_deref().map(Regex::new).transpose(); + let deny = deny.with_context(|| format!("rule {id}: bad deny regex"))?; + match rules.iter_mut().find(|r| r.id == id) { + Some(rule) if rule.deny.is_none() && deny.is_some() => { + bail!("rule {id} is built in: it may set only enabled and message") } - } - Self::load_from_embedded() - } - - /// Load config from embedded default string. - fn load_from_embedded() -> Result { - toml::from_str(DEFAULT_CONFIG).context("embedded guard policy is invalid TOML") - } - - /// Load config from a specific file path; `Ok(None)` only when it does not exist. - fn load_from_file(path: &Path) -> Result> { - let contents = match std::fs::read_to_string(path) { - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), - read => read.with_context(|| format!("cannot read guard policy {}", path.display()))?, - }; - toml::from_str(&contents) - .map(Some) - .with_context(|| format!("invalid guard policy {}", path.display())) - } - - /// Compile patterns from configuration into regex matchers. - /// Returns compiled patterns sorted by priority (highest first). - fn compile_patterns(self) -> Vec { - let mut compiled = Vec::new(); - - for pattern_def in self.patterns { - if !pattern_def.enabled { - continue; // Skip disabled patterns + Some(rule) => { + rule.deny = deny.or(rule.deny.take()); + rule.enabled = entry.enabled.unwrap_or(rule.enabled); + rule.message = entry.message.unwrap_or(std::mem::take(&mut rule.message)); + } + None => { + let (Some(deny), Some(message)) = (deny, entry.message) else { + bail!("rule {id} is new: it needs deny and message; {POLICY_HELP}") + }; + let enabled = entry.enabled.unwrap_or(true); + rules.push(Rule { + id, + enabled, + message, + deny: Some(deny), + }); } - - let MatcherConfig::Regex { pattern: regex_str } = &pattern_def.matcher; - - let regex = match Regex::new(regex_str) { - Ok(r) => r, - Err(e) => { - eprintln!( - "[agent-guard] WARNING: Failed to compile regex for pattern '{}': {}", - pattern_def.id, e - ); - continue; - } - }; - - compiled.push(CompiledPattern { - id: pattern_def.id, - priority: pattern_def.priority, - regex, - message: pattern_def.message, - validator: pattern_def.validator, - }); } - - // Sort by priority (highest first) - compiled.sort_by_key(|a| std::cmp::Reverse(a.priority)); - - compiled } + Ok(()) } // ── Public API ────────────────────────────────────────── -/// Entry point for `meta agent guard`. +/// Entry point for `agent guard`. /// /// Reads PreToolUse hook JSON from stdin, evaluates the tool input, /// prints denial JSON to stdout if blocked, exits silently if safe. +/// Every failure, a panic included, prints a denial and exits 0. /// -/// For Bash tools: checks command against destructive patterns. +/// For Bash tools: judges the command by its arguments. /// For Edit/Write/Read/NotebookEdit: validates file_path against `AGENT_ALLOWED_PATHS`. pub fn handle_guard() -> Result<()> { + // A denial it cannot write exits non-zero, which the hook reads as a block. + std::panic::set_hook(Box::new(|info| { + let denial = emit_denial(&format!( + "agent guard failed ({info}), so it denies the call." + )); + std::process::exit(i32::from(denial.is_err())); + })); let mut input = String::new(); - std::io::stdin().read_to_string(&mut input)?; - - let trimmed = input.trim(); - if trimmed.is_empty() { - return Ok(()); + let reason = match std::io::stdin().read_to_string(&mut input) { + Err(e) => Some(format!( + "agent guard cannot read its input ({e}), so it denies the call." + )), + Ok(_) if input.trim().is_empty() => None, + Ok(_) => judge_hook(&input), + }; + match reason { + Some(reason) => emit_denial(&reason).context("agent guard cannot write its denial"), + None => Ok(()), } +} - let hook_input: HookInput = match serde_json::from_str(trimmed) { - Ok(hi) => hi, - Err(_) => return Ok(()), // Malformed input — allow +/// The reason to deny one PreToolUse payload, if any. +fn judge_hook(input: &str) -> Option { + let Ok(hook) = serde_json::from_str::(input) else { + return Some( + "agent guard cannot read the hook input (not JSON), so it denies the call.".into(), + ); }; - - let tool_name = hook_input.tool_name.as_deref().unwrap_or(""); - - // File-path tools: validate ALL path fields against allowed directories. - // Both file_path and notebook_path are checked when present, preventing - // bypass via a payload that smuggles a second path field. - if matches!(tool_name, "Edit" | "Write" | "Read" | "NotebookEdit") { - let paths: Vec<&String> = hook_input - .tool_input - .as_ref() - .map(|ti| { - let mut v = Vec::new(); - if let Some(fp) = ti.file_path.as_ref() { - v.push(fp); - } - if let Some(np) = ti.notebook_path.as_ref() { - v.push(np); - } - v - }) - .unwrap_or_default(); - - if paths.is_empty() { - // When sandboxing is active, deny file-path tools with no path - // to prevent bypass via malformed payloads - if std::env::var_os("AGENT_ALLOWED_PATHS").is_some_and(|v| !v.is_empty()) { - emit_denial(format!( - "{} blocked: no file path provided for sandboxed tool.", - tool_name - ))?; - } - } else { - for fp in &paths { - if let Some(denial) = evaluate_file_path(tool_name, fp) { - emit_denial(denial.reason)?; - break; - } + let tool = hook["tool_name"].as_str().unwrap_or_default(); + let tool_input = &hook["tool_input"]; + match tool.to_ascii_lowercase().as_str() { + "edit" | "write" | "read" | "notebookedit" => { + // Every path field present is checked, so a second one can't smuggle a path past. + let paths: Vec<&str> = ["file_path", "notebook_path"] + .iter() + .filter(|key| !tool_input[**key].is_null()) + .map(|key| tool_input[*key].as_str().unwrap_or_default()) + .collect(); + if paths.is_empty() { + let sandboxed = + std::env::var_os("AGENT_ALLOWED_PATHS").is_some_and(|v| !v.is_empty()); + return sandboxed + .then(|| format!("{tool} blocked: no file path provided for sandboxed tool.")); } + paths + .iter() + .find_map(|p| evaluate_file_path(tool, p)) + .map(|d| d.reason) } - return Ok(()); - } - - // Only evaluate Bash tool for destructive command patterns - if !matches!(tool_name, "" | "Bash") { - return Ok(()); - } - - let command = match parse_command(&input) { - Some(cmd) => cmd, - None => return Ok(()), // No command to evaluate — allow - }; - - if let Some(denial) = evaluate_command(&command) { - emit_denial(denial.reason)?; + "" | "bash" | "shell" => { + let command = match &tool_input["command"] { + Value::String(command) => Some(command.clone()), + Value::Array(words) => words + .iter() + .map(Value::as_str) + .collect::>>() + .map(quote), + _ => None, + }; + let Some(command) = command else { + return Some(format!( + "agent guard found no command string in this {tool} call, so it denies it." + )); + }; + evaluate_command(&command, hook["cwd"].as_str().map(Path::new)) + } + _ => None, } - - Ok(()) -} - -// ── Types ─────────────────────────────────────────────── - -#[derive(Deserialize)] -struct HookInput { - tool_name: Option, - tool_input: Option, -} - -#[derive(Deserialize)] -struct ToolInput { - command: Option, - file_path: Option, - notebook_path: Option, -} - -#[derive(Serialize)] -struct HookOutput { - #[serde(rename = "hookSpecificOutput")] - hook_specific_output: HookSpecificOutput, -} - -#[derive(Serialize)] -struct HookSpecificOutput { - #[serde(rename = "hookEventName")] - hook_event_name: String, - #[serde(rename = "permissionDecision")] - permission_decision: String, - #[serde(rename = "permissionDecisionReason")] - permission_decision_reason: String, } /// A denial reason returned when a destructive pattern is detected. @@ -399,17 +220,27 @@ pub struct DenyReason { pub reason: String, } +/// Words quoted for the shell, joined by spaces. +fn quote<'w>(words: impl IntoIterator) -> String { + let quoted: Vec = words + .into_iter() + .map(|w| format!("'{}'", w.replace('\'', r"'\''"))) + .collect(); + quoted.join(" ") +} + /// Emit a denial JSON response to stdout. -fn emit_denial(reason: String) -> Result<()> { - let output = HookOutput { - hook_specific_output: HookSpecificOutput { - hook_event_name: "PreToolUse".to_string(), - permission_decision: "deny".to_string(), - permission_decision_reason: reason, - }, - }; - println!("{}", serde_json::to_string(&output)?); - Ok(()) +fn emit_denial(reason: &str) -> std::io::Result<()> { + let output = serde_json::json!({ + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "deny", + "permissionDecisionReason": reason, + } + }); + let mut stdout = std::io::stdout().lock(); + writeln!(stdout, "{output}")?; + stdout.flush() } // ── File Path Sandboxing ──────────────────────────────── @@ -543,926 +374,977 @@ fn normalize_path(path: &Path) -> std::path::PathBuf { normalized } -// ── Input Parsing ─────────────────────────────────────── +// ── Command Evaluation ────────────────────────────────── -/// Extract the command string from hook JSON input. -/// Returns None if input is empty, malformed, or missing the command field. -fn parse_command(input: &str) -> Option { - let trimmed = input.trim(); - if trimmed.is_empty() { - return None; +/// Judges a Bash command line under the built-ins and the policy files in +/// force; the reason if it is denied. `cwd` is the hook's working directory; +/// without it, relative `rm` targets are not looked up on disk. +pub fn evaluate_command(command: &str, cwd: Option<&Path>) -> Option { + let home = dirs::home_dir().map(|home| home.join(".claude/agent-guard.toml")); + let paths: Vec = home + .into_iter() + .chain([".claude/agent-guard.toml".into()]) + .collect(); + let cwds: Vec = cwd.map(Path::to_path_buf).into_iter().collect(); + match load_policy(&paths) { + Ok(rules) => Judge { rules: &rules }.script(command, 0, &cwds), + Err(e) => Some(format!( + "agent guard cannot load its policy: {e:#}. Fix or remove the file." + )), } - let hook_input: HookInput = serde_json::from_str(trimmed).ok()?; - let command = hook_input.tool_input?.command?; - if command.trim().is_empty() { - return None; +} + +/// Whether the built-in rules deny `command` (for `agent score`). +pub fn is_destructive(command: &str) -> bool { + Judge { + rules: &builtin_rules(), } - Some(command) + .script(command, 0, &[]) + .is_some() } -// ── Command Evaluation ────────────────────────────────── +/// Words that start a compound command or negate one, skipped before argv0. +const KEYWORDS: &str = "! { } if then else elif fi do done while until esac"; -/// Evaluate a command string for destructive patterns. -/// Returns a DenyReason if the command should be blocked or the policy cannot -/// be loaded, None if safe. -/// -/// Patterns are loaded and compiled once, then cached for the lifetime of the process. -pub fn evaluate_command(command: &str) -> Option { - let patterns = CACHED_PATTERNS.get_or_init(|| { - GuardConfig::load() - .map(GuardConfig::compile_patterns) - .map_err(|e| format!("{e:#}").trim_end().to_string()) - }); - let patterns = match patterns { - Ok(patterns) => patterns, - Err(e) => { - return Some(DenyReason { - reason: format!("agent guard cannot load its policy: {e}. Fix or remove the file."), +/// Commands that may run their stdin as a script. +const SHELLS: &str = "sh bash zsh dash ksh eval source"; + +/// Git's global options that take the next word as their value. +const GIT_VALUE_OPTIONS: &str = + "-C -c --git-dir --work-tree --namespace --super-prefix --config-env --attr-source"; + +/// The id of the rule for `rm` (and `find -delete`). +const RM_RULE: &str = "meta.rm.dangerous_paths"; + +/// Whether `word` is one of the space-separated `words`. +fn one_of(words: &str, word: &str) -> bool { + words.split(' ').any(|w| w == word) +} + +fn cannot_parse(e: &str) -> String { + format!( + "agent guard cannot parse this command: {e}. It cannot tell whether it is destructive, so write it more plainly." + ) +} + +struct Judge<'a> { + rules: &'a [Rule], +} + +impl Judge<'_> { + /// The reason to deny a command line `depth` levels into `sh -c`, `eval` + /// and the like. `cwds` are the folders it may run in (see [`folders`]). + /// With a shell anywhere in it, every heredoc and here-string is judged + /// as a script, wherever it goes. + fn script(&self, command: &str, depth: usize, cwds: &[PathBuf]) -> Option { + let cmds = match crate::shell::parse(command, depth) { + Ok(cmds) => cmds, + Err(e) => return Some(cannot_parse(&e)), + }; + let cwds = match depth { + 0 => folders(&cmds, cwds), + _ => cwds.to_vec(), + }; + let shell = cmds.iter().any(|c| runs_shell(&c.words)); + let mut bodies = cmds + .iter() + .filter_map(|c| c.stdin.as_deref().filter(|_| shell)); + bodies + .find_map(|body| self.script(body, depth + 1, &cwds)) + .or_else(|| { + cmds.iter() + .find_map(|c| self.command(&c.words, depth, &cwds)) }) + } + + /// Unwraps one simple command to the program it runs, then applies the rules. + fn command(&self, mut words: &[String], depth: usize, cwds: &[PathBuf]) -> Option { + if let Err(e) = crate::shell::within(depth) { + return Some(cannot_parse(&e)); } - }; + let (name, args) = loop { + let [first, args @ ..] = skip_prefix(words) else { + return None; + }; + let name = basename(first); + words = match name { + "sudo" | "doas" | "env" | "command" | "exec" | "nohup" | "nice" | "time" + | "timeout" | "setsid" | "stdbuf" => match unwrap(name, args) { + Err(e) => return Some(cannot_parse(&e)), + Ok((rest, Some(split))) => { + let rest = quote(rest.iter().map(String::as_str)); + return self.script(&format!("env {split} {rest}"), depth + 1, cwds); + } + Ok((rest, None)) => rest, + }, + "meta" => match meta_command(args) { + Some(inner) => inner, + None => break (name, args), + }, + "sh" | "bash" | "zsh" | "dash" | "ksh" => return self.shell(args, depth, cwds), + "eval" => return self.script(&args.join(" "), depth + 1, cwds), + "find" => match self.find_exec(args, depth, cwds) { + Some(reason) => return Some(reason), + None => break (name, args), + }, + _ => break (name, args), + }; + }; + let mut normalized = vec![name]; + let hit = match name { + "git" => { + let sub = match git_command(args) { + Ok(sub) => sub, + Err(e) => return Some(e), + }; + normalized.extend(sub.iter().map(String::as_str)); + sub.split_first() + .and_then(|(sub, rest)| git_rule(sub, rest)) + } + _ => { + normalized.extend(args.iter().map(String::as_str)); + let hit = match name { + "rm" => rm_rule(args, cwds), + "find" => finds_git(args) && args.iter().any(|a| a == "-delete"), + _ => false, + }; + hit.then_some(RM_RULE) + } + }; + let line = normalized.join(" "); + let rule = self + .rules + .iter() + .filter(|r| r.enabled) + .find(|r| match &r.deny { + None => hit == Some(r.id.as_str()), + Some(deny) => deny.is_match(&line), + }); + rule.map(|r| r.message.clone()) + } - for segment in split_compound_command(command) { - let trimmed = segment.trim(); - if trimmed.is_empty() { - continue; + /// `sh -c STR` judges STR (`-` ends the options); stdin is judged by + /// [`Judge::script`]; a script file can't be seen; `+o` and the like deny. + fn shell(&self, args: &[String], depth: usize, cwds: &[PathBuf]) -> Option { + let f = Flags::new(args, "oO", "rcfile init-file", true); + let mut rest = args.get(f.rest..).unwrap_or_default(); + if let [dash, more @ ..] = rest { + rest = if dash == "-" { more } else { rest }; + } + match rest.first() { + Some(arg) if arg.starts_with('+') => Some(cannot_parse("a shell option with +")), + Some(script) if f.has(Some('c'), "") => self.script(script, depth + 1, cwds), + _ => None, } - if let Some(denial) = evaluate_segment(trimmed, patterns) { - return Some(denial); + } + + /// Judges each `-exec CMD … ;` of a `find`, with `{}` as `.git` when the + /// find selects `.git` folders. + fn find_exec(&self, mut args: &[String], depth: usize, cwds: &[PathBuf]) -> Option { + let git = finds_git(args); + while let Some(at) = args + .iter() + .position(|a| matches!(a.as_str(), "-exec" | "-execdir" | "-ok" | "-okdir")) + { + let cmd = args.get(at + 1..).unwrap_or_default(); + let end = cmd + .iter() + .position(|a| a == ";" || a == "+") + .unwrap_or(cmd.len()); + let words: Vec = cmd + .get(..end) + .unwrap_or_default() + .iter() + .map(|w| w.replace("{}", if git { ".git" } else { "{}" })) + .collect(); + if let Some(reason) = self.command(&words, depth + 1, cwds) { + return Some(reason); + } + args = cmd.get(end..).unwrap_or_default(); } + None + } +} + +/// `words` from the program on: without assignments, keywords and `function f`. +fn skip_prefix(mut words: &[String]) -> &[String] { + while let [first, rest @ ..] = words { + words = match first.as_str() { + "function" => rest.get(1..).unwrap_or_default(), + w if is_assignment(w) || one_of(KEYWORDS, w) => rest, + _ => break, + }; } - None + words +} + +fn basename(word: &str) -> &str { + word.rsplit('/').next().unwrap_or(word) } -/// Evaluate a single command segment using compiled regex patterns. -fn evaluate_segment(segment: &str, patterns: &[CompiledPattern]) -> Option { - for pattern in patterns { - if pattern.regex.is_match(segment) { - // Additional validation if required - if let Some(ref validator) = pattern.validator { - if !execute_validator(segment, validator) { - continue; // Regex matched but validator rejected +/// Whether a command names a shell, `eval` or `source` anywhere, or runs `.`. +fn runs_shell(words: &[String]) -> bool { + let words = skip_prefix(words); + let dot = match words.first().map(String::as_str) { + Some(".") => true, + Some(w) => one_of("command builtin time", w) && words.iter().any(|w| w == "."), + None => false, + }; + dot || words.iter().any(|w| one_of(SHELLS, basename(w))) +} + +/// The folders a script may run `rm` in: `cwds`, every folder a `cd` or +/// `pushd` anywhere in it (or in a string or heredoc it passes on) names, from +/// `cwds` and from each other, and an empty path if one names a folder that +/// can't be known (`cd "$DIR"`, `cd -`). +fn folders(cmds: &[crate::shell::Command], cwds: &[PathBuf]) -> Vec { + fn targets(cmds: &[crate::shell::Command], depth: usize, out: &mut Vec) { + for c in cmds { + for (i, w) in c.words.iter().enumerate() { + if w == "cd" || w == "pushd" { + let args = c.words.get(i + 1..).unwrap_or_default(); + let dir = args.iter().find(|a| *a == "-" || !a.starts_with('-')); + out.push(dir.map_or("~", String::as_str).into()); } } - - // Debug logging when META_DEBUG_GUARD is set - if std::env::var("META_DEBUG_GUARD").is_ok() { - eprintln!( - "[agent-guard] Pattern '{}' triggered for: {}", - pattern.id, segment - ); + let texts = c.words.iter().filter(|w| w.contains(char::is_whitespace)); + for text in texts.chain(c.stdin.as_ref()) { + if let Ok(inner) = crate::shell::parse(text, depth + 1) { + targets(&inner, depth + 1, out); + } } + } + } + let mut dirs = Vec::new(); + targets(cmds, 0, &mut dirs); + let dirs: Vec = dirs.iter().map(|d| expand(d)).collect(); + let unknown = dirs.iter().any(|d| { + let d = d.to_string_lossy(); + d == "-" || d.starts_with('~') || d.contains(['$', '`', '*', '?', '[', '{']) + }); + let mut all = cwds.to_vec(); + let mut bases: Vec = cwds.iter().cloned().chain([PathBuf::new()]).collect(); + for _ in 0..2 { + bases = bases + .iter() + .flat_map(|base| dirs.iter().map(move |d| base.join(d))) + .filter(|d| d.is_absolute()) + .collect(); + all.extend(bases.iter().cloned()); + } + all.extend(unknown.then(PathBuf::new)); + all +} - return Some(DenyReason { - reason: pattern.message.clone(), - }); +fn is_assignment(word: &str) -> bool { + word.split_once('=').is_some_and(|(name, _)| { + name.starts_with(|c: char| c == '_' || c.is_ascii_alphabetic()) + && name.chars().all(|c| c == '_' || c.is_ascii_alphanumeric()) + }) +} + +/// The command a wrapper such as `sudo -u x`, `env -i` or `timeout 5` runs, +/// and the words `env -S` puts in front of it; an error for an option it does +/// not know, or an `env -S` string it would have to unquote. +fn unwrap<'a>( + wrapper: &str, + args: &'a [String], +) -> Result<(&'a [String], Option<&'a str>), String> { + // The options that take a value, then the other options. + let (shorts, longs, flags, long_flags) = match wrapper { + "sudo" | "doas" => ( + "ugCDhprtTUR", + "user group host prompt close-from chdir chroot command-timeout other-user role type", + "AbBEeHiKklNnPSsVv", + "askpass background bell edit list login non-interactive preserve-env preserve-groups remove-timestamp reset-timestamp set-home shell stdin validate", + ), + "env" => ("uCS", "unset chdir split-string", "i0v", "ignore-environment null debug"), + "nice" => ("n", "adjustment", "0123456789", ""), + "timeout" => ("sk", "signal kill-after", "v", "foreground preserve-status verbose"), + "stdbuf" => ("ioe", "input output error", "", ""), + "exec" => ("a", "", "cl", ""), + "time" => ("fo", "format output", "apqv", "append portability quiet verbose"), + "command" => ("", "", "pvV", ""), + "setsid" => ("", "", "cfw", "ctty fork wait"), + _ => ("", "", "", ""), + }; + let f = Flags::new(args, shorts, longs, true); + let known = format!("{longs} {long_flags} help version"); + let unknown = f.opts.iter().find(|(opt, ..)| match *opt { + Opt::Short(c) => !shorts.contains(c) && !flags.contains(c), + Opt::Long(l) => l.is_empty() || !known.split(' ').any(|k| k.starts_with(l)), + }); + if unknown.is_some() || args.get(f.rest).is_some_and(|a| a == "-") { + return Err(format!("an option of {wrapper} it does not know")); + } + let splits: Vec<_> = (f.opts.iter()) + .filter(|(opt, ..)| match *opt { + Opt::Short(c) => c == 'S', + Opt::Long(l) => "split-string".starts_with(l), + }) + .filter(|_| wrapper == "env") + .collect(); + let skip = usize::from(wrapper == "timeout"); + match splits.as_slice() { + [] => Ok((args.get(f.rest + skip..).unwrap_or_default(), None)), + [(_, Some(split), end)] + if !split.starts_with('-') && !split.contains(['\\', '\'', '"']) => + { + Ok((args.get(*end..).unwrap_or_default(), Some(split))) } + _ => Err("env -S with an option, quote, backslash or second -S".into()), } - None } -/// Split a compound command on `&&`, `||`, `;`, and `|` delimiters. -/// Simple split — does not handle quoting. Sufficient for Claude-generated commands. -/// Returns trimmed segments. -fn split_compound_command(command: &str) -> Vec<&str> { - let mut segments = Vec::new(); - let mut rest = command; - - loop { - // Find the earliest delimiter. - // Order matters: check `||` before `|`, and multi-char before single-char. - let delimiters: &[&str] = &["||", "&&", ";"]; - let earliest = delimiters - .iter() - .filter_map(|d| rest.find(d).map(|pos| (pos, d.len()))) - .min_by_key(|(pos, _)| *pos); - - // Also check for standalone pipe `|` (not part of ||) - let pipe_pos = find_standalone_pipe(rest); - - // Take whichever delimiter comes first - let next_delimiter = match (earliest, pipe_pos) { - (Some((pos1, len1)), Some(pos2)) => { - if pos2 < pos1 { - Some((pos2, 1)) // pipe comes first - } else { - Some((pos1, len1)) // other delimiter comes first - } - } - (Some(delim), None) => Some(delim), - (None, Some(pos)) => Some((pos, 1)), - (None, None) => None, - }; +/// What `meta [opts] exec [--] CMD` or `meta [opts] git …` runs in each repo. +fn meta_command(args: &[String]) -> Option<&[String]> { + let longs = "config exclude include tag fields depth"; + let rest = args.get(Flags::new(args, "ceit", longs, true).rest..)?; + match rest { + [exec, dashes, inner @ ..] if exec == "exec" && dashes == "--" => Some(inner), + [exec, inner @ ..] if exec == "exec" => Some(inner), + [git, ..] if git == "git" => Some(rest), + _ => None, + } +} - match next_delimiter { - Some((pos, len)) => { - segments.push(rest[..pos].trim()); - rest = &rest[pos + len..]; +/// git's subcommand and its arguments, after the global options; an error for +/// an alias defined inline with `-c alias.…`. +fn git_command(args: &[String]) -> Result<&[String], String> { + let mut i = 0; + while let Some(arg) = args.get(i).filter(|a| a.starts_with('-')) { + let config = match arg.as_str() { + "-c" | "--config-env" => { + i += 1; + args.get(i).map(String::as_str) } - None => { - segments.push(rest.trim()); - break; + a if one_of(GIT_VALUE_OPTIONS, a) => { + i += 1; + None } + a => a + .strip_prefix("--config-env=") + .or_else(|| a.strip_prefix("-c")), + }; + if config.is_some_and(|c| c.to_ascii_lowercase().starts_with("alias.")) { + return Err("git -c alias.… defines a git command inline, which agent guard cannot judge. Run the git command it stands for instead.".into()); } + i += 1; } + Ok(args.get(i..).unwrap_or_default()) +} - segments +/// One option as written: a short letter or a long name. +#[derive(Clone, Copy)] +enum Opt<'a> { + Short(char), + Long(&'a str), } -/// Find a standalone pipe `|` that is NOT part of `||`. -/// Returns the position of the first such pipe, or None if not found. -fn find_standalone_pipe(s: &str) -> Option { - let bytes = s.as_bytes(); - for i in 0..bytes.len() { - if bytes[i] == b'|' { - // Check if it's part of || - let prev_is_pipe = i > 0 && bytes[i - 1] == b'|'; - let next_is_pipe = i + 1 < bytes.len() && bytes[i + 1] == b'|'; - if !prev_is_pipe && !next_is_pipe { - return Some(i); +/// A command's arguments read the way git and getopt read them: short +/// clusters split (`-Df`) and end at a letter that takes a value (`-ekeep`, +/// `-e keep`); `--x=v`, and `--x v` for a long option that takes a value, are +/// one option; everything after `--` is an operand. With `posix`, so is +/// everything from the first operand on (`rest` is where that starts). Each +/// option has its value and the index of the argument after them. +struct Flags<'a> { + opts: Vec<(Opt<'a>, Option<&'a str>, usize)>, + operands: Vec<&'a str>, + rest: usize, +} + +impl<'a> Flags<'a> { + /// `shorts` and the space-separated `longs` are the options that take a value. + fn new(args: &'a [String], shorts: &str, longs: &str, posix: bool) -> Self { + let mut f = Flags { + opts: Vec::new(), + operands: Vec::new(), + rest: args.len(), + }; + let mut i = 0; + let next = |i: &mut usize| { + *i += 1; + args.get(*i - 1).map(String::as_str) + }; + while let Some(arg) = next(&mut i) { + if arg == "--" { + f.rest = i; + break; + } else if let Some(long) = arg.strip_prefix("--") { + let (name, value) = long + .split_once('=') + .map_or((long, None), |(n, v)| (n, Some(v))); + let takes = value.is_none() && longs.split(' ').any(|l| l.starts_with(name)); + let value = if takes { next(&mut i) } else { value }; + f.opts.push((Opt::Long(name), value, i)); + } else if let Some(cluster) = arg.strip_prefix('-').filter(|s| !s.is_empty()) { + for (at, c) in cluster.char_indices() { + if !shorts.contains(c) { + f.opts.push((Opt::Short(c), None, i)); + continue; + } + let attached = cluster.get(at + c.len_utf8()..).filter(|v| !v.is_empty()); + let value = attached.or_else(|| next(&mut i)); + f.opts.push((Opt::Short(c), value, i)); + break; + } + } else if posix { + f.rest = i - 1; + break; + } else { + f.operands.push(arg); } } + f.operands + .extend(args.iter().skip(f.rest).map(String::as_str)); + f + } + + /// Whether `-short` or `--long` is given; any prefix of `long` counts, as + /// git and getopt accept a unique one and refuse an ambiguous one. + fn has(&self, short: Option, long: &str) -> bool { + self.opts.iter().any(|(opt, ..)| match *opt { + Opt::Short(c) => short == Some(c), + Opt::Long(l) => !l.is_empty() && long.starts_with(l), + }) + } + + /// Whether an option that makes a command safe is in force: only its + /// exact letter or full name counts, and a later `--no-…` cancels it. + fn exempt(&self, short: char, long: &str) -> bool { + self.opts.iter().fold(false, |on, (opt, ..)| match *opt { + Opt::Short(c) if c == short => true, + Opt::Long(l) if l == long => true, + Opt::Long(l) => { + let no = l.strip_prefix("no-").filter(|n| !n.is_empty()); + on && !no.is_some_and(|n| long.starts_with(n)) + } + _ => on, + }) } - None } -// ── Tests ─────────────────────────────────────────────── +/// The built-in rule a git subcommand breaks, if any. +fn git_rule(sub: &str, args: &[String]) -> Option<&'static str> { + let (shorts, longs) = match sub { + "push" => ("o", "push-option repo receive-pack exec"), + "clean" => ("e", "exclude"), + "checkout" => ("bB", "orphan conflict"), + "switch" => ("cC", "create force-create orphan conflict"), + "restore" => ("s", "source"), + "branch" => ("u", "set-upstream-to"), + "stash" => ("m", "message"), + _ => ("", ""), + }; + let f = Flags::new(args, shorts, longs, false); + let force = f.has(Some('f'), "force"); + let everything = f + .operands + .iter() + .any(|p| matches!(normalize(p).as_str(), "." | ".." | "*" | ":" | ":(top)")); + let rewrites = |p: &&str| p.starts_with('+') || (p.len() > 1 && p.starts_with(':')); + let (id, hit) = match (sub, f.operands.first()) { + ("push", _) => ( + "meta.git.force_push", + !f.exempt('n', "dry-run") + && (force + || f.has(None, "mirror") + || f.has(Some('d'), "delete") + || f.operands.iter().any(rewrites)), + ), + ("reset", _) => ("meta.git.reset_hard", f.has(None, "hard")), + ("clean", _) => ( + "meta.git.clean_force", + force && f.has(Some('d'), "dirs") && !f.exempt('n', "dry-run"), + ), + ("checkout", _) => ("meta.git.checkout_dot", force || everything), + ("restore", _) => ( + "meta.git.checkout_dot", + everything && (f.has(Some('W'), "worktree") || !f.exempt('S', "staged")), + ), + ("switch", _) => ( + "meta.git.checkout_dot", + force || f.has(None, "discard-changes"), + ), + ("branch", _) => ( + "meta.git.branch_force_delete", + f.has(Some('D'), "") || (force && f.has(Some('d'), "delete")), + ), + ("stash", Some(&"drop")) => ("meta.git.stash_drop", true), + ("stash", Some(&"clear")) => ("meta.git.stash_clear", true), + _ => return None, + }; + hit.then_some(id) +} -#[cfg(test)] -mod tests { - use super::*; +/// `rm -r` of `.git` (or a glob matching it), of a folder holding one (looked +/// up from each of `cwds`), of `.meta`, or of the workspace, home or root; any +/// `rm -r` when one of `cwds` is unknown (empty). +fn rm_rule(args: &[String], cwds: &[PathBuf]) -> bool { + let f = Flags::new(args, "", "", false); + let dangerous = |p: &str| { + let n = normalize(p); + let last = n.rsplit('/').next().unwrap_or_default(); + holds_git_name(&n) + || matches!(last, ".meta" | ".meta.yaml" | ".meta.yml") + || n.split('/') + .all(|part| matches!(part, "" | "." | ".." | "~" | "$HOME" | "$PWD" | "*" | ".*")) + }; + let holds_git = |p: &str| { + let p = expand(p); + (p.is_absolute() && p.join(".git").exists()) + || cwds.iter().any(|cwd| cwd.join(&p).join(".git").exists()) + }; + let unknown = cwds.iter().any(|cwd| cwd.as_os_str().is_empty()); + (f.has(Some('r'), "recursive") || f.has(Some('R'), "")) + && (unknown || f.operands.iter().any(|p| dangerous(p) || holds_git(p))) +} - // ── parse_command ────────────────────────────────── +/// Whether a `find` may reach `.git`: any of its arguments (a start path or +/// the value of `-name`, `-ipath`…) has a `.git` part, in any case. +fn finds_git(args: &[String]) -> bool { + args.iter().any(|a| holds_git_name(&a.to_ascii_lowercase())) +} - #[test] - fn parse_command_extracts_command() { - let input = r#"{"tool_input": {"command": "git status"}}"#; - assert_eq!(parse_command(input), Some("git status".to_string())); - } +/// Whether a part of `path` is `.git`, or a dot-glob (`.*`, `.g*`) that may +/// match it. +fn holds_git_name(path: &str) -> bool { + path.split('/') + .any(|part| part == ".git" || (part.starts_with('.') && part.contains(['*', '?', '[']))) +} - #[test] - fn parse_command_returns_none_for_empty_input() { - assert_eq!(parse_command(""), None); - assert_eq!(parse_command(" "), None); +/// `path` with a leading `~` or `$HOME` replaced by the home folder. +fn expand(path: &str) -> PathBuf { + let rest = ["~", "$HOME"].iter().find_map(|h| { + path.strip_prefix(h) + .filter(|r| r.is_empty() || r.starts_with('/')) + }); + match (rest, dirs::home_dir()) { + (Some(rest), Some(home)) => home.join(rest.trim_start_matches('/')), + _ => path.into(), } +} - #[test] - fn parse_command_returns_none_for_malformed_json() { - assert_eq!(parse_command("not json"), None); - assert_eq!(parse_command("{"), None); +/// A path with `.`, `name/..`, repeated and trailing slashes removed, lexically. +fn normalize(path: &str) -> String { + let mut parts: Vec<&str> = Vec::new(); + for part in path.split('/') { + match part { + "" | "." => {} + ".." if parts.last().is_some_and(|last| *last != "..") => { + parts.pop(); + } + part => parts.push(part), + } } - - #[test] - fn parse_command_returns_none_for_missing_fields() { - assert_eq!(parse_command(r#"{}"#), None); - assert_eq!(parse_command(r#"{"tool_input": {}}"#), None); - assert_eq!(parse_command(r#"{"tool_input": {"command": ""}}"#), None); + match (path.starts_with('/'), parts.join("/")) { + (true, joined) => format!("/{joined}"), + (false, joined) if joined.is_empty() => ".".into(), + (false, joined) => joined, } +} - // ── split_compound_command ───────────────────────── +// ── Tests ─────────────────────────────────────────────── - #[test] - fn split_simple_command() { - assert_eq!(split_compound_command("git status"), vec!["git status"]); +#[cfg(test)] +mod tests { + use super::*; + + fn builtin(command: &str) -> Option { + Judge { + rules: &builtin_rules(), + } + .script(command, 0, &[]) + } + + /// Every spelling of a refused operation: git global options, quoting, + /// clusters, abbreviations, +refspecs, wrappers, nesting, and input the + /// lexer cannot close. + #[test] + fn denies_every_spelling() { + let deep = format!("echo {}{}", "${".repeat(100_000), "}".repeat(100_000)); + let deny = [ + deep.as_str(), + "find . -exec find . -exec find . -exec find . -exec find . -exec git status \\; \\; \\; \\; \\;", + "git reset --ha", + "git reset --h", + "git push --mi", + "git push --de origin x", + "git clean --fo -d", + "git switch --di main", + "rm --r --f ~", + "git clean -fd -enode_modules", + "git clean -fdx -e.env", + "git push -f -onx origin main", + "git restore -sSTABLE .", + "git push --dry-run --no-dry-run --force", + "git push -n --no-dry --force", + "git push --dry --force", + "sudo --user root rm -rf /", + "sudo -Eu root git push -f", + "env --unset X git reset --hard", + "env -iu X git reset --hard", + "env --chdir d git reset --hard", + "env -S 'git reset --hard'", + "env --split-string='git reset --hard'", + "env -iS'git reset' --hard", + "timeout --signal TERM 5 git reset --hard", + "timeout --kill-after 5 10 rm -rf .", + "nice --adjustment 5 git reset --hard", + "stdbuf --output L git reset --hard", + "exec -a x git reset --hard", + "meta -ri api git reset --hard", + "meta -Ai api exec -- git push -f", + "bash -s api <<'EOF'\ngit -C \"$1\" reset --hard\nEOF", + "bash --rcfile f -c 'git reset --hard'", + "bash --init-file f -c 'git reset --hard'", + "cat <<'EOF' |& sh\ngit reset --hard\nEOF", + "cat <<'EOF' |\ngit reset --hard\nEOF\nsh", + "cat <<'EOF' | (sh)\ngit reset --hard\nEOF", + "((x</dev/null; git reset --hard #'", + "(( '))\"' )) 2>/dev/null; git reset --hard #\"", + "(( $'))\\'' )) 2>/dev/null; git reset --hard #'", + "if ((1< = deny.iter().filter(|c| builtin(c).is_none()).collect(); + assert!(allowed.is_empty(), "allowed: {allowed:#?}"); + } + + /// Ordinary work, including text that only mentions a refused command. + #[test] + fn allows_ordinary_commands() { + let allow = [ + "git status", + "git push", + "git push origin main", + "git push -u origin HEAD", + "git push --force-with-lease", + "git push --force-with-lease=main origin main", + "git push origin feature-f", + "git push origin feat/-f-thing", + "git push --dry-run --force", + "git commit -m \"$(cat <<'EOF'\nfix: don't git reset --hard or git push --force\n\nIt's fine.\nEOF\n)\"", + "git commit -m \"never git reset --hard\"", + "echo \"git push --force\"", + "echo 'rm -rf .' # git reset --hard", + "rm -rf target", + "rm -rf node_modules", + "rm -rf ./target build/", + "rm -r .cache", + "rm -rf .metadata", + "rm -f .meta.yaml.bak", + "rm file.txt", + "git clean -nd", + "git clean -f", + "git branch -d x", + "git branch -f topic main", + "git checkout -b new", + "git checkout ./src/main.rs", + "git checkout -- src", + "git checkout .gitignore", + "git restore --staged .", + "git restore src/main.rs", + "git reset --soft HEAD~1", + "git reset HEAD file.txt", + "git stash push -m 'WIP'", + "git stash pop", + "git stash list", + "git -C api status", + "git -c core.pager=cat log --format='%h %s' | head", + "grep -rf patterns.txt .", + "cargo build --features force", + "firm -rf .", + "command -v git", + "meta git status", + "meta exec -- cargo test", + "meta --dry-run git update", + "git diff --stat && git push 2>&1 | tee out.log >/dev/null", + "echo ${x:-\"a b\"} $((1 + 2))", + "cat < notes.md\nIt's fine to mention git reset --hard here.\nEOF", + "sudo -u root ls", + "nice -10 git status", + "env -S 'git status'", + "bash -x script.sh", + "find src -exec rm -rf {} +", + "timeout --foreground 5 git status", + "sudo --list", + "rm -rf build/*", + "find . -name '*.o' -delete", + ]; + let denied: Vec<_> = allow + .iter() + .filter_map(|c| Some((c, builtin(c)?))) + .collect(); + assert!(denied.is_empty(), "denied: {denied:#?}"); } + /// Policy files merge onto the built-ins by id, and any mistake in one + /// is an error naming the file (which denies every Bash command). #[test] - fn split_and_chain() { + fn policy_merges_by_id_and_fails_closed() { + let dir = tempfile::tempdir().unwrap(); + let (user, project) = ( + dir.path().join("user.toml"), + dir.path().join("project.toml"), + ); + let judge = |text: &str, command: &str| { + std::fs::write(&project, text).unwrap(); + let rules = + load_policy(&[user.clone(), project.clone()]).map_err(|e| format!("{e:#}"))?; + Ok::<_, String>(Judge { rules: &rules }.script(command, 0, &[])) + }; + std::fs::write(&user, "schema_version = \"2\"\n[[rules]]\nid = \"meta.git.reset_hard\"\nmessage = \"user says no\"\n").unwrap(); + let custom = "schema_version = \"2\"\n[[rules]]\nid = \"custom.tf\"\ndeny = '^terraform destroy\\b'\nmessage = \"no tf\"\n"; assert_eq!( - split_compound_command("git add . && git commit -m msg"), - vec!["git add .", "git commit -m msg"] + judge(custom, "terraform destroy -auto-approve"), + Ok(Some("no tf".into())) ); - } - - #[test] - fn split_or_chain() { - assert_eq!(split_compound_command("cmd1 || cmd2"), vec!["cmd1", "cmd2"]); - } - - #[test] - fn split_semicolon() { - assert_eq!(split_compound_command("cmd1; cmd2"), vec!["cmd1", "cmd2"]); - } - - #[test] - fn split_mixed_delimiters() { assert_eq!( - split_compound_command("cmd1 && cmd2; cmd3 || cmd4"), - vec!["cmd1", "cmd2", "cmd3", "cmd4"] + judge(custom, "git -C x reset --hard"), + Ok(Some("user says no".into())) ); + assert!(judge(custom, "git push --force").unwrap().is_some()); + let off = + "schema_version = \"2\"\n[[rules]]\nid = \"meta.git.checkout_dot\"\nenabled = false\n"; + assert_eq!(judge(off, "git checkout ."), Ok(None)); + assert!(judge(off, "git reset --hard").unwrap().is_some()); + + let broken = [ + ("schema_version = \"2\"\n[[rules]]\nid = \"c\"\ndeny = 'git\\s+push.*(?!-with-lease)'\nmessage = \"m\"\n", "bad deny regex"), + ("schema_version = \"1.0\"\n[[patterns]]\nid = \"custom.x\"\n", "schema_version = \"2\""), + ("schema_version = \"2\"\n[[rules]]\nid = \"c\"\ndeny = 'x'\nmessage = \"m\"\npriority = 1\n", "unknown field"), + ("schema_version = \"2\"\n[[rules]]\nid = \"meta.git.force_push\"\ndeny = 'x'\n", "built in"), + ("schema_version = \"2\"\n[[rules]]\nid = \"c\"\nenabled = false\n", "needs deny and message"), + ("schema_version = \"2\"\n[[rules]]\nid = \"meta.git.checkout_dot\"\n[[rules]]\nid = \"meta.git.checkout_dot\"\n", "appears twice"), + ("rules = [ not toml", "invalid guard policy"), + ]; + for (text, error) in broken { + let e = judge(text, "git status").unwrap_err(); + assert!( + e.contains(&project.display().to_string()) && e.contains(error), + "{e}" + ); + } } - // ── git push --force ────────────────────────────── - - #[test] - fn denies_git_push_force() { - assert!(evaluate_command("git push --force origin main").is_some()); - } - - #[test] - fn denies_git_push_f() { - assert!(evaluate_command("git push -f origin main").is_some()); - } - + /// Hook payloads the guard cannot read are denied; non-Bash tools pass. #[test] - fn allows_git_push_force_with_lease() { - assert!(evaluate_command("git push --force-with-lease origin main").is_none()); + fn hook_input_fails_closed() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(dir.path().join("api/.git")).unwrap(); + std::fs::create_dir_all(dir.path().join("plain")).unwrap(); + std::fs::create_dir_all(dir.path().join("sub/repo/.git")).unwrap(); + std::fs::create_dir_all(dir.path().join("other")).unwrap(); + let cwd = dir.path().display().to_string(); + let bash = |cwd: &str, command: String| { + serde_json::json!({"tool_name": "Bash", "cwd": cwd, "tool_input": {"command": command}}) + .to_string() + }; + let rm = |target: &str| bash(&cwd, format!("rm -r {target}")); + let mut cases = vec![ + (r#"{"tool_name":"Bash","tool_input":{"command":"git push --force"}"#.to_string(), true), + (r#"{"tool_name":"Bash","tool_input":{"command":"git push --force","file_path":5}}"#.into(), true), + (r#"{"tool_name":"bash","tool_input":{"command":["bash","-lc","git push --force"]}}"#.into(), true), + (r#"{"tool_name":"Bash","tool_input":{"command":["git","status"]}}"#.into(), false), + (r#"{"tool_name":"Bash","tool_input":{"command":5}}"#.into(), true), + (r#"{"tool_name":"Bash","tool_input":{}}"#.into(), true), + (r#"{"other":"field"}"#.into(), true), + ("not json".into(), true), + (r#"{"tool_name":"Grep","tool_input":{"pattern":"git push --force"}}"#.into(), false), + (rm("api"), true), + (rm("plain"), false), + (bash(&cwd, "cd \"$X\" && rm -rf api".into()), true), + (bash(&cwd, "cd missing; cd sub && rm -r repo".into()), true), + (bash(&cwd, "cd missing 2>/dev/null; cd sub && rm -rf repo".into()), true), + (bash(&cwd, "(cd other && true) && cd sub && rm -rf repo".into()), true), + (bash(&cwd, "(cd other && true) && cd sub && rm -rf target".into()), false), + (bash(&cwd, "cd - && rm -r plain".into()), true), + (bash(&cwd, "cd $(pwd)/plain && rm -r x".into()), true), + ]; + // A Unix path can be written unquoted into a command and reached from ~. + #[cfg(not(windows))] + let ups = "../".repeat(dirs::home_dir().unwrap().components().count()); + #[cfg(not(windows))] + cases.extend([ + (bash("/", format!("cd {cwd} && rm -rf api")), true), + (bash("/", format!("cd -- {cwd}; rm -rf plain api")), true), + (bash("/", format!("pushd {cwd} && rm -rf plain")), false), + (bash("/", format!("(cd /) ; cd {cwd}/plain && rm -rf ../api")), true), + (bash("/", format!("if cd {cwd}; then rm -rf api; fi")), true), + (bash("/", format!("{{ cd {cwd}; }} && rm -rf api")), true), + (bash("/", format!("eval cd {cwd}; rm -rf api")), true), + (bash("/", format!("{{ cd {cwd}/sub && rm -rf repo; }}")), true), + (bash("/", format!("rm -rf ~/{ups}{cwd}/api")), true), + (bash("/", format!("rm -rf $HOME/{ups}{cwd}/api")), true), + (bash("/", format!("rm -rf ${{HOME}}/{ups}{cwd}/api")), true), + (serde_json::json!({"tool_name": "Bash", "tool_input": {"command": format!("rm -r {cwd}/api")}}).to_string(), true), + ]); + let wrong: Vec<_> = cases + .iter() + .filter(|(input, denied)| judge_hook(input).is_some() != *denied) + .collect(); + assert!(wrong.is_empty(), "wrong: {wrong:#?}"); } - #[test] - fn allows_git_push_force_with_lease_equals() { - assert!(evaluate_command("git push --force-with-lease=main origin main").is_none()); - } + // ── File path sandboxing ──────────────────────────── + // + // Tests use evaluate_file_path_with_allowed() to avoid env var races + // when tests run in parallel. Tests use Unix-style paths and are + // skipped on Windows where `/tmp/...` is not considered absolute. - #[test] - fn allows_normal_git_push() { - assert!(evaluate_command("git push origin main").is_none()); - } - - #[test] - fn allows_git_push_no_force() { - assert!(evaluate_command("git push").is_none()); - } - - // ── git reset --hard ────────────────────────────── - - #[test] - fn denies_git_reset_hard() { - assert!(evaluate_command("git reset --hard").is_some()); - } - - #[test] - fn denies_git_reset_hard_with_ref() { - assert!(evaluate_command("git reset --hard HEAD~3").is_some()); - } - - #[test] - fn allows_git_reset_soft() { - assert!(evaluate_command("git reset --soft HEAD~1").is_none()); - } - - #[test] - fn allows_git_reset_no_flag() { - assert!(evaluate_command("git reset HEAD file.txt").is_none()); - } - - // ── git clean ───────────────────────────────────── - - #[test] - fn denies_git_clean_fd() { - assert!(evaluate_command("git clean -fd").is_some()); - } - - #[test] - fn denies_git_clean_fdx() { - assert!(evaluate_command("git clean -fdx").is_some()); - } - - #[test] - fn denies_git_clean_fxd() { - assert!(evaluate_command("git clean -fxd").is_some()); - } - - #[test] - fn denies_git_clean_df() { - assert!(evaluate_command("git clean -df").is_some()); - } - - #[test] - fn allows_git_clean_dry_run() { - assert!(evaluate_command("git clean -nd").is_none()); - } - - #[test] - fn allows_git_clean_no_force() { - assert!(evaluate_command("git clean -n").is_none()); - } - - // ── git checkout . ──────────────────────────────── - - #[test] - fn denies_git_checkout_dot() { - assert!(evaluate_command("git checkout .").is_some()); - } - - #[test] - fn denies_git_checkout_dashdash_dot() { - assert!(evaluate_command("git checkout -- .").is_some()); - } - - #[test] - fn allows_git_checkout_branch() { - assert!(evaluate_command("git checkout main").is_none()); - } - - #[test] - fn allows_git_checkout_specific_file() { - assert!(evaluate_command("git checkout -- src/main.rs").is_none()); - } - - #[test] - fn allows_git_checkout_b() { - assert!(evaluate_command("git checkout -b feature/new").is_none()); - } - - // ── rm -rf ──────────────────────────────────────── - - #[test] - fn denies_rm_rf_dot() { - assert!(evaluate_command("rm -rf .").is_some()); - } - - #[test] - fn denies_rm_rf_parent() { - assert!(evaluate_command("rm -rf ..").is_some()); - } - - #[test] - fn denies_rm_rf_slash() { - assert!(evaluate_command("rm -rf /").is_some()); - } - - #[test] - fn denies_rm_rf_meta() { - assert!(evaluate_command("rm -rf .meta").is_some()); - } - - #[test] - fn denies_rm_rf_star() { - assert!(evaluate_command("rm -rf *").is_some()); - } - - #[test] - fn denies_rm_fr_dot() { - assert!(evaluate_command("rm -fr .").is_some()); - } - - #[test] - fn allows_rm_rf_specific_dir() { - assert!(evaluate_command("rm -rf node_modules").is_none()); - } - - #[test] - fn allows_rm_rf_specific_path() { - assert!(evaluate_command("rm -rf target/debug").is_none()); - } - - #[test] - fn allows_rm_without_rf() { - assert!(evaluate_command("rm file.txt").is_none()); - } - - // ── Compound commands ───────────────────────────── - - #[test] - fn denies_destructive_in_compound() { - assert!(evaluate_command("git add . && git push --force").is_some()); - } - - #[test] - fn allows_safe_compound() { - assert!(evaluate_command("git add . && git commit -m msg && git push").is_none()); - } - - #[test] - fn denies_second_segment_in_semicolon() { - assert!(evaluate_command("echo hi; git reset --hard").is_some()); - } - - // ── Safe commands ───────────────────────────────── - - #[test] - fn allows_git_status() { - assert!(evaluate_command("git status").is_none()); - } - - #[test] - fn allows_cargo_build() { - assert!(evaluate_command("cargo build").is_none()); - } - - #[test] - fn allows_ls() { - assert!(evaluate_command("ls -la").is_none()); - } - - #[test] - fn allows_meta_commands() { - assert!(evaluate_command("meta git status").is_none()); - assert!(evaluate_command("meta exec -- cargo test").is_none()); - } - - // ── Denial reason content ───────────────────────── - - #[test] - fn force_push_reason_suggests_lease() { - let denial = evaluate_command("git push --force").unwrap(); - assert!(denial.reason.contains("--force-with-lease")); - } - - #[test] - fn reset_hard_reason_suggests_reflog() { - let denial = evaluate_command("git reset --hard").unwrap(); - assert!(denial.reason.contains("git reflog")); - } - - #[test] - fn clean_reason_suggests_dry_run() { - let denial = evaluate_command("git clean -fd").unwrap(); - assert!(denial.reason.contains("-nd")); - } - - // ── JSON output structure ───────────────────────── - - #[test] - fn hook_output_serializes_correctly() { - let output = HookOutput { - hook_specific_output: HookSpecificOutput { - hook_event_name: "PreToolUse".to_string(), - permission_decision: "deny".to_string(), - permission_decision_reason: "test reason".to_string(), - }, - }; - let json = serde_json::to_string(&output).unwrap(); - let v: serde_json::Value = serde_json::from_str(&json).unwrap(); - assert_eq!(v["hookSpecificOutput"]["hookEventName"], "PreToolUse"); - assert_eq!(v["hookSpecificOutput"]["permissionDecision"], "deny"); - assert_eq!( - v["hookSpecificOutput"]["permissionDecisionReason"], - "test reason" - ); - } - - // ── Pipe delimiter ─────────────────────────────── - - #[test] - fn split_pipe_delimiter() { - assert_eq!( - split_compound_command("git push --force | tee log.txt"), - vec!["git push --force", "tee log.txt"] - ); - } - - #[test] - fn denies_force_push_piped() { - assert!(evaluate_command("git push --force origin main | tee output.log").is_some()); - } - - #[test] - fn denies_reset_hard_piped() { - assert!(evaluate_command("git reset --hard | cat").is_some()); - } - - #[test] - fn split_pipe_does_not_confuse_or() { - // " || " should be matched as OR, not as two pipes - assert_eq!(split_compound_command("cmd1 || cmd2"), vec!["cmd1", "cmd2"]); - } - - // ── git clean separate flags ───────────────────── - - #[test] - fn denies_git_clean_f_d_separate() { - assert!(evaluate_command("git clean -f -d").is_some()); - } - - #[test] - fn denies_git_clean_d_f_separate() { - assert!(evaluate_command("git clean -d -f").is_some()); - } - - #[test] - fn denies_git_clean_f_d_x_separate() { - assert!(evaluate_command("git clean -f -d -x").is_some()); - } - - #[test] - fn allows_git_clean_f_only() { - // -f alone without -d should be allowed (only removes files, not dirs) - assert!(evaluate_command("git clean -f").is_none()); - } - - // ── rm -rf edge cases ──────────────────────────── - - #[test] - fn denies_rm_rf_meta_yaml() { - assert!(evaluate_command("rm -rf .meta.yaml").is_some()); - } - - #[test] - fn denies_rm_rf_meta_yml() { - assert!(evaluate_command("rm -rf .meta.yml").is_some()); - } - - #[test] - fn denies_rm_rf_home_tilde() { - assert!(evaluate_command("rm -rf ~").is_some()); - } - - #[test] - fn denies_rm_rf_home_var() { - assert!(evaluate_command("rm -rf $HOME").is_some()); - } - - #[test] - fn denies_rm_rf_dot_star() { - assert!(evaluate_command("rm -rf ./*").is_some()); - } - - #[test] - fn denies_rm_rf_parent_star() { - assert!(evaluate_command("rm -rf ../*").is_some()); - } - - #[test] - fn denies_rm_rf_trailing_slash() { - assert!(evaluate_command("rm -rf ./").is_some()); - } - - #[test] - fn denies_rm_rf_multiple_targets_with_dangerous() { - // Should catch .meta even among safe targets - assert!(evaluate_command("rm -rf node_modules .meta target").is_some()); - } - - // ── parse_command edge cases ───────────────────── - - #[test] - fn parse_command_handles_null_tool_input() { - assert_eq!(parse_command(r#"{"tool_input": null}"#), None); - } - - #[test] - fn parse_command_handles_null_command() { - assert_eq!(parse_command(r#"{"tool_input": {"command": null}}"#), None); - } - - #[test] - fn parse_command_ignores_extra_fields() { - let input = r#"{"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"git status","description":"check status"},"session_id":"abc"}"#; - assert_eq!(parse_command(input), Some("git status".to_string())); - } - - // ── git branch -D ──────────────────────────────────── - - #[test] - fn denies_git_branch_force_delete() { - assert!(evaluate_command("git branch -D feature-branch").is_some()); - } - - #[test] - fn denies_git_branch_force_delete_multiple() { - assert!(evaluate_command("git branch -D feat1 feat2").is_some()); - } - - #[test] - fn allows_git_branch_safe_delete() { - assert!(evaluate_command("git branch -d feature-branch").is_none()); - } - - #[test] - fn allows_git_branch_list() { - assert!(evaluate_command("git branch").is_none()); - assert!(evaluate_command("git branch -v").is_none()); - assert!(evaluate_command("git branch -a").is_none()); - } - - #[test] - fn allows_git_branch_create() { - assert!(evaluate_command("git branch new-feature").is_none()); - } - - #[test] - fn branch_delete_reason_suggests_safe_alternative() { - let denial = evaluate_command("git branch -D old-branch").unwrap(); - assert!(denial.reason.contains("git branch -d")); - assert!(denial.reason.contains("safe delete")); - } - - // ── git stash drop/clear ────────────────────────── - - #[test] - fn denies_git_stash_drop() { - assert!(evaluate_command("git stash drop").is_some()); - } - - #[test] - fn denies_git_stash_drop_with_ref() { - assert!(evaluate_command("git stash drop stash@{0}").is_some()); - } - - #[test] - fn denies_git_stash_clear() { - assert!(evaluate_command("git stash clear").is_some()); - } - - #[test] - fn allows_git_stash() { - assert!(evaluate_command("git stash").is_none()); - } - - #[test] - fn allows_git_stash_push() { - assert!(evaluate_command("git stash push -m 'WIP'").is_none()); - } - - #[test] - fn allows_git_stash_list() { - assert!(evaluate_command("git stash list").is_none()); - } - - #[test] - fn allows_git_stash_show() { - assert!(evaluate_command("git stash show").is_none()); - assert!(evaluate_command("git stash show stash@{0}").is_none()); - } - - #[test] - fn allows_git_stash_apply() { - assert!(evaluate_command("git stash apply").is_none()); - assert!(evaluate_command("git stash apply stash@{1}").is_none()); - } - - #[test] - fn allows_git_stash_pop() { - assert!(evaluate_command("git stash pop").is_none()); - } - - #[test] - fn stash_drop_reason_suggests_alternatives() { - let denial = evaluate_command("git stash drop").unwrap(); - assert!(denial.reason.contains("git stash list")); - assert!(denial.reason.contains("git stash apply")); - } - - #[test] - fn stash_clear_reason_suggests_alternatives() { - let denial = evaluate_command("git stash clear").unwrap(); - assert!(denial.reason.contains("ALL stash entries")); - assert!(denial.reason.contains("git stash drop")); - } - - // ── Pipe handling without spaces ────────────────── - - #[test] - fn split_pipe_no_spaces() { - assert_eq!( - split_compound_command("git status|tee log.txt"), - vec!["git status", "tee log.txt"] - ); - } - - #[test] - fn denies_force_push_piped_no_spaces() { - assert!(evaluate_command("git push --force|tee output.log").is_some()); - } - - #[test] - fn denies_reset_hard_piped_no_spaces() { - assert!(evaluate_command("git reset --hard|cat").is_some()); - } - - #[test] - fn split_pipe_mixed_spacing() { - assert_eq!( - split_compound_command("cmd1|cmd2 | cmd3"), - vec!["cmd1", "cmd2", "cmd3"] - ); - } - - #[test] - fn split_does_not_break_or_without_spaces() { - // "cmd1||cmd2" should still be treated as OR (not two pipes) - assert_eq!(split_compound_command("cmd1||cmd2"), vec!["cmd1", "cmd2"]); - } - - #[test] - fn pipe_in_compound_with_destructive() { - assert!(evaluate_command("git add .|git commit -m msg && git push --force").is_some()); - } - - // ── Edge cases for new patterns ─────────────────── - - #[test] - fn compound_with_branch_delete() { - assert!(evaluate_command("git checkout main && git branch -D old-feature").is_some()); - } - - #[test] - fn compound_with_stash_clear() { - assert!(evaluate_command("git stash && git stash clear").is_some()); - } - - #[test] - fn all_new_patterns_in_one_chain() { - assert!( - evaluate_command("git branch -D feat1 && git stash drop && git reset --hard").is_some() - ); - } - - // ── Configuration loading tests ──────────────────── - - #[test] - fn config_loads_embedded_defaults() { - let config = GuardConfig::load_from_embedded().unwrap(); - assert_eq!(config.schema_version, "1.0"); - assert!(!config.patterns.is_empty()); - - // Verify all expected patterns are present - let pattern_ids: Vec<&str> = config.patterns.iter().map(|p| p.id.as_str()).collect(); - assert!(pattern_ids.contains(&"meta.git.force_push")); - assert!(pattern_ids.contains(&"meta.git.reset_hard")); - assert!(pattern_ids.contains(&"meta.git.branch_force_delete")); - assert!(pattern_ids.contains(&"meta.git.stash_drop")); - assert!(pattern_ids.contains(&"meta.git.stash_clear")); - } - - #[test] - fn absent_policy_file_is_no_policy() { - let dir = tempfile::tempdir().unwrap(); - let absent = dir.path().join("agent-guard.toml"); - assert!(GuardConfig::load_from_file(&absent).unwrap().is_none()); - } - - #[test] - fn present_policy_file_that_cannot_be_read_or_parsed_is_an_error() { - let dir = tempfile::tempdir().unwrap(); - let malformed = dir.path().join("agent-guard.toml"); - std::fs::write(&malformed, "patterns = [ not toml").unwrap(); - // A directory where the file should be: exists, but unreadable as a file. - for path in [malformed, dir.path().to_path_buf()] { - let err = GuardConfig::load_from_file(&path).unwrap_err(); - assert!(format!("{err:#}").contains(&path.display().to_string())); - } - } - - #[test] - fn config_default_patterns_are_enabled() { - let config = GuardConfig::load().unwrap(); - - // All default patterns should be enabled - for pattern in &config.patterns { - assert!( - pattern.enabled, - "Pattern {} should be enabled by default", - pattern.id - ); - } - - // Verify we have the expected number of patterns - assert!( - config.patterns.len() >= 8, - "Should have at least 8 default patterns" - ); - } - - #[test] - fn config_can_parse_custom_toml() { - let toml = r#" -schema_version = "1.0" - -[[patterns]] -id = "meta.git.force_push" -enabled = false -matcher = { type = "regex", pattern = 'git\s+push.*--force' } -message = "Force push disabled" - -[[patterns]] -id = "meta.git.reset_hard" -enabled = true -matcher = { type = "regex", pattern = 'git\s+reset.*--hard' } -message = "Custom reset message" -"#; - let config: GuardConfig = toml::from_str(toml).unwrap(); - assert_eq!(config.schema_version, "1.0"); - assert_eq!(config.patterns.len(), 2); - - assert!(!config.patterns[0].enabled); - assert_eq!(config.patterns[0].id, "meta.git.force_push"); - - assert!(config.patterns[1].enabled); - assert_eq!(config.patterns[1].message, "Custom reset message"); - } - - #[test] - fn disabled_pattern_is_not_checked() { - // Create a custom config with git_force_push disabled - let toml = r#" -schema_version = "1.0" - -[[patterns]] -id = "meta.git.force_push" -enabled = false -matcher = { type = "regex", pattern = 'git\s+push.*\s+(--force|-f)\b(?!-with-lease)' } -message = "test" -"#; - let config: GuardConfig = toml::from_str(toml).unwrap(); - let patterns = config.compile_patterns(); - - // This command should normally be denied, but with the pattern disabled it should pass - let result = evaluate_segment("git push --force origin main", &patterns); - assert!(result.is_none()); - } - - #[test] - fn custom_message_overrides_default() { - let toml = r#" -schema_version = "1.0" - -[[patterns]] -id = "meta.git.force_push" -enabled = true -matcher = { type = "regex", pattern = 'git\s+push.*(--force|-f)\b' } -message = "TEAM POLICY: No force push ever!" -"#; - let config: GuardConfig = toml::from_str(toml).unwrap(); - let patterns = config.compile_patterns(); - let result = evaluate_segment("git push --force", &patterns).unwrap(); - assert_eq!(result.reason, "TEAM POLICY: No force push ever!"); - } - - #[test] - fn pattern_registry_covers_all_patterns() { - // Ensure all expected patterns are in the default config - let config = GuardConfig::load_from_embedded().unwrap(); - let pattern_ids: Vec<&str> = config.patterns.iter().map(|p| p.id.as_str()).collect(); - - assert!(pattern_ids.contains(&"meta.git.force_push")); - assert!(pattern_ids.contains(&"meta.git.reset_hard")); - assert!(pattern_ids.contains(&"meta.git.clean_force")); - assert!(pattern_ids.contains(&"meta.git.checkout_dot")); - assert!(pattern_ids.contains(&"meta.git.branch_force_delete")); - assert!(pattern_ids.contains(&"meta.git.stash_drop")); - assert!(pattern_ids.contains(&"meta.git.stash_clear")); - assert!(pattern_ids.contains(&"meta.rm.dangerous_paths")); - } - - #[test] - fn patterns_are_cached_across_evaluations() { - // First evaluation loads and compiles patterns - let result1 = evaluate_command("git status"); - assert!(result1.is_none()); - - // Second evaluation should use cached patterns (no additional file I/O or compilation) - let result2 = evaluate_command("git push --force"); - assert!(result2.is_some()); - - // Verify both evaluations worked correctly - let result3 = evaluate_command("git branch -D test"); - assert!(result3.is_some()); - } - - #[test] - fn debug_logging_available() { - // Test that debug env var is checked (doesn't crash) - std::env::set_var("META_DEBUG_GUARD", "1"); - let result = evaluate_command("git push --force"); - assert!(result.is_some()); - std::env::remove_var("META_DEBUG_GUARD"); - } - - #[test] - fn patterns_sorted_by_priority() { - let toml = r#" -schema_version = "1.0" - -[[patterns]] -id = "low" -priority = 50 -enabled = true -matcher = { type = "regex", pattern = 'test' } -message = "low priority" - -[[patterns]] -id = "high" -priority = 200 -enabled = true -matcher = { type = "regex", pattern = 'test' } -message = "high priority" - -[[patterns]] -id = "medium" -priority = 100 -enabled = true -matcher = { type = "regex", pattern = 'test' } -message = "medium priority" -"#; - let config: GuardConfig = toml::from_str(toml).unwrap(); - let patterns = config.compile_patterns(); - - // Should be sorted by priority (highest first) - assert_eq!(patterns[0].priority, 200); - assert_eq!(patterns[1].priority, 100); - assert_eq!(patterns[2].priority, 50); - } - - // ── File path sandboxing ──────────────────────────── - // - // Tests use evaluate_file_path_with_allowed() to avoid env var races - // when tests run in parallel. Tests use Unix-style paths and are - // skipped on Windows where `/tmp/...` is not considered absolute. - - #[cfg(not(windows))] + #[cfg(not(windows))] #[test] fn file_path_allows_within_prefix() { let allowed = std::env::join_paths(["/tmp/worktrees/test", "/tmp"]) @@ -1585,43 +1467,6 @@ message = "medium priority" assert!(result.unwrap().reason.contains("must be absolute")); } - // ── handle_guard with tool_name ───────────────────── - - #[test] - fn parse_hook_input_with_tool_name() { - let input = r#"{"tool_name":"Edit","tool_input":{"file_path":"/tmp/test.rs"}}"#; - let hi: HookInput = serde_json::from_str(input).unwrap(); - assert_eq!(hi.tool_name.as_deref(), Some("Edit")); - assert_eq!( - hi.tool_input.as_ref().unwrap().file_path.as_deref(), - Some("/tmp/test.rs") - ); - } - - #[test] - fn parse_hook_input_with_notebook_path() { - let input = - r#"{"tool_name":"NotebookEdit","tool_input":{"notebook_path":"/tmp/nb.ipynb"}}"#; - let hi: HookInput = serde_json::from_str(input).unwrap(); - assert_eq!(hi.tool_name.as_deref(), Some("NotebookEdit")); - assert_eq!( - hi.tool_input.as_ref().unwrap().notebook_path.as_deref(), - Some("/tmp/nb.ipynb") - ); - } - - #[test] - fn parse_hook_input_bash_still_works() { - let input = r#"{"tool_name":"Bash","tool_input":{"command":"git status"}}"#; - let hi: HookInput = serde_json::from_str(input).unwrap(); - assert_eq!(hi.tool_name.as_deref(), Some("Bash")); - assert_eq!( - hi.tool_input.as_ref().unwrap().command.as_deref(), - Some("git status") - ); - assert!(hi.tool_input.as_ref().unwrap().file_path.is_none()); - } - #[cfg(not(windows))] #[test] fn resolve_path_handles_existing_paths() { diff --git a/src/main.rs b/src/main.rs index a9e70a4..4eec68f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,7 @@ use clap::{Parser, Subcommand}; mod guard; mod score; +mod shell; /// Claude Code agent toolkit #[derive(Parser)] diff --git a/src/score.rs b/src/score.rs index 53b5cbe..9fcb190 100644 --- a/src/score.rs +++ b/src/score.rs @@ -280,7 +280,7 @@ fn process_bash_command( ) { let is_git = command.contains("git"); let is_meta_git = command.starts_with("meta git") || command.contains(" meta git "); - let is_destructive = is_destructive_command(command); + let is_destructive = crate::guard::is_destructive(command); // Metric 1: Meta-command ratio if is_git { @@ -319,17 +319,6 @@ fn process_bash_command( }); } -fn is_destructive_command(cmd: &str) -> bool { - // Reuse patterns from agent_guard.rs - cmd.contains("git push --force") - || cmd.contains("git push -f") - || cmd.contains("git reset --hard") - || cmd.contains("git clean -fd") - || cmd.contains("git clean -f -d") - || cmd.contains("git checkout .") - || cmd.contains("rm -rf") -} - // ── Scoring ───────────────────────────────────────────── /// Computed score for a session with grading. @@ -577,6 +566,21 @@ pub fn format_markdown(score: &SessionScore) -> String { mod tests { use super::*; + /// Destructive commands are classified by the guard's own evaluator. + #[test] + fn destructive_uses_the_guard() { + let mut metrics = SessionMetrics::default(); + for command in ["git -C api reset --hard", "echo \"git reset --hard\""] { + process_bash_command(command, 0, String::new(), &mut metrics); + } + let flags: Vec = metrics + .bash_commands + .iter() + .map(|c| c.is_destructive) + .collect(); + assert_eq!(flags, [true, false]); + } + #[test] fn test_compute_project_hash() { let path = Path::new("/Users/matt/development/meta"); @@ -662,15 +666,6 @@ mod tests { assert_eq!(metrics.workspace_discovery_rank, Some(2)); } - #[test] - fn test_is_destructive_command() { - assert!(is_destructive_command("git push --force origin main")); - assert!(is_destructive_command("git reset --hard")); - assert!(is_destructive_command("rm -rf .")); - assert!(!is_destructive_command("git status")); - assert!(!is_destructive_command("meta git status")); - } - #[test] fn test_overall_weights() { // Only bare git: (0*5 + 4 + 4 + 2) / 15 ≈ 0.67 → D diff --git a/src/shell.rs b/src/shell.rs new file mode 100644 index 0000000..9444755 --- /dev/null +++ b/src/shell.rs @@ -0,0 +1,461 @@ +//! A small shell lexer for the guard: it finds each simple command in a +//! command line and its words, the way sh would, without running anything. +//! +//! It removes quotes, decodes `$'…'`, joins `\`-newline, skips comments, +//! splits on `; & && || | |& ( ) newline`, drops redirections, keeps heredoc +//! bodies as the command's stdin, and lexes `$(…)`, backticks and `<(…)` as +//! commands of their own. What it does not model exactly is an error, so the +//! guard can deny it: a quote, substitution or heredoc it cannot close, nesting +//! deeper than [`MAX_DEPTH`], `case` inside `$(…)`, and a quote, backslash, +//! backtick, `$(`, `<<` or newline inside `((…))`. + +/// How deep substitutions and `sh -c` strings may nest. +pub const MAX_DEPTH: usize = 4; + +/// One simple command: its words without quotes, and the text its heredoc or +/// here-string feeds it. +#[derive(Debug, Default)] +pub struct Command { + pub words: Vec, + pub stdin: Option, +} + +/// The simple commands in `src`, nested `depth` levels deep. +pub fn parse(src: &str, depth: usize) -> Result, String> { + within(depth)?; + let mut lexer = Lexer::new(src, depth, Vec::new()); + lexer.script(None)?; + let mut cmds = lexer.cmds; + cmds.retain(|c| !c.words.is_empty()); + Ok(cmds) +} + +pub fn within(depth: usize) -> Result<(), String> { + match depth <= MAX_DEPTH { + true => Ok(()), + false => Err(format!("nested deeper than {MAX_DEPTH} levels")), + } +} + +struct Lexer { + s: Vec, + i: usize, + depth: usize, + cmds: Vec, + /// Heredocs whose bodies start at the next newline: + /// (command, delimiter, body is literal, strip leading tabs). + heredocs: Vec<(usize, String, bool, bool)>, +} + +impl Lexer { + fn new(src: &str, depth: usize, cmds: Vec) -> Self { + let s = src.chars().collect(); + Lexer { + s, + i: 0, + depth, + cmds, + heredocs: Vec::new(), + } + } + + fn at(&self, n: usize) -> Option { + self.s.get(self.i + n).copied() + } + + fn bump(&mut self) -> Option { + let c = self.at(0); + self.i += 1; + c + } + + fn start(&mut self) -> usize { + self.cmds.push(Command::default()); + self.cmds.len() - 1 + } + + /// Commands up to the end, or up to `close` (the `)` of `$(`). + fn script(&mut self, close: Option) -> Result<(), String> { + let mut cur = self.start(); + let mut parens = 0usize; + loop { + let Some(c) = self.at(0) else { + return match (close, self.heredocs.first()) { + (Some(_), _) => Err("unterminated $(".into()), + (None, Some((_, delim, ..))) => Err(format!("unterminated heredoc {delim}")), + (None, None) => Ok(()), + }; + }; + let empty = self.cmds.get(cur).is_none_or(|c| c.words.is_empty()); + match c { + ')' if parens == 0 && close == Some(')') => { + self.i += 1; + return Ok(()); + } + ' ' | '\t' => self.i += 1, + '\\' if self.at(1) == Some('\n') => self.i += 2, + '#' => { + while self.at(0).is_some_and(|c| c != '\n') { + self.i += 1; + } + } + '(' if self.at(1) == Some('(') => { + let start = self.i; + self.i += 2; + if !self.arith()? { + self.i = start + 1; + parens += 1; + } + } + '&' if self.at(1) == Some('>') => self.redirect(cur)?, + '<' | '>' if self.at(1) != Some('(') => self.redirect(cur)?, + ';' | '&' | '|' | '(' | ')' | '\n' => { + match c { + '(' => parens += 1, + ')' => parens = parens.saturating_sub(1), + _ => {} + } + self.i += 1; + if c == '\n' { + self.bodies()?; + } + if !empty { + cur = self.start(); + } + } + _ => { + if let Some(w) = self.word()? { + // A `case` pattern's `)` would end `$(` early. + if close.is_some() && (w == "case" || w == "esac") { + return Err("case inside $(…)".into()); + } + if let Some(cmd) = self.cmds.get_mut(cur) { + cmd.words.push(w); + } + } + } + } + } + } + + /// A redirection: its target is dropped, a heredoc is queued, and a + /// here-string becomes the command's stdin. + fn redirect(&mut self, cur: usize) -> Result<(), String> { + let mut op = String::new(); + while let Some(c @ ('<' | '>' | '&' | '-')) = self.at(0) { + if c == '-' && !op.starts_with("<<") { + break; + } + op.push(c); + self.i += 1; + } + if op == ">" && self.at(0) == Some('|') { + self.i += 1; + } + while matches!(self.at(0), Some(' ' | '\t')) { + self.i += 1; + } + let start = self.i; + let target = self.word()?.ok_or("a redirection without a target")?; + match op.as_str() { + "<<" | "<<-" => { + let raw = self.s.get(start..self.i).unwrap_or_default(); + let literal = raw.iter().any(|c| matches!(c, '\'' | '"' | '\\')); + self.heredocs.push((cur, target, literal, op == "<<-")); + } + "<<<" => { + if let Some(cmd) = self.cmds.get_mut(cur) { + cmd.stdin = Some(target); + } + } + _ => {} + } + Ok(()) + } + + /// Reads the bodies of the queued heredocs, which start after a newline. + fn bodies(&mut self) -> Result<(), String> { + for (cur, delim, literal, strip) in std::mem::take(&mut self.heredocs) { + let mut body = String::new(); + loop { + if self.i >= self.s.len() { + return Err(format!("unterminated heredoc {delim}")); + } + let rest = self.s.get(self.i..).unwrap_or_default(); + let line: String = rest.iter().take_while(|&&c| c != '\n').collect(); + self.i += line.chars().count() + 1; + let line = if strip { + line.trim_start_matches('\t') + } else { + &line + }; + if line == delim { + break; + } + body.push_str(line); + body.push('\n'); + } + if !literal { + self.nested(&body, |l| l.dquote(None).map(drop))?; + } + if let Some(cmd) = self.cmds.get_mut(cur) { + cmd.stdin = Some(body); + } + } + Ok(()) + } + + /// One word with its quotes removed; `None` for a file-descriptor number + /// such as the `2` in `2>&1`. + fn word(&mut self) -> Result, String> { + let start = self.i; + let mut w = String::new(); + while let Some(c) = self.at(0) { + match c { + ' ' | '\t' | '\n' | ';' | '&' | '|' | '(' | ')' => break, + '<' | '>' if self.at(1) != Some('(') => break, + '<' | '>' => { + self.i += 2; + self.substitution()?; + w.push_str("<(…)"); + } + '\'' => { + self.i += 1; + while let Some(c) = self.bump() { + if c == '\'' { + break; + } + w.push(c); + } + if self.i > self.s.len() { + return Err("unterminated '".into()); + } + } + '"' => { + self.i += 1; + w.push_str(&self.dquote(Some('"'))?); + } + '\\' => { + self.i += 1; + match self.bump() { + Some('\n') => {} + Some(c) => w.push(c), + None => return Err("a trailing backslash".into()), + } + } + '$' => self.dollar(&mut w, false)?, + '`' => self.backtick(&mut w, false)?, + c => { + self.i += 1; + w.push(c); + } + } + } + let raw = self.s.get(start..self.i).unwrap_or_default(); + let fd = raw.iter().all(char::is_ascii_digit) && matches!(self.at(0), Some('<' | '>')); + Ok((self.i > start && !fd).then_some(w)) + } + + /// The inside of `"…"` (or of an unquoted heredoc body, with no `end`). + fn dquote(&mut self, end: Option) -> Result { + let mut out = String::new(); + loop { + match self.at(0) { + None if end.is_none() => return Ok(out), + None => return Err("unterminated \"".into()), + Some(c) if Some(c) == end => { + self.i += 1; + return Ok(out); + } + Some('\\') => { + self.i += 1; + match self.bump() { + Some('\n') | None => {} + Some(c @ ('$' | '`' | '"' | '\\')) => out.push(c), + Some(c) => out.extend(['\\', c]), + } + } + Some('$') => self.dollar(&mut out, true)?, + Some('`') => self.backtick(&mut out, end.is_some())?, + Some(c) => { + self.i += 1; + out.push(c); + } + } + } + } + + /// `$'…'`, `$((…))`, `$(…)`, `${…}` or a plain `$`; `${NAME}` becomes `$NAME`. + fn dollar(&mut self, w: &mut String, in_dquote: bool) -> Result<(), String> { + match self.at(1) { + Some('\'') if !in_dquote => { + self.i += 2; + w.push_str(&self.ansi()?); + } + Some('"') if !in_dquote => self.i += 1, + Some('(') => { + let start = self.i; + self.i += 3; + if self.s.get(start + 2) != Some(&'(') || !self.arith()? { + self.i = start + 2; + self.substitution()?; + } + w.push_str("$(…)"); + } + Some('{') => { + self.i += 2; + let inner = self.deeper(Self::braces)?; + let name = !inner.is_empty() + && inner.chars().all(|c| c == '_' || c.is_ascii_alphanumeric()); + match name { + true => w.extend(std::iter::once('$').chain(inner.chars())), + false => w.push_str(&format!("${{{inner}}}")), + } + } + _ => { + self.i += 1; + w.push('$'); + } + } + Ok(()) + } + + /// The inside of `${…}`, with nested quotes, escapes and substitutions. + fn braces(&mut self) -> Result { + let mut out = String::new(); + let mut open = 1; + loop { + match self.at(0).ok_or("unterminated ${")? { + '$' => self.dollar(&mut out, false)?, + '`' => self.backtick(&mut out, false)?, + '"' => { + self.i += 1; + out.push_str(&self.dquote(Some('"'))?); + } + '\\' => { + self.i += 1; + out.push(self.bump().ok_or("unterminated ${")?); + } + '\'' => { + self.i += 1; + while let Some(c) = self.bump().filter(|&c| c != '\'') { + out.push(c); + } + if self.i > self.s.len() { + return Err("unterminated '".into()); + } + } + c => { + self.i += 1; + match c { + '{' => open += 1, + '}' if open == 1 => return Ok(out), + '}' => open -= 1, + _ => {} + } + out.push(c); + } + } + } + } + + /// The inside of `$'…'`, with its escapes decoded. + fn ansi(&mut self) -> Result { + let mut out = String::new(); + loop { + let c = match self.bump().ok_or("unterminated $'")? { + '\'' => return Ok(out), + '\\' => match self.bump().ok_or("unterminated $'")? { + 'n' => '\n', + 't' => '\t', + 'r' => '\r', + 'e' | 'E' => '\x1b', + 'x' => self.code(16, 2, 0), + 'u' => self.code(16, 4, 0), + 'U' => self.code(16, 8, 0), + d @ '0'..='7' => self.code(8, 2, d.to_digit(8).unwrap_or(0)), + c => c, + }, + c => c, + }; + out.push(c); + } + } + + /// Up to `max` more digits in `radix` after `acc`, as a character. + fn code(&mut self, radix: u32, max: usize, mut acc: u32) -> char { + for _ in 0..max { + let Some(d) = self.at(0).and_then(|c| c.to_digit(radix)) else { + break; + }; + acc = acc.saturating_mul(radix).saturating_add(d); + self.i += 1; + } + char::from_u32(acc).unwrap_or('\u{fffd}') + } + + /// The inside of `((…))` after its opening, which is opaque: `false` at a + /// lone `)`, as it was `( (…) …)`. Bash and this lexer may end it at + /// different places, so what could hide that is an error. + fn arith(&mut self) -> Result { + let mut open = 0usize; + loop { + match self.bump().ok_or("unterminated ((")? { + c @ ('\'' | '"' | '`' | '\\' | '\n') => return Err(format!("{c:?} inside ((…))")), + '$' if self.at(0) == Some('(') => return Err("$( inside ((…))".into()), + '<' if self.at(0) == Some('<') => return Err("<< inside ((…))".into()), + '(' => open += 1, + ')' if open == 0 => return Ok(self.bump() == Some(')')), + ')' => open -= 1, + _ => {} + } + } + } + + /// `` `…` ``: its commands are lexed one level deeper. Inside `"…"`, `\"` is `"`. + fn backtick(&mut self, w: &mut String, in_dquote: bool) -> Result<(), String> { + self.i += 1; + let mut inner = String::new(); + loop { + match self.bump().ok_or("unterminated `")? { + '`' => break, + '\\' => match self.bump() { + Some(c @ ('`' | '\\' | '$')) => inner.push(c), + Some('"') if in_dquote => inner.push('"'), + Some(c) => inner.extend(['\\', c]), + None => {} + }, + c => inner.push(c), + } + } + w.push_str("`…`"); + self.nested(&inner, |l| l.script(None)) + } + + /// `$(…)` or `<(…)` after its opening: its commands, one level deeper. + fn substitution(&mut self) -> Result<(), String> { + self.deeper(|l| l.script(Some(')'))) + } + + /// Runs `f` one level deeper, or fails past [`MAX_DEPTH`]. + fn deeper(&mut self, f: impl FnOnce(&mut Self) -> Result) -> Result { + within(self.depth + 1)?; + self.depth += 1; + let result = f(self); + self.depth -= 1; + result + } + + /// Lexes `text` one level deeper, adding its commands to this lexer's. + fn nested( + &mut self, + text: &str, + f: impl FnOnce(&mut Self) -> Result<(), String>, + ) -> Result<(), String> { + within(self.depth + 1)?; + let mut sub = Lexer::new(text, self.depth + 1, std::mem::take(&mut self.cmds)); + let result = f(&mut sub); + self.cmds = sub.cmds; + result + } +} diff --git a/tests/guard.bats b/tests/guard.bats index ca87031..9f4c07c 100644 --- a/tests/guard.bats +++ b/tests/guard.bats @@ -3,7 +3,7 @@ # Integration tests for `agent guard` setup() { - AGENT_BIN="$BATS_TEST_DIRNAME/../target/debug/agent" + AGENT_BIN="${CARGO_TARGET_DIR:-$BATS_TEST_DIRNAME/../target}/debug/agent" if [ ! -f "$AGENT_BIN" ]; then cargo build --manifest-path "$BATS_TEST_DIRNAME/../Cargo.toml" --quiet @@ -139,7 +139,7 @@ setup() { [[ "$output" == *"deny"* ]] } -# ============ Graceful degradation ============ +# ============ Fail closed ============ @test "guard handles empty stdin" { run bash -c 'echo "" | '"$AGENT_BIN"' guard' @@ -147,22 +147,51 @@ setup() { [ -z "$output" ] } -@test "guard handles malformed JSON" { +@test "guard denies malformed JSON" { run bash -c 'echo "not json" | '"$AGENT_BIN"' guard' [ "$status" -eq 0 ] - [ -z "$output" ] + [[ "$output" == *"deny"* ]] } -@test "guard handles missing tool_input" { - run bash -c 'echo '"'"'{"other":"field"}}'"'"' | '"$AGENT_BIN"' guard' +@test "guard denies input without tool_input" { + run bash -c 'echo '"'"'{"other":"field"}'"'"' | '"$AGENT_BIN"' guard' [ "$status" -eq 0 ] - [ -z "$output" ] + [ "$(echo "$output" | jq -r .hookSpecificOutput.permissionDecision)" = deny ] } -@test "guard handles missing command field" { +@test "guard denies a Bash call without a command" { run bash -c 'echo '"'"'{"tool_input":{}}'"'"' | '"$AGENT_BIN"' guard' [ "$status" -eq 0 ] - [ -z "$output" ] + [[ "$output" == *"deny"* ]] +} + +@test "guard denies every Bash call while the policy file is broken" { + cd "$BATS_TEST_TMPDIR" + mkdir -p .claude + printf 'schema_version = "1.0"\n[[patterns]]\nid = "x"\n' > .claude/agent-guard.toml + run bash -c 'echo '"'"'{"tool_input":{"command":"git status"}}'"'"' | HOME="$PWD" '"$AGENT_BIN"' guard' + [ "$status" -eq 0 ] + [[ "$output" == *"deny"* ]] + [[ "$output" == *"agent-guard.toml"* ]] +} + +# ============ End to end through meta's hook ============ + +@test "meta's PreToolUse hook stops git -C api reset --hard before it destroys an unpushed commit" { + cd "$BATS_TEST_TMPDIR" + export HOME="$PWD" GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@t GIT_COMMITTER_NAME=t GIT_COMMITTER_EMAIL=t@t + export PATH="$(dirname "$AGENT_BIN"):$PATH" + git init -q --bare -b main r.git + git clone -q r.git api 2>/dev/null + (cd api && echo a > a && git add a && git commit -qm init && git push -q origin main \ + && echo c > CANARY && git add CANARY && git commit -qm CANARY) + # The hook command `meta init skills` writes (meta_cli/src/init.rs). + HOOK="agent --help 2>/dev/null | grep -q 'Claude Code agent toolkit' && agent guard; exit 0" + C='git -C api reset --hard origin/main' + out=$(printf '{"tool_name":"Bash","tool_input":{"command":"%s"}}' "$C" | sh -c "$HOOK") + [[ "$out" == *'"permissionDecision":"deny"'* ]] + [ -z "$out" ] && sh -c "$C" + [ -f api/CANARY ] } # ============ JSON output structure ============