fix(orchestrator): approve only a plain commit of the exact staged index
The approval hook binds a hub approval to a plain git commit of the staged index only; commits that add files from the working tree, amend, take a pathspec, run in a chain or inside a shell wrapper fall back to the normal dialog. Every git call of the hook runs with an environment allowlist. Tests run once on unify/skills-20261114 after the merge (operator order 2026-11-14). 🎯 Fix: 93 % 💥 Break: 3 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 90 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a2a03995cb
commit
4ec1a43238
8 files changed
+732
-303
No files matched your search
@@ -24,9 +24,11 @@ changed and what it costs, and a gate means something again.
|
|||||||
line or matches a MEDUSA secret rule (every file when no rule loads)
|
line or matches a MEDUSA secret rule (every file when no rule loads)
|
||||||
ships only path, status, mode and counts with the note "content withheld".
|
ships only path, status, mode and counts with the note "content withheld".
|
||||||
Rejected: the hub reads git.
|
Rejected: the hub reads git.
|
||||||
Every Ask for a `git commit` shows the staged diff the same way (with
|
Every Ask for a `git commit` of the staged index shows the staged diff
|
||||||
`-a` or `--all` the diff against HEAD); the permission hook on the host
|
the same way; the permission hook on the host attaches it (operator order
|
||||||
attaches it (operator order 2026-11-11).
|
2026-11-11). A commit that reads the working tree (`-a`, `--all`, `-i`,
|
||||||
|
`-o`, `-p`, a pathspec, a chain or a wrapper) is not approvable here: the
|
||||||
|
hook sends no Ask and Claude Code asks instead.
|
||||||
4. **Inline feedback**: selected lines of a diff or a command go back to the
|
4. **Inline feedback**: selected lines of a diff or a command go back to the
|
||||||
agent as one radio `post` with path, line range, quote and text, through
|
agent as one radio `post` with path, line range, quote and text, through
|
||||||
the right-click menu, the key `f` or a button at the selection.
|
the right-click menu, the key `f` or a button at the selection.
|
||||||
@@ -173,14 +175,17 @@ flowchart TD
|
|||||||
- [x] The review request of `approval.py` (kvb-git-diff) carries
|
- [x] The review request of `approval.py` (kvb-git-diff) carries
|
||||||
`git diff --cached` of the exact staged tree; past 2 MiB the rest is
|
`git diff --cached` of the exact staged tree; past 2 MiB the rest is
|
||||||
listed per file with its stat.
|
listed per file with its stat.
|
||||||
- [x] An Ask for a `git commit` carries the staged diff of its working
|
- [x] An Ask for a `git commit` of the staged index carries the staged diff
|
||||||
directory (with `-a` or `--all` the diff against HEAD), attached by
|
of its working directory, attached by `permission_hook.py`, and shows
|
||||||
`permission_hook.py`, and shows it like a review, feedback included.
|
it like a review, feedback included; a commit that reads the working
|
||||||
|
tree gets no Ask, only the line "commit reads the working tree; stage
|
||||||
|
the files and commit the index" on the hook's stderr.
|
||||||
- [x] A file whose content holds an armour line or matches MEDUSA's secret
|
- [x] A file whose content holds an armour line or matches MEDUSA's secret
|
||||||
rules, and every file when no rule loads, is shown by stat with the
|
rules, and every file when no rule loads, is shown by stat with the
|
||||||
note "content withheld".
|
note "content withheld".
|
||||||
- [x] An allow of a commit Ask is bound to the staged tree `git write-tree`
|
- [x] An allow of a commit Ask is bound to the staged tree, the sha256 of
|
||||||
prints (with `-a` also the working tree); a different tree at approval
|
`git ls-files -s -z`, read without writing the index or running a hook;
|
||||||
|
a different tree at approval
|
||||||
turns it into a deny "staged tree changed since the preview".
|
turns it into a deny "staged tree changed since the preview".
|
||||||
- [ ] Selecting lines in a diff or a command and choosing Feedback (right-click
|
- [ ] Selecting lines in a diff or a command and choosing Feedback (right-click
|
||||||
menu, key `f`, or the button at the selection) posts one radio `post` to
|
menu, key `f`, or the button at the selection) posts one radio `post` to
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ B64URL = re.compile(r"[A-Za-z0-9_-]+")
|
|||||||
ASSERTION_KEYS = ("id", "clientDataJSON", "authenticatorData", "signature")
|
ASSERTION_KEYS = ("id", "clientDataJSON", "authenticatorData", "signature")
|
||||||
CBOR_DEPTH = 16
|
CBOR_DEPTH = 16
|
||||||
TIMEOUT = 30
|
TIMEOUT = 30
|
||||||
|
OPENSSL = "/usr/bin/openssl"
|
||||||
|
|
||||||
|
|
||||||
def b64decode(text: object, name: str) -> bytes:
|
def b64decode(text: object, name: str) -> bytes:
|
||||||
@@ -263,9 +264,9 @@ def by_openssl(alg: int, spki: bytes, data: bytes, signature: bytes) -> bool:
|
|||||||
message.write_bytes(data)
|
message.write_bytes(data)
|
||||||
sealed.write_bytes(signature)
|
sealed.write_bytes(signature)
|
||||||
if alg == -8:
|
if alg == -8:
|
||||||
argv = ["openssl", "pkeyutl", "-verify", "-pubin", "-inkey", str(key), "-rawin", "-in", str(message), "-sigfile", str(sealed)]
|
argv = [OPENSSL, "pkeyutl", "-verify", "-pubin", "-inkey", str(key), "-rawin", "-in", str(message), "-sigfile", str(sealed)]
|
||||||
else:
|
else:
|
||||||
argv = ["openssl", "dgst", "-sha256", "-verify", str(key), "-signature", str(sealed), str(message)]
|
argv = [OPENSSL, "dgst", "-sha256", "-verify", str(key), "-signature", str(sealed), str(message)]
|
||||||
try:
|
try:
|
||||||
done = subprocess.run(argv, capture_output=True, timeout=TIMEOUT, check=False)
|
done = subprocess.run(argv, capture_output=True, timeout=TIMEOUT, check=False)
|
||||||
except (OSError, subprocess.TimeoutExpired):
|
except (OSError, subprocess.TimeoutExpired):
|
||||||
|
|||||||
@@ -16,14 +16,17 @@ Returns:
|
|||||||
reason only when a pinned passkey signed it. Nothing on timeout,
|
reason only when a pinned passkey signed it. Nothing on timeout,
|
||||||
error, a missing or invalid signature, a value longer than the hub
|
error, a missing or invalid signature, a value longer than the hub
|
||||||
takes or a hub that is down, so Claude Code shows its own dialog.
|
takes or a hub that is down, so Claude Code shows its own dialog.
|
||||||
The exit code is 0. An ask for a Bash git commit carries the diff
|
The exit code is 0. An ask for a Bash git commit of exactly the
|
||||||
staged_diff.py builds of the tree its directory stages (of the
|
staged index (staged_diff.commit_of) carries the diff staged_diff.py
|
||||||
working tree against HEAD with -a or --all), content withheld per
|
builds of the tree its directory stages, content withheld per the
|
||||||
the MEDUSA rules of the pipx install; none when it cannot be built
|
MEDUSA rules of the pipx install; none when it cannot be built or
|
||||||
or the body would pass DIFF_BODY_LIMIT. An allow of such an ask
|
the body would pass DIFF_BODY_LIMIT. An allow of such an ask turns
|
||||||
turns into a deny with CHANGED when what the commit records
|
into a deny with CHANGED when what the commit records
|
||||||
(staged_diff.binding) differs right before answering from the
|
(staged_diff.binding) differs right before answering from the
|
||||||
preview's, and with UNBOUND when either cannot be read.
|
preview's, and with UNBOUND when either cannot be read. Any other
|
||||||
|
Bash command that may run git commit (-a, --all, -i, -o, -p, a
|
||||||
|
pathspec, a chain, a wrapper) is not approvable: no ask reaches the
|
||||||
|
hub, stderr gets WORKTREE and Claude Code shows its own dialog.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -50,6 +53,8 @@ LIMITS = {"tool": NAME_LIMIT, "command": COMMAND_LIMIT, "cwd": PATH_LIMIT, "sess
|
|||||||
DENIED = "The operator denied this in the Agent Orchestrator."
|
DENIED = "The operator denied this in the Agent Orchestrator."
|
||||||
CHANGED = "staged tree changed since the preview"
|
CHANGED = "staged tree changed since the preview"
|
||||||
UNBOUND = "the staged tree cannot be read, so the allow is not bound to it"
|
UNBOUND = "the staged tree cannot be read, so the allow is not bound to it"
|
||||||
|
WORKTREE = "commit reads the working tree; stage the files and commit the index"
|
||||||
|
ALLOW = {"behavior": "allow"}
|
||||||
REASON_LIMIT = 2000
|
REASON_LIMIT = 2000
|
||||||
FAILURES = (OSError, ValueError, staged_diff.DiffError)
|
FAILURES = (OSError, ValueError, staged_diff.DiffError)
|
||||||
|
|
||||||
@@ -72,10 +77,14 @@ def facts(hook: dict) -> dict:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def commit_target(ask: dict) -> tuple[Path, bool] | None:
|
def commit_target(ask: dict) -> Path | None:
|
||||||
return staged_diff.commit_of(ask["command"], ask["cwd"]) if ask["tool"] == "Bash" and ask["cwd"] else None
|
return staged_diff.commit_of(ask["command"], ask["cwd"]) if ask["tool"] == "Bash" and ask["cwd"] else None
|
||||||
|
|
||||||
|
|
||||||
|
def unapprovable(ask: dict) -> bool:
|
||||||
|
return ask["tool"] == "Bash" and staged_diff.names_commit(ask["command"]) and commit_target(ask) is None
|
||||||
|
|
||||||
|
|
||||||
def commit_diff(ask: dict, rules: Path | None) -> tuple[str | None, dict]:
|
def commit_diff(ask: dict, rules: Path | None) -> tuple[str | None, dict]:
|
||||||
"""Returns:
|
"""Returns:
|
||||||
For a commit ask, what the commit records (staged_diff.binding, None
|
For a commit ask, what the commit records (staged_diff.binding, None
|
||||||
@@ -86,12 +95,12 @@ def commit_diff(ask: dict, rules: Path | None) -> tuple[str | None, dict]:
|
|||||||
if target is None:
|
if target is None:
|
||||||
return None, {}
|
return None, {}
|
||||||
try:
|
try:
|
||||||
pinned = staged_diff.binding(*target)
|
pinned = staged_diff.binding(target)
|
||||||
except FAILURES as error:
|
except FAILURES as error:
|
||||||
print(f"kvb-orchestrator: the ask goes without its diff and an allow of it turns into a deny: {error}", file=sys.stderr)
|
print(f"kvb-orchestrator: the ask goes without its diff and an allow of it turns into a deny: {error}", file=sys.stderr)
|
||||||
return None, {}
|
return None, {}
|
||||||
try:
|
try:
|
||||||
return pinned, {"diff": staged_diff.bound_diff(*target, pinned, rules)}
|
return pinned, {"diff": staged_diff.bound_diff(target, pinned, rules)}
|
||||||
except FAILURES as error:
|
except FAILURES as error:
|
||||||
print(f"kvb-orchestrator: the ask goes without its diff: {error}", file=sys.stderr)
|
print(f"kvb-orchestrator: the ask goes without its diff: {error}", file=sys.stderr)
|
||||||
return pinned, {}
|
return pinned, {}
|
||||||
@@ -128,12 +137,17 @@ def bound(chosen: dict | None, ask: dict, pinned: str | None) -> dict | None:
|
|||||||
Returns:
|
Returns:
|
||||||
chosen, or for an allow of a commit ask a deny with CHANGED when
|
chosen, or for an allow of a commit ask a deny with CHANGED when
|
||||||
what it records now differs from pinned, with UNBOUND and the error
|
what it records now differs from pinned, with UNBOUND and the error
|
||||||
when either cannot be read.
|
when either cannot be read; None for an allow of an unapprovable ask.
|
||||||
"""
|
"""
|
||||||
if chosen != {"behavior": "allow"} or commit_target(ask) is None:
|
if chosen != ALLOW:
|
||||||
|
return chosen
|
||||||
|
if unapprovable(ask):
|
||||||
|
return None
|
||||||
|
target = commit_target(ask)
|
||||||
|
if target is None:
|
||||||
return chosen
|
return chosen
|
||||||
try:
|
try:
|
||||||
now = staged_diff.binding(*commit_target(ask))
|
now = staged_diff.binding(target)
|
||||||
except FAILURES as error:
|
except FAILURES as error:
|
||||||
return {"behavior": "deny", "message": f"{UNBOUND}: {clean(str(error))}"}
|
return {"behavior": "deny", "message": f"{UNBOUND}: {clean(str(error))}"}
|
||||||
if pinned is None:
|
if pinned is None:
|
||||||
@@ -207,6 +221,9 @@ def main() -> int:
|
|||||||
if too_long:
|
if too_long:
|
||||||
print(f"kvb-orchestrator: {', '.join(too_long)} too long to sign in full, Claude Code asks instead", file=sys.stderr)
|
print(f"kvb-orchestrator: {', '.join(too_long)} too long to sign in full, Claude Code asks instead", file=sys.stderr)
|
||||||
return 0
|
return 0
|
||||||
|
if unapprovable(ask):
|
||||||
|
print(f"kvb-orchestrator: {WORKTREE}", file=sys.stderr)
|
||||||
|
return 0
|
||||||
pinned, shown = commit_diff(ask, staged_diff.rules_root())
|
pinned, shown = commit_diff(ask, staged_diff.rules_root())
|
||||||
ask_id = create(base, ask, args.timeout, shown)
|
ask_id = create(base, ask, args.timeout, shown)
|
||||||
answer = {"status": "pending"}
|
answer = {"status": "pending"}
|
||||||
|
|||||||
+121
-164
@@ -1,48 +1,47 @@
|
|||||||
"""Args:
|
"""Args:
|
||||||
cwd: the working directory whose repository the diff is taken of.
|
cwd: the working directory whose repository the diff is taken of.
|
||||||
everything: False for the staged tree against HEAD (git diff --cached),
|
|
||||||
True for what git commit -a records (every index path as it lies in
|
|
||||||
the working tree) against HEAD.
|
|
||||||
tree: for tree_diff, the tree object (git write-tree) diffed against
|
tree: for tree_diff, the tree object (git write-tree) diffed against
|
||||||
HEAD instead of the live index.
|
HEAD instead of the live index.
|
||||||
rules: the MEDUSA rules directory, None when MEDUSA is not installed.
|
rules: the MEDUSA rules directory, None when MEDUSA is not installed.
|
||||||
pinned: for bound_diff, what binding returned for the same cwd and everything.
|
pinned: for bound_diff, what binding returned for the same cwd.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
review_diff, tree_diff, bound_diff: the review diff of requirement 003,
|
review_diff, tree_diff, bound_diff: the review diff of requirement 003
|
||||||
one {path, status, mode, additions, deletions, patch, note} per
|
of the staged tree against HEAD (git diff --cached), one {path,
|
||||||
changed path, sorted by path, status A, M, D or B (binary); path is
|
status, mode, additions, deletions, patch, note} per changed path,
|
||||||
the file name with bytes that are no UTF-8 written as backslash
|
sorted by path, status A, M, D or B (binary); path is the file name
|
||||||
escapes; mode the git file mode, "old => new" when it changed (with
|
with bytes that are no UTF-8 written as backslash escapes; mode the
|
||||||
everything, the executable bit on disk). patch holds the unified
|
git file mode, "old => new" when it changed. patch holds the unified
|
||||||
hunks; it is empty for a binary file, a gitlink, a side over
|
hunks; it is empty for a binary file, a gitlink, a side over
|
||||||
BLOB_LIMIT bytes (counted 0/0), a path sandbox_paths denies (its
|
BLOB_LIMIT bytes (counted 0/0), a path sandbox_paths denies (its
|
||||||
FLOOR and the settings' deny lists) and every file past DIFF_LIMIT
|
FLOOR and the settings' deny lists) and every file past DIFF_LIMIT
|
||||||
bytes of JSON-encoded patch text. A file whose old or new content
|
bytes of JSON-encoded patch text. A file whose old or new content
|
||||||
holds an ARMOUR line or matches a MEDUSA secret rule for its name,
|
holds an ARMOUR line or matches a MEDUSA secret rule for its name,
|
||||||
and every file when no secret rule pattern loads, ships no patch,
|
and every file when no secret rule pattern loads, ships no patch,
|
||||||
only its counts and the note WITHHELD. With everything, a working
|
only its counts and the note WITHHELD. The diff fails when more
|
||||||
tree file over BLOB_LIMIT or under a denied path is not read and so
|
than FILE_CAP paths changed or one is longer than PATH_LIMIT, a
|
||||||
always counts as changed. The diff fails when more than FILE_CAP
|
settings file sandbox_paths reads is unreadable, the working tree
|
||||||
paths changed or one is longer than PATH_LIMIT, a settings file
|
lies under a denied path, HEAD exists but its tree cannot be listed,
|
||||||
sandbox_paths reads is unreadable, the working tree lies under a
|
HEAD is neither a commit nor unborn, or for bound_diff, the index no
|
||||||
denied path, HEAD exists but its tree cannot be listed, HEAD is
|
longer matches pinned.
|
||||||
neither a commit nor unborn, or for bound_diff, the working tree
|
|
||||||
changed while it was read.
|
|
||||||
binding: what a commit records, for the permission hook to bind an
|
binding: what a commit records, for the permission hook to bind an
|
||||||
allow to: the tree git write-tree prints; with everything, joined by
|
allow to: the sha256 of staged() (the mode, object id and name of
|
||||||
the digest of every index path's mode and content id as it lies in
|
every index entry git write-tree records, so no intent-to-add one;
|
||||||
the working tree, a file not read by its size, inode and times.
|
an index with unmerged paths fails).
|
||||||
commit_of: the directory and -a mode of a single git commit whose
|
commit_of: the directory of a single git commit that records exactly
|
||||||
preview matches what it records, None for any other command.
|
the staged index, None for any other command.
|
||||||
|
names_commit: whether a command may run git commit anywhere in it.
|
||||||
|
|
||||||
Only git plumbing runs (rev-parse, symbolic-ref, ls-tree, ls-files, cat-file,
|
Every git call runs GIT with core.fsmonitor, core.hooksPath, lazy fetching,
|
||||||
write-tree) with core.fsmonitor and lazy fetching off, and the diff itself is computed here:
|
the system and the global config off, and an environment of only PASSED_ENV
|
||||||
|
and FIXED_ENV (PATH set to TRUSTED_PATH). The permission hook path
|
||||||
|
(binding, bound_diff, commit_of) runs only plumbing that writes nothing
|
||||||
|
(rev-parse, symbolic-ref, ls-tree, ls-files, cat-file); only approval.py, run
|
||||||
|
inside the sandbox, adds git write-tree. The diff itself is computed here:
|
||||||
the permission hook calls this outside the sandbox in a directory the agent
|
the permission hook calls this outside the sandbox in a directory the agent
|
||||||
chose, where a planted repository config, filter, diff driver or promisor
|
chose, where a planted repository config, hook, filter, diff driver, promisor
|
||||||
remote must start no program, and a working tree path must not lead the read
|
remote or program on PATH must start nothing, and nothing in the working tree
|
||||||
through a symlinked directory, out of the working tree or into a path the
|
is read.
|
||||||
sandbox denies reading.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -54,7 +53,6 @@ import json
|
|||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import shlex
|
import shlex
|
||||||
import stat
|
|
||||||
import subprocess
|
import subprocess
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -70,15 +68,21 @@ BINARY_PROBE = 8000
|
|||||||
CONTEXT = 3
|
CONTEXT = 3
|
||||||
GIT_TIMEOUT = 30
|
GIT_TIMEOUT = 30
|
||||||
GITLINK = "160000"
|
GITLINK = "160000"
|
||||||
SYMLINK = "120000"
|
|
||||||
REGULAR = "100644"
|
|
||||||
EXECUTABLE = "100755"
|
|
||||||
SECRET_CWE = re.compile(r"CWE-(?:259|321|540|798)\b")
|
SECRET_CWE = re.compile(r"CWE-(?:259|321|540|798)\b")
|
||||||
RULES_HOME = Path.home() / ".local" / "pipx" / "venvs" / "medusa-security" / "lib"
|
RULES_HOME = Path.home() / ".local" / "pipx" / "venvs" / "medusa-security" / "lib"
|
||||||
RULES_TAIL = "python3*/site-packages/medusa/rules"
|
RULES_TAIL = "python3*/site-packages/medusa/rules"
|
||||||
CACHE = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "kvb-orchestrator" / "secret-rules.json"
|
CACHE = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "kvb-orchestrator" / "secret-rules.json"
|
||||||
UNREAD = "unread"
|
GIT = "/usr/bin/git"
|
||||||
SAFE = ("git", "--no-pager", "--no-lazy-fetch", "-c", "core.fsmonitor=false")
|
TRUSTED_PATH = "/usr/bin:/bin"
|
||||||
|
SAFE = (GIT, "--no-pager", "--no-lazy-fetch", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null")
|
||||||
|
PASSED_ENV = ("HOME", "LANG", "LC_ALL", "LC_CTYPE")
|
||||||
|
FIXED_ENV = {"GIT_OPTIONAL_LOCKS": "0", "GIT_NO_LAZY_FETCH": "1", "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "PATH": TRUSTED_PATH}
|
||||||
|
INTENT_TO_ADD = 0x20000000
|
||||||
|
DEBUG_LINES = 5
|
||||||
|
NAMES_COMMIT = re.compile(r"(?<![\w.-])git(?![\w.-]).*(?<![\w-])commit(?![\w-])", re.DOTALL)
|
||||||
|
LAYOUT = "unexpected ls-files --debug layout"
|
||||||
|
RECORD = re.compile(rb"[0-7]{6} (?:[0-9a-f]{40}|[0-9a-f]{64}) [0-3]\t.+", re.DOTALL)
|
||||||
|
FLAGS_LINE = re.compile(rb" size: [0-9]+\tflags: ([0-9a-f]+)")
|
||||||
COMMIT_LONGS = {
|
COMMIT_LONGS = {
|
||||||
"quiet", "verbose", "file", "author", "date", "message", "reedit-message", "reuse-message", "fixup", "squash", "reset-author", "trailer", "signoff",
|
"quiet", "verbose", "file", "author", "date", "message", "reedit-message", "reuse-message", "fixup", "squash", "reset-author", "trailer", "signoff",
|
||||||
"template", "edit", "cleanup", "status", "gpg-sign", "all", "include", "interactive", "patch", "unified", "inter-hunk-context", "only", "no-verify",
|
"template", "edit", "cleanup", "status", "gpg-sign", "all", "include", "interactive", "patch", "unified", "inter-hunk-context", "only", "no-verify",
|
||||||
@@ -91,6 +95,7 @@ COMMIT_LONGS = {
|
|||||||
}
|
}
|
||||||
LONG_ARGS = {"message", "file", "reuse-message", "reedit-message", "template", "author", "date", "cleanup", "fixup", "squash", "trailer", "unified", "inter-hunk-context"}
|
LONG_ARGS = {"message", "file", "reuse-message", "reedit-message", "template", "author", "date", "cleanup", "fixup", "squash", "trailer", "unified", "inter-hunk-context"}
|
||||||
NARROWING = {"only", "include", "interactive", "patch", "pathspec-from-file", "no-all"}
|
NARROWING = {"only", "include", "interactive", "patch", "pathspec-from-file", "no-all"}
|
||||||
|
REWRITING = {"amend"}
|
||||||
SHORT_ARGS = set("mFcCtuSU")
|
SHORT_ARGS = set("mFcCtuSU")
|
||||||
KEPT_VARS = {"GIT_EDITOR", "GIT_SEQUENCE_EDITOR", "GIT_PAGER", "GIT_TERMINAL_PROMPT", "GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_AUTHOR_DATE", "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL", "GIT_COMMITTER_DATE"}
|
KEPT_VARS = {"GIT_EDITOR", "GIT_SEQUENCE_EDITOR", "GIT_PAGER", "GIT_TERMINAL_PROMPT", "GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_AUTHOR_DATE", "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL", "GIT_COMMITTER_DATE"}
|
||||||
ASSIGNMENT = re.compile(r"([A-Za-z_][A-Za-z0-9_]*)=.*")
|
ASSIGNMENT = re.compile(r"([A-Za-z_][A-Za-z0-9_]*)=.*")
|
||||||
@@ -105,7 +110,8 @@ class DiffError(Exception):
|
|||||||
|
|
||||||
def git(cwd: Path, args: list[str], data: bytes | None) -> bytes:
|
def git(cwd: Path, args: list[str], data: bytes | None) -> bytes:
|
||||||
try:
|
try:
|
||||||
done = subprocess.run([*SAFE, *args], cwd=cwd, input=data, capture_output=True, timeout=GIT_TIMEOUT, check=False, env={**os.environ, "GIT_OPTIONAL_LOCKS": "0", "GIT_NO_LAZY_FETCH": "1"})
|
env = {**{key: os.environ[key] for key in PASSED_ENV if key in os.environ}, **FIXED_ENV}
|
||||||
|
done = subprocess.run([*SAFE, *args], cwd=cwd, input=data, capture_output=True, timeout=GIT_TIMEOUT, check=False, env=env)
|
||||||
except (OSError, subprocess.TimeoutExpired) as error:
|
except (OSError, subprocess.TimeoutExpired) as error:
|
||||||
raise DiffError(f"git {args[0]} failed to start: {error}") from error
|
raise DiffError(f"git {args[0]} failed to start: {error}") from error
|
||||||
if done.returncode != 0:
|
if done.returncode != 0:
|
||||||
@@ -147,112 +153,69 @@ def blobs(cwd: Path, oids: set[str]) -> dict[str, bytes]:
|
|||||||
return found
|
return found
|
||||||
|
|
||||||
|
|
||||||
def worktree(top: Path, path: str, mode: str, algorithm: str, roots: list[str]) -> tuple[str, str, bytes | None] | None:
|
|
||||||
"""Args:
|
|
||||||
top: the working tree, resolved through symlinks.
|
|
||||||
roots: the paths the sandbox denies reading (sandbox_paths.denied_roots).
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
The mode (for a regular file its executable bit on disk), blob id and
|
|
||||||
content of an index path as it lies in the working tree; for a file
|
|
||||||
over BLOB_LIMIT or under one of roots, which is not read, content
|
|
||||||
None and in place of the blob id UNREAD with its size, inode and
|
|
||||||
times; None when it is gone, lies behind a symlinked directory or is
|
|
||||||
neither a regular file nor a symlink.
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
DiffError: for a path with an empty, . or .. component.
|
|
||||||
"""
|
|
||||||
parts = path.split("/")
|
|
||||||
if any(part in ("", ".", "..") for part in parts):
|
|
||||||
raise DiffError(f"index path {path!r} leaves the working tree")
|
|
||||||
try:
|
|
||||||
if sandbox_paths.denied(os.path.join(top, *parts), roots):
|
|
||||||
return mode, unread(os.lstat(os.path.join(top, *parts))), None
|
|
||||||
found = on_disk(top, parts)
|
|
||||||
except OSError:
|
|
||||||
return None
|
|
||||||
if found is None:
|
|
||||||
return None
|
|
||||||
mode, data, info = found
|
|
||||||
if data is None:
|
|
||||||
return mode, unread(info), None
|
|
||||||
return mode, hashlib.new(algorithm, b"blob %d\0" % len(data) + data).hexdigest(), data
|
|
||||||
|
|
||||||
|
|
||||||
def unread(info: os.stat_result) -> str:
|
|
||||||
return f"{UNREAD}:{info.st_size}:{info.st_ino}:{info.st_mtime_ns}:{info.st_ctime_ns}"
|
|
||||||
|
|
||||||
|
|
||||||
def on_disk(top: Path, parts: list[str]) -> tuple[str, bytes | None, os.stat_result] | None:
|
|
||||||
"""Returns:
|
|
||||||
The mode, content (None past BLOB_LIMIT) and status of top/parts,
|
|
||||||
every folder from / on opened without following a symlink, None for
|
|
||||||
an entry that is neither a regular file nor a symlink.
|
|
||||||
"""
|
|
||||||
folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY)
|
|
||||||
try:
|
|
||||||
for part in [*top.parts[1:], *parts[:-1]]:
|
|
||||||
inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)
|
|
||||||
os.close(folder)
|
|
||||||
folder = inner
|
|
||||||
return leaf(folder, parts[-1])
|
|
||||||
finally:
|
|
||||||
os.close(folder)
|
|
||||||
|
|
||||||
|
|
||||||
def leaf(folder: int, name: str) -> tuple[str, bytes | None, os.stat_result] | None:
|
|
||||||
info = os.stat(name, dir_fd=folder, follow_symlinks=False)
|
|
||||||
if stat.S_ISLNK(info.st_mode):
|
|
||||||
return SYMLINK, os.readlink(name, dir_fd=folder).encode("utf-8", "surrogateescape"), info
|
|
||||||
fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)
|
|
||||||
try:
|
|
||||||
info = os.fstat(fd)
|
|
||||||
if not stat.S_ISREG(info.st_mode):
|
|
||||||
return None
|
|
||||||
mode = EXECUTABLE if info.st_mode & stat.S_IXUSR else REGULAR
|
|
||||||
if info.st_size > BLOB_LIMIT:
|
|
||||||
return mode, None, info
|
|
||||||
with open(fd, "rb", closefd=False) as handle:
|
|
||||||
data = handle.read(BLOB_LIMIT + 1)
|
|
||||||
return mode, data if len(data) <= BLOB_LIMIT else None, info
|
|
||||||
finally:
|
|
||||||
os.close(fd)
|
|
||||||
|
|
||||||
|
|
||||||
def toplevel(cwd: Path) -> Path:
|
def toplevel(cwd: Path) -> Path:
|
||||||
return Path(os.path.realpath(git(cwd, ["rev-parse", "--show-toplevel"], None).decode("utf-8", "surrogateescape").strip()))
|
return Path(os.path.realpath(git(cwd, ["rev-parse", "--show-toplevel"], None).decode("utf-8", "surrogateescape").strip()))
|
||||||
|
|
||||||
|
|
||||||
def binding(cwd: Path, everything: bool) -> str:
|
def flagged(raw: bytes) -> list[tuple[bytes, int]]:
|
||||||
top = toplevel(cwd)
|
"""Args:
|
||||||
tree = git(top, ["write-tree"], None).decode("ascii").strip()
|
raw: what git ls-files -s -z --debug prints.
|
||||||
if not everything:
|
|
||||||
return tree
|
Returns:
|
||||||
new, _ = working_side(top, denied_roots(top))
|
Per index entry its -s -z record without the NUL and its flags.
|
||||||
return f"{tree} {hashlib.sha256(json.dumps(sorted(new.items())).encode('utf-8', 'surrogateescape')).hexdigest()}"
|
|
||||||
|
Raises:
|
||||||
|
DiffError: with LAYOUT when a record is no RECORD or is not followed
|
||||||
|
by DEBUG_LINES debug lines ending in a FLAGS_LINE.
|
||||||
|
"""
|
||||||
|
chunks = raw.split(b"\0")
|
||||||
|
found, record = [], chunks[0]
|
||||||
|
for chunk in chunks[1:]:
|
||||||
|
lines = chunk.split(b"\n", DEBUG_LINES)
|
||||||
|
flags = FLAGS_LINE.fullmatch(lines[-2]) if len(lines) == DEBUG_LINES + 1 else None
|
||||||
|
if flags is None or not RECORD.fullmatch(record):
|
||||||
|
raise DiffError(LAYOUT)
|
||||||
|
found.append((record, int(flags.group(1), 16)))
|
||||||
|
record = lines[-1]
|
||||||
|
if record:
|
||||||
|
raise DiffError(LAYOUT)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
def bound_diff(cwd: Path, everything: bool, pinned: str, rules: Path | None) -> list[dict]:
|
def staged(top: Path) -> bytes:
|
||||||
if not everything:
|
"""Returns:
|
||||||
return tree_diff(cwd, pinned, rules)
|
The git ls-files -s -z records of the entries git write-tree and git
|
||||||
diff = review_diff(cwd, True, rules)
|
commit record: every index entry but an intent-to-add one.
|
||||||
if binding(cwd, True) != pinned:
|
|
||||||
raise DiffError("the working tree changed while its preview was read")
|
Raises:
|
||||||
return diff
|
DiffError: for an index with unmerged paths, as git write-tree.
|
||||||
|
"""
|
||||||
|
found = flagged(git(top, ["ls-files", "-s", "-z", "--debug"], None))
|
||||||
|
if any(record.partition(b"\t")[0].split()[2:] != [b"0"] for record, _ in found):
|
||||||
|
raise DiffError("the index holds unmerged paths")
|
||||||
|
return b"".join(record + b"\0" for record, flags in found if not flags & INTENT_TO_ADD)
|
||||||
|
|
||||||
|
|
||||||
def sides(cwd: Path, everything: bool, tree: str | None) -> tuple[dict, dict, dict[str, bytes | None]]:
|
def binding(cwd: Path) -> str:
|
||||||
|
return hashlib.sha256(staged(toplevel(cwd))).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def bound_diff(cwd: Path, pinned: str, rules: Path | None) -> list[dict]:
|
||||||
|
index = staged(toplevel(cwd))
|
||||||
|
if hashlib.sha256(index).hexdigest() != pinned:
|
||||||
|
raise DiffError("the staged tree changed while its preview was read")
|
||||||
|
return built(cwd, sides(cwd, None, index), rules)
|
||||||
|
|
||||||
|
|
||||||
|
def sides(cwd: Path, tree: str | None, index: bytes | None) -> tuple[dict, dict, dict[str, bytes | None]]:
|
||||||
top = toplevel(cwd)
|
top = toplevel(cwd)
|
||||||
roots = denied_roots(top)
|
roots = denied_roots(top)
|
||||||
old = head_tree(top)
|
old = head_tree(top)
|
||||||
if tree is not None:
|
if tree is not None:
|
||||||
new, contents = listed(git(top, ["ls-tree", "-r", "-z", "--full-tree", tree], None), 2), {}
|
new = listed(git(top, ["ls-tree", "-r", "-z", "--full-tree", tree], None), 2)
|
||||||
elif everything:
|
|
||||||
new, contents = working_side(top, roots)
|
|
||||||
else:
|
else:
|
||||||
new, contents = listed(git(top, ["ls-files", "-s", "-z"], None), 1), {}
|
new = listed(index if index is not None else staged(top), 1)
|
||||||
contents.update(dict.fromkeys(side[path][1] for side in (old, new) for path in side if sandbox_paths.denied(os.path.join(top, path), roots)))
|
contents: dict[str, bytes | None] = dict.fromkeys(side[path][1] for side in (old, new) for path in side if sandbox_paths.denied(os.path.join(top, path), roots))
|
||||||
return old, new, contents
|
return old, new, contents
|
||||||
|
|
||||||
|
|
||||||
@@ -283,17 +246,6 @@ def head_tree(top: Path) -> dict[str, tuple[str, str]]:
|
|||||||
return listed(git(top, ["ls-tree", "-r", "-z", "--full-tree", "HEAD"], None), 2)
|
return listed(git(top, ["ls-tree", "-r", "-z", "--full-tree", "HEAD"], None), 2)
|
||||||
|
|
||||||
|
|
||||||
def working_side(top: Path, roots: list[str]) -> tuple[dict, dict[str, bytes | None]]:
|
|
||||||
algorithm = git(top, ["rev-parse", "--show-object-format"], None).decode("ascii").strip()
|
|
||||||
new, contents = {}, {}
|
|
||||||
for path, (mode, oid) in listed(git(top, ["ls-files", "-s", "-z"], None), 1).items():
|
|
||||||
found = (mode, oid, None) if mode == GITLINK else worktree(top, path, mode, algorithm, roots)
|
|
||||||
if found is not None:
|
|
||||||
new[path] = found[:2]
|
|
||||||
contents[found[1]] = found[2]
|
|
||||||
return new, contents
|
|
||||||
|
|
||||||
|
|
||||||
def text_lines(text: str) -> list[str]:
|
def text_lines(text: str) -> list[str]:
|
||||||
lines = text.split("\n")
|
lines = text.split("\n")
|
||||||
return lines[:-1] if lines[-1] == "" else lines
|
return lines[:-1] if lines[-1] == "" else lines
|
||||||
@@ -407,12 +359,12 @@ def content_of(side: tuple[str, str] | None, gitlink: bool, contents: dict[str,
|
|||||||
return None if gitlink else contents.get(side[1])
|
return None if gitlink else contents.get(side[1])
|
||||||
|
|
||||||
|
|
||||||
def review_diff(cwd: Path, everything: bool, rules: Path | None) -> list[dict]:
|
def review_diff(cwd: Path, rules: Path | None) -> list[dict]:
|
||||||
return built(cwd, sides(cwd, everything, None), rules)
|
return built(cwd, sides(cwd, None, None), rules)
|
||||||
|
|
||||||
|
|
||||||
def tree_diff(cwd: Path, tree: str, rules: Path | None) -> list[dict]:
|
def tree_diff(cwd: Path, tree: str, rules: Path | None) -> list[dict]:
|
||||||
return built(cwd, sides(cwd, False, tree), rules)
|
return built(cwd, sides(cwd, tree, None), rules)
|
||||||
|
|
||||||
|
|
||||||
def fetched(cwd: Path, old: dict, new: dict, changed: list[str], contents: dict[str, bytes | None]) -> None:
|
def fetched(cwd: Path, old: dict, new: dict, changed: list[str], contents: dict[str, bytes | None]) -> None:
|
||||||
@@ -459,14 +411,18 @@ def built(cwd: Path, found_sides: tuple[dict, dict, dict[str, bytes | None]], ru
|
|||||||
return diff
|
return diff
|
||||||
|
|
||||||
|
|
||||||
def commit_of(command: str, cwd: str) -> tuple[Path, bool] | None:
|
def names_commit(command: str) -> bool:
|
||||||
|
return NAMES_COMMIT.search(command) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def commit_of(command: str, cwd: str) -> Path | None:
|
||||||
"""Returns:
|
"""Returns:
|
||||||
The directory git commit runs in and whether it records every
|
The directory git commit runs in, for a command that is one git
|
||||||
tracked change (-a or --all), for a command that is one git commit,
|
commit of exactly the staged index, optionally behind variable
|
||||||
optionally behind variable assignments, env -C and git -C; None for
|
assignments, env -C and git -C; None for any other command and for a
|
||||||
any other command and for one whose commit the preview would not
|
commit that reads the working tree or that the preview would not
|
||||||
match (a pathspec, -o, -i, -p, --no-all, an unknown or ambiguous long
|
match (-a, --all, --amend, a pathspec, -o, -i, -p, --no-all, an unknown or
|
||||||
option, git -c, or a GIT_ variable outside KEPT_VARS).
|
ambiguous long option, git -c, or a GIT_ variable outside KEPT_VARS).
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
words = shlex.split(command)
|
words = shlex.split(command)
|
||||||
@@ -478,8 +434,7 @@ def commit_of(command: str, cwd: str) -> tuple[Path, bool] | None:
|
|||||||
if not words or Path(words[0]).name != "git":
|
if not words or Path(words[0]).name != "git":
|
||||||
return None
|
return None
|
||||||
place, rest = past_git_options(place, words[1:])
|
place, rest = past_git_options(place, words[1:])
|
||||||
mode = commit_mode(rest[1:]) if rest else None
|
return place if rest and index_only(rest[1:]) else None
|
||||||
return None if mode is None else (place, mode)
|
|
||||||
|
|
||||||
|
|
||||||
def launched(place: Path, words: list[str]) -> tuple[Path, list[str]]:
|
def launched(place: Path, words: list[str]) -> tuple[Path, list[str]]:
|
||||||
@@ -526,23 +481,25 @@ def past_git_options(place: Path, rest: list[str]) -> tuple[Path, list[str]]:
|
|||||||
return place, rest
|
return place, rest
|
||||||
|
|
||||||
|
|
||||||
def commit_mode(words: list[str]) -> bool | None:
|
def index_only(words: list[str]) -> bool:
|
||||||
"""Returns:
|
"""Returns:
|
||||||
True for -a or --all, False for the staged tree, None when the
|
True when git commit with these words records exactly the staged
|
||||||
commit records something else (NARROWING, -o, -i, -p or a pathspec).
|
index on top of HEAD: every word an option() it knows or that
|
||||||
|
option's argument, none -a or --all, NARROWING, REWRITING, -o, -i,
|
||||||
|
-p, and no pathspec.
|
||||||
"""
|
"""
|
||||||
skip, everything = False, False
|
skip = False
|
||||||
for at, word in enumerate(words):
|
for at, word in enumerate(words):
|
||||||
if skip:
|
if skip:
|
||||||
skip = False
|
skip = False
|
||||||
continue
|
continue
|
||||||
if word == "--":
|
if word == "--":
|
||||||
return None if words[at + 1 :] else everything
|
return not words[at + 1 :]
|
||||||
found = option(word)
|
found = option(word)
|
||||||
if found is None:
|
if found is None or found[0]:
|
||||||
return None
|
return False
|
||||||
everything, skip = everything or found[0], found[1]
|
skip = found[1]
|
||||||
return everything
|
return True
|
||||||
|
|
||||||
|
|
||||||
def option(word: str) -> tuple[bool, bool] | None:
|
def option(word: str) -> tuple[bool, bool] | None:
|
||||||
@@ -550,12 +507,12 @@ def option(word: str) -> tuple[bool, bool] | None:
|
|||||||
Whether a git commit option word is -a or --all and whether the next
|
Whether a git commit option word is -a or --all and whether the next
|
||||||
word is its argument, a long option named in full or by a prefix of
|
word is its argument, a long option named in full or by a prefix of
|
||||||
exactly one of COMMIT_LONGS (what git 2.56 lists for git commit
|
exactly one of COMMIT_LONGS (what git 2.56 lists for git commit
|
||||||
--git-completion-helper-all); None for NARROWING, -o, -i, -p, a
|
--git-completion-helper-all); None for NARROWING, REWRITING, -o,
|
||||||
pathspec and a long option it names no single one of.
|
-i, -p, a pathspec and a long option it names no single one of.
|
||||||
"""
|
"""
|
||||||
if word.startswith("--"):
|
if word.startswith("--"):
|
||||||
name = long_option(word[2:].partition("=")[0])
|
name = long_option(word[2:].partition("=")[0])
|
||||||
return None if name is None or name in NARROWING else (name == "all", name in LONG_ARGS and "=" not in word)
|
return None if name is None or name in NARROWING | REWRITING else (name == "all", name in LONG_ARGS and "=" not in word)
|
||||||
if word.startswith("-") and word != "-":
|
if word.startswith("-") and word != "-":
|
||||||
return cluster(word[1:])
|
return cluster(word[1:])
|
||||||
return None
|
return None
|
||||||
|
|||||||
@@ -416,7 +416,7 @@ pin() {
|
|||||||
|
|
||||||
hook() {
|
hook() {
|
||||||
local command
|
local command
|
||||||
command="python3 \"${HUB}/client/permission_hook.py\" --port $(port_of "${HUB}/.env") --timeout ${HOOK_TIMEOUT} --approvers \"${APPROVERS}/approvers.json\" --replay \"${APPROVALS}/hook.json\""
|
command="/usr/bin/python3 -E -s \"${HUB}/client/permission_hook.py\" --port $(port_of "${HUB}/.env") --timeout ${HOOK_TIMEOUT} --approvers \"${APPROVERS}/approvers.json\" --replay \"${APPROVALS}/hook.json\""
|
||||||
[[ -f "${SETTINGS}" ]] && cp -p "${SETTINGS}" "${SETTINGS}.before-${NAME}-hook"
|
[[ -f "${SETTINGS}" ]] && cp -p "${SETTINGS}" "${SETTINGS}.before-${NAME}-hook"
|
||||||
rewrite_hooks "${SETTINGS}" "${NAME}/client/permission_hook.py" "${command}" "$((HOOK_TIMEOUT + 10))"
|
rewrite_hooks "${SETTINGS}" "${NAME}/client/permission_hook.py" "${command}" "$((HOOK_TIMEOUT + 10))"
|
||||||
log "skills: registered the PermissionRequest hook in ${SETTINGS} (copy before: ${SETTINGS}.before-${NAME}-hook); restart Claude Code to load it"
|
log "skills: registered the PermissionRequest hook in ${SETTINGS} (copy before: ${SETTINGS}.before-${NAME}-hook); restart Claude Code to load it"
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ export PATH=/usr/bin:/bin
|
|||||||
interval="${DREAM_INTERVAL_SECONDS:-43200}"
|
interval="${DREAM_INTERVAL_SECONDS:-43200}"
|
||||||
stamps="${DREAM_STAMP_DIR:-${HOME}/.claude/.dream-stamps}"
|
stamps="${DREAM_STAMP_DIR:-${HOME}/.claude/.dream-stamps}"
|
||||||
|
|
||||||
session="$(python3 -c 'import json, sys; print(json.load(sys.stdin).get("session_id", ""))' 2>/dev/null)" || exit 0
|
session="$(/usr/bin/python3 -I -c'import json, sys; print(json.load(sys.stdin).get("session_id", ""))' 2>/dev/null)" || exit 0
|
||||||
[[ "${session}" =~ ^[A-Za-z0-9_-]+$ ]] || exit 0
|
[[ "${session}" =~ ^[A-Za-z0-9_-]+$ ]] || exit 0
|
||||||
stamp="${stamps}/${session}"
|
stamp="${stamps}/${session}"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,509 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import importlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from collections.abc import Callable
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
CLIENT = ROOT / "orchestrator" / "client"
|
||||||
|
REMINDER = ROOT / "skills" / "kvb-dream" / "hooks" / "reminder.sh"
|
||||||
|
ORCHESTRATOR = ROOT / "scripts" / "orchestrator.sh"
|
||||||
|
sys.path[:0] = [str(CLIENT)]
|
||||||
|
staged_diff = importlib.import_module("staged_diff")
|
||||||
|
permission_hook = importlib.import_module("permission_hook")
|
||||||
|
passkey = importlib.import_module("passkey")
|
||||||
|
sandbox_paths = importlib.import_module("sandbox_paths")
|
||||||
|
GIT_ENV = {
|
||||||
|
"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@example.invalid", "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@example.invalid",
|
||||||
|
"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1",
|
||||||
|
}
|
||||||
|
ALLOW = {"behavior": "allow"}
|
||||||
|
|
||||||
|
|
||||||
|
def git(cwd: Path, *args: str) -> str:
|
||||||
|
return subprocess.run(["git", *args], cwd=cwd, env={**os.environ, **GIT_ENV}, check=True, capture_output=True, text=True).stdout
|
||||||
|
|
||||||
|
|
||||||
|
def probe(path: Path, marker: Path, tail: str) -> Path:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_text(f"#!/bin/sh\n: > '{marker}'\n{tail}\n", encoding="utf-8")
|
||||||
|
path.chmod(0o755)
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
class Scratch(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(tmp.cleanup)
|
||||||
|
self.root = Path(os.path.realpath(tmp.name))
|
||||||
|
self.marker = self.root / "planted-code-ran"
|
||||||
|
|
||||||
|
|
||||||
|
class Isolated(Scratch):
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
for patch in (
|
||||||
|
mock.patch.object(staged_diff, "CACHE", self.root / "cache" / "secret-rules.json"),
|
||||||
|
mock.patch.object(sandbox_paths, "MANAGED", self.root / "managed"),
|
||||||
|
mock.patch.dict(os.environ, {**GIT_ENV, "HOME": str(self.root), "CLAUDE_CONFIG_DIR": str(self.root / ".claude"), "CLAUDE_PROJECT_DIR": str(self.root / "project")}),
|
||||||
|
):
|
||||||
|
patch.start()
|
||||||
|
self.addCleanup(patch.stop)
|
||||||
|
|
||||||
|
|
||||||
|
class TestPermissionHookGit(Isolated):
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.repo = self.root / "repo"
|
||||||
|
self.repo.mkdir()
|
||||||
|
git(self.repo, "init", "-q", "-b", "main")
|
||||||
|
(self.repo / "base.txt").write_text("one\n", encoding="utf-8")
|
||||||
|
git(self.repo, "add", "-A")
|
||||||
|
git(self.repo, "commit", "-q", "-m", "base")
|
||||||
|
(self.repo / "base.txt").write_text("two\n", encoding="utf-8")
|
||||||
|
(self.repo / "added.txt").write_text("fresh\n", encoding="utf-8")
|
||||||
|
git(self.repo, "add", "-A")
|
||||||
|
self.ask = {"tool": "Bash", "command": "git commit -m x", "cwd": str(self.repo), "session": "s", "agent": ""}
|
||||||
|
|
||||||
|
def hook_path(self) -> tuple[str | None, dict, dict | None]:
|
||||||
|
pinned, shown = permission_hook.commit_diff(self.ask, None)
|
||||||
|
return pinned, shown, permission_hook.bound(ALLOW, self.ask, pinned)
|
||||||
|
|
||||||
|
def assert_clean_run(self) -> None:
|
||||||
|
_, shown, chosen = self.hook_path()
|
||||||
|
self.assertEqual(([entry["path"] for entry in shown["diff"]], chosen), (["added.txt", "base.txt"], ALLOW))
|
||||||
|
self.assertFalse(self.marker.exists())
|
||||||
|
|
||||||
|
def test_a_planted_post_index_change_hook_never_runs(self):
|
||||||
|
probe(self.repo / ".git" / "hooks" / "post-index-change", self.marker, "exit 0")
|
||||||
|
self.assert_clean_run()
|
||||||
|
|
||||||
|
def test_a_planted_core_hooks_path_never_runs(self):
|
||||||
|
hooks = self.root / "planted-hooks"
|
||||||
|
for name in ("post-index-change", "pre-commit", "reference-transaction"):
|
||||||
|
probe(hooks / name, self.marker, "exit 0")
|
||||||
|
git(self.repo, "config", "core.hooksPath", str(hooks))
|
||||||
|
self.assert_clean_run()
|
||||||
|
|
||||||
|
def test_a_planted_git_earlier_on_path_never_runs(self):
|
||||||
|
planted = probe(self.root / "bin" / "git", self.marker, 'exec /usr/bin/git "$@"')
|
||||||
|
with mock.patch.dict(os.environ, {"PATH": f"{planted.parent}{os.pathsep}{os.environ['PATH']}"}):
|
||||||
|
self.assert_clean_run()
|
||||||
|
|
||||||
|
def test_the_hook_path_leaves_the_index_file_untouched(self):
|
||||||
|
index = self.repo / ".git" / "index"
|
||||||
|
before = (index.read_bytes(), index.stat().st_mtime_ns)
|
||||||
|
self.hook_path()
|
||||||
|
self.assertEqual((index.read_bytes(), index.stat().st_mtime_ns), before)
|
||||||
|
|
||||||
|
def test_the_binding_changes_with_the_staged_tree_and_only_with_it(self):
|
||||||
|
pinned = staged_diff.binding(self.repo)
|
||||||
|
self.assertEqual(staged_diff.bound_diff(self.repo, pinned, None), staged_diff.review_diff(self.repo, None))
|
||||||
|
(self.repo / "added.txt").write_text("unstaged\n", encoding="utf-8")
|
||||||
|
git(self.repo, "status", "--porcelain")
|
||||||
|
self.assertEqual(staged_diff.binding(self.repo), pinned)
|
||||||
|
git(self.repo, "add", "added.txt")
|
||||||
|
content = staged_diff.binding(self.repo)
|
||||||
|
self.assertNotEqual(content, pinned)
|
||||||
|
with self.assertRaises(staged_diff.DiffError):
|
||||||
|
staged_diff.bound_diff(self.repo, pinned, None)
|
||||||
|
(self.repo / "added.txt").chmod(0o755)
|
||||||
|
git(self.repo, "add", "added.txt")
|
||||||
|
self.assertNotIn(staged_diff.binding(self.repo), (pinned, content))
|
||||||
|
(self.repo / "added.txt").write_text("fresh\n", encoding="utf-8")
|
||||||
|
(self.repo / "added.txt").chmod(0o644)
|
||||||
|
git(self.repo, "add", "added.txt")
|
||||||
|
self.assertEqual(staged_diff.binding(self.repo), pinned)
|
||||||
|
|
||||||
|
def test_an_index_with_unmerged_paths_has_no_binding(self):
|
||||||
|
oid = git(self.repo, "hash-object", "-w", "base.txt").strip()
|
||||||
|
entries = f"0 {'0' * len(oid)}\tbase.txt\n100644 {oid} 1\tbase.txt\n100644 {oid} 2\tbase.txt\n"
|
||||||
|
subprocess.run(["git", "update-index", "--index-info"], cwd=self.repo, input=entries, env={**os.environ, **GIT_ENV}, check=True, capture_output=True, text=True)
|
||||||
|
with self.assertRaises(staged_diff.DiffError):
|
||||||
|
staged_diff.binding(self.repo)
|
||||||
|
|
||||||
|
|
||||||
|
def stage_a(repo: Path) -> None:
|
||||||
|
(repo / "a.txt").write_text("two\n", encoding="utf-8")
|
||||||
|
git(repo, "add", "a.txt")
|
||||||
|
|
||||||
|
|
||||||
|
def restage_a(repo: Path) -> None:
|
||||||
|
(repo / "a.txt").write_text("three\n", encoding="utf-8")
|
||||||
|
git(repo, "add", "a.txt")
|
||||||
|
|
||||||
|
|
||||||
|
def chmod_a(repo: Path) -> None:
|
||||||
|
(repo / "a.txt").chmod(0o755)
|
||||||
|
git(repo, "add", "a.txt")
|
||||||
|
|
||||||
|
|
||||||
|
def intend_new(repo: Path) -> None:
|
||||||
|
(repo / "new.txt").write_text("x\n", encoding="utf-8")
|
||||||
|
git(repo, "add", "-N", "new.txt")
|
||||||
|
|
||||||
|
|
||||||
|
def swap_empty_to_intent(repo: Path) -> None:
|
||||||
|
git(repo, "rm", "-q", "--cached", "empty.txt")
|
||||||
|
git(repo, "add", "-N", "empty.txt")
|
||||||
|
|
||||||
|
|
||||||
|
def stage_a_and_intend_empty(repo: Path) -> None:
|
||||||
|
stage_a(repo)
|
||||||
|
(repo / "fresh_empty.txt").write_text("", encoding="utf-8")
|
||||||
|
git(repo, "add", "-N", "fresh_empty.txt")
|
||||||
|
|
||||||
|
|
||||||
|
def stage_intended_empty(repo: Path) -> None:
|
||||||
|
git(repo, "add", "fresh_empty.txt")
|
||||||
|
|
||||||
|
|
||||||
|
def add_gitlink(repo: Path) -> None:
|
||||||
|
git(repo, "update-index", "--add", "--cacheinfo", f"160000,{git(repo, 'rev-parse', 'HEAD').strip()},mod")
|
||||||
|
|
||||||
|
|
||||||
|
def skip_a(repo: Path) -> None:
|
||||||
|
git(repo, "update-index", "--skip-worktree", "a.txt")
|
||||||
|
|
||||||
|
|
||||||
|
def refresh(repo: Path) -> None:
|
||||||
|
os.utime(repo / "a.txt", ns=(1, 1))
|
||||||
|
git(repo, "status", "--porcelain")
|
||||||
|
|
||||||
|
|
||||||
|
def sparse(repo: Path) -> None:
|
||||||
|
git(repo, "sparse-checkout", "init", "--cone", "--sparse-index")
|
||||||
|
git(repo, "sparse-checkout", "set", "sub")
|
||||||
|
|
||||||
|
|
||||||
|
def split_v4(repo: Path) -> None:
|
||||||
|
git(repo, "update-index", "--index-version", "4")
|
||||||
|
git(repo, "update-index", "--split-index")
|
||||||
|
|
||||||
|
|
||||||
|
def uncache_c(repo: Path) -> None:
|
||||||
|
git(repo, "rm", "-q", "--cached", "other/c.txt")
|
||||||
|
|
||||||
|
|
||||||
|
def odd_names(repo: Path) -> None:
|
||||||
|
(repo / "tab\tname.txt").write_text("t\n", encoding="utf-8")
|
||||||
|
(repo / "new\nline.txt").write_text("n\n", encoding="utf-8")
|
||||||
|
git(repo, "add", "-A")
|
||||||
|
|
||||||
|
|
||||||
|
def to_symlink(repo: Path) -> None:
|
||||||
|
(repo / "a.txt").unlink()
|
||||||
|
(repo / "a.txt").symlink_to("other/c.txt")
|
||||||
|
git(repo, "add", "a.txt")
|
||||||
|
|
||||||
|
|
||||||
|
CASES = {
|
||||||
|
"content": (stage_a, restage_a),
|
||||||
|
"mode only": (stage_a, chmod_a),
|
||||||
|
"intent-to-add new file": (stage_a, intend_new),
|
||||||
|
"tracked empty file swapped to intent-to-add": (stage_a, swap_empty_to_intent),
|
||||||
|
"intent-to-add empty file staged for real": (stage_a_and_intend_empty, stage_intended_empty),
|
||||||
|
"gitlink added": (stage_a, add_gitlink),
|
||||||
|
"skip-worktree flag": (stage_a, skip_a),
|
||||||
|
"stat refresh only": (stage_a, refresh),
|
||||||
|
"sparse index": (stage_a, sparse),
|
||||||
|
"index v4 and split index": (stage_a, split_v4),
|
||||||
|
"rm --cached": (stage_a, uncache_c),
|
||||||
|
"tab and newline names": (stage_a, odd_names),
|
||||||
|
"file to symlink": (stage_a, to_symlink),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def hide_staged_b(flag: str) -> Callable[[Path], None]:
|
||||||
|
def hide(repo: Path) -> None:
|
||||||
|
(repo / "sub" / "b.txt").write_text("evil\n", encoding="utf-8")
|
||||||
|
git(repo, "add", "sub/b.txt")
|
||||||
|
(repo / "sub" / "b.txt").write_text("b\n", encoding="utf-8")
|
||||||
|
git(repo, "update-index", flag, "sub/b.txt")
|
||||||
|
return hide
|
||||||
|
|
||||||
|
|
||||||
|
def flag_after(change: Callable[[Path], None], path: str, flag: str) -> Callable[[Path], None]:
|
||||||
|
def flagged(repo: Path) -> None:
|
||||||
|
change(repo)
|
||||||
|
git(repo, "update-index", flag, path)
|
||||||
|
return flagged
|
||||||
|
|
||||||
|
|
||||||
|
def sparse_no_cone(repo: Path) -> None:
|
||||||
|
git(repo, "sparse-checkout", "set", "--no-cone", "/sub/")
|
||||||
|
|
||||||
|
|
||||||
|
UNREAD_CASES = {
|
||||||
|
"staged change hidden by assume-unchanged": hide_staged_b("--assume-unchanged"),
|
||||||
|
"staged change hidden by skip-worktree": hide_staged_b("--skip-worktree"),
|
||||||
|
"sparse index in cone mode": sparse,
|
||||||
|
"sparse checkout without cone": sparse_no_cone,
|
||||||
|
"intent-to-add new file with skip-worktree": flag_after(intend_new, "new.txt", "--skip-worktree"),
|
||||||
|
"intent-to-add new file with assume-unchanged": flag_after(intend_new, "new.txt", "--assume-unchanged"),
|
||||||
|
"tracked empty file swapped to intent-to-add with skip-worktree": flag_after(swap_empty_to_intent, "empty.txt", "--skip-worktree"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class TestDebugLayout(unittest.TestCase):
|
||||||
|
def test_an_unexpected_ls_files_debug_layout_fails_closed_with_its_own_message(self):
|
||||||
|
entry = b"100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0\t%s\0 ctime: 0:0\n mtime: 0:0\n dev: 0\tino: 0\n uid: 0\tgid: 0\n size: 0\tflags: %s\n"
|
||||||
|
good = entry % (b"a", b"20004000") + entry % (b"b", b"0")
|
||||||
|
self.assertEqual(staged_diff.flagged(good), [(b"100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0\ta", 0x20004000), (b"100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0\tb", 0)])
|
||||||
|
broken = {
|
||||||
|
"extra line after flags": entry % (b"a", b"0") + b" extra: 1\n" + entry % (b"b", b"0"),
|
||||||
|
"flags not hex": entry % (b"a", b"zz"),
|
||||||
|
"flags with a suffix": entry % (b"a", b"0 extended"),
|
||||||
|
"one line missing": entry.replace(b" dev: 0\tino: 0\n", b"") % (b"a", b"0"),
|
||||||
|
"trailing garbage": good + b"junk",
|
||||||
|
}
|
||||||
|
for name, raw in broken.items():
|
||||||
|
with self.subTest(layout=name), self.assertRaisesRegex(staged_diff.DiffError, "^unexpected ls-files --debug layout$"):
|
||||||
|
staged_diff.flagged(raw)
|
||||||
|
|
||||||
|
|
||||||
|
class Repos(Isolated):
|
||||||
|
def fresh(self, name: str) -> Path:
|
||||||
|
repo = self.root / name
|
||||||
|
(repo / "sub").mkdir(parents=True)
|
||||||
|
(repo / "other").mkdir()
|
||||||
|
git(repo, "init", "-q", "-b", "main")
|
||||||
|
for path, text in (("a.txt", "one\n"), ("empty.txt", ""), ("sub/b.txt", "b\n"), ("other/c.txt", "c\n")):
|
||||||
|
(repo / path).write_text(text, encoding="utf-8")
|
||||||
|
git(repo, "add", "-A")
|
||||||
|
git(repo, "commit", "-q", "-m", "base")
|
||||||
|
return repo
|
||||||
|
|
||||||
|
def ids(self, repo: Path) -> tuple[str, str]:
|
||||||
|
return git(repo, "write-tree").strip(), staged_diff.binding(repo)
|
||||||
|
|
||||||
|
def recorded(self, repo: Path) -> list[tuple[str, str]]:
|
||||||
|
lines = git(repo, "diff-tree", "--no-commit-id", "--name-status", "-r", "HEAD~1", "HEAD").splitlines()
|
||||||
|
return sorted((path, status) for status, path in (line.split("\t", 1) for line in lines))
|
||||||
|
|
||||||
|
|
||||||
|
class TestBindingMatchesWriteTree(Repos):
|
||||||
|
def test_the_binding_changes_exactly_when_the_tree_git_write_tree_records_changes(self):
|
||||||
|
for name, (setup, mutate) in CASES.items():
|
||||||
|
with self.subTest(case=name):
|
||||||
|
repo = self.fresh(name.replace(" ", "-"))
|
||||||
|
setup(repo)
|
||||||
|
before = self.ids(repo)
|
||||||
|
mutate(repo)
|
||||||
|
after = self.ids(repo)
|
||||||
|
self.assertEqual(before[1] != after[1], before[0] != after[0])
|
||||||
|
self.assertEqual(shown(staged_diff.bound_diff(repo, after[1], None)), shown(staged_diff.tree_diff(repo, after[0], None)))
|
||||||
|
|
||||||
|
def test_the_preview_lists_exactly_what_git_commit_records(self):
|
||||||
|
for name, setup in {"intent-to-add new file": intend_new, **UNREAD_CASES}.items():
|
||||||
|
with self.subTest(case=name):
|
||||||
|
repo = self.fresh(name.replace(" ", "-"))
|
||||||
|
stage_a(repo)
|
||||||
|
setup(repo)
|
||||||
|
preview = shown(staged_diff.bound_diff(repo, staged_diff.binding(repo), None))
|
||||||
|
git(repo, "commit", "-q", "-m", "x")
|
||||||
|
self.assertEqual(preview, self.recorded(repo))
|
||||||
|
|
||||||
|
def test_an_allow_turns_into_a_deny_when_a_tracked_empty_file_is_swapped_to_intent_to_add(self):
|
||||||
|
repo = self.fresh("swap")
|
||||||
|
stage_a(repo)
|
||||||
|
ask = {"tool": "Bash", "command": "git commit -m x", "cwd": str(repo), "session": "s", "agent": ""}
|
||||||
|
pinned, attached = permission_hook.commit_diff(ask, None)
|
||||||
|
self.assertEqual(shown(attached["diff"]), [("a.txt", "M")])
|
||||||
|
swap_empty_to_intent(repo)
|
||||||
|
self.assertEqual(permission_hook.bound(ALLOW, ask, pinned), {"behavior": "deny", "message": permission_hook.CHANGED})
|
||||||
|
|
||||||
|
|
||||||
|
def shown(diff: list[dict]) -> list[tuple[str, str]]:
|
||||||
|
return sorted((entry["path"], entry["status"]) for entry in diff)
|
||||||
|
|
||||||
|
|
||||||
|
WORKTREE_FORMS = (
|
||||||
|
"git commit -a -m x", "git commit -am x", "git commit -av -m x", "git commit -m x -a", "git commit --all -m x",
|
||||||
|
"git commit --all= -m x", "git commit --al -m x", "git commit -i -m x a.txt", "git commit --include -m x a.txt",
|
||||||
|
"git commit -o -m x a.txt", "git commit --only -m x a.txt", "git commit -m x a.txt", "git commit -m x -- a.txt",
|
||||||
|
"git commit -p -m x", "git commit --interactive", "git commit --pathspec-from-file=list -m x",
|
||||||
|
"git commit -a -m x ; true", "git commit -am x&&true", "git add -A && git commit -m x", "sh -c 'git commit -am x'",
|
||||||
|
"git -c core.fileMode=false commit -am x", "env GIT_INDEX_FILE=other git commit -m x", "/usr/bin/git commit -am x",
|
||||||
|
)
|
||||||
|
NOT_APPROVABLE = "kvb-orchestrator: commit reads the working tree; stage the files and commit the index"
|
||||||
|
AMEND_FORMS = ("git commit --amend --no-edit", "git commit --amend -m x", "git commit -m x --amend", "git commit --amen -m x")
|
||||||
|
|
||||||
|
|
||||||
|
def gitlink_without_folder(repo: Path) -> None:
|
||||||
|
git(repo, "update-index", "--add", "--cacheinfo", f"160000,{git(repo, 'rev-parse', 'HEAD').strip()},mod")
|
||||||
|
git(repo, "commit", "-q", "-m", "link")
|
||||||
|
stage_a(repo)
|
||||||
|
|
||||||
|
|
||||||
|
def file_mode_off_index_x(repo: Path) -> None:
|
||||||
|
stage_a(repo)
|
||||||
|
git(repo, "config", "core.fileMode", "false")
|
||||||
|
git(repo, "update-index", "--chmod=+x", "other/c.txt")
|
||||||
|
|
||||||
|
|
||||||
|
def clean_filter(repo: Path) -> None:
|
||||||
|
(repo / ".gitattributes").write_text("*.txt filter=upper\n", encoding="utf-8")
|
||||||
|
git(repo, "add", ".gitattributes")
|
||||||
|
stage_a(repo)
|
||||||
|
git(repo, "config", "filter.upper.clean", "tr a-z A-Z")
|
||||||
|
|
||||||
|
|
||||||
|
REVIEWER_STATES = {
|
||||||
|
"gitlink whose folder is gone": gitlink_without_folder,
|
||||||
|
"core.fileMode=false with +x only in the index": file_mode_off_index_x,
|
||||||
|
"clean filter": clean_filter,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class TestWorkingTreeCommitsAreNotApprovable(Repos):
|
||||||
|
def ask(self, repo: Path, command: str) -> dict:
|
||||||
|
return {"tool": "Bash", "command": command, "cwd": str(repo), "session": "s", "agent": ""}
|
||||||
|
|
||||||
|
def test_no_commit_form_that_reads_the_working_tree_is_approved(self):
|
||||||
|
repo = self.fresh("forms")
|
||||||
|
stage_a(repo)
|
||||||
|
for command in WORKTREE_FORMS:
|
||||||
|
with self.subTest(command=command):
|
||||||
|
ask = self.ask(repo, command)
|
||||||
|
pinned, attached = permission_hook.commit_diff(ask, None)
|
||||||
|
self.assertEqual((pinned, attached), (None, {}))
|
||||||
|
self.assertIsNone(permission_hook.bound(ALLOW, ask, pinned))
|
||||||
|
|
||||||
|
def test_an_amend_is_never_approved_and_a_plain_commit_of_the_same_index_still_binds(self):
|
||||||
|
repo = self.fresh("amend")
|
||||||
|
stage_a(repo)
|
||||||
|
for command in AMEND_FORMS:
|
||||||
|
with self.subTest(command=command):
|
||||||
|
ask = self.ask(repo, command)
|
||||||
|
self.assertEqual(permission_hook.commit_diff(ask, None), (None, {}))
|
||||||
|
self.assertIsNone(permission_hook.bound(ALLOW, ask, None))
|
||||||
|
plain = self.ask(repo, "git commit --no-amend -m x")
|
||||||
|
pinned, attached = permission_hook.commit_diff(plain, None)
|
||||||
|
self.assertEqual((shown(attached["diff"]), permission_hook.bound(ALLOW, plain, pinned)), ([("a.txt", "M")], ALLOW))
|
||||||
|
|
||||||
|
def test_the_reviewer_states_give_commit_all_no_approval_and_a_plain_commit_its_bound_one(self):
|
||||||
|
for name, setup in REVIEWER_STATES.items():
|
||||||
|
with self.subTest(state=name):
|
||||||
|
repo = self.fresh(name.replace(" ", "-").replace("=", "-"))
|
||||||
|
setup(repo)
|
||||||
|
everything = self.ask(repo, "git commit -am x")
|
||||||
|
self.assertEqual(permission_hook.commit_diff(everything, None), (None, {}))
|
||||||
|
self.assertIsNone(permission_hook.bound(ALLOW, everything, None))
|
||||||
|
plain = self.ask(repo, "git commit -m x")
|
||||||
|
pinned, attached = permission_hook.commit_diff(plain, None)
|
||||||
|
self.assertEqual((pinned is not None, permission_hook.bound(ALLOW, plain, pinned)), (True, ALLOW))
|
||||||
|
self.assertIn(("a.txt", "M"), shown(attached["diff"]))
|
||||||
|
|
||||||
|
def test_the_hook_creates_no_ask_and_names_the_reason_for_such_a_commit(self):
|
||||||
|
repo = self.fresh("hook")
|
||||||
|
stage_a(repo)
|
||||||
|
hook = {"tool_name": "Bash", "tool_input": {"command": "git commit -am x"}, "cwd": str(repo), "session_id": "s"}
|
||||||
|
argv = ["/usr/bin/python3", "-E", "-s", str(CLIENT / "permission_hook.py"), "--port", "1", "--timeout", "1", "--approvers", str(self.root / "approvers.json"), "--replay", str(self.root / "replay.json")]
|
||||||
|
done = subprocess.run(argv, input=json.dumps(hook), capture_output=True, text=True, timeout=60, check=False)
|
||||||
|
self.assertEqual((done.returncode, done.stdout, done.stderr.strip()), (0, "", NOT_APPROVABLE))
|
||||||
|
|
||||||
|
|
||||||
|
class TestHookGitEnvironment(Isolated):
|
||||||
|
def test_planted_git_variables_in_the_hook_environment_are_never_used(self):
|
||||||
|
repo = self.root / "repo"
|
||||||
|
repo.mkdir()
|
||||||
|
git(repo, "init", "-q", "-b", "main")
|
||||||
|
(repo / "base.txt").write_text("one\n", encoding="utf-8")
|
||||||
|
git(repo, "add", "-A")
|
||||||
|
git(repo, "commit", "-q", "-m", "base")
|
||||||
|
(repo / "base.txt").write_text("two\n", encoding="utf-8")
|
||||||
|
(repo / "added.txt").write_text("fresh\n", encoding="utf-8")
|
||||||
|
git(repo, "add", "-A")
|
||||||
|
expected = hashlib.sha256(subprocess.run(["git", "ls-files", "-s", "-z"], cwd=repo, env={**os.environ, **GIT_ENV}, capture_output=True, check=True).stdout).hexdigest()
|
||||||
|
decoys = {"GIT_DIR": self.root / "decoy-git", "GIT_EXEC_PATH": self.root / "decoy-exec", "GIT_INDEX_FILE": self.root / "decoy-index", "GIT_CONFIG_GLOBAL": self.root / "decoy-gitconfig"}
|
||||||
|
decoys["GIT_DIR"].mkdir()
|
||||||
|
decoys["GIT_EXEC_PATH"].mkdir()
|
||||||
|
decoys["GIT_INDEX_FILE"].write_bytes(b"DIRC")
|
||||||
|
decoys["GIT_CONFIG_GLOBAL"].write_text("[[[\n", encoding="utf-8")
|
||||||
|
for decoy in decoys.values():
|
||||||
|
decoy.chmod(0)
|
||||||
|
self.addCleanup(decoy.chmod, 0o700)
|
||||||
|
seen, run = [], subprocess.run
|
||||||
|
|
||||||
|
def spy(*args, **kwargs):
|
||||||
|
seen.append(kwargs.get("env"))
|
||||||
|
return run(*args, **kwargs)
|
||||||
|
|
||||||
|
ask = {"tool": "Bash", "command": "git commit -m x", "cwd": str(repo), "session": "s", "agent": ""}
|
||||||
|
with mock.patch.dict(os.environ, {name: str(path) for name, path in decoys.items()}), mock.patch.object(subprocess, "run", spy):
|
||||||
|
pinned = staged_diff.binding(repo)
|
||||||
|
preview = shown(staged_diff.bound_diff(repo, pinned, None))
|
||||||
|
chosen = permission_hook.bound(ALLOW, ask, permission_hook.commit_diff(ask, None)[0])
|
||||||
|
self.assertEqual((pinned, preview, chosen), (expected, [("added.txt", "A"), ("base.txt", "M")], ALLOW))
|
||||||
|
self.assertTrue(seen)
|
||||||
|
for env in seen:
|
||||||
|
self.assertLessEqual(set(env), {"HOME", "LANG", "LC_ALL", "LC_CTYPE", "GIT_OPTIONAL_LOCKS", "GIT_NO_LAZY_FETCH", "GIT_CONFIG_NOSYSTEM", "GIT_CONFIG_GLOBAL", "PATH"})
|
||||||
|
self.assertEqual((env["GIT_CONFIG_GLOBAL"], env["PATH"]), (os.devnull, staged_diff.TRUSTED_PATH))
|
||||||
|
|
||||||
|
|
||||||
|
class TestPasskeyOpenssl(Scratch):
|
||||||
|
def test_a_planted_openssl_earlier_on_path_never_runs_nor_forges_a_signature(self):
|
||||||
|
planted = probe(self.root / "bin" / "openssl", self.marker, "exit 0")
|
||||||
|
spki = passkey.EC_PREFIX + b"\x04" + bytes(64)
|
||||||
|
with mock.patch.dict(os.environ, {"PATH": f"{planted.parent}{os.pathsep}{os.environ['PATH']}"}):
|
||||||
|
self.assertFalse(passkey.by_openssl(-7, spki, b"data", b"signature"))
|
||||||
|
self.assertFalse(self.marker.exists())
|
||||||
|
|
||||||
|
|
||||||
|
class TestReminderHook(Scratch):
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.work = self.root / "work"
|
||||||
|
self.work.mkdir()
|
||||||
|
|
||||||
|
def run_reminder(self, path: str) -> subprocess.CompletedProcess:
|
||||||
|
env = {**os.environ, "HOME": str(self.root), "DREAM_STAMP_DIR": str(self.root / "stamps"), "PATH": path}
|
||||||
|
return subprocess.run(["/usr/bin/bash", str(REMINDER)], cwd=self.work, input='{"session_id": "abc"}', env=env, capture_output=True, text=True, timeout=30, check=False)
|
||||||
|
|
||||||
|
def test_a_planted_json_module_in_the_cwd_is_never_imported(self):
|
||||||
|
(self.work / "json.py").write_text(f"open({str(self.marker)!r}, 'w').close()\n", encoding="utf-8")
|
||||||
|
done = self.run_reminder(os.environ["PATH"])
|
||||||
|
self.assertFalse(self.marker.exists())
|
||||||
|
self.assertIn("DREAM HINT", done.stdout)
|
||||||
|
|
||||||
|
def test_a_planted_python3_earlier_on_path_never_runs(self):
|
||||||
|
planted = probe(self.root / "bin" / "python3", self.marker, 'exec /usr/bin/python3 "$@"')
|
||||||
|
done = self.run_reminder(f"{planted.parent}{os.pathsep}{os.environ['PATH']}")
|
||||||
|
self.assertFalse(self.marker.exists())
|
||||||
|
self.assertIn("DREAM HINT", done.stdout)
|
||||||
|
|
||||||
|
|
||||||
|
class TestPermissionHookInstall(Scratch):
|
||||||
|
def test_the_installed_command_is_absolute_isolated_and_imports_its_modules(self):
|
||||||
|
home = self.root / "home"
|
||||||
|
hub = home / ".local" / "share" / "kvb-orchestrator"
|
||||||
|
shutil.copytree(CLIENT, hub / "client", ignore=shutil.ignore_patterns("__pycache__"))
|
||||||
|
(hub / ".env").write_text("KVB_ORCHESTRATOR_PORT=1\n", encoding="utf-8")
|
||||||
|
(home / ".claude").mkdir(parents=True)
|
||||||
|
env = {**os.environ, "HOME": str(home)}
|
||||||
|
subprocess.run(["/usr/bin/bash", str(ORCHESTRATOR), "hook"], env=env, check=True, capture_output=True, text=True, timeout=60)
|
||||||
|
settings = json.loads((home / ".claude" / "settings.json").read_text(encoding="utf-8"))
|
||||||
|
command = settings["hooks"]["PermissionRequest"][-1]["hooks"][0]["command"]
|
||||||
|
self.assertTrue(command.startswith("/usr/bin/python3 -E -s "), command)
|
||||||
|
planted = probe(self.root / "bin" / "python3", self.marker, 'exec /usr/bin/python3 "$@"')
|
||||||
|
work = self.root / "work"
|
||||||
|
work.mkdir()
|
||||||
|
(work / "json.py").write_text(f"open({str(self.marker)!r}, 'w').close()\n", encoding="utf-8")
|
||||||
|
run = {**env, "PATH": f"{planted.parent}{os.pathsep}{os.environ['PATH']}"}
|
||||||
|
done = subprocess.run(["/usr/bin/bash", "-c", command], cwd=work, input="no hook input", env=run, capture_output=True, text=True, timeout=60, check=False)
|
||||||
|
self.assertEqual((done.returncode, done.stdout, done.stderr), (0, "", ""))
|
||||||
|
self.assertFalse(self.marker.exists())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import ast
|
import ast
|
||||||
|
import hashlib
|
||||||
import importlib
|
import importlib
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
@@ -8,7 +9,6 @@ import shlex
|
|||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
|
||||||
import unittest
|
import unittest
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest import mock
|
from unittest import mock
|
||||||
@@ -219,11 +219,6 @@ def scratch_repo(root: Path) -> Path:
|
|||||||
return repo
|
return repo
|
||||||
|
|
||||||
|
|
||||||
def bytes_read() -> int:
|
|
||||||
counters = dict(line.split(": ") for line in Path("/proc/self/io").read_text(encoding="ascii").splitlines())
|
|
||||||
return int(counters["rchar"])
|
|
||||||
|
|
||||||
|
|
||||||
def deny(entries: object) -> dict:
|
def deny(entries: object) -> dict:
|
||||||
return {"sandbox": {"filesystem": {"denyRead": entries}}}
|
return {"sandbox": {"filesystem": {"denyRead": entries}}}
|
||||||
|
|
||||||
@@ -354,7 +349,7 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
self.addCleanup(patch.stop)
|
self.addCleanup(patch.stop)
|
||||||
|
|
||||||
def test_the_staged_diff_lists_each_file_once_and_a_file_matching_a_secret_rule_ships_only_its_counts_and_the_note(self):
|
def test_the_staged_diff_lists_each_file_once_and_a_file_matching_a_secret_rule_ships_only_its_counts_and_the_note(self):
|
||||||
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo, False, self.rules)}
|
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo,self.rules)}
|
||||||
self.assertEqual(sorted(found), ["added.txt", "app.py", "gone.txt", "logo.png"])
|
self.assertEqual(sorted(found), ["added.txt", "app.py", "gone.txt", "logo.png"])
|
||||||
self.assertEqual({path: (entry["status"], entry["mode"], entry["additions"], entry["deletions"], entry["note"]) for path, entry in found.items()}, {
|
self.assertEqual({path: (entry["status"], entry["mode"], entry["additions"], entry["deletions"], entry["note"]) for path, entry in found.items()}, {
|
||||||
"added.txt": ("A", "100644", 1, 0, ""), "app.py": ("M", "100644", 3, 1, WITHHELD), "gone.txt": ("D", "100644", 0, 1, ""), "logo.png": ("B", "100644", 0, 0, ""),
|
"added.txt": ("A", "100644", 1, 0, ""), "app.py": ("M", "100644", 3, 1, WITHHELD), "gone.txt": ("D", "100644", 0, 1, ""), "logo.png": ("B", "100644", 0, 0, ""),
|
||||||
@@ -373,14 +368,14 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
(self.repo / "plain.txt").write_text("plain\n-----BEGIN lowercase is no armour-----\n", encoding="utf-8")
|
(self.repo / "plain.txt").write_text("plain\n-----BEGIN lowercase is no armour-----\n", encoding="utf-8")
|
||||||
(self.repo / "fresh.txt").write_text(ARMOURED, encoding="utf-8")
|
(self.repo / "fresh.txt").write_text(ARMOURED, encoding="utf-8")
|
||||||
git(self.repo, "add", "key.txt", "plain.txt", "fresh.txt")
|
git(self.repo, "add", "key.txt", "plain.txt", "fresh.txt")
|
||||||
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo, False, self.rules)}
|
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo,self.rules)}
|
||||||
self.assertEqual([(found[path]["patch"], found[path]["note"], found[path]["deletions"]) for path in ("key.txt", "fresh.txt")], [("", WITHHELD, 3), ("", WITHHELD, 0)])
|
self.assertEqual([(found[path]["patch"], found[path]["note"], found[path]["deletions"]) for path in ("key.txt", "fresh.txt")], [("", WITHHELD, 3), ("", WITHHELD, 0)])
|
||||||
self.assertEqual((found["plain.txt"]["note"], found["plain.txt"]["additions"]), ("", 1))
|
self.assertEqual((found["plain.txt"]["note"], found["plain.txt"]["additions"]), ("", 1))
|
||||||
self.assertNotIn("plain words only", json.dumps(list(found.values())))
|
self.assertNotIn("plain words only", json.dumps(list(found.values())))
|
||||||
|
|
||||||
def test_past_the_cap_the_rest_is_listed_by_stat_only(self):
|
def test_past_the_cap_the_rest_is_listed_by_stat_only(self):
|
||||||
with mock.patch.object(staged_diff, "DIFF_LIMIT", 40):
|
with mock.patch.object(staged_diff, "DIFF_LIMIT", 40):
|
||||||
found = staged_diff.review_diff(self.repo, False, self.rules)
|
found = staged_diff.review_diff(self.repo,self.rules)
|
||||||
self.assertEqual([(entry["path"], bool(entry["patch"]), entry["note"]) for entry in found], [("added.txt", True, ""), ("app.py", False, WITHHELD), ("gone.txt", False, ""), ("logo.png", False, "")])
|
self.assertEqual([(entry["path"], bool(entry["patch"]), entry["note"]) for entry in found], [("added.txt", True, ""), ("app.py", False, WITHHELD), ("gone.txt", False, ""), ("logo.png", False, "")])
|
||||||
self.assertEqual([(entry["additions"], entry["deletions"]) for entry in found], [(1, 0), (3, 1), (0, 1), (0, 0)])
|
self.assertEqual([(entry["additions"], entry["deletions"]) for entry in found], [(1, 0), (3, 1), (0, 1), (0, 0)])
|
||||||
|
|
||||||
@@ -390,40 +385,22 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
(broken / "bad.yaml").write_text("cwe: CWE-798\nrules: [unclosed\n", encoding="utf-8")
|
(broken / "bad.yaml").write_text("cwe: CWE-798\nrules: [unclosed\n", encoding="utf-8")
|
||||||
for rules in (None, self.root / "missing", broken):
|
for rules in (None, self.root / "missing", broken):
|
||||||
with self.subTest(rules=str(rules)):
|
with self.subTest(rules=str(rules)):
|
||||||
found = staged_diff.review_diff(self.repo, False, rules)
|
found = staged_diff.review_diff(self.repo,rules)
|
||||||
self.assertEqual([(entry["patch"], entry["note"]) for entry in found], [("", WITHHELD)] * 3 + [("", "")])
|
self.assertEqual([(entry["patch"], entry["note"]) for entry in found], [("", WITHHELD)] * 3 + [("", "")])
|
||||||
self.assertIsNone(staged_diff.secret_rules(broken))
|
self.assertIsNone(staged_diff.secret_rules(broken))
|
||||||
|
|
||||||
def test_the_diff_fails_past_the_file_cap_or_the_path_limit_instead_of_the_hub_refusing_it(self):
|
def test_the_diff_fails_past_the_file_cap_or_the_path_limit_instead_of_the_hub_refusing_it(self):
|
||||||
for name, value in (("FILE_CAP", 3), ("PATH_LIMIT", 8)):
|
for name, value in (("FILE_CAP", 3), ("PATH_LIMIT", 8)):
|
||||||
with self.subTest(limit=name), mock.patch.object(staged_diff, name, value), self.assertRaises(staged_diff.DiffError):
|
with self.subTest(limit=name), mock.patch.object(staged_diff, name, value), self.assertRaises(staged_diff.DiffError):
|
||||||
staged_diff.review_diff(self.repo, False, self.rules)
|
staged_diff.review_diff(self.repo,self.rules)
|
||||||
self.assertEqual((staged_diff.FILE_CAP, staged_diff.PATH_LIMIT, diffs.FILE_CAP, diffs.PATH_LIMIT), (hub_limits.FILE_CAP, hub_limits.PATH_LIMIT) * 2)
|
self.assertEqual((staged_diff.FILE_CAP, staged_diff.PATH_LIMIT, diffs.FILE_CAP, diffs.PATH_LIMIT), (hub_limits.FILE_CAP, hub_limits.PATH_LIMIT) * 2)
|
||||||
|
|
||||||
def test_commit_all_shows_the_executable_bit_on_disk(self):
|
|
||||||
(self.repo / "added.txt").chmod(0o755)
|
|
||||||
everything = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo, True, self.rules)}
|
|
||||||
self.assertEqual((everything["added.txt"]["mode"], everything["app.py"]["mode"]), ("100755", "100644"))
|
|
||||||
git(self.repo, "commit", "-q", "-m", "next")
|
|
||||||
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo, True, self.rules)}
|
|
||||||
self.assertEqual((found["added.txt"]["status"], found["added.txt"]["mode"], found["added.txt"]["additions"]), ("M", "100644 => 100755", 0))
|
|
||||||
self.assertEqual(staged_diff.review_diff(self.repo, False, self.rules), [])
|
|
||||||
|
|
||||||
def test_commit_all_diffs_the_tracked_working_tree_against_head_without_untracked_files(self):
|
|
||||||
(self.repo / "added.txt").write_text("fresh\nlater\n", encoding="utf-8")
|
|
||||||
(self.repo / "untracked.txt").write_text("not mine\n", encoding="utf-8")
|
|
||||||
staged = {entry["path"]: entry["additions"] for entry in staged_diff.review_diff(self.repo, False, self.rules)}
|
|
||||||
everything = {entry["path"]: entry["additions"] for entry in staged_diff.review_diff(self.repo, True, self.rules)}
|
|
||||||
self.assertEqual((staged["added.txt"], everything["added.txt"]), (1, 2))
|
|
||||||
self.assertNotIn("untracked.txt", everything)
|
|
||||||
|
|
||||||
def test_a_planted_fsmonitor_or_clean_filter_starts_no_program(self):
|
def test_a_planted_fsmonitor_or_clean_filter_starts_no_program(self):
|
||||||
marker = self.root / "ran"
|
marker = self.root / "ran"
|
||||||
git(self.repo, "config", "core.fsmonitor", f"touch {marker}")
|
git(self.repo, "config", "core.fsmonitor", f"touch {marker}")
|
||||||
git(self.repo, "config", "filter.evil.clean", f"touch {marker}; cat")
|
git(self.repo, "config", "filter.evil.clean", f"touch {marker}; cat")
|
||||||
(self.repo / ".gitattributes").write_text("* filter=evil\n", encoding="utf-8")
|
(self.repo / ".gitattributes").write_text("* filter=evil\n", encoding="utf-8")
|
||||||
for everything in (False, True):
|
staged_diff.review_diff(self.repo, self.rules)
|
||||||
staged_diff.review_diff(self.repo, everything, self.rules)
|
|
||||||
self.assertFalse(marker.exists())
|
self.assertFalse(marker.exists())
|
||||||
|
|
||||||
def test_a_planted_promisor_remote_fetches_no_missing_object_and_starts_no_program(self):
|
def test_a_planted_promisor_remote_fetches_no_missing_object_and_starts_no_program(self):
|
||||||
@@ -436,63 +413,23 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
}
|
}
|
||||||
for key, value in promisor.items():
|
for key, value in promisor.items():
|
||||||
git(self.repo, "config", key, value)
|
git(self.repo, "config", key, value)
|
||||||
for everything in (False, True):
|
with self.assertRaises(staged_diff.DiffError):
|
||||||
with self.subTest(everything=everything), self.assertRaises(staged_diff.DiffError):
|
staged_diff.review_diff(self.repo, self.rules)
|
||||||
staged_diff.review_diff(self.repo, everything, self.rules)
|
|
||||||
self.assertFalse(marker.exists())
|
self.assertFalse(marker.exists())
|
||||||
|
|
||||||
def test_commit_all_reads_no_file_behind_a_symlinked_parent_directory(self):
|
def test_the_staged_diff_ships_nothing_under_a_deny_read_path_and_still_its_sibling(self):
|
||||||
outside = self.root / "outside"
|
|
||||||
outside.mkdir()
|
|
||||||
(outside / "key").write_text("stolen = 1\n", encoding="utf-8")
|
|
||||||
for folder in ("k", "d"):
|
|
||||||
(self.repo / folder).mkdir()
|
|
||||||
(self.repo / folder / "key").write_text("mine = 1\n", encoding="utf-8")
|
|
||||||
(self.repo / "d" / "link").symlink_to("key")
|
|
||||||
git(self.repo, "add", "k", "d")
|
|
||||||
(self.repo / "k" / "key").unlink()
|
|
||||||
(self.repo / "k").rmdir()
|
|
||||||
(self.repo / "k").symlink_to(outside)
|
|
||||||
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo, True, self.rules)}
|
|
||||||
self.assertEqual([found[path]["patch"] for path in ("d/key", "d/link")], ["@@ -0,0 +1 @@\n+mine = 1", "@@ -0,0 +1 @@\n+key"])
|
|
||||||
self.assertNotIn("k/key", found)
|
|
||||||
self.assertNotIn("stolen", json.dumps(list(found.values())))
|
|
||||||
|
|
||||||
def test_an_index_path_leaving_the_working_tree_is_refused(self):
|
|
||||||
(self.root / "outside.txt").write_text("stolen = 1\n", encoding="utf-8")
|
|
||||||
for path in ("../outside.txt", "d/../../outside.txt", str(self.root / "outside.txt")):
|
|
||||||
with self.subTest(path=path), self.assertRaises(staged_diff.DiffError):
|
|
||||||
staged_diff.worktree(self.repo, path, "100644", "sha1", [])
|
|
||||||
|
|
||||||
def test_a_fifo_in_the_working_tree_is_skipped_without_blocking(self):
|
|
||||||
os.mkfifo(self.repo / "pipe")
|
|
||||||
found = []
|
|
||||||
reader = threading.Thread(target=lambda: found.append(staged_diff.worktree(self.repo, "pipe", "100644", "sha1", [])), daemon=True)
|
|
||||||
reader.start()
|
|
||||||
reader.join(10)
|
|
||||||
self.assertEqual(found, [None])
|
|
||||||
|
|
||||||
def test_a_working_tree_file_over_the_blob_limit_is_not_read(self):
|
|
||||||
with (self.repo / "big.bin").open("wb") as handle:
|
|
||||||
handle.truncate(4 * staged_diff.BLOB_LIMIT)
|
|
||||||
before = bytes_read()
|
|
||||||
found = staged_diff.worktree(self.repo, "big.bin", "100644", "sha1", [])
|
|
||||||
self.assertLess(bytes_read() - before, staged_diff.BLOB_LIMIT)
|
|
||||||
self.assertEqual((found[0], found[2]), ("100644", None))
|
|
||||||
|
|
||||||
def test_commit_all_reads_no_file_under_a_deny_read_path_and_still_reads_its_sibling(self):
|
|
||||||
(self.repo / "vault").mkdir()
|
(self.repo / "vault").mkdir()
|
||||||
(self.repo / "vault" / "key").write_text("stolen = 1\n", encoding="utf-8")
|
(self.repo / "vault" / "key").write_text("stolen = 1\n", encoding="utf-8")
|
||||||
(self.repo / "open.txt").write_text("seen = 1\n", encoding="utf-8")
|
(self.repo / "open.txt").write_text("seen = 1\n", encoding="utf-8")
|
||||||
git(self.repo, "add", "vault", "open.txt")
|
git(self.repo, "add", "vault", "open.txt")
|
||||||
write_settings(self.repo / ".claude" / "settings.local.json", deny(["~/repo/vault"]))
|
write_settings(self.repo / ".claude" / "settings.local.json", deny(["~/repo/vault"]))
|
||||||
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo, True, self.rules)}
|
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo, self.rules)}
|
||||||
self.assertEqual([found[path]["patch"] for path in ("vault/key", "open.txt")], ["", "@@ -0,0 +1 @@\n+seen = 1"])
|
self.assertEqual([found[path]["patch"] for path in ("vault/key", "open.txt")], ["", "@@ -0,0 +1 @@\n+seen = 1"])
|
||||||
self.assertNotIn("stolen", json.dumps(list(found.values())))
|
self.assertNotIn("stolen", json.dumps(list(found.values())))
|
||||||
|
|
||||||
def test_commit_all_without_any_settings_file_diffs_normal_files(self):
|
def test_the_staged_diff_without_any_settings_file_diffs_normal_files(self):
|
||||||
self.assertEqual([file for file, _ in sandbox_paths.settings_files(self.repo) if file.exists()], [])
|
self.assertEqual([file for file, _ in sandbox_paths.settings_files(self.repo) if file.exists()], [])
|
||||||
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo, True, self.rules)}
|
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo, self.rules)}
|
||||||
self.assertEqual((found["added.txt"]["patch"], found["app.py"]["additions"]), ("@@ -0,0 +1 @@\n+fresh", 3))
|
self.assertEqual((found["added.txt"]["patch"], found["app.py"]["additions"]), ("@@ -0,0 +1 @@\n+fresh", 3))
|
||||||
|
|
||||||
def test_a_planted_empty_deny_read_list_still_leaves_the_floor_unread(self):
|
def test_a_planted_empty_deny_read_list_still_leaves_the_floor_unread(self):
|
||||||
@@ -502,25 +439,24 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
git(self.repo, "add", ".ssh", "notes.txt")
|
git(self.repo, "add", ".ssh", "notes.txt")
|
||||||
write_settings(self.repo / ".claude" / "settings.json", deny([]))
|
write_settings(self.repo / ".claude" / "settings.json", deny([]))
|
||||||
with mock.patch.dict(os.environ, {"HOME": str(self.repo)}):
|
with mock.patch.dict(os.environ, {"HOME": str(self.repo)}):
|
||||||
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo, True, self.rules)}
|
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo, self.rules)}
|
||||||
self.assertEqual([found[path]["patch"] for path in (".ssh/id_ed25519", "notes.txt")], ["", "@@ -0,0 +1 @@\n+seen = 1"])
|
self.assertEqual([found[path]["patch"] for path in (".ssh/id_ed25519", "notes.txt")], ["", "@@ -0,0 +1 @@\n+seen = 1"])
|
||||||
self.assertNotIn("stolen", json.dumps(list(found.values())))
|
self.assertNotIn("stolen", json.dumps(list(found.values())))
|
||||||
|
|
||||||
def test_commit_all_fails_closed_on_an_unreadable_deny_read_setting_or_in_a_denied_working_tree(self):
|
def test_the_staged_diff_fails_closed_on_an_unreadable_deny_read_setting_or_in_a_denied_working_tree(self):
|
||||||
cases = {"unparsable": b"{", "no utf-8": b"\xff", "no paths": deny("~/x"), "denied top": deny(["~"])}
|
cases = {"unparsable": b"{", "no utf-8": b"\xff", "no paths": deny("~/x"), "denied top": deny(["~"])}
|
||||||
for case, content in cases.items():
|
for case, content in cases.items():
|
||||||
with self.subTest(case=case):
|
with self.subTest(case=case):
|
||||||
write_settings(self.root / ".claude" / "settings.json", content)
|
write_settings(self.root / ".claude" / "settings.json", content)
|
||||||
for everything in (True, False):
|
with self.assertRaises(staged_diff.DiffError):
|
||||||
with self.assertRaises(staged_diff.DiffError):
|
staged_diff.review_diff(self.repo, self.rules)
|
||||||
staged_diff.review_diff(self.repo, everything, self.rules)
|
|
||||||
|
|
||||||
def test_the_staged_diff_ships_no_content_under_a_denied_path(self):
|
def test_the_staged_diff_ships_no_content_under_a_denied_path(self):
|
||||||
(self.repo / "vault").mkdir()
|
(self.repo / "vault").mkdir()
|
||||||
(self.repo / "vault" / "key").write_text("stolen = 1\n", encoding="utf-8")
|
(self.repo / "vault" / "key").write_text("stolen = 1\n", encoding="utf-8")
|
||||||
git(self.repo, "add", "vault")
|
git(self.repo, "add", "vault")
|
||||||
write_settings(self.repo / ".claude" / "settings.json", deny(["vault"]))
|
write_settings(self.repo / ".claude" / "settings.json", deny(["vault"]))
|
||||||
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo, False, self.rules)}
|
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo,self.rules)}
|
||||||
self.assertEqual((found["vault/key"]["status"], found["vault/key"]["patch"], found["added.txt"]["patch"]), ("A", "", "@@ -0,0 +1 @@\n+fresh"))
|
self.assertEqual((found["vault/key"]["status"], found["vault/key"]["patch"], found["added.txt"]["patch"]), ("A", "", "@@ -0,0 +1 @@\n+fresh"))
|
||||||
|
|
||||||
def test_the_session_project_settings_and_read_rules_add_denies(self):
|
def test_the_session_project_settings_and_read_rules_add_denies(self):
|
||||||
@@ -531,7 +467,7 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
write_settings(self.root / "project" / ".claude" / "settings.local.json", deny(["~/repo/vault"]))
|
write_settings(self.root / "project" / ".claude" / "settings.local.json", deny(["~/repo/vault"]))
|
||||||
write_settings(self.repo / ".claude" / "settings.json", {"permissions": {"deny": ["Read(/notes.txt)", "Bash(rm:*)"]}})
|
write_settings(self.repo / ".claude" / "settings.json", {"permissions": {"deny": ["Read(/notes.txt)", "Bash(rm:*)"]}})
|
||||||
write_settings(self.root / ".claude" / "settings.json", {"permissions": {"deny": ["Read(*.pem)"]}})
|
write_settings(self.root / ".claude" / "settings.json", {"permissions": {"deny": ["Read(*.pem)"]}})
|
||||||
found = {entry["path"]: entry["patch"] for entry in staged_diff.review_diff(self.repo, True, self.rules)}
|
found = {entry["path"]: entry["patch"] for entry in staged_diff.review_diff(self.repo, self.rules)}
|
||||||
self.assertEqual([found[path] for path in ("vault/key", "notes.txt", "deep.pem", "open.txt")], ["", "", "", "@@ -0,0 +1 @@\n+seen = 1"])
|
self.assertEqual([found[path] for path in ("vault/key", "notes.txt", "deep.pem", "open.txt")], ["", "", "", "@@ -0,0 +1 @@\n+seen = 1"])
|
||||||
|
|
||||||
def test_each_settings_scope_resolves_relative_entries_from_its_own_folder_and_read_rules_like_claude_code(self):
|
def test_each_settings_scope_resolves_relative_entries_from_its_own_folder_and_read_rules_like_claude_code(self):
|
||||||
@@ -555,7 +491,7 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
self.assertFalse(sandbox_paths.denied(str(self.repo / "env.txt"), roots))
|
self.assertFalse(sandbox_paths.denied(str(self.repo / "env.txt"), roots))
|
||||||
(self.repo / ".env").write_text("hidden = 1\n", encoding="utf-8")
|
(self.repo / ".env").write_text("hidden = 1\n", encoding="utf-8")
|
||||||
git(self.repo, "add", ".env")
|
git(self.repo, "add", ".env")
|
||||||
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo, True, self.rules)}
|
found = {entry["path"]: entry for entry in staged_diff.review_diff(self.repo, self.rules)}
|
||||||
self.assertEqual((found[".env"]["patch"], found["added.txt"]["patch"]), ("", "@@ -0,0 +1 @@\n+fresh"))
|
self.assertEqual((found[".env"]["patch"], found["added.txt"]["patch"]), ("", "@@ -0,0 +1 @@\n+fresh"))
|
||||||
|
|
||||||
def test_an_allow_turns_into_a_deny_when_the_staged_tree_changed_since_the_preview_even_in_a_file_it_withholds(self):
|
def test_an_allow_turns_into_a_deny_when_the_staged_tree_changed_since_the_preview_even_in_a_file_it_withholds(self):
|
||||||
@@ -570,7 +506,8 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
with self.subTest(case=case):
|
with self.subTest(case=case):
|
||||||
git(self.repo, "add", "-A")
|
git(self.repo, "add", "-A")
|
||||||
pinned, shown = permission_hook.commit_diff(ask, self.rules)
|
pinned, shown = permission_hook.commit_diff(ask, self.rules)
|
||||||
self.assertEqual((pinned, len(shown["diff"])), (git(self.repo, "write-tree").strip(), len(shown["diff"])))
|
index = subprocess.run(["git", "ls-files", "-s", "-z"], cwd=self.repo, capture_output=True, check=True).stdout
|
||||||
|
self.assertEqual((pinned, shown["diff"]), (hashlib.sha256(index).hexdigest(), staged_diff.review_diff(self.repo,self.rules)))
|
||||||
self.assertEqual(permission_hook.bound(ALLOW, ask, pinned), ALLOW)
|
self.assertEqual(permission_hook.bound(ALLOW, ask, pinned), ALLOW)
|
||||||
edit()
|
edit()
|
||||||
self.assertEqual(permission_hook.bound(ALLOW, ask, pinned), ALLOW)
|
self.assertEqual(permission_hook.bound(ALLOW, ask, pinned), ALLOW)
|
||||||
@@ -578,13 +515,10 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
self.assertEqual(permission_hook.bound(ALLOW, ask, pinned), changed)
|
self.assertEqual(permission_hook.bound(ALLOW, ask, pinned), changed)
|
||||||
self.assertEqual(permission_hook.bound({"behavior": "deny", "message": "no"}, ask, pinned), {"behavior": "deny", "message": "no"})
|
self.assertEqual(permission_hook.bound({"behavior": "deny", "message": "no"}, ask, pinned), {"behavior": "deny", "message": "no"})
|
||||||
|
|
||||||
def test_an_allow_of_commit_all_is_bound_to_the_working_tree_too(self):
|
def test_an_allow_of_commit_all_is_never_approved(self):
|
||||||
ask = {**ASK, "tool": "Bash", "command": "git commit -am x", "cwd": str(self.repo)}
|
ask = {**ASK, "tool": "Bash", "command": "git commit -am x", "cwd": str(self.repo)}
|
||||||
pinned, shown = permission_hook.commit_diff(ask, self.rules)
|
self.assertEqual(permission_hook.commit_diff(ask, self.rules), (None, {}))
|
||||||
self.assertEqual([entry["path"] for entry in shown["diff"]], ["added.txt", "app.py", "gone.txt", "logo.png"])
|
self.assertIsNone(permission_hook.bound(ALLOW, ask, None))
|
||||||
self.assertEqual(permission_hook.bound(ALLOW, ask, pinned), ALLOW)
|
|
||||||
(self.repo / "app.py").write_text("unstaged edit\n", encoding="utf-8")
|
|
||||||
self.assertEqual(permission_hook.bound(ALLOW, ask, pinned)["behavior"], "deny")
|
|
||||||
|
|
||||||
def test_an_allow_fails_closed_with_a_reason_when_the_tree_cannot_be_read(self):
|
def test_an_allow_fails_closed_with_a_reason_when_the_tree_cannot_be_read(self):
|
||||||
ask = {**ASK, "tool": "Bash", "command": "git commit -m x", "cwd": str(self.repo)}
|
ask = {**ASK, "tool": "Bash", "command": "git commit -m x", "cwd": str(self.repo)}
|
||||||
@@ -606,18 +540,18 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
(self.repo / "added.txt").write_text("fresh\nslipped in\n", encoding="utf-8")
|
(self.repo / "added.txt").write_text("fresh\nslipped in\n", encoding="utf-8")
|
||||||
git(self.repo, "add", "added.txt")
|
git(self.repo, "add", "added.txt")
|
||||||
self.assertEqual(staged_diff.tree_diff(self.repo, tree, self.rules), before)
|
self.assertEqual(staged_diff.tree_diff(self.repo, tree, self.rules), before)
|
||||||
self.assertNotEqual(staged_diff.review_diff(self.repo, False, self.rules), before)
|
self.assertNotEqual(staged_diff.review_diff(self.repo,self.rules), before)
|
||||||
|
|
||||||
def test_without_a_secret_pattern_no_patch_ships(self):
|
def test_without_a_secret_pattern_no_patch_ships(self):
|
||||||
empty = self.root / "empty-rules"
|
empty = self.root / "empty-rules"
|
||||||
empty.mkdir()
|
empty.mkdir()
|
||||||
(empty / "none.yaml").write_text("rules: []\n", encoding="utf-8")
|
(empty / "none.yaml").write_text("rules: []\n", encoding="utf-8")
|
||||||
self.assertEqual({(entry["patch"], entry["note"]) for entry in staged_diff.review_diff(self.repo, False, empty)}, {("", WITHHELD), ("", "")})
|
self.assertEqual({(entry["patch"], entry["note"]) for entry in staged_diff.review_diff(self.repo,empty)}, {("", WITHHELD), ("", "")})
|
||||||
|
|
||||||
def test_a_file_name_that_is_no_utf8_ships_as_backslash_escapes(self):
|
def test_a_file_name_that_is_no_utf8_ships_as_backslash_escapes(self):
|
||||||
(self.repo / os.fsdecode(b"caf\xe9.txt")).write_text("x\n", encoding="utf-8")
|
(self.repo / os.fsdecode(b"caf\xe9.txt")).write_text("x\n", encoding="utf-8")
|
||||||
git(self.repo, "add", "-A")
|
git(self.repo, "add", "-A")
|
||||||
found = staged_diff.review_diff(self.repo, False, self.rules)
|
found = staged_diff.review_diff(self.repo,self.rules)
|
||||||
self.assertIn("caf\\xe9.txt", [entry["path"] for entry in found])
|
self.assertIn("caf\\xe9.txt", [entry["path"] for entry in found])
|
||||||
json.dumps(found, ensure_ascii=False).encode("utf-8")
|
json.dumps(found, ensure_ascii=False).encode("utf-8")
|
||||||
|
|
||||||
@@ -625,10 +559,10 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
tree = git(self.repo, "rev-parse", "HEAD^{tree}").strip()
|
tree = git(self.repo, "rev-parse", "HEAD^{tree}").strip()
|
||||||
(self.repo / "added.txt").write_text("one\x0ctwo\n", encoding="utf-8")
|
(self.repo / "added.txt").write_text("one\x0ctwo\n", encoding="utf-8")
|
||||||
git(self.repo, "add", "added.txt")
|
git(self.repo, "add", "added.txt")
|
||||||
self.assertEqual(next(entry for entry in staged_diff.review_diff(self.repo, False, self.rules) if entry["path"] == "added.txt")["additions"], 1)
|
self.assertEqual(next(entry for entry in staged_diff.review_diff(self.repo,self.rules) if entry["path"] == "added.txt")["additions"], 1)
|
||||||
(self.repo / ".git" / "objects" / tree[:2] / tree[2:]).unlink()
|
(self.repo / ".git" / "objects" / tree[:2] / tree[2:]).unlink()
|
||||||
with self.assertRaises(staged_diff.DiffError):
|
with self.assertRaises(staged_diff.DiffError):
|
||||||
staged_diff.review_diff(self.repo, False, self.rules)
|
staged_diff.review_diff(self.repo,self.rules)
|
||||||
|
|
||||||
def test_a_head_naming_a_missing_commit_or_a_broken_ref_fails_and_only_an_unborn_one_is_empty(self):
|
def test_a_head_naming_a_missing_commit_or_a_broken_ref_fails_and_only_an_unborn_one_is_empty(self):
|
||||||
fresh = self.root / "fresh"
|
fresh = self.root / "fresh"
|
||||||
@@ -636,14 +570,14 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
git(fresh, "init", "-q", "-b", "main")
|
git(fresh, "init", "-q", "-b", "main")
|
||||||
(fresh / "one.txt").write_text("one\n", encoding="utf-8")
|
(fresh / "one.txt").write_text("one\n", encoding="utf-8")
|
||||||
git(fresh, "add", "one.txt")
|
git(fresh, "add", "one.txt")
|
||||||
self.assertEqual([(entry["path"], entry["status"]) for entry in staged_diff.review_diff(fresh, False, self.rules)], [("one.txt", "A")])
|
self.assertEqual([(entry["path"], entry["status"]) for entry in staged_diff.review_diff(fresh, self.rules)], [("one.txt", "A")])
|
||||||
commit = git(self.repo, "rev-parse", "HEAD").strip()
|
commit = git(self.repo, "rev-parse", "HEAD").strip()
|
||||||
(self.repo / ".git" / "objects" / commit[:2] / commit[2:]).unlink()
|
(self.repo / ".git" / "objects" / commit[:2] / commit[2:]).unlink()
|
||||||
with self.assertRaises(staged_diff.DiffError):
|
with self.assertRaises(staged_diff.DiffError):
|
||||||
staged_diff.review_diff(self.repo, False, self.rules)
|
staged_diff.review_diff(self.repo,self.rules)
|
||||||
(self.repo / ".git" / "refs" / "heads" / "main").write_text("not a ref\n", encoding="utf-8")
|
(self.repo / ".git" / "refs" / "heads" / "main").write_text("not a ref\n", encoding="utf-8")
|
||||||
with self.assertRaises(staged_diff.DiffError):
|
with self.assertRaises(staged_diff.DiffError):
|
||||||
staged_diff.review_diff(self.repo, False, self.rules)
|
staged_diff.review_diff(self.repo,self.rules)
|
||||||
|
|
||||||
def test_the_rules_are_cached_until_a_rule_file_changes(self):
|
def test_the_rules_are_cached_until_a_rule_file_changes(self):
|
||||||
first = staged_diff.secret_rules(self.rules)
|
first = staged_diff.secret_rules(self.rules)
|
||||||
@@ -661,17 +595,18 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
staged_diff.CACHE.write_text(broken, encoding="utf-8")
|
staged_diff.CACHE.write_text(broken, encoding="utf-8")
|
||||||
self.assertEqual([globs for globs, _ in staged_diff.secret_rules(self.rules)], [("*.txt",)])
|
self.assertEqual([globs for globs, _ in staged_diff.secret_rules(self.rules)], [("*.txt",)])
|
||||||
|
|
||||||
def test_only_a_single_git_commit_names_its_directory_and_all_mode(self):
|
def test_only_a_single_git_commit_of_the_staged_index_names_its_directory(self):
|
||||||
cases = {
|
cases = {
|
||||||
"git commit -m 'feat: x'": ("/w", False),
|
"git commit -m 'feat: x'": "/w",
|
||||||
"git commit -am 'feat: x'": ("/w", True),
|
"git commit -am 'feat: x'": None,
|
||||||
"git commit -m all -a": ("/w", True),
|
"git commit -m all -a": None,
|
||||||
"git commit --all --no-verify -m x": ("/w", True),
|
"git commit --all --no-verify -m x": None,
|
||||||
"git commit -ma": ("/w", False),
|
"git commit -ma": "/w",
|
||||||
"git -C sub commit -m x": ("/w/sub", False),
|
"git -C sub commit -m x": "/w/sub",
|
||||||
"GIT_EDITOR=true git commit": ("/w", False),
|
"GIT_EDITOR=true git commit": "/w",
|
||||||
"env -C sub git commit -m x": ("/w/sub", False),
|
"env -C sub git commit -m x": "/w/sub",
|
||||||
"env --chdir=sub GIT_EDITOR=true git -C deeper commit -am x": ("/w/sub/deeper", True),
|
"env --chdir=sub GIT_EDITOR=true git -C deeper commit -m x": "/w/sub/deeper",
|
||||||
|
"env --chdir=sub GIT_EDITOR=true git -C deeper commit -am x": None,
|
||||||
"git commit -m x -- -a": None,
|
"git commit -m x -- -a": None,
|
||||||
"git commit -m x file.txt": None,
|
"git commit -m x file.txt": None,
|
||||||
"git commit -a -m x file.txt": None,
|
"git commit -a -m x file.txt": None,
|
||||||
@@ -689,10 +624,14 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
"git commit -a --no-all -m x": None,
|
"git commit -a --no-all -m x": None,
|
||||||
"git commit --al -m x": None,
|
"git commit --al -m x": None,
|
||||||
"git commit --frobnicate -m x": None,
|
"git commit --frobnicate -m x": None,
|
||||||
"git commit --mess 'feat: x' --no-veri": ("/w", False),
|
"git commit --mess 'feat: x' --no-veri": "/w",
|
||||||
"git commit --all-m": None,
|
"git commit --all-m": None,
|
||||||
"git commit -U 3 -m x": ("/w", False),
|
"git commit -U 3 -m x": "/w",
|
||||||
"git commit --unified 3 -am x": ("/w", True),
|
"git commit --unified 3 -am x": None,
|
||||||
|
"git commit -m x --": "/w",
|
||||||
|
"git commit --amend --no-edit": None,
|
||||||
|
"git commit --amen -m x": None,
|
||||||
|
"git commit --no-amend -m x": "/w",
|
||||||
"GIT_INDEX_FILE=/tmp/other git commit -m x": None,
|
"GIT_INDEX_FILE=/tmp/other git commit -m x": None,
|
||||||
"GIT_DIR=/tmp/other git commit -m x": None,
|
"GIT_DIR=/tmp/other git commit -m x": None,
|
||||||
"env GIT_WORK_TREE=/tmp/other git commit -m x": None,
|
"env GIT_WORK_TREE=/tmp/other git commit -m x": None,
|
||||||
@@ -707,7 +646,7 @@ class TestStagedDiff(unittest.TestCase):
|
|||||||
for command, expected in cases.items():
|
for command, expected in cases.items():
|
||||||
with self.subTest(command=command):
|
with self.subTest(command=command):
|
||||||
found = staged_diff.commit_of(command, "/w")
|
found = staged_diff.commit_of(command, "/w")
|
||||||
self.assertEqual(None if found is None else (str(found[0]), found[1]), expected)
|
self.assertEqual(None if found is None else str(found), expected)
|
||||||
|
|
||||||
|
|
||||||
class TestHubOperatorTasks(HubCase):
|
class TestHubOperatorTasks(HubCase):
|
||||||
@@ -769,7 +708,8 @@ class TestHubOperatorTasks(HubCase):
|
|||||||
with mock.patch.object(staged_diff, "CACHE", self.outside / "cache.json"), mock.patch.dict(os.environ, {key: env[key] for key in ("HOME", "CLAUDE_CONFIG_DIR", "CLAUDE_PROJECT_DIR")}):
|
with mock.patch.object(staged_diff, "CACHE", self.outside / "cache.json"), mock.patch.dict(os.environ, {key: env[key] for key in ("HOME", "CLAUDE_CONFIG_DIR", "CLAUDE_PROJECT_DIR")}):
|
||||||
commit = {**ASK, "command": "git commit -m 'feat: w1'", "cwd": str(repo)}
|
commit = {**ASK, "command": "git commit -m 'feat: w1'", "cwd": str(repo)}
|
||||||
pinned, attached = permission_hook.commit_diff(commit, rules)
|
pinned, attached = permission_hook.commit_diff(commit, rules)
|
||||||
self.assertEqual(([entry["path"] for entry in attached["diff"]], pinned), (["added.txt", "app.py", "gone.txt", "logo.png"], git(repo, "write-tree").strip()))
|
index = subprocess.run(["git", "ls-files", "-s", "-z"], cwd=repo, capture_output=True, check=True).stdout
|
||||||
|
self.assertEqual(([entry["path"] for entry in attached["diff"]], pinned), (["added.txt", "app.py", "gone.txt", "logo.png"], hashlib.sha256(index).hexdigest()))
|
||||||
self.assertEqual(permission_hook.commit_diff({**commit, "command": "make deploy"}, rules), (None, {}))
|
self.assertEqual(permission_hook.commit_diff({**commit, "command": "make deploy"}, rules), (None, {}))
|
||||||
self.assertEqual(permission_hook.commit_diff({**commit, "tool": "Write"}, rules), (None, {}))
|
self.assertEqual(permission_hook.commit_diff({**commit, "tool": "Write"}, rules), (None, {}))
|
||||||
self.assertEqual(permission_hook.commit_diff({**commit, "cwd": str(self.outside / "nowhere")}, rules), (None, {}))
|
self.assertEqual(permission_hook.commit_diff({**commit, "cwd": str(self.outside / "nowhere")}, rules), (None, {}))
|
||||||
|
|||||||
Reference in new issue
Block a user