#!/usr/bin/env python3 """delivery guard hook: ADR-0032 enforcement layer 2. A pre-tool-use hook. It denies the Never tier on every runtime and asks before Odd-job commands where the runtime honours `ask` (Claude Code, Copilot CLI), denying them elsewhere. It is a guardrail, not the boundary: credentials the agent does not hold are the boundary (ADR-0032). Anything this script cannot see (a script the agent writes then runs, `python -c`, a subprocess, an MCP tool) gets past it by construction. Self-contained on purpose: standard library only, one file, no network. A hook that fails to start blocks the call on Claude Code (`onFailure: block`) and on Copilot CLI (non-zero exit denies), so the cost of a broken guard is a stopped session, never a silent pass, except on Codex, which may let an errored hook's call through. Runtime detection is by where apm deployed this file: .claude/hooks/... Claude Code ask honoured .github/hooks/scripts/... Copilot CLI ask honoured (see ADR-0032 risks) .codex/hooks/... Codex ask unsupported, so deny anywhere else unknown deny A camelCase payload (`toolName`) is also taken as Copilot. """ import fnmatch import json import os import re import sys # -------------------------------------------------------------------------- # Decisions # -------------------------------------------------------------------------- ALLOW, ASK, DENY = "allow", "ask", "deny" _RANK = {ALLOW: 0, ASK: 1, DENY: 2} HANDOFF = ( " This is an Odd job (ADR-0032): run it only in a HITL session the human " "started for it; otherwise hand the command to the human." ) class Verdict: def __init__(self, decision=ALLOW, reason=""): self.decision = decision self.reason = reason def merge(self, other): if _RANK[other.decision] > _RANK[self.decision]: return other return self def deny(reason): return Verdict(DENY, "delivery guard: Never tier (ADR-0032). " + reason) def ask(reason): return Verdict(ASK, "delivery guard: " + reason + HANDOFF) OK = Verdict() HOOK_BYPASS = "never bypass the repo's gates." # -------------------------------------------------------------------------- # Secret material: paths an agent never reads # -------------------------------------------------------------------------- SECRET_BASENAME_GLOBS = ( ".vault_pass*", ".vault-pass*", "vault_pass*", "vault-pass*", "*vault_password*", "*vault-password*", "*.tfstate", "*.tfstate.*", "id_rsa", "id_dsa", "id_ecdsa", "id_ed25519", "id_ecdsa_sk", "id_ed25519_sk", "*.key", "key.pem", "*-key.pem", "*_key.pem", "*.key.pem", "privkey*.pem", "*private*.pem", "*.p12", "*.pfx", ) # Representative secret names, used to decide whether a shell glob the agent # wrote (`cat .vault_pa*`) could expand to secret material. SECRET_SAMPLES = ( ".vault_pass", ".vault-pass", "vault_pass.txt", "vault_password", ".vault_password_file", "terraform.tfstate", "terraform.tfstate.backup", "id_rsa", "id_ed25519", "id_ecdsa", "server.key", "privkey.pem", "tls-key.pem", "sealed-secrets-key.pem", "cert.p12", ) GLOB_CHARS = set("*?[") def _literal_count(pattern): return sum(1 for ch in pattern if ch not in "*?[]!") def is_secret_path(word): if not word: return False candidates = {word} # --flag=value, NAME=value, curl's @file if "=" in word: candidates.add(word.rsplit("=", 1)[1]) if word.startswith("@"): candidates.add(word[1:]) for cand in candidates: cand = cand.strip().rstrip("/") if not cand: continue norm = cand.replace("\\", "/") # the admin kubeconfig, its backups, and the directory holding them if norm == ".kube" or norm.endswith("/.kube") or "/.kube/config" in "/" + norm: return True base = os.path.basename(norm).lower() if base.endswith(".pub"): continue if any(fnmatch.fnmatchcase(base, g) for g in SECRET_BASENAME_GLOBS): return True if GLOB_CHARS & set(base) and _literal_count(base) >= 3: if any(fnmatch.fnmatchcase(s, base) for s in SECRET_SAMPLES): return True parent = os.path.basename(os.path.dirname(norm)) if parent == ".kube" and fnmatch.fnmatchcase("config", base): return True return False # -------------------------------------------------------------------------- # Shell tokenising # -------------------------------------------------------------------------- OPERATORS = ("&&", "||", ";;", "|&", ";", "|", "&", "\n", "(", ")") REDIRECTS = ("<<<", "<<-", "<<", ">>", "&>", ">&", "<&", "<>", ">|", "<", ">") class Shell: """Splits a command line into simple commands (lists of unquoted words). Not a full shell parser. It understands quoting, escapes, the control operators, redirections, here-documents (whose bodies are data, not commands), and command / process substitution, whose inner text is analysed as further commands. A word that still holds a parameter expansion after unquoting is marked dynamic, because its value is unknown. """ def __init__(self, text): self.text = text self.i = 0 self.commands = [] # list of list of (word, dynamic) self.nested = [] # inner texts of $(...), `...`, <(...), >(...) self.pending = [] # (delimiter, strip_tabs) of here-docs to skip def parse(self): current = [] n = len(self.text) while self.i < n: c = self.text[self.i] if c in " \t": self.i += 1 continue if self.text.startswith("\\\n", self.i): self.i += 2 continue if c == "#" and self._at_word_start(): while self.i < n and self.text[self.i] != "\n": self.i += 1 continue op = self._match(OPERATORS) if op: self.i += len(op) if op == "\n" and self.pending: self._skip_heredocs() if current: self.commands.append(current) current = [] continue if self.text.startswith(("<(", ">("), self.i): self.i += 1 self.nested.append(self._balanced("(", ")")) continue red = self._match(REDIRECTS) if red: self.i += len(red) if red in ("<<", "<<-"): while self.i < n and self.text[self.i] in " \t": self.i += 1 delim, _ = self._word() self.pending.append((delim, red == "<<-")) # any other redirect target stays a word of this command, so a # `< .vault_pass` is caught by the secret-path check continue word, dynamic = self._word() current.append((word, dynamic)) if current: self.commands.append(current) return self def _skip_heredocs(self): n = len(self.text) for delim, strip_tabs in self.pending: while self.i < n: end = self.text.find("\n", self.i) end = n if end == -1 else end line = self.text[self.i:end] self.i = min(end + 1, n) if (line.lstrip("\t") if strip_tabs else line) == delim: break self.pending = [] def _at_word_start(self): return self.i == 0 or self.text[self.i - 1] in " \t\n;&|()" def _match(self, ops): for op in ops: if self.text.startswith(op, self.i): return op return None def _balanced(self, open_c, close_c): # self.i is at open_c depth, start = 0, self.i + 1 n = len(self.text) quote = None while self.i < n: c = self.text[self.i] if quote: if c == "\\" and quote == '"': self.i += 2 continue if c == quote: quote = None elif c in "'\"": quote = c elif c == "\\": self.i += 2 continue elif c == open_c: depth += 1 elif c == close_c: depth -= 1 if depth == 0: inner = self.text[start:self.i] self.i += 1 return inner self.i += 1 return self.text[start:] def _backtick(self): start = self.i + 1 self.i += 1 n = len(self.text) while self.i < n and self.text[self.i] != "`": if self.text[self.i] == "\\": self.i += 1 self.i += 1 inner = self.text[start:self.i] self.i += 1 return inner def _word(self): out = [] dynamic = False n = len(self.text) while self.i < n: c = self.text[self.i] if c in " \t\n;&|()<>": break if c == "\\": if self.i + 1 < n and self.text[self.i + 1] != "\n": out.append(self.text[self.i + 1]) self.i += 2 # a backslash-newline is a line continuation elif c == "'": end = self.text.find("'", self.i + 1) end = n if end == -1 else end out.append(self.text[self.i + 1:end]) self.i = end + 1 elif c == '"': self.i += 1 while self.i < n and self.text[self.i] != '"': d = self.text[self.i] if d == "\\" and self.i + 1 < n and self.text[self.i + 1] in '"\\$`\n': if self.text[self.i + 1] != "\n": out.append(self.text[self.i + 1]) self.i += 2 elif d == "$" and self.text.startswith("$(", self.i): self.i += 1 self.nested.append(self._balanced("(", ")")) dynamic = True elif d == "`": self.nested.append(self._backtick()) dynamic = True elif d == "$" and self.i + 1 < n and re.match(r"[A-Za-z_{0-9@*#?!$-]", self.text[self.i + 1]): out.append(d) dynamic = True self.i += 1 else: out.append(d) self.i += 1 self.i += 1 elif c == "$" and self.text.startswith("$'", self.i): self.i += 1 end = self.text.find("'", self.i + 1) end = n if end == -1 else end raw = self.text[self.i + 1:end] try: raw = raw.encode("latin-1", "backslashreplace").decode("unicode_escape") except Exception: pass out.append(raw) self.i = end + 1 elif c == "$" and self.text.startswith("$(", self.i): self.i += 1 self.nested.append(self._balanced("(", ")")) dynamic = True elif c == "`": self.nested.append(self._backtick()) dynamic = True elif c == "$" and self.i + 1 < n and re.match(r"[A-Za-z_{0-9@*#?!$-]", self.text[self.i + 1]): out.append(c) dynamic = True self.i += 1 else: out.append(c) self.i += 1 return "".join(out), dynamic # -------------------------------------------------------------------------- # Unwrapping: find the program a simple command really runs # -------------------------------------------------------------------------- SHELLS = {"sh", "bash", "zsh", "dash", "ksh", "ash", "mksh", "fish"} SHELL_VALUE_OPTS = {"-o", "+o", "-O", "+O", "--rcfile", "--init-file"} # Words that only prefix the real command. Matched on the basename, so # /usr/bin/time and /usr/bin/nohup count. KEYWORDS = {"!", "{", "}", "then", "do", "else", "elif", "if", "while", "until", "time", "coproc", "exec", "command", "builtin", "nohup", "setsid", "chronic", "unbuffer", "caffeinate"} KEYWORD_VALUE_OPTS = {("exec", "-a"), ("time", "-f"), ("time", "-o"), ("time", "--format"), ("time", "--output")} # wrapper -> options that consume the next word WRAPPERS = { "env": {"-u", "--unset", "-C", "--chdir", "-S", "--split-string"}, "sudo": {"-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-U", "-T", "--user", "--group", "--chdir", "--host", "--prompt", "--role", "--type"}, "doas": {"-u", "-C"}, "nice": {"-n", "--adjustment"}, "ionice": {"-c", "-n", "-p"}, "timeout": {"-s", "--signal", "-k", "--kill-after"}, "stdbuf": {"-i", "-o", "-e"}, "xargs": {"-I", "-L", "-n", "-P", "-s", "-d", "-E", "-a", "--replace", "--max-lines", "--max-args", "--max-procs", "--max-chars", "--delimiter", "--eof", "--arg-file"}, "watch": {"-n", "--interval", "-d"}, "strace": {"-o", "-e", "-p", "-s", "-u"}, "ltrace": {"-o", "-e", "-p", "-s", "-u"}, "taskset": set(), "chrt": set(), "flock": {"-w", "-E", "--timeout", "--conflict-exit-code"}, "unshare": set(), "systemd-run": {"-p", "--property", "-u", "--unit", "-E", "--setenv"}, "su": {"-s", "--shell", "-g", "--group"}, "runuser": {"-u", "-g", "-s"}, "script": {"-c", "--command"}, "parallel": {"-j", "--jobs", "-S", "--sshlogin", "--joblog", "-a", "--arg-file", "--delay", "--timeout", "-I", "--colsep"}, "ssh": {"-B", "-b", "-c", "-D", "-E", "-e", "-F", "-I", "-i", "-J", "-L", "-l", "-m", "-O", "-o", "-p", "-Q", "-R", "-S", "-W", "-w"}, } ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\+?=") GUARDED = re.compile( r"\b(kubectl|kubecolor|helm|helm3|tofu|terraform|terragrunt|ansible-playbook|" r"ansible-vault|ansible|ansible-pull|ansible-console|kubeseal|flux|sops|" r"pre-commit)\b" r"|--no-verif|hookspath|\bSKIP\+?=|vault.pass|\.tfstate|id_rsa|id_ed25519|\.kube", re.I, ) BRACE = re.compile(r"\{[^{}]*,[^{}]*\}") # Options whose value a tool reads itself on the agent's behalf, as Ansible # does with the vault password file and the SSH key. Such a run is an Odd job. SECRET_ARG_EXEMPT = ("--vault-password-file", "--vault-pass-file", "--vault-id", "--private-key", "--key-file") SEARCHERS = {"grep", "egrep", "fgrep", "rg", "ag", "ack"} SEARCH_VALUE_OPTS = {"-A", "-B", "-C", "-m", "-d", "-D", "-g", "-t", "-T", "--include", "--exclude", "--exclude-dir", "--glob", "--type", "--max-count", "--context", "--after-context", "--before-context"} # Programs that only print their arguments or look at file metadata. NEUTRAL = {"echo", "printf", "ls", "stat", "test", "[", "[[", "true", ":"} # Tool runners: args. Ansible repos commonly # run their tools through a project venv this way. RUNNERS = { "uv": {"run", "tool"}, "poetry": {"run"}, "pipenv": {"run"}, "pdm": {"run"}, "hatch": {"run"}, "pipx": {"run"}, "direnv": {"exec"}, "mise": {"exec", "x"}, "devbox": {"run"}, "uvx": None, } def assignment_verdict(word): name, value = word.split("=", 1) name = name.rstrip("+") low = value.lower() if name == "SKIP": return deny("SKIP= skips pre-commit hooks; " + HOOK_BYPASS) if "hookspath" in low or (name.startswith("GIT_CONFIG") and "no-verify" in low): return deny("Overriding core.hooksPath skips the repo's git hooks; " + HOOK_BYPASS) if is_secret_path(value): return deny("'%s' is secret material; agents never read it." % value) return OK def search_pattern_indexes(args): """Indexes of args that are a search pattern rather than a file.""" explicit = any(a in ("-e", "--regexp", "-f", "--file") or a.startswith(("--regexp=", "--file=")) for a in args) skip = set() idx = 0 while idx < len(args): a = args[idx] if a in ("-e", "--regexp") and idx + 1 < len(args): skip.add(idx + 1) idx += 2 continue if a in SEARCH_VALUE_OPTS: skip.add(idx + 1) idx += 2 continue if a == "--": if not explicit and idx + 1 < len(args): skip.add(idx + 1) break if not a.startswith("-"): if not explicit: skip.add(idx) break idx += 1 return skip def secret_words(prog_word, prog, args): if prog in NEUTRAL: return OK if prog == "git": sub_idx = _git_sub_index(args) sub = args[sub_idx] if sub_idx is not None else "" if sub in ("rm", "check-ignore", "ls-files", "status"): return OK skip = set() if prog in SEARCHERS: skip = search_pattern_indexes(args) elif prog == "git" and sub == "grep": skip = {i + sub_idx + 1 for i in search_pattern_indexes(args[sub_idx + 1:])} if is_secret_path(prog_word): return deny("'%s' is secret material; agents never run or read it." % prog_word) skip_next = False for idx, w in enumerate(args): if skip_next: skip_next = False continue if idx in skip: continue if w in SECRET_ARG_EXEMPT: skip_next = True continue if w.startswith(tuple(e + "=" for e in SECRET_ARG_EXEMPT)): continue if is_secret_path(w): return deny("'%s' is secret material (vault password, private key, " "admin kubeconfig or tofu state); agents never read, copy " "or commit it." % w) return OK class Analyzer: def __init__(self): self.depth = 0 def text(self, command): """Verdict for a whole command line.""" if self.depth > 8: return deny("Command nesting too deep for the guard to read; simplify it.") self.depth += 1 try: sh = Shell(command).parse() verdict = OK for words in sh.commands: verdict = verdict.merge(self.simple(words, command)) for inner in sh.nested: verdict = verdict.merge(self.text(inner)) return verdict finally: self.depth -= 1 def simple(self, words, whole): joined = " ".join(w for w, _ in words) if any(BRACE.search(w) for w, _ in words) and GUARDED.search(joined): return deny("Brace expansion hides what this command runs; write it " "out literally.") return self.program(list(words), whole) def program(self, words, whole): verdict = OK # leading assignments: NAME=value cmd ... while words and ASSIGNMENT.match(words[0][0]): verdict = verdict.merge(assignment_verdict(words[0][0])) words = words[1:] while words and os.path.basename(words[0][0]) in KEYWORDS: head = os.path.basename(words[0][0]) words = words[1:] if head == "command" and words and words[0][0] in ("-v", "-V"): return verdict if head == "coproc" and len(words) >= 2 and words[1][0] == "{": words = words[1:] while words and words[0][0].startswith("-") and len(words[0][0]) > 1: opt = words[0][0] words = words[1:] if opt == "--": break if (head, opt) in KEYWORD_VALUE_OPTS: words = words[1:] while words and ASSIGNMENT.match(words[0][0]): verdict = verdict.merge(assignment_verdict(words[0][0])) words = words[1:] if not words or verdict.decision == DENY: return verdict prog_word, prog_dynamic = words[0] if prog_dynamic: # The program name is only known at run time. Fail safe when the # line mentions a guarded tool at all. if GUARDED.search(whole): return deny("The program name is built at run time ('%s'), so the guard " "cannot classify this command. Write the command out literally." % prog_word) return verdict if GLOB_CHARS & set(prog_word): return deny("The program name '%s' is a glob; write it out literally." % prog_word) prog = os.path.basename(prog_word) args = [w for w, _ in words[1:]] if prog in ("export", "declare", "typeset", "local", "readonly"): for a in args: if ASSIGNMENT.match(a): verdict = verdict.merge(assignment_verdict(a)) return verdict if prog in SHELLS: return verdict.merge(self.shell(args, whole)) if prog == "eval": return verdict.merge(self.text(" ".join(args))) if prog in WRAPPERS: return verdict.merge(self.wrapper(prog, words[1:], whole)) if prog == "busybox" and args: return verdict.merge(self.program(words[1:], whole)) if prog == "find": verdict = verdict.merge(self.find_exec(args)) if prog == "rtk": return verdict.merge(self.rtk(words[1:], whole)) if prog in RUNNERS: return verdict.merge(self.runner(prog, words[1:], whole)) verdict = verdict.merge(secret_words(prog_word, prog, args)) rule = RULES.get(prog) if rule: verdict = verdict.merge(rule(args, self)) return verdict def shell(self, args, whole): idx = 0 while idx < len(args): a = args[idx] if a in SHELL_VALUE_OPTS: idx += 2 continue if a == "--": idx += 1 break if a.startswith("--"): idx += 1 continue if a[:1] in "-+" and len(a) > 1: if "c" in a[1:]: j = idx + 1 while j < len(args) and args[j] in SHELL_VALUE_OPTS: j += 2 return self.text(args[j]) if j < len(args) else OK idx += 1 continue break rest = args[idx:] if not rest: # The shell reads its commands from stdin: a pipe or here-doc the # guard cannot follow. if GUARDED.search(whole): return deny("A shell reading commands from stdin hides what it runs; " "run the command directly.") return OK # bash script.sh, or a here-string (`bash <<< 'cmd'`), whose word lands here verdict = OK for r in rest: verdict = verdict.merge(self.text(r)) return verdict def rtk(self, words, whole): # rtk args passes through to ; rtk run is sh -c; proxy, # err, test and summary run the rest as a command. while words and words[0][0].startswith("-"): words = words[1:] if not words: return OK sub = words[0][0] if sub == "run": return self.text(" ".join(w for w, _ in words[1:])) if sub in ("proxy", "err", "test", "summary"): return self.program(words[1:], whole) return self.program(words, whole) def runner(self, prog, words, whole): subs = RUNNERS[prog] start = 0 if subs is not None: while start < len(words) and words[start][0].startswith("-"): start += 1 if start >= len(words) or words[start][0] not in subs: return OK start += 1 # Runner options take values (`uv run --with x …`), so rather than # model each runner's options, start at the first word that names a # program the guard knows. for idx in range(start, len(words)): base = os.path.basename(words[idx][0]) if base in RULES or base in SHELLS or base in WRAPPERS or \ base in ("eval", "rtk") or base in RUNNERS: return self.program(words[idx:], whole) return OK def find_exec(self, args): verdict = OK idx = 0 while idx < len(args): if args[idx] in ("-exec", "-execdir", "-ok", "-okdir"): end = idx + 1 while end < len(args) and args[end] not in (";", "+"): end += 1 inner = [(w, False) for w in args[idx + 1:end]] verdict = verdict.merge(self.program(inner, " ".join(args))) idx = end idx += 1 return verdict def wrapper(self, prog, words, whole): takes_value = WRAPPERS[prog] if prog in ("su", "script"): # su -c / su -lc / script -qc carry a command string for idx, (w, _) in enumerate(words): is_c = w in ("-c", "--command") or ( w.startswith("-") and not w.startswith("--") and "c" in w[1:]) if is_c and idx + 1 < len(words): return self.text(words[idx + 1][0]) if w.startswith("--command="): return self.text(w.split("=", 1)[1]) return OK if prog == "watch": rest = self._skip_opts(words, takes_value) return self.text(" ".join(w for w, _ in rest)) if prog == "ssh": rest = self._skip_opts(words, takes_value) if len(rest) > 1: return self.text(" ".join(w for w, _ in rest[1:])) return OK if prog == "parallel": rest = self._skip_opts(words, takes_value) cmd = [] for w in rest: if w[0] in (":::", "::::", ":::+", "::::+"): break cmd.append(w) return self.program(cmd, whole) if prog == "xargs": for idx, (w, _) in enumerate(words): if w in ("-a", "--arg-file") and idx + 1 < len(words) and \ is_secret_path(words[idx + 1][0]): return deny("'%s' is secret material; agents never read it." % words[idx + 1][0]) if prog == "env": idx = 0 verdict = OK while idx < len(words): w = words[idx][0] if w in ("-S", "--split-string") and idx + 1 < len(words): return self.text(words[idx + 1][0] + " " + " ".join(x for x, _ in words[idx + 2:])) if w.startswith("--split-string="): return self.text(w.split("=", 1)[1] + " " + " ".join(x for x, _ in words[idx + 1:])) if w in takes_value: idx += 2 continue if w.startswith("-"): idx += 1 continue if ASSIGNMENT.match(w): verdict = verdict.merge(assignment_verdict(w)) idx += 1 continue break return verdict.merge(self.program(words[idx:], whole)) rest = self._skip_opts(words, takes_value) if prog == "timeout" and rest: rest = rest[1:] # DURATION if prog in ("taskset", "chrt") and rest: rest = rest[1:] # mask / priority if prog == "flock" and rest: rest = rest[1:] # lock file if len(rest) >= 2 and rest[0][0] in ("-c", "--command"): return self.text(rest[1][0]) return self.program(rest, whole) @staticmethod def _skip_opts(words, takes_value): idx = 0 while idx < len(words): w = words[idx][0] if w == "--": idx += 1 break if w in takes_value: idx += 2 continue if w.startswith("-") and len(w) > 1: idx += 1 continue break return words[idx:] # -------------------------------------------------------------------------- # Per-tool rules: rule(args, analyzer) -> Verdict # -------------------------------------------------------------------------- def first_positional(args, takes_value): """(index, word) of the first non-option argument, skipping option values.""" idx = 0 while idx < len(args): a = args[idx] if a == "--": idx += 1 break if a in takes_value: idx += 2 continue if a.startswith("-") and len(a) > 1: idx += 1 continue return idx, a if idx < len(args): return idx, args[idx] return None, None def wants_help(args): return any(a in ("--help", "-h", "-help") for a in args) KUBECTL_GLOBAL = {"-n", "--namespace", "--context", "--kubeconfig", "--cluster", "--user", "-s", "--server", "--token", "--as", "--as-group", "--as-uid", "--certificate-authority", "--client-certificate", "--client-key", "--request-timeout", "--tls-server-name", "--cache-dir", "-v", "--profile", "--profile-output", "--username", "--password", "--kuberc", "--log-file", "--log-dir", "--vmodule"} KUBECTL_READ = {"get", "describe", "logs", "top", "explain", "api-resources", "api-versions", "version", "cluster-info", "events", "kustomize", "wait", "completion", "help", "options"} SECRET_RESOURCES = {"secret", "secrets"} SAFE_OUTPUTS = {"wide", "name"} def kubectl(args, an=None): idx, verb = first_positional(args, KUBECTL_GLOBAL) if verb is None or wants_help(args): return OK rest = args[idx + 1:] if verb in KUBECTL_READ: if verb == "get": for j, a in enumerate(rest): raw = None if a == "--raw" and j + 1 < len(rest): raw = rest[j + 1] elif a.startswith("--raw="): raw = a.split("=", 1)[1] if raw is not None and "secret" in raw.lower(): return deny("'kubectl get --raw' on a Secrets path prints Secret " "data; agents never read Secrets.") if _names_secret(rest) and _secret_output(rest): return deny("'kubectl get secret -o …' prints Secret data; agents never " "read Secrets. Plain 'kubectl get secrets' lists names only.") return OK if verb == "auth": sub = rest[0] if rest else "" if sub in ("can-i", "whoami"): return OK if verb == "rollout": sub = rest[0] if rest else "" if sub in ("status", "history"): return OK if verb == "create" and any(a == "--dry-run=client" for a in rest) or \ verb == "create" and any(a == "--dry-run" and j + 1 < len(rest) and rest[j + 1] == "client" for j, a in enumerate(rest)): # renders a manifest locally (e.g. a Secret to pipe into kubeseal) return OK if verb == "config": sub = rest[0] if rest else "" if sub in ("view",) and not any(a in ("--raw", "--flatten") or a.startswith(("--raw=", "--flatten=")) for a in rest): return OK if sub in ("get-contexts", "current-context", "get-clusters", "get-users", "use-context", "use"): return OK if sub == "view": return deny("'kubectl config view --raw' prints cluster credentials.") if verb == "diff": return deny("Live 'kubectl diff' is a server-side dry run that needs write " "RBAC and is not used; use the offline render (kustomize build / " "flux build --dry-run).") return deny("'kubectl %s' is not a read verb. Direct cluster changes never happen " "from an agent; every change applies by approved merge." % verb) def _names_secret(rest): for a in rest: if a.startswith("-"): continue for part in re.split(r"[,/]", a.lower()): if part.split(".", 1)[0] in SECRET_RESOURCES: return True return False def _secret_output(rest): for idx, a in enumerate(rest): val = None if a in ("-o", "--output") and idx + 1 < len(rest): val = rest[idx + 1] elif a.startswith("--output="): val = a.split("=", 1)[1] elif a.startswith("-o") and len(a) > 2: val = a[2:].lstrip("=") elif a == "--template" or a.startswith("--template="): return True if val is not None and val.split("=", 1)[0] not in SAFE_OUTPUTS: return True return False HELM_GLOBAL = {"-n", "--namespace", "--kube-context", "--kubeconfig", "--kube-apiserver", "--kube-as-user", "--kube-as-group", "--kube-token", "--kube-ca-file", "--registry-config", "--repository-config", "--repository-cache", "--burst-limit", "--qps", "--kube-tls-server-name"} HELM_READ = {"template", "lint", "list", "ls", "status", "history", "show", "inspect", "version", "env", "search", "dependency", "dep", "pull", "fetch", "package", "verify", "create", "completion", "help", "repo"} def helm(args, an=None): idx, verb = first_positional(args, HELM_GLOBAL) if verb is None or wants_help(args): return OK rest = args[idx + 1:] if verb in HELM_READ: if verb == "repo" and rest and rest[0] not in ("add", "update", "list", "ls", "index"): return deny("'helm repo %s' is not in the guard's allowlist." % rest[0]) return OK if verb == "get": sub = rest[0] if rest else "" if sub in ("notes", "metadata", "hooks"): return OK return deny("'helm get %s' prints release values or manifests, which can " "hold secret material." % (sub or "")) if verb == "plugin": sub = rest[0] if rest else "" if sub in ("list", "ls"): return OK return deny("'helm %s' changes a release or the cluster. Releases change only " "by approved merge." % verb) TOFU_READ = {"init", "validate", "fmt", "plan", "providers", "version", "graph", "get", "metadata", "modules", "help"} def tofu(args, an=None): # -chdir=DIR and other leading -flags are single words idx, verb = first_positional(args, set()) if verb is None or wants_help(args): return OK rest = args[idx + 1:] if verb == "run-all": # terragrunt return tofu(rest, an) if verb in TOFU_READ: return OK if verb == "workspace": sub = rest[0] if rest else "" if sub in ("list", "show", "select"): return OK return deny("'tofu workspace %s' changes state." % sub) if verb == "output": if any(a.lstrip("-").split("=")[0] in ("json", "raw") for a in rest): return deny("'tofu output -json/-raw' prints sensitive outputs in clear.") return OK if verb == "show": if any(a.lstrip("-").split("=")[0] == "json" for a in rest): return deny("'tofu show -json' prints sensitive values in clear.") files = [a for a in rest if not a.startswith("-")] if not files: return deny("'tofu show' with no plan file prints the current state, " "which holds secret material.") return OK if verb == "state": sub = rest[0] if rest else "" if sub == "list": return OK return deny("'tofu state %s' reads or edits state directly." % sub) if verb == "destroy": return deny("'tofu destroy' is never run by an agent.") if verb == "apply": if any(a.lstrip("-").split("=")[0] == "destroy" for a in rest): return deny("'tofu apply -destroy' is a destroy; never run by an agent.") return ask("'tofu apply' changes real infrastructure.") if verb in ("import", "refresh", "test"): return ask("'tofu %s' writes state or creates real resources." % verb) if verb in ("taint", "untaint", "force-unlock", "console", "push"): return deny("'tofu %s' edits or exposes state directly." % verb) return deny("'tofu %s' is not in the guard's allowlist." % verb) ANSIBLE_READ_FLAGS = {"--check", "--syntax-check", "--list-tasks", "--list-hosts", "--list-tags", "--version", "--help", "-h"} ANSIBLE_VALUE_SHORT = set("ieftuMlkKbcTPBmaJ") # options whose value may follow def _ansible_check_mode(args): for a in args: if a in ANSIBLE_READ_FLAGS: return True if a.startswith("--check="): return True if a.startswith("-") and not a.startswith("--") and len(a) > 1: for ch in a[1:]: if ch == "C": return True if ch in ANSIBLE_VALUE_SHORT: break return False def ansible_playbook(args, an=None): if _ansible_check_mode(args): return OK return ask("'ansible-playbook' without --check changes real hosts.") def ansible_adhoc(args, an=None): if _ansible_check_mode(args) or not args: return OK return ask("ad-hoc 'ansible' without --check runs modules on real hosts.") def ansible_pull(args, an=None): if _ansible_check_mode(args): return OK return ask("'ansible-pull' without --check changes real hosts.") def ansible_console(args, an=None): return ask("'ansible-console' runs modules on real hosts.") def ansible_vault(args, an=None): idx, verb = first_positional(args, {"--vault-id", "--vault-password-file"}) if verb in ("view", "decrypt", "edit", "rekey"): return deny("'ansible-vault %s' decrypts vaulted secrets; agents never do." % verb) return OK def kubeseal(args, an=None): for a in args: if a.split("=", 1)[0] in ("--recovery-unseal", "--recovery-private-key"): return deny("kubeseal recovery decrypts Sealed Secrets; agents never do.") return OK SOPS_SAFE = {"-e", "--encrypt", "encrypt", "updatekeys", "filestatus", "--version", "-v", "--help", "-h", "help", "keyservice"} def sops(args, an=None): # A bare `sops ` opens it decrypted in $EDITOR, so only the # encrypting and metadata modes are allowed. if any(a in SOPS_SAFE for a in args): if not any(a in ("-d", "--decrypt", "decrypt") for a in args): return OK return deny("sops would decrypt here; agents never decrypt secrets. Only " "'sops --encrypt', 'updatekeys' and 'filestatus' are allowed.") FLUX_GLOBAL = {"-n", "--namespace", "--context", "--kubeconfig", "--timeout", "--cluster", "--user", "--token", "--as", "--as-group", "--server", "-s", "--certificate-authority", "--client-certificate", "--client-key"} FLUX_READ = {"get", "logs", "events", "tree", "trace", "stats", "check", "version", "build", "completion", "help", "debug", "envsubst"} def flux(args, an=None): idx, verb = first_positional(args, FLUX_GLOBAL) if verb is None or wants_help(args): return OK rest = args[idx + 1:] if verb == "debug" and any(a.split("=", 1)[0] == "--show-values" for a in rest): return deny("'flux debug --show-values' can print values pulled from Secrets.") if verb in FLUX_READ: return OK if verb == "export": if any(a.split("=", 1)[0] == "--with-credentials" for a in rest): return deny("'flux export --with-credentials' prints source credentials.") return OK if verb in ("create", "install") and "--export" in rest: return OK if verb == "reconcile": return ask("'flux reconcile' makes the cluster act now.") if verb == "diff": return deny("Live 'flux diff' needs write RBAC and is not used; use " "'flux build --dry-run' or the PR's offline render diff.") return deny("'flux %s' changes the cluster. Cluster changes apply by approved " "merge." % verb) GIT_GLOBAL = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env", "--super-prefix"} GIT_COMMIT_VALUE_SHORT = set("mFcCt") def _git_sub_index(args): idx = 0 while idx < len(args): a = args[idx] if a in GIT_GLOBAL: idx += 2 continue if a.startswith("-"): idx += 1 continue return idx return None def _git_config_value(value, an): low = value.lower() if "hookspath" in low: return deny("Overriding core.hooksPath skips the repo's git hooks; " + HOOK_BYPASS) if "no-verif" in low: return deny("A git alias carrying --no-verify skips the repo's git hooks; " + HOOK_BYPASS) if "=" in value: key, val = value.split("=", 1) if key.lower().startswith("alias.") and val.startswith("!") and an: return an.text(val[1:]) return OK def git(args, an=None): verdict = OK idx = 0 while idx < len(args): a = args[idx] if a in ("-c", "--config-env") and idx + 1 < len(args): verdict = verdict.merge(_git_config_value(args[idx + 1], an)) idx += 2 continue if a.startswith("--config-env="): verdict = verdict.merge(_git_config_value(a.split("=", 1)[1], an)) elif a.startswith("-c") and len(a) > 2: verdict = verdict.merge(_git_config_value(a[2:].lstrip("="), an)) if a in GIT_GLOBAL: idx += 2 continue if a.startswith("-"): idx += 1 continue break if verdict.decision == DENY or idx >= len(args): return verdict sub = args[idx] rest = args[idx + 1:] # git accepts any unambiguous prefix of a long option: --no-verif, --no-ve… if sub != "grep" and any(len(a) >= 6 and "--no-verify".startswith(a) for a in rest): return deny("'--no-verify' skips the repo's git hooks; " + HOOK_BYPASS) if sub == "config": for j, a in enumerate(rest): if a.lower() == "core.hookspath" and j + 1 < len(rest) and \ not any(x in ("--get", "--get-all", "-l", "--list", "--unset", "--unset-all") for x in rest): return deny("Setting core.hooksPath skips the repo's git hooks; " + HOOK_BYPASS) if sub == "rebase" and an: for j, a in enumerate(rest): if a in ("-x", "--exec") and j + 1 < len(rest): verdict = verdict.merge(an.text(rest[j + 1])) elif a.startswith("--exec="): verdict = verdict.merge(an.text(a.split("=", 1)[1])) if sub == "bisect" and an and rest[:1] == ["run"]: verdict = verdict.merge(an.program([(w, False) for w in rest[1:]], " ".join(rest))) if sub == "submodule" and an and "foreach" in rest: cmd = [w for w in rest[rest.index("foreach") + 1:] if not w.startswith("--")] verdict = verdict.merge(an.text(" ".join(cmd))) if sub == "commit": skip = False for a in rest: if skip: skip = False continue if a in ("--message", "--file", "--reuse-message", "--reedit-message", "--template", "--author", "--date", "--cleanup", "--fixup", "--squash", "--trailer"): skip = True continue if a.startswith("-") and not a.startswith("--") and len(a) > 1: letters = a[1:] for pos, ch in enumerate(letters): if ch == "n": return deny("'git commit -n' is --no-verify; it skips the " "repo's git hooks.") if ch in GIT_COMMIT_VALUE_SHORT: if pos == len(letters) - 1: skip = True break return verdict def pre_commit(args, an=None): idx, verb = first_positional(args, {"-c", "--config"}) if verb == "uninstall": return deny("'pre-commit uninstall' turns the repo's gates off; " + HOOK_BYPASS) return OK RULES = { "kubectl": kubectl, "kubectl.exe": kubectl, "kubecolor": kubectl, "helm": helm, "helm3": helm, "tofu": tofu, "terraform": tofu, "terragrunt": tofu, "ansible-playbook": ansible_playbook, "ansible": ansible_adhoc, "ansible-pull": ansible_pull, "ansible-console": ansible_console, "ansible-vault": ansible_vault, "kubeseal": kubeseal, "sops": sops, "flux": flux, "git": git, "pre-commit": pre_commit, } # -------------------------------------------------------------------------- # Tool dispatch # -------------------------------------------------------------------------- SHELL_TOOLS = {"bash", "shell", "powershell", "local_shell", "exec_command", "unified_exec", "run_shell_command", "container.exec", "monitor"} PATH_KEYS = ("file_path", "path", "notebook_path", "filePath", "absolute_path") def analyse_tool(tool, tool_input): if not isinstance(tool_input, dict): tool_input = {} lname = (tool or "").lower() if lname in SHELL_TOOLS: cmd = tool_input.get("command", "") if isinstance(cmd, list): cmd = " ".join(_quote(c) for c in cmd) return Analyzer().text(str(cmd)) if lname == "apply_patch": cmd = str(tool_input.get("command", "") or tool_input.get("input", "")) for m in re.finditer(r"^\*\*\* (?:Add|Update|Delete) File: (.+)$", cmd, re.M): if is_secret_path(m.group(1).strip()): return deny("'%s' is secret material; agents never touch it." % m.group(1).strip()) return OK for key in PATH_KEYS: val = tool_input.get(key) if isinstance(val, str) and is_secret_path(val): return deny("'%s' is secret material (vault password, private key, " "admin kubeconfig or tofu state); agents never read it." % val) for key in ("glob", "include"): val = tool_input.get(key) if isinstance(val, str) and is_secret_path(val): return deny("A search over '%s' reads secret material." % val) return OK def _quote(s): s = str(s) if re.match(r"^[A-Za-z0-9_./=:@%+,-]+$", s): return s return "'" + s.replace("'", "'\\''") + "'" def detect_runtime(payload=None): here = os.path.abspath(__file__).replace("\\", "/") if "/.claude/hooks/" in here: return "claude" if "/.github/hooks/" in here: return "copilot" if "/.codex/hooks/" in here: return "codex" if isinstance(payload, dict) and "toolName" in payload: return "copilot" return "unknown" def read_payload(raw): payload = json.loads(raw) if raw.strip() else {} if not isinstance(payload, dict): raise ValueError("payload is not an object") if "toolName" in payload: tool = payload.get("toolName") args = payload.get("toolArgs") if isinstance(args, str): try: args = json.loads(args) except ValueError: args = {"command": args} return tool, args return payload.get("tool_name"), payload.get("tool_input") def emit(runtime, event, verdict): decision = verdict.decision if decision == ASK and runtime not in ("claude", "copilot"): decision = DENY verdict = Verdict(DENY, verdict.reason + " This runtime cannot ask, so the guard denies.") if decision == ALLOW: return 0 if runtime == "copilot": print(json.dumps({"permissionDecision": decision, "permissionDecisionReason": verdict.reason})) return 0 if runtime == "claude": print(json.dumps({"hookSpecificOutput": { "hookEventName": event or "PreToolUse", "permissionDecision": decision, "permissionDecisionReason": verdict.reason}})) return 0 # Codex and unknown runtimes: exit 2 with the reason on stderr is the # portable deny. sys.stderr.write(verdict.reason + "\n") return 2 def main(): raw = sys.stdin.read() runtime = detect_runtime() event = "PreToolUse" try: payload = json.loads(raw) if raw.strip() else {} if isinstance(payload, dict): runtime = detect_runtime(payload) event = payload.get("hook_event_name") or event tool, tool_input = read_payload(raw) verdict = analyse_tool(tool, tool_input) except Exception as exc: # fail closed verdict = Verdict(DENY, "delivery guard: could not read the tool call (%s); " "denying to stay safe." % exc.__class__.__name__) return emit(runtime, event, verdict) if __name__ == "__main__": sys.dont_write_bytecode = True sys.exit(main())