Files
ai-agent/sidecar/routes_git.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

128 lines
5.0 KiB
Python

"""
``/git/commit`` and ``/git/range`` — a commit's patch, or the net diff
across a run of commits, read from a repo on *this* machine. The hub asks a
worker for these when a conversation that ran here made a commit whose patch
the transcript doesn't carry (the Bash hook's cap, a terminal session, a
transcript from before the hook): the lab has no copy of the Mac's repos.
Read-only git, never a fetch, and nothing the repo's config could make it
execute (``safegit.py``). The caller names candidate directories — the
repo root the hook saw, the session cwd, … — and the first one that is a git
checkout under this user's home *and* has the commit answers. A torn-down
worktree's commits still resolve from its main checkout (shared objects).
"""
from __future__ import annotations
import os
import re
import subprocess
from fastapi import APIRouter, Header, HTTPException
from pydantic import BaseModel
import safegit
from validate import _auth
router = APIRouter()
_SHA_RE = re.compile(r"^[0-9a-f]{7,40}$")
_US = "\x1f"
TIMEOUT_S = 20
# The patch answered for one request; past it the hunks are cut at a file.
MAX_PATCH_BYTES = 4 * 1024 * 1024
MAX_DIRS = 6
class CommitBody(BaseModel):
dirs: list[str]
sha: str
class RangeBody(BaseModel):
dirs: list[str]
base: str # the oldest commit; the diff starts at its parent
head: str
def _git(args: list[str], cwd: str) -> str | None:
"""Git that reads commits only (never the work tree), and never runs what
the repo's own config names — an external diff, a textconv, an fsmonitor,
a gpg program (``safegit``): a guest's project is such a repo."""
try:
p = subprocess.run(safegit.argv(args, config=("-c", "core.quotePath=false")), cwd=cwd,
capture_output=True, timeout=TIMEOUT_S, env=safegit.env())
except (OSError, subprocess.SubprocessError):
return None
return p.stdout.decode(errors="replace") if p.returncode == 0 else None
def _home() -> str:
return os.path.realpath(os.path.expanduser("~"))
def _repo_for(dirs: list[str], *shas: str) -> str:
"""The first candidate that is a checkout under ``~`` holding every sha."""
for s in shas:
if not _SHA_RE.match(s or ""):
raise HTTPException(400, "bad sha")
home = _home()
for d in dirs[:MAX_DIRS]:
d = os.path.realpath(os.path.expanduser(d or ""))
# Walk up from a torn-down worktree to whatever still exists.
while d and not os.path.isdir(d):
d = os.path.dirname(d)
if not d or d == home or not d.startswith(home + os.sep):
continue
top = _git(["rev-parse", "--show-toplevel"], d)
if not top:
continue
top = top.strip()
if all(_git(["cat-file", "-e", f"{s}^{{commit}}"], top) is not None for s in shas):
return top
raise HTTPException(404, {"message": "commit not found on this machine",
"kind": "not_found"})
def _cap(patch: str) -> tuple[str, bool]:
raw = patch.encode()
if len(raw) <= MAX_PATCH_BYTES:
return patch, False
cut = raw.rfind(b"\ndiff --git ", 0, MAX_PATCH_BYTES)
return (raw[:cut + 1].decode(errors="replace") if cut > 0 else ""), True
@router.post("/git/commit")
def git_commit(body: CommitBody, authorization: str | None = Header(None)):
"""One commit: its metadata and patch (``git show``), plus whether a
remote-tracking branch already contains it."""
_auth(authorization)
top = _repo_for(body.dirs, body.sha)
fmt = _US.join(["%H", "%h", "%P", "%cI", "%an", "%s"])
meta = (_git(["show", "-s", f"--format={fmt}", body.sha], top) or "").strip().split(_US)
if len(meta) < 6:
raise HTTPException(404, {"message": "commit not found", "kind": "not_found"})
sha, short, parents, date, author = meta[:5]
patch = _git(["show", "--format=", "--no-color", "-U3", "-M", "--first-parent", body.sha],
top) or ""
patch, truncated = _cap(patch)
remotes = _git(["branch", "-r", "--contains", body.sha, "--format=%(refname:short)"], top)
return {"sha": sha, "short": short, "parents": parents.split(), "date": date,
"author": author, "subject": _US.join(meta[5:]), "root": top,
"patch": patch, "truncated": truncated,
"remotes": [r for r in (remotes or "").split() if not r.endswith("/HEAD")][:20]}
@router.post("/git/range")
def git_range(body: RangeBody, authorization: str | None = Header(None)):
"""The net diff from ``base``'s parent to ``head``."""
_auth(authorization)
top = _repo_for(body.dirs, body.base, body.head)
parent = f"{body.base}^" if _git(["rev-parse", "--verify", "-q", f"{body.base}^"], top) \
else "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
patch = _git(["diff", "--no-color", "-U3", "-M", parent, body.head], top)
if patch is None:
raise HTTPException(404, {"message": "range not found", "kind": "not_found"})
patch, truncated = _cap(patch)
return {"root": top, "patch": patch, "truncated": truncated}