Files
Holocron/plugins/delivery/.apm/hooks/guard.py
T
Defame1297andClaude Opus 5.5 d86ae521e7 fix(delivery): harden the guard hook after three review rounds
Two fresh-context adversarial reviews and a spec/standards review of the
guard found bypasses, false denies and fail-open paths. Fixes:

- Substitution bodies are parsed by the tokenizer itself, so an
  apostrophe in a here-doc commit/PR body no longer hides later commands.
- Redirect operands never become words; every redirect target is checked
  for secret paths and .git/hooks.
- Unquoted here-doc substitutions are analysed; stdin shells (bash -,
  ssh host, pwsh) analyse their here-doc as a script.
- Option clusters ending in a value letter (bash -euo pipefail -c,
  sudo -iu root) consume their value.
- PowerShell mode: backtick escapes, iex, cmd /c, -EncodedCommand denied.
- Malformed payloads and unknown runtimes fail closed; runtime comes from
  the deploy path only.
- Linear-time parsing with size, word, command, depth and unwrap caps, so
  Copilot cannot time out (and fail open) on long input.
- Wider secret coverage (.ssh/.kube globs and dirs, id_* suffixes, sops
  age key, k3s/admin kubeconfigs, git-credentials, deploy keys, REV:path)
  and hook-bypass routes (git config alias, .git/hooks writes, find
  -delete, HUSKY=0, LEFTHOOK=0).
- Fewer false denies: commit/PR message values, find -name, search globs,
  jq/yq filters, pytest -k, git -S/--grep, ssh -i naming, non-admin
  kubeconfigs, quoted braces, option names, doc and test files.
- New allowlists: helmfile, terragrunt hcl/render, helm diff.
- delivery 0.2.0: a new hook changes compiled output (configure.md).
- ADR-0032: allowlists described as "no cluster or state change and no
  secret printed"; Write added to the file tools.

Refs #190

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012CqgnwEGtmfsjcoG9QwByN
2026-11-23 11:51:26 +00:00

1940 lines
75 KiB
Python
Executable File

#!/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
The payload's shape (camelCase `toolName` or snake_case `tool_name`) picks only
how the payload is read, never the runtime.
"""
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."
# Copilot lets a timed-out hook's call through, so the guard refuses input too
# big to read quickly instead of trying.
MAX_COMMAND = 256 * 1024
# Bounds that keep the guard linear on pathological input: words in one simple
# command, and wrappers unwrapped inside one another (`sudo sudo sudo …`).
MAX_WORDS = 2000
MAX_COMMANDS = 5000
MAX_UNWRAP = 32
# --------------------------------------------------------------------------
# Secret material: paths an agent never reads
# --------------------------------------------------------------------------
SECRET_BASENAME_GLOBS = (
".vault_pass*", ".vault-pass*",
"*.tfstate", "*.tfstate.*",
"id_rsa*", "id_dsa*", "id_ecdsa*", "id_ed25519*",
"*.key", "key.pem", "*-key.pem", "*_key.pem", "*.key.pem", "privkey*.pem",
"*private*.pem", "*.p12", "*.pfx", ".git-credentials*",
)
# Names that also fit source and docs about the secret (`vault_password.yml`,
# `test_vault_password.py`). A doc or data suffix exempts them. A code suffix
# exempts only a test file: `vault_pass.py` / `vault-pass.sh` is the usual name
# of an Ansible vault-password script, and running it prints the password.
SECRET_NAME_GLOBS = ("vault_pass*", "vault-pass*", "*vault_password*",
"*vault-password*", "*deploy_key*")
DOC_SUFFIXES = (".yml", ".yaml", ".md", ".rst", ".j2", ".adoc", ".html")
CODE_SUFFIXES = (".py", ".sh", ".go", ".rs", ".js", ".ts")
def _is_doc_or_test(base):
if base.endswith(DOC_SUFFIXES):
return True
if base.endswith(CODE_SUFFIXES):
stem = base.rsplit(".", 1)[0]
return stem.startswith(("test_", "test-")) or stem.endswith(("_test", "-test"))
return False
# Secret files whose basename alone is too common to match on.
SECRET_PATH_SUFFIXES = ("/sops/age/keys.txt", "/rancher/k3s/k3s.yaml",
"/kubernetes/admin.conf")
# Directories whose contents are secret as a whole: naming the directory, or
# any glob inside it, counts.
SECRET_DIRS = (".kube", ".ssh")
# 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", ".git-credentials",
"deploy_key",
)
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:])
# git's REV:path (`git show HEAD:.vault_pass`)
if ":" in word:
candidates.add(word.split(":", 1)[1])
for cand in candidates:
norm = cand.strip().replace("\\", "/").rstrip("/")
if not norm:
continue
parts = norm.split("/")
base = parts[-1].lower()
parent = parts[-2].lower() if len(parts) > 1 else ""
if base in SECRET_DIRS:
return True
if parent in SECRET_DIRS and GLOB_CHARS & set(base):
return True
# the admin kubeconfig and its backups; other kubeconfigs are fine
if parent == ".kube" and (base == "config" or base.startswith("config.")
or base == "config~"):
return True
if ("/" + norm.lower()).endswith(SECRET_PATH_SUFFIXES):
return True
if base.endswith(".pub"):
continue
if any(fnmatch.fnmatchcase(base, g) for g in SECRET_BASENAME_GLOBS):
return True
if not _is_doc_or_test(base) and \
any(fnmatch.fnmatchcase(base, g) for g in SECRET_NAME_GLOBS):
return True
if GLOB_CHARS & set(base) and len(base) < 256 and _literal_count(base) >= 3:
if any(fnmatch.fnmatchcase(s, base) for s in SECRET_SAMPLES):
return True
return False
HOOKS_DIR = re.compile(r"(?:^|/)\.git/hooks(?:/|$)")
def is_hooks_path(word):
return bool(HOOKS_DIR.search(word.replace("\\", "/")))
# --------------------------------------------------------------------------
# Shell tokenising
# --------------------------------------------------------------------------
# Longest first, so `&&` wins over `&` and `<<<` over `<<`.
OPERATORS = re.compile(r"&&|\|\||;;|\|&|[;|&\n()]")
REDIRECTS = re.compile(r"<<<|<<-|<<|&>>|>>|&>|>&|<&|<>|>\||[<>]")
WORD_END = set(" \t\r\n;&|()<>")
# Runs of characters with no special meaning inside a word.
PLAIN = re.compile(r"[^\s;&|()<>\\'\"`$@{]+")
PS_PLAIN = re.compile(r"[^\s;&|()<>`'\"$@{]+")
FD_PREFIX = re.compile(r"[0-9]+(?=[<>])")
PS_FD_PREFIX = re.compile(r"(?:[0-9]+|\*)(?=>)")
VAR_START = re.compile(r"[A-Za-z_{0-9@*#?!$-]")
MAX_NESTING = 40
class TooComplex(Exception):
pass
class Word(str):
"""A shell word after unquoting.
dynamic: it still holds an expansion, so its value is only known at run
time. brace: its unquoted text has a brace expansion (`{a,b}`, `{1..3}`).
"""
dynamic = False
brace = False
def __new__(cls, text, dynamic=False, brace=False):
word = str.__new__(cls, text)
word.dynamic = dynamic
word.brace = brace
return word
def _has_brace(text):
# Linear: an opening brace, then a comma or `..`, then the closing brace,
# with no other brace between.
if "{" not in text:
return False
open_, list_, prev = False, False, ""
for ch in text:
if ch == "{":
open_, list_ = True, False
elif ch == "}":
if open_ and list_:
return True
open_ = False
elif open_ and (ch == "," or (ch == "." and prev == ".")):
list_ = True
prev = ch
return False
class Command:
"""One simple command: its words, its redirections, and what it reads on
stdin from here-documents and here-strings."""
def __init__(self):
self.words = []
self.redirects = [] # (operator, target word)
self.stdin = []
class Shell:
"""Splits a command line into simple commands.
Not a full shell parser. It understands quoting, escapes, the control
operators, redirections, here-documents, arithmetic and command / process
substitution. A substitution's body is parsed by a nested Shell over the
same text, so the end of `$(...)` is found by the same rules as the rest
of the line, here-documents included. Here-document bodies are data,
except that an unquoted delimiter's body still runs its substitutions.
`ps` switches to PowerShell quoting: backtick escapes, backslash does not.
"""
def __init__(self, text, ps=False, depth=0, arith=False, start=0):
if depth > MAX_NESTING:
raise TooComplex()
self.text = text
self.ps = ps
self.depth = depth
self.arith = arith # inside (( )) or $(( )): no commands, no here-docs
self.i = start
self.commands = []
self.nested = [] # Shells of substitutions and here-doc bodies
self.pending = [] # here-docs whose bodies start at the next newline
def _child(self, start, arith=False):
return Shell(self.text, self.ps, self.depth + 1, arith, start)
def parse(self, closer=False):
"""Parse to the end, or with closer=True to the first unmatched ')'."""
text, n = self.text, len(self.text)
cur = Command()
parens = 0
while self.i < n:
c = text[self.i]
if c in " \t\r":
self.i += 1
continue
if text.startswith("`\n" if self.ps else "\\\n", self.i):
self.i += 2
continue
if c == "#" and self._at_word_start():
end = text.find("\n", self.i)
self.i = n if end == -1 else end
continue
if self.ps and text.startswith("<#", self.i):
end = text.find("#>", self.i)
self.i = n if end == -1 else end + 2
continue
if text.startswith("((", self.i) and not (cur.words or self.ps or self.arith):
self._arith(self.i + 2)
continue
op = self._match(OPERATORS)
if op:
self.i += len(op)
if op == "(":
parens += 1
elif op == ")":
if parens == 0 and closer:
break
parens = max(0, parens - 1)
elif op == "\n" and self.pending:
self._read_heredocs()
self._end(cur)
cur = Command()
continue
if not self.ps and text.startswith(("<(", ">("), self.i):
self._nest(self.i + 2)
cur.words.append(Word("/dev/fd/63", dynamic=True))
continue
fd = (PS_FD_PREFIX if self.ps else FD_PREFIX).match(text, self.i)
if fd:
self.i = fd.end()
red = self._match(REDIRECTS)
if red:
self.i += len(red)
self._redirect(red, cur)
continue
cur.words.append(self._word())
if len(cur.words) > MAX_WORDS:
raise TooComplex()
self._end(cur)
return self
def _end(self, cmd):
if cmd.words or cmd.redirects or cmd.stdin:
self.commands.append(cmd)
if len(self.commands) > MAX_COMMANDS:
raise TooComplex()
def _nest(self, start, arith=False):
sub = self._child(start, arith).parse(closer=True)
self.nested.append(sub)
self.i = sub.i
return sub
def _arith(self, start):
# (( ... )) / $(( ... )): `<<` is a shift, not a here-doc
self._nest(start, arith=True)
if self.text.startswith(")", self.i):
self.i += 1
def _redirect(self, red, cmd):
if self.arith:
return
while self.i < len(self.text) and self.text[self.i] in " \t":
self.i += 1
start = self.i
target = self._word()
if red in ("<<", "<<-") and not self.ps:
raw = self.text[start:self.i]
expands = not any(q in raw for q in "'\"\\")
self.pending.append((str(target), red == "<<-", expands, cmd))
elif red == "<<<":
cmd.stdin.append(target)
else:
cmd.redirects.append((red, target))
def _read_heredocs(self):
text, n = self.text, len(self.text)
for delim, strip_tabs, expands, cmd in self.pending:
lines = []
while self.i < n:
end = text.find("\n", self.i)
end = n if end == -1 else end
line = text[self.i:end]
self.i = min(end + 1, n)
if (line.lstrip("\t") if strip_tabs else line) == delim:
break
lines.append(line)
body = "\n".join(lines)
cmd.stdin.append(body)
if expands:
sub = Shell(body, self.ps, self.depth + 1)
sub._dquote(None)
self.nested.append(sub)
self.pending = []
def _at_word_start(self):
return self.i == 0 or self.text[self.i - 1] in " \t\n;&|()"
def _match(self, ops):
m = ops.match(self.text, self.i)
return m.group() if m else None
def _substitution(self):
# self.i is at "$(" (bash or PowerShell)
if not self.ps and self.text.startswith("$((", self.i):
self._arith(self.i + 3)
else:
self._nest(self.i + 2)
def _backtick(self):
text, n = self.text, len(self.text)
j = self.i + 1
out = []
while j < n and text[j] != "`":
if text[j] == "\\" and j + 1 < n:
out.append(text[j + 1] if text[j + 1] in "$`\\" else text[j:j + 2])
j += 2
continue
out.append(text[j])
j += 1
self.i = j + 1
self.nested.append(Shell("".join(out), self.ps, self.depth + 1).parse())
def _dquote(self, stop):
"""Read double-quoted text (or a here-doc body, stop=None) up to stop.
Returns (text, dynamic). Substitutions inside are parsed as nested.
"""
text, n = self.text, len(self.text)
esc = "`" if self.ps else "\\"
out = []
dynamic = False
while self.i < n:
d = text[self.i]
if stop and d == stop:
if self.ps and text.startswith(stop * 2, self.i):
out.append(stop)
self.i += 2
continue
self.i += 1
break
if d == esc and self.i + 1 < n:
nxt = text[self.i + 1]
if self.ps or nxt in '"\\$`\n':
if nxt != "\n":
out.append(nxt)
self.i += 2
continue
if text.startswith("$(", self.i):
self._substitution()
dynamic = True
continue
if d == "`" and not self.ps:
self._backtick()
dynamic = True
continue
if d == "$" and self.i + 1 < n and VAR_START.match(text[self.i + 1]):
dynamic = True
out.append(d)
self.i += 1
return "".join(out), dynamic
def _single(self):
# self.i is at the opening quote; PowerShell doubles a quote to escape it
text, n = self.text, len(self.text)
out = []
j = self.i + 1
while True:
end = text.find("'", j)
if end == -1:
out.append(text[j:])
self.i = n
return "".join(out)
out.append(text[j:end])
if self.ps and text.startswith("''", end):
out.append("'")
j = end + 2
continue
self.i = end + 1
return "".join(out)
def _ansi_c(self):
# $'...': backslash escapes, including \'
text, n = self.text, len(self.text)
j = self.i + 2
while j < n and text[j] != "'":
j += 2 if text[j] == "\\" else 1
raw = text[self.i + 2:min(j, n)]
self.i = j + 1
try:
return raw.encode("latin-1", "backslashreplace").decode("unicode_escape")
except Exception:
return raw
def _ps_herestring(self):
# @' ... '@ and @" ... "@: the terminator sits at the start of a line
quote = self.text[self.i + 1]
start = self.i + 2
end = self.text.find("\n" + quote + "@", start)
end = len(self.text) if end == -1 else end
body = self.text[start:end]
self.i = end + 3
if quote == "'":
return body, False
sub = Shell(body, True, self.depth + 1)
out, dynamic = sub._dquote(None)
self.nested.append(sub)
return out, dynamic
def _word(self):
text, n = self.text, len(self.text)
out = []
unquoted = []
dynamic = False
plain = PS_PLAIN if self.ps else PLAIN
while self.i < n:
run = plain.match(text, self.i)
if run:
out.append(run.group())
unquoted.append(run.group())
self.i = run.end()
continue
c = text[self.i]
if c in WORD_END:
break
if self.ps and c == "`" or not self.ps and c == "\\":
if self.i + 1 < n and text[self.i + 1] != "\n":
out.append(text[self.i + 1])
self.i += 2 # an escaped newline is a line continuation
elif c == "'":
out.append(self._single())
elif c == '"' or (not self.ps and text.startswith('$"', self.i)):
self.i += 1 if c == '"' else 2
part, dyn = self._dquote('"')
out.append(part)
dynamic = dynamic or dyn
elif self.ps and text.startswith(("@'", '@"'), self.i):
part, dyn = self._ps_herestring()
out.append(part)
dynamic = dynamic or dyn
elif not self.ps and text.startswith("$'", self.i):
out.append(self._ansi_c())
elif text.startswith("$(", self.i):
self._substitution()
dynamic = True
elif c == "`" and not self.ps:
self._backtick()
dynamic = True
else:
if c == "$" and self.i + 1 < n and VAR_START.match(text[self.i + 1]):
dynamic = True
out.append(c)
unquoted.append(c)
self.i += 1
return Word("".join(out), dynamic, _has_brace("".join(unquoted)))
# --------------------------------------------------------------------------
# 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"}
PWSH = {"powershell", "pwsh"}
PWSH_VALUE_OPTS = {"-executionpolicy", "-ep", "-ex", "-workingdirectory", "-wd",
"-windowstyle", "-w", "-outputformat", "-of", "-o",
"-inputformat", "-if", "-i", "-configurationname", "-version",
"-v", "-settingsfile", "-psconsolefile"}
EVALS = {"eval", "iex", "invoke-expression"}
# Words that only prefix the real command. Matched on the basename, so
# /usr/bin/time and /usr/bin/nohup count.
KEYWORDS = {"!", "{", "}", "then", "do", "done", "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"},
"chroot": {"--userspec", "--groups"},
}
# Tool runners: <runner> <subcommand> ... <program> args. The program is the
# first word the guard knows, or whatever follows `--`.
RUNNERS = {
"uv": {"run", "tool"}, "poetry": {"run"}, "pipenv": {"run"}, "pdm": {"run"},
"hatch": {"run"}, "pipx": {"run"}, "direnv": {"exec"}, "mise": {"exec", "x"},
"devbox": {"run"}, "uvx": None, "aws-vault": {"exec"}, "op": {"run"},
"doppler": {"run"},
}
# Distributions that bundle a tool as a subcommand: `k3s kubectl ...`.
BUNDLES = {"busybox", "k3s", "microk8s"}
TMUX_RUN = {"new-session", "new", "new-window", "neww", "split-window", "splitw",
"respawn-pane", "respawnp", "respawn-window", "respawnw"}
TMUX_VALUE_OPTS = {"-s", "-n", "-c", "-x", "-y", "-t", "-e", "-F", "-l", "-f"}
ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\+?=")
# Assignments whose value is a command line git runs.
COMMAND_VARS = {"GIT_SSH_COMMAND"}
GUARDED = re.compile(
r"(?<![\w.-])(?:kubectl|kubecolor|helmfile|helm3|helm|tofu|terraform|terragrunt|"
r"ansible-playbook|ansible-vault|ansible-pull|ansible-console|ansible|kubeseal|"
r"flux|sops|pre-commit|k3s|microk8s|gpg|helm-secrets)(?![\w-])"
r"|--no-verif|hookspath|\bSKIP\+?=|vault.pass|\.tfstate|id_rsa|id_ed25519|id_ecdsa|"
r"id_dsa|\.kube|\.ssh|git-credentials|\.git/hooks|deploy_key",
re.I,
)
# 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,
# so the exemption holds only for the Ansible runners.
SECRET_ARG_EXEMPT = {"--vault-password-file", "--vault-pass-file", "--vault-id",
"--private-key", "--key-file"}
ANSIBLE_RUNS = {"ansible-playbook", "ansible", "ansible-pull"}
SEARCHERS = {"grep", "egrep", "fgrep", "rg", "ag", "ack"}
SEARCH_VALUE_OPTS = {"-A", "-B", "-C", "-m", "-d", "-D", "-g", "-t",
"--include", "--exclude", "--exclude-dir", "--glob",
"--type", "--max-count", "--context", "--after-context",
"--before-context"}
# Search options whose value is a file-name pattern, not a file.
SEARCH_GLOB_OPTS = {"--include", "--exclude", "--exclude-dir", "--glob",
"--iglob", "-g"}
FIND_ACTIONS = {"-delete", "-exec", "-execdir", "-ok", "-okdir"}
FIND_PATTERN_OPTS = {"-name", "-iname", "-path", "-ipath", "-regex", "-iregex",
"-wholename", "-iwholename", "-lname", "-ilname"}
JQ_LIKE = {"jq", "gojq", "yq"}
JQ_VALUE_OPTS = {"--indent", "-L", "--tab-width", "-o", "--output-format", "-p",
"--input-format", "-I", "--expression"}
JQ_PAIR_OPTS = {"--arg", "--argjson", "--slurpfile", "--rawfile"}
YQ_SUBS = {"e", "eval", "ea", "eval-all"}
def _jq_filter_index(prog, args):
"""The filter of jq / yq is a program, not a path, unless -f reads it from
a file."""
if any(a in ("-f", "--from-file") for a in args):
return set()
idx = 0
while idx < len(args):
a = args[idx]
if a in JQ_PAIR_OPTS:
idx += 3
elif a in JQ_VALUE_OPTS:
idx += 2
elif a == "--":
return {idx + 1}
elif a.startswith("-") and len(a) > 1:
idx += 1
elif prog == "yq" and a in YQ_SUBS:
idx += 1
else:
return {idx}
return set()
# Options whose value is prose: a title, a body, release notes.
MESSAGE_OPTS = {
"gh": {"-t", "--title", "-b", "--body", "-n", "--notes", "--subject"},
"tea": {"-t", "--title", "-d", "--description", "--body"},
}
# Programs that only print their arguments or look at file metadata.
NEUTRAL = {"echo", "printf", "ls", "stat", "test", "[", "[[", "true", ":"}
# Programs that hand a key to ssh rather than print it.
SSH_KEY_USERS = {"scp", "sftp"}
# Programs that change the files they name. Copiers change only the last one.
HOOK_WRITERS = {"rm", "rmdir", "unlink", "shred", "mv", "chmod", "chown",
"chgrp", "truncate", "tee", "sed"}
HOOK_COPIERS = {"cp", "ln", "install", "rsync"}
def _takes_value(word, takes_value):
"""True when the option word consumes the next word: it is a value option,
or a short cluster (`-iu`) whose last letter is one."""
if word in takes_value:
return True
return (len(word) > 2 and word[0] == "-" and word[1] != "-"
and "-" + word[-1] in takes_value)
def prog_name(word, ps=False):
base = os.path.basename(word.replace("\\", "/"))
low = base.lower()
if low.endswith(".exe"):
return low[:-4]
return low if ps else base
def option_values(args, opts):
"""Indexes of the values of `opts`: the next word, or an inline value."""
found = set()
for idx, a in enumerate(args):
if a in opts:
found.add(idx + 1)
elif "=" in a and a.split("=", 1)[0] in opts:
found.add(idx)
elif len(a) > 2 and a[:2] in opts and not a.startswith("--"):
found.add(idx)
return found
def search_pattern_indexes(args, value_opts):
"""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 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 exempt_indexes(prog, args):
"""Indexes of args that name no file (patterns, prose, values a tool reads
itself), or None when the program's arguments are never read as files."""
if prog == "git":
sub_idx = _git_sub_index(args)
if sub_idx is None:
return option_values(args, {"-c"})
sub = args[sub_idx]
if sub in ("rm", "check-ignore", "ls-files", "status"):
return None
skip = option_values(args[:sub_idx], {"-c"})
rest = args[sub_idx + 1:]
inner = set()
if sub == "grep":
inner = search_pattern_indexes(rest, SEARCH_VALUE_OPTS)
elif sub in GIT_MESSAGE_SUBS:
inner = _git_message_indexes(rest)
return skip | {i + sub_idx + 1 for i in inner}
if prog in SEARCHERS:
value_opts = SEARCH_VALUE_OPTS | ({"-T"} if prog == "rg" else set())
return search_pattern_indexes(args, value_opts) | option_values(args, SEARCH_GLOB_OPTS)
if prog in MESSAGE_OPTS:
return option_values(args, MESSAGE_OPTS[prog])
if prog == "find":
if _find_acts(args):
return set() # it deletes or runs something: every name counts
return option_values(args, FIND_PATTERN_OPTS)
if prog in ANSIBLE_RUNS:
return option_values(args, SECRET_ARG_EXEMPT)
if prog in JQ_LIKE:
return _jq_filter_index(prog, args)
if prog in ("pytest", "py.test") or (prog.startswith("python") and
args[:2] == ["-m", "pytest"]):
return option_values(args, {"-k", "-m"})
if prog in SSH_KEY_USERS:
return option_values(args, {"-i"})
if prog == "ssh-add":
return None
return set()
def secret_words(prog_word, prog, args):
if prog in NEUTRAL:
return OK
if is_secret_path(prog_word):
return deny("'%s' is secret material; agents never run or read it." % prog_word)
skip = exempt_indexes(prog, args)
if skip is None:
return OK
for idx, w in enumerate(args):
if idx in skip:
continue
if w.startswith("-"):
# an option name is never a path; only an inline value can be
if "=" not in w:
continue
w = w.split("=", 1)[1]
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
def _find_acts(args):
return any(a in FIND_ACTIONS for a in args)
def hook_writes(prog, args):
if prog == "find" and _find_acts(args):
targets = args
elif prog in HOOK_WRITERS:
if prog == "sed" and not any(a.startswith(("-i", "--in-place")) for a in args):
return OK
targets = [a for a in args if not a.startswith("-")]
elif prog in HOOK_COPIERS:
targets = [a for a in args if not a.startswith("-")][-1:]
else:
return OK
for t in targets:
if is_hooks_path(t):
return deny("Changing '%s' turns the repo's git hooks off; %s" % (t, HOOK_BYPASS))
return OK
def redirect_verdict(redirects):
for op, target in redirects:
if op in (">&", "<&") and (target.isdigit() or target == "-"):
continue
if op != "<" and is_hooks_path(target):
return deny("Writing '%s' changes the repo's git hooks; %s" % (target, HOOK_BYPASS))
if is_secret_path(target):
return deny("'%s' is secret material; agents never read or write it." % target)
return OK
class Ctx:
"""What a simple command carries besides its words.
guarded: the line it came from mentions a guarded tool or secret, so a
part the guard cannot read is denied rather than allowed.
stdin: here-doc bodies and here-strings the command reads.
"""
def __init__(self, guarded=True, stdin=(), ps=False):
self.guarded = guarded
self.stdin = stdin
self.ps = ps
class Analyzer:
def __init__(self):
self.depth = 0
self.unwraps = 0
def text(self, command, ps=False, guarded=False):
"""Verdict for a whole command line."""
if len(command) > MAX_COMMAND:
return deny("The command is longer than %d KB, too long for the guard "
"to read; split it up." % (MAX_COMMAND // 1024))
if self.depth > 8:
return deny("Command nesting too deep for the guard to read; simplify it.")
self.depth += 1
try:
try:
sh = Shell(command, ps).parse()
except (TooComplex, RecursionError):
return deny("The command is too long or nested too deep for the guard "
"to read (over %d words in one command, %d commands, or %d "
"levels); simplify it." % (MAX_WORDS, MAX_COMMANDS, MAX_NESTING))
return self.tree(sh, guarded or bool(GUARDED.search(command)))
finally:
self.depth -= 1
def tree(self, sh, guarded):
verdict = OK
if not sh.arith:
for cmd in sh.commands:
verdict = verdict.merge(self.simple(cmd, Ctx(guarded, cmd.stdin, sh.ps)))
if verdict.decision == DENY:
return verdict
for sub in sh.nested:
verdict = verdict.merge(self.tree(sub, guarded))
if verdict.decision == DENY:
return verdict
return verdict
def simple(self, cmd, ctx):
if any(w.brace for w in cmd.words) and GUARDED.search(" ".join(cmd.words)):
return deny("Brace expansion hides what this command runs; write it "
"out literally.")
verdict = redirect_verdict(cmd.redirects)
if verdict.decision == DENY:
return verdict
return verdict.merge(self.program(cmd.words, ctx))
def assignment(self, word, ctx):
name, value = word.split("=", 1)
name = name.rstrip("+")
low = value.lower()
if name == "SKIP":
return deny("SKIP= skips pre-commit hooks; " + HOOK_BYPASS)
if name in ("HUSKY", "LEFTHOOK") and value in ("0", "false"):
return deny("%s=0 skips the repo's git hooks; %s" % (name, 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 name in COMMAND_VARS:
return self.text(value, guarded=ctx.guarded)
if is_secret_path(value):
return deny("'%s' is secret material; agents never read it." % value)
return OK
def program(self, words, ctx):
if len(words) > MAX_WORDS:
return deny("The command has more than %d words, too many for the guard "
"to read; split it up." % MAX_WORDS)
if self.unwraps >= MAX_UNWRAP:
return deny("Too many wrappers inside one another for the guard to read; "
"simplify the command.")
self.unwraps += 1
try:
return self._program(words, ctx)
finally:
self.unwraps -= 1
def _program(self, words, ctx):
verdict = OK
# Walk past assignments and keywords by index: slicing at each step
# is quadratic on a long run of `! ! ! …`.
i, n = 0, len(words)
while i < n:
if ASSIGNMENT.match(words[i]):
verdict = verdict.merge(self.assignment(words[i], ctx))
i += 1
continue
head = prog_name(words[i], ctx.ps)
if head == "function" and i + 1 < n:
i += 2 # function NAME { ...
continue
if head not in KEYWORDS:
break
i += 1
if head == "command" and i < n and words[i] in ("-v", "-V"):
return verdict
if head == "coproc" and i + 1 < n and words[i + 1] == "{":
i += 1
while i < n and words[i].startswith("-") and len(words[i]) > 1:
opt = words[i]
i += 1
if opt == "--":
break
if (head, opt) in KEYWORD_VALUE_OPTS:
i += 1
if verdict.decision == DENY:
return verdict
words = words[i:]
if not words or verdict.decision == DENY:
return verdict
prog_word = words[0]
if prog_word.dynamic:
# The program name is only known at run time. Fail safe when the
# line mentions a guarded tool at all.
if ctx.guarded:
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 = prog_name(prog_word, ctx.ps)
args = words[1:]
if prog in ("export", "declare", "typeset", "local", "readonly"):
for a in args:
if ASSIGNMENT.match(a):
verdict = verdict.merge(self.assignment(a, ctx))
return verdict
if prog in SHELLS:
return verdict.merge(self.shell(args, ctx))
if prog in PWSH:
return verdict.merge(self.powershell(args, ctx))
if prog == "cmd":
for idx, a in enumerate(args):
if a.lower() in ("/c", "/k", "/r"):
return verdict.merge(self.text(" ".join(args[idx + 1:]),
guarded=ctx.guarded))
return verdict
if prog in EVALS:
if any(a.dynamic for a in args) and ctx.guarded:
return deny("'%s' runs a string built at run time; write the command "
"out literally." % prog)
return verdict.merge(self.text(" ".join(args), ctx.ps, ctx.guarded))
if prog in ("source", "."):
if any(a.dynamic for a in args) and ctx.guarded:
return deny("'%s' runs a script built at run time; run the command "
"directly." % prog)
if prog == "trap":
rest = [a for a in args if not a.startswith("-")]
return verdict.merge(self.text(rest[0], guarded=ctx.guarded) if rest else OK)
if prog in WRAPPERS:
return verdict.merge(self.wrapper(prog, args, ctx))
if prog in BUNDLES and args:
return verdict.merge(self.program(args, ctx))
if prog == "find":
verdict = verdict.merge(self.find_exec(args))
if verdict.decision == DENY:
return verdict
if prog == "rtk":
return verdict.merge(self.rtk(args, ctx))
if prog in RUNNERS:
return verdict.merge(self.runner(prog, args, ctx))
if prog in ("nix-shell", "nix", "tmux"):
return verdict.merge(self.launcher(prog, args, ctx))
verdict = verdict.merge(secret_words(prog_word, prog, args))
verdict = verdict.merge(hook_writes(prog, args))
rule = RULES.get(prog)
if rule:
verdict = verdict.merge(rule(args, self))
return verdict
def stdin_script(self, ctx, who):
"""A program that reads its commands from stdin."""
if ctx.stdin:
verdict = OK
for doc in ctx.stdin:
verdict = verdict.merge(self.text(doc, guarded=ctx.guarded))
return verdict
if ctx.guarded:
return deny("%s reading commands from stdin hides what it runs; run the "
"command directly." % who)
return OK
def shell(self, args, ctx):
# Options come first. In a cluster (`-euo pipefail`), a last letter
# that takes a value consumes the next word. With -c, the command
# string is the first word after the options.
idx = 0
from_stdin = has_c = False
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:
has_c = has_c or "c" in a[1:]
from_stdin = from_stdin or "s" in a[1:]
idx += 2 if a[-1] in "oO" else 1
continue
break
rest = args[idx:]
if has_c:
if not rest:
return OK
if rest[0].dynamic and ctx.guarded:
return deny("The shell runs a string built at run time; write "
"the command out literally.")
return self.text(rest[0], guarded=ctx.guarded)
if from_stdin or not rest or rest[0] == "-":
return self.stdin_script(ctx, "A shell")
if rest[0].dynamic and ctx.guarded:
return deny("The shell runs a script built at run time; run the command "
"directly.")
if is_secret_path(rest[0]):
return deny("'%s' is secret material; agents never run or read it." % rest[0])
return OK
def powershell(self, args, ctx):
idx = 0
while idx < len(args):
a = args[idx].lower()
if a in PWSH_VALUE_OPTS:
idx += 2
continue
if a in ("-e", "-ec") or (len(a) > 2 and "-encodedcommand".startswith(a)):
return deny("An encoded PowerShell command hides what it runs; write "
"it out literally.")
if a == "-c" or (len(a) > 3 and "-command".startswith(a)):
idx += 1
break
if a.startswith("-"):
idx += 1
continue
break
rest = args[idx:]
if not rest or rest == ["-"]:
return self.stdin_script(ctx, "PowerShell")
return self.text(" ".join(rest), ps=True, guarded=ctx.guarded)
def rtk(self, words, ctx):
# rtk <tool> args passes through to <tool>; rtk run is sh -c; proxy,
# err, test and summary run the rest as a command.
while words and words[0].startswith("-"):
words = words[1:]
if not words:
return OK
sub = words[0]
if sub == "run":
return self.text(" ".join(words[1:]), guarded=ctx.guarded)
if sub in ("proxy", "err", "test", "summary"):
return self.program(words[1:], ctx)
return self.program(words, ctx)
def runner(self, prog, words, ctx):
subs = RUNNERS[prog]
start = 0
if subs is not None:
while start < len(words) and words[start].startswith("-"):
start += 1
if start >= len(words) or words[start] not in subs:
return OK
start += 1
rest = words[start:]
# 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, or else after `--`.
for idx, w in enumerate(rest):
base = prog_name(w, ctx.ps)
if base in RULES or base in SHELLS or base in WRAPPERS or \
base in EVALS or base in RUNNERS or base in BUNDLES or base == "rtk":
return self.program(rest[idx:], ctx)
if "--" in rest:
return self.program(rest[rest.index("--") + 1:], ctx)
return OK
def launcher(self, prog, args, ctx):
if prog == "nix-shell":
for idx, a in enumerate(args):
if a in ("--run", "--command") and idx + 1 < len(args):
return self.text(args[idx + 1], guarded=ctx.guarded)
return OK
if prog == "nix":
for idx, a in enumerate(args):
if a in ("-c", "--command"):
return self.program(args[idx + 1:], ctx)
return OK
# tmux: the shell command is what follows a command-running subcommand
for idx, a in enumerate(args):
if a in TMUX_RUN:
rest = self._skip_opts(args[idx + 1:], TMUX_VALUE_OPTS)
return self.text(" ".join(rest), guarded=ctx.guarded) if rest else OK
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
verdict = verdict.merge(self.program(args[idx + 1:end], Ctx()))
idx = end
idx += 1
return verdict
def wrapper(self, prog, words, ctx):
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], guarded=ctx.guarded)
if w.startswith("--command="):
return self.text(w.split("=", 1)[1], guarded=ctx.guarded)
return OK
if prog in ("watch", "parallel"):
# both join their command words and hand them to a shell
rest = self._skip_opts(words, takes_value)
cmd = []
for w in rest:
if w in (":::", "::::", ":::+", "::::+"):
break
cmd.append(w)
return self.text(" ".join(cmd), guarded=ctx.guarded)
if prog == "ssh":
rest = self._skip_opts(words, takes_value)
if len(rest) > 1:
return self.text(" ".join(rest[1:]), guarded=ctx.guarded)
if rest: # a host and no command: the remote shell reads stdin
return self.stdin_script(ctx, "ssh")
return OK # no host: git's GIT_SSH_COMMAND, which git completes
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]):
return deny("'%s' is secret material; agents never read it."
% words[idx + 1])
if prog == "env":
idx = 0
verdict = OK
while idx < len(words):
w = words[idx]
if w in ("-S", "--split-string") and idx + 1 < len(words):
return self.text(" ".join(words[idx + 1:]), guarded=ctx.guarded)
if w.startswith("--split-string="):
return self.text(" ".join([w.split("=", 1)[1]] + words[idx + 1:]),
guarded=ctx.guarded)
if _takes_value(w, takes_value):
idx += 2
continue
if w.startswith("-"):
idx += 1
continue
if ASSIGNMENT.match(w):
verdict = verdict.merge(self.assignment(w, ctx))
idx += 1
continue
break
return verdict.merge(self.program(words[idx:], ctx))
rest = self._skip_opts(words, takes_value)
if prog in ("timeout", "taskset", "chrt", "chroot") and rest:
rest = rest[1:] # duration / mask / priority / new root
if prog == "flock" and rest:
rest = rest[1:] # lock file
if len(rest) >= 2 and rest[0] in ("-c", "--command"):
return self.text(rest[1], guarded=ctx.guarded)
return self.program(rest, ctx)
@staticmethod
def _skip_opts(words, takes_value):
idx = 0
while idx < len(words):
w = words[idx]
if w == "--":
idx += 1
break
if _takes_value(w, 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)
def _flag(args, *names):
"""True when an option in `names` is given, with or without a value."""
return any(a.lstrip("-").split("=", 1)[0] in names for a in args
if a.startswith("-"))
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):
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.")
if _kustomize(rest) and _secret_output(rest):
return deny("'kubectl get -k … -o …' prints every object the "
"kustomization names, Secrets included.")
if _secret_manifest(rest) and _secret_output(rest):
return deny("'kubectl get -f <secret manifest> -o …' prints the live "
"Secret's data; agents never read Secrets.")
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 _dry_run(rest) == "client":
# 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 on the allowlist of subcommands that change no "
"cluster and print no secret. Direct cluster changes never happen "
"from an agent; every change applies by approved merge." % verb)
def _dry_run(rest):
"""The effective --dry-run mode: the last one given wins."""
mode = None
for j, a in enumerate(rest):
if a.startswith("--dry-run="):
mode = a.split("=", 1)[1]
elif a == "--dry-run":
mode = rest[j + 1] if j + 1 < len(rest) else "unknown"
return mode
def _kustomize(rest):
return any(a in ("-k", "--kustomize") or a.startswith(("--kustomize=", "-k="))
for a in rest)
def _secret_manifest(rest):
"""A -f file whose name says it holds a Secret. A SealedSecret is
encrypted, so it does not count."""
for j in option_values(rest, {"-f", "--filename"}):
if j < len(rest):
name = os.path.basename(rest[j].split("=", 1)[-1]).lower()
if "secret" in name and "sealed" not in name:
return True
return False
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):
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"):
return OK
return deny("'helm get %s' prints release values, manifests or hooks, which "
"can hold secret material." % sub)
if verb == "plugin":
sub = rest[0] if rest else ""
if sub in ("list", "ls"):
return OK
if verb == "diff": # the helm-diff plugin: read-only, Secrets redacted
if _flag(rest, "show-secrets", "show-secrets-decoded"):
return deny("'helm diff --show-secrets' prints Secret data.")
if rest[:1] and rest[0] in HELM_DIFF_SUBS:
return OK
if verb == "secrets": # the helm-secrets plugin
return helm_secrets(rest, an)
return deny("'helm %s' changes a release or the cluster. Releases change only "
"by approved merge." % verb)
HELM_DIFF_SUBS = {"upgrade", "install", "revision", "rollback", "release", "version"}
def helm_secrets(args, an):
# every helm-secrets mode but encrypt decrypts, or deploys decrypted values
_, verb = first_positional(args, set())
if verb in ("encrypt", "enc", "help", "version") or wants_help(args):
return OK
return deny("'helm secrets %s' decrypts secrets; agents never decrypt them. Only "
"'helm secrets encrypt' is allowed." % (verb or ""))
HELMFILE_GLOBAL = {"-f", "--file", "-e", "--environment", "-n", "--namespace",
"--kube-context", "-l", "--selector", "--state-values-set",
"--state-values-file", "-b", "--helm-binary", "--log-level",
"--chart", "-c"}
HELMFILE_READ = {"template", "lint", "build", "list", "deps", "repos", "version",
"help", "write-values", "show-dag", "completion"}
def helmfile(args, an):
idx, verb = first_positional(args, HELMFILE_GLOBAL)
if verb is None or wants_help(args) or verb in HELMFILE_READ:
return OK
return deny("'helmfile %s' is not on the allowlist of subcommands that change "
"no release and print no secret. Releases change only by approved "
"merge." % verb)
TOFU_READ = {"init", "validate", "fmt", "plan", "providers", "version", "graph",
"get", "metadata", "modules", "help"}
def tofu(args, an):
# -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 in ("run-all", "run"): # terragrunt: run-all <cmd>, run [--all] <cmd>
return tofu(rest, an)
if verb == "init" and _flag(rest, "migrate-state", "force-copy"):
return deny("'tofu init -migrate-state/-force-copy' moves state between "
"backends.")
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 _flag(rest, "json", "raw"):
return deny("'tofu output -json/-raw' prints sensitive outputs in clear.")
return OK
if verb == "show":
if _flag(rest, "json"):
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 _flag(rest, "destroy"):
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)
# terragrunt's own commands on top of tofu's; they only read or format HCL.
TERRAGRUNT_READ = {"hclfmt", "render-json", "render", "hclvalidate",
"validate-inputs", "graph-dependencies", "output-module-groups",
"info", "find", "list"}
def terragrunt(args, an):
idx, verb = first_positional(args, set())
if verb in TERRAGRUNT_READ:
return OK
if verb == "hcl" and args[idx + 1:idx + 2] in (["fmt"], ["validate"], ["format"]):
return OK
return tofu(args, an)
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):
if _ansible_check_mode(args):
return OK
return ask("'ansible-playbook' without --check changes real hosts.")
def ansible_adhoc(args, an):
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):
if _ansible_check_mode(args):
return OK
return ask("'ansible-pull' without --check changes real hosts.")
def ansible_console(args, an):
return ask("'ansible-console' runs modules on real hosts.")
def ansible_vault(args, an):
_, 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):
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):
# A bare `sops <file>` 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.")
def gpg(args, an):
# gpg takes any unambiguous prefix of a long option
if any(a.startswith("--export-secret") for a in args):
return deny("'gpg --export-secret-keys' prints private keys.")
return OK
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):
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 _flag(rest, "show-values", "show-vars"):
return deny("'flux debug --show-values/--show-vars' can print values pulled "
"from Secrets.")
if verb in FLUX_READ:
return OK
if verb == "export":
if _flag(rest, "with-credentials"):
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"}
# Subcommands that take a message with -m, and the short options whose value
# is the next word when they end a cluster (`-am msg`).
GIT_MESSAGE_SUBS = {"commit", "tag", "merge", "notes", "stash", "revert"}
GIT_VALUE_SHORT = {"commit": "mFcCt", "tag": "mFu", "merge": "mFsX",
"notes": "mFcC", "stash": "m", "revert": "mX",
"log": "SGn", "show": "SG", "whatchanged": "SG",
"rev-list": "SGn", "diff": "SG"}
GIT_VALUE_LONG = {"--message", "--file", "--reuse-message", "--reedit-message",
"--template", "--author", "--date", "--cleanup", "--fixup",
"--squash", "--trailer", "--grep", "--format", "--pretty",
"--committer"}
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_value_indexes(sub, rest):
"""Indexes of option values in a git subcommand's arguments."""
letters = GIT_VALUE_SHORT.get(sub, "")
skip = set()
for j, a in enumerate(rest):
if j in skip:
continue
if a in GIT_VALUE_LONG:
skip.add(j + 1)
elif a.startswith("-") and not a.startswith("--"):
for pos, ch in enumerate(a[1:]):
if ch in letters:
if pos == len(a) - 2:
skip.add(j + 1)
break
return skip
def _git_message_indexes(rest):
"""Indexes of the words that are a -m / --message value."""
found = set()
for j, a in enumerate(rest):
if a in ("-m", "--message"):
found.add(j + 1)
elif a.startswith("--message="):
found.add(j)
elif a.startswith("-") and not a.startswith("--") and "m" in a:
found.add(j + 1 if a.endswith("m") and a.index("m") == len(a) - 1 else j)
return found
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)
key, _, val = value.partition("=")
key = key.lower()
if key == "core.sshcommand":
return an.text(val)
if key.startswith("alias.") and val.startswith("!"):
return an.text(val[1:])
if is_secret_path(val):
return deny("'%s' is secret material; agents never read it." % val)
return OK
def git(args, an):
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:]
values = _git_value_indexes(sub, rest)
opts = [a for j, a in enumerate(rest) if j not in values]
# 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 opts):
return deny("'--no-verify' skips the repo's git hooks; " + HOOK_BYPASS)
if sub == "config":
setting = not any(x in ("--get", "--get-all", "-l", "--list", "--unset",
"--unset-all", "get", "list", "unset") for x in rest)
for j, a in enumerate(rest):
key = a.lower()
if j + 1 >= len(rest) or not setting:
break
if key == "core.hookspath":
return deny("Setting core.hooksPath skips the repo's git hooks; "
+ HOOK_BYPASS)
if key.startswith("alias.") or key == "core.sshcommand":
verdict = verdict.merge(_git_config_value(a + "=" + rest[j + 1], an))
if sub == "rebase":
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 rest[:1] == ["run"]:
verdict = verdict.merge(an.program(rest[1:], Ctx()))
if sub == "submodule" 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":
for j, a in enumerate(rest):
if j in values or not a.startswith("-") or a.startswith("--"):
continue
for ch in a[1:]:
if ch == "n":
return deny("'git commit -n' is --no-verify; it skips the "
"repo's git hooks.")
if ch in GIT_VALUE_SHORT["commit"]:
break
return verdict
def pre_commit(args, an):
_, 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, "kubecolor": kubectl, "microk8s.kubectl": kubectl,
"helm": helm, "helm3": helm,
"helmfile": helmfile, "helm-secrets": helm_secrets,
"tofu": tofu, "terraform": tofu, "terragrunt": terragrunt,
"ansible-playbook": ansible_playbook,
"ansible": ansible_adhoc,
"ansible-pull": ansible_pull,
"ansible-console": ansible_console,
"ansible-vault": ansible_vault,
"kubeseal": kubeseal,
"sops": sops,
"gpg": gpg, "gpg2": gpg,
"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",
"write_stdin", "write_bash"}
PS_TOOLS = {"powershell"}
COMMAND_KEYS = ("command", "cmd", "input", "chars")
PATH_KEYS = ("file_path", "path", "notebook_path", "filePath", "absolute_path")
WRITE_TOOLS = {"write", "edit", "multiedit", "notebookedit", "create",
"str_replace", "str_replace_editor", "insert"}
PATCH_TARGET = re.compile(r"^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$", re.M)
def analyse_tool(tool, tool_input):
if not isinstance(tool, str) or not tool:
raise ValueError("no tool name")
lname = tool.lower()
if lname in SHELL_TOOLS:
if not isinstance(tool_input, dict):
raise ValueError("tool input is not an object")
cmd = next((tool_input[k] for k in COMMAND_KEYS if k in tool_input), None)
if isinstance(cmd, list) and cmd and all(isinstance(c, str) for c in cmd):
cmd = " ".join(_quote(c) for c in cmd)
if not isinstance(cmd, str):
raise ValueError("no command string")
return Analyzer().text(cmd, ps=lname in PS_TOOLS)
if not isinstance(tool_input, dict):
tool_input = {}
if lname == "apply_patch":
cmd = str(tool_input.get("command", "") or tool_input.get("input", ""))
for m in PATCH_TARGET.finditer(cmd):
path = m.group(1).strip()
if is_secret_path(path):
return deny("'%s' is secret material; agents never touch it." % path)
if is_hooks_path(path):
return deny("Changing '%s' changes the repo's git hooks; %s"
% (path, HOOK_BYPASS))
return OK
for key in PATH_KEYS:
val = tool_input.get(key)
if not isinstance(val, str):
continue
if is_secret_path(val):
return deny("'%s' is secret material (vault password, private key, "
"admin kubeconfig or tofu state); agents never read it." % val)
if lname in WRITE_TOOLS and is_hooks_path(val):
return deny("Changing '%s' changes the repo's git hooks; %s" % (val, HOOK_BYPASS))
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):
if re.match(r"^[A-Za-z0-9_./=:@%+,-]+$", s):
return s
return "'" + s.replace("'", "'\\''") + "'"
def detect_runtime():
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"
return "unknown"
def read_payload(payload):
"""(tool name, tool input) from either payload shape."""
if "toolName" in payload:
args = payload.get("toolArgs")
if isinstance(args, str):
try:
args = json.loads(args)
except ValueError:
args = {"command": args}
if args is not None and not isinstance(args, dict):
raise ValueError("toolArgs is not an object")
return payload.get("toolName"), 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,
"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():
runtime = detect_runtime()
event = "PreToolUse"
try:
payload = json.loads(sys.stdin.read())
if not isinstance(payload, dict):
raise ValueError("payload is not an object")
if isinstance(payload.get("hook_event_name"), str):
event = payload["hook_event_name"]
verdict = analyse_tool(*read_payload(payload))
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.exit(main())