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>
148 lines
6.5 KiB
Python
148 lines
6.5 KiB
Python
"""Git on a repo someone else can write (a guest's project, a worktree of it):
|
|
the one place the hub's git command lines are built (``diff/gitdiff.py``,
|
|
``diff/worktreediff.py``, ``githist.py``), so none of them runs what that
|
|
repo's own config names — the hub's process holds the sidecar token.
|
|
|
|
Same rules as the sidecar's ``safegit.py`` (they share no code: two
|
|
deployables), see its docstring for the why of each:
|
|
|
|
* :data:`SAFE_CONFIG` on every command: no fsmonitor, no hooks, no
|
|
``gpg.program`` through ``log.showSignature``;
|
|
* :data:`DIFF_FLAGS` on every diff-producing command: no external diff, no
|
|
textconv, no ``git log`` inside a submodule;
|
|
* a command that hashes **work-tree** files (``git diff <commit>`` in a
|
|
worktree) would run the clean filter its ``.gitattributes`` names from the
|
|
repo's config, and no flag stops that — so it runs through
|
|
:func:`worktree_git`: a git dir of ours (:func:`skeleton`) with the repo's
|
|
objects and index named by environment, where that config is never read.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import subprocess
|
|
import tempfile
|
|
import threading
|
|
|
|
SAFE_CONFIG = ("-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null",
|
|
"-c", "log.showSignature=false")
|
|
DIFF_FLAGS = ("--no-ext-diff", "--no-textconv", "--submodule=short")
|
|
_DIFFING = frozenset({"diff", "show", "log", "diff-tree", "diff-index", "diff-files"})
|
|
# The container has no owner of the bind-mounted repos: every caller needs it.
|
|
TRUST = ("-c", "safe.directory=*")
|
|
|
|
# Work-tree settings of the real repo worth keeping (how a changed file is
|
|
# hashed), passed as ``-c`` once their value is one of these.
|
|
_BOOL = frozenset({"true", "false"})
|
|
SAFE_KEYS = {
|
|
"core.autocrlf": _BOOL | {"input"},
|
|
"core.eol": frozenset({"lf", "crlf", "native"}),
|
|
"core.safecrlf": _BOOL | {"warn"},
|
|
"core.filemode": _BOOL,
|
|
"core.ignorecase": _BOOL,
|
|
"core.symlinks": _BOOL,
|
|
}
|
|
SAFE_KEYS_RE = r"^core\.(autocrlf|eol|safecrlf|filemode|ignorecase|symlinks)$"
|
|
|
|
|
|
def argv(args, pre=()) -> list[str]:
|
|
"""``git <pre> <args>`` (``args``: subcommand first; ``pre``: global
|
|
options such as ``-C <dir>``) with the overrides above."""
|
|
args = [str(a) for a in args]
|
|
flags = list(DIFF_FLAGS) if args and args[0] in _DIFFING else []
|
|
return ["git", *TRUST, *SAFE_CONFIG, *pre, *args[:1], *flags, *args[1:]]
|
|
|
|
|
|
def env(base=None) -> dict:
|
|
"""No inherited ``GIT_*``, no prompt, no optional index write-back."""
|
|
e = {k: v for k, v in (os.environ if base is None else base).items()
|
|
if not k.startswith("GIT_")}
|
|
e["GIT_OPTIONAL_LOCKS"] = "0"
|
|
e["GIT_TERMINAL_PROMPT"] = "0"
|
|
return e
|
|
|
|
|
|
def run(args, cwd, *, text: bool = True, timeout: int = 20):
|
|
"""``git -C <cwd> <args>`` for commands that read **objects and refs
|
|
only**; its stdout, or None on any failure."""
|
|
try:
|
|
out = subprocess.run(argv(args, pre=("-C", str(cwd))), capture_output=True, text=text,
|
|
timeout=timeout, env=env())
|
|
except (OSError, subprocess.SubprocessError):
|
|
return None
|
|
return out.stdout if out.returncode == 0 else None
|
|
|
|
|
|
# ── work-tree commands: a git dir of ours ────────────────────────────────────
|
|
_skeleton: str | None = None
|
|
_skeleton_lock = threading.Lock()
|
|
|
|
|
|
def skeleton() -> str:
|
|
"""An empty git dir of the hub's own (``HEAD``, ``refs/``, a two-line
|
|
config): what work-tree commands run against instead of the repo's."""
|
|
global _skeleton
|
|
with _skeleton_lock:
|
|
if _skeleton and os.path.isfile(os.path.join(_skeleton, "HEAD")):
|
|
return _skeleton
|
|
d = tempfile.mkdtemp(prefix="aia-safegit-")
|
|
os.makedirs(os.path.join(d, "refs"))
|
|
with open(os.path.join(d, "config"), "w") as f:
|
|
f.write("[core]\n\trepositoryformatversion = 0\n\tbare = false\n")
|
|
with open(os.path.join(d, "HEAD"), "w") as f:
|
|
f.write("ref: refs/heads/none\n")
|
|
_skeleton = d
|
|
return d
|
|
|
|
|
|
def real(git_dir, work_tree, args, timeout: int = 20) -> str | None:
|
|
"""An object/ref/config read on the real git dir (runs nothing of it)."""
|
|
e = env()
|
|
e["GIT_DIR"], e["GIT_WORK_TREE"] = str(git_dir), str(work_tree)
|
|
try:
|
|
out = subprocess.run(argv(args), capture_output=True, text=True, cwd=str(work_tree),
|
|
timeout=timeout, env=e)
|
|
except (OSError, subprocess.SubprocessError):
|
|
return None
|
|
return out.stdout if out.returncode == 0 else None
|
|
|
|
|
|
def worktree_context(git_dir, work_tree) -> dict | None:
|
|
"""What :func:`worktree_git` needs to stand in for ``git_dir``: its
|
|
objects, its index, its ``info/exclude``, the commit ``HEAD`` names and
|
|
the vetted work-tree settings. None when it can't be read."""
|
|
out = real(git_dir, work_tree, ["rev-parse", "--git-path", "objects", "--git-path", "index",
|
|
"--git-path", "info/exclude"])
|
|
lines = (out or "").splitlines()
|
|
if len(lines) < 3:
|
|
return None
|
|
objects, index, exclude = (os.path.normpath(os.path.join(str(work_tree), p))
|
|
for p in lines[:3])
|
|
head = (real(git_dir, work_tree, ["rev-parse", "-q", "--verify", "HEAD^{commit}"])
|
|
or "").strip() or None
|
|
cfg = real(git_dir, work_tree, ["config", "--local", "-z", "--get-regexp", SAFE_KEYS_RE])
|
|
settings: list[str] = []
|
|
for rec in (cfg or "").split("\0"):
|
|
key, _, value = rec.partition("\n")
|
|
key, value = key.strip().lower(), value.strip().lower()
|
|
if value in SAFE_KEYS.get(key, ()):
|
|
settings += ["-c", f"{key}={value}"]
|
|
return {"objects": objects, "index": index, "exclude": exclude, "head": head,
|
|
"settings": tuple(settings), "workTree": str(work_tree)}
|
|
|
|
|
|
def worktree_git(ctx: dict, args, timeout: int = 20) -> str | None:
|
|
"""A command that reads the **work tree** (``diff <commit>``,
|
|
``ls-files --others``), run where the repo's config, hooks and
|
|
``info/attributes`` don't exist. The repo's index is read in place and
|
|
never written (optional locks are off)."""
|
|
e = env()
|
|
e.update(GIT_DIR=skeleton(), GIT_WORK_TREE=ctx["workTree"],
|
|
GIT_OBJECT_DIRECTORY=ctx["objects"], GIT_INDEX_FILE=ctx["index"])
|
|
try:
|
|
out = subprocess.run(argv(args, pre=ctx["settings"]), capture_output=True, text=True,
|
|
cwd=ctx["workTree"], timeout=timeout, env=e)
|
|
except (OSError, subprocess.SubprocessError):
|
|
return None
|
|
return out.stdout if out.returncode == 0 else None
|