Files
ai-agent/backend/test_safegit.py
gabrielvidal aaab115fa2 fix(sidecar): Monitor through the guard, fail-closed, scoped runs ignore project Claude settings; safe git, egress, ship from a copy
Monitor ran shell commands the guard never saw; the owner CLI, docker and ssh
rules fell to ordinary spellings (the CLI now refuses under AIA_GUEST); a guard
exception let the call through; chat-level runs still had the owner's gitea.lab
and gh credential helpers. Scoped lab runs: --setting-sources user,
--strict-mcp-config, hooks under python -I, the project CLAUDE.md appended as
text, scope.noBash. 3d-render uploads carry data: URIs only; a guest's video
URL resolves to public addresses through a vetting proxy; git on a guest repo
runs with fsmonitor, hooks, filters and textconv out of reach; the ship broker
deploys a checked copy; tokens leave argv.
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-15 15:23:05 +01:00

144 lines
6.6 KiB
Python

"""safegit: the hub's git never runs what a repo's own config names — a
guest's project (or a worktree of it) can carry a clean filter, an fsmonitor,
a hook, an external diff, a textconv or a gpg program in ``.git/config``."""
import os
import pathlib
import subprocess
import tempfile
import unittest
TMP = pathlib.Path(tempfile.mkdtemp())
os.environ["PROJECTS_DIR"] = str(TMP / "projects")
os.environ["REPO_DIR"] = str(TMP)
os.environ["WORKTREES_DIR"] = str(TMP / "worktrees")
(TMP / "projects").mkdir()
(TMP / "worktrees").mkdir()
import githist # noqa: E402
import safegit # noqa: E402
from diff import gitdiff, worktreediff # noqa: E402
def git(cwd, *args):
return subprocess.run(["git", "-C", str(cwd), *args], check=True, capture_output=True,
text=True).stdout.strip()
class HostileRepo(unittest.TestCase):
def setUp(self):
self.name = f"site{len(os.listdir(TMP / 'projects'))}"
self.repo = TMP / "projects" / self.name
self.repo.mkdir()
git(self.repo, "init", "-q", "-b", "main")
git(self.repo, "config", "user.email", "t@t")
git(self.repo, "config", "user.name", "t")
(self.repo / "a.txt").write_text("1\n")
(self.repo / "keep.txt").write_text("k\n")
git(self.repo, "add", ".")
git(self.repo, "commit", "-qm", "first")
(self.repo / "a.txt").write_text("2\n")
git(self.repo, "commit", "-qam", "second")
self.wt_name = f"{self.name}-wt"
self.wt = TMP / "worktrees" / self.wt_name
git(self.repo, "worktree", "add", "-q", str(self.wt), "-b", f"b-{self.name}")
self.marker = TMP / f"{self.name}.ran"
self.trap = TMP / f"{self.name}-trap.sh"
self.trap.write_text(f"#!/bin/sh\necho x >> {self.marker}\ncat\n")
self.trap.chmod(0o755)
def arm(self):
"""Everything a repo's config can name that git would execute."""
for key in ("core.fsmonitor", "filter.x.clean", "filter.x.smudge", "filter.x.process",
"diff.x.textconv", "diff.x.command", "diff.external", "gpg.program"):
git(self.repo, "config", key, str(self.trap))
git(self.repo, "config", "log.showSignature", "true")
git(self.repo, "config", "diff.submodule", "log")
hooks = self.repo / ".git" / "hooks"
hooks.mkdir(exist_ok=True)
for hook in ("post-index-change", "reference-transaction", "post-checkout"):
(hooks / hook).write_text(self.trap.read_text())
(hooks / hook).chmod(0o755)
for d in (self.repo, self.wt):
(d / ".gitattributes").write_text("* filter=x diff=x\n")
def test_commit_reads_run_nothing(self):
self.arm()
sha = git(self.repo, "rev-parse", "HEAD")
patch = gitdiff._git(["show", "--format=", "--no-color", "-U3", "-M", sha], self.repo)
self.assertIn("+2", patch)
self.assertIn("second", gitdiff._git(["log", "--format=%s", "-3"], self.repo))
self.assertIn("+2", gitdiff._git(["diff", "--no-color", f"{sha}^..{sha}"], self.repo))
self.assertEqual(gitdiff._git_bytes(["show", f"{sha}:a.txt"], self.repo), b"2\n")
self.assertIn("second", githist._git(["log", "-2", "--format=%s"], self.repo))
self.assertFalse(self.marker.exists())
def test_a_worktrees_uncommitted_diff_runs_nothing(self):
(self.wt / "a.txt").write_text("3\n")
(self.wt / "new.txt").write_text("n\n")
(self.wt / "keep.txt").unlink()
self.arm()
wt = worktreediff.resolve(self.wt_name)
self.assertEqual(wt["repo"], f"project:{self.name}")
for stats in (True, False):
files = {f["path"]: f for f in worktreediff._diff_one(dict(wt), stats=stats)}
self.assertEqual(files["a.txt"]["status"], "modified")
self.assertEqual(files["keep.txt"]["status"], "deleted")
self.assertIn("new.txt", files)
self.assertIn(".gitattributes", files)
self.assertFalse(self.marker.exists())
# the worktree's index was read in place, never rewritten
self.assertIn("a.txt", git(self.wt, "-c", "core.fsmonitor=false", "-c",
"filter.x.clean=cat", "-c", "filter.x.process=",
"status", "--porcelain"))
def test_a_nested_repo_is_never_entered(self):
sub = self.wt / "sub"
sub.mkdir()
git(sub, "init", "-q")
git(sub, "config", "user.email", "t@t")
git(sub, "config", "user.name", "t")
(sub / "s.txt").write_text("s\n")
git(sub, "add", ".")
git(sub, "commit", "-qm", "sub")
git(self.wt, "add", "sub") # a gitlink in the real index
git(self.wt, "commit", "-qm", "link")
git(sub, "config", "filter.x.clean", str(self.trap))
git(sub, "config", "core.fsmonitor", str(self.trap))
(sub / ".gitattributes").write_text("* filter=x\n")
(sub / "s.txt").write_text("changed\n")
(self.wt / "a.txt").write_text("3\n")
wt = worktreediff.resolve(self.wt_name)
files = [f["path"] for f in worktreediff._diff_one(wt, stats=True)]
self.assertEqual(files, ["a.txt"])
self.assertFalse(self.marker.exists())
def test_info_exclude_and_work_tree_settings_are_kept(self):
(self.repo / ".git" / "info").mkdir(exist_ok=True)
(self.repo / ".git" / "info" / "exclude").write_text("scratch/\n")
(self.wt / "scratch").mkdir()
(self.wt / "scratch" / "x").write_text("no\n")
(self.wt / "shown.txt").write_text("yes\n")
git(self.repo, "config", "core.autocrlf", "input")
git(self.repo, "config", "core.eol", "$(touch /tmp/never)")
wt = worktreediff.resolve(self.wt_name)
self.assertEqual(worktreediff._untracked(wt), ["shown.txt"])
settings = wt["_safe"]["settings"]
self.assertIn("core.autocrlf=input", settings)
self.assertFalse([v for v in settings if v.startswith("core.eol")])
def test_argv_and_env(self):
a = safegit.argv(["log", "-1"], pre=("-C", "/x"))
self.assertEqual(a[-5:], ["log", "--no-ext-diff", "--no-textconv", "--submodule=short", "-1"])
for flag in ("core.fsmonitor=false", "core.hooksPath=/dev/null", "log.showSignature=false",
"safe.directory=*"):
self.assertIn(flag, a)
self.assertNotIn("--no-textconv", safegit.argv(["rev-parse", "HEAD"]))
env = safegit.env({"GIT_EXTERNAL_DIFF": "/x", "GIT_DIR": "/y", "PATH": "/bin"})
self.assertEqual(env, {"PATH": "/bin", "GIT_OPTIONAL_LOCKS": "0",
"GIT_TERMINAL_PROMPT": "0"})
if __name__ == "__main__":
unittest.main()