Files
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

216 lines
8.9 KiB
Python

"""
A guest's run pushes to Gitea **as the guest** (docs/security.md): never with
the owner's token, which the host's ``~/.gitconfig`` hands to every ``git
push`` (``tea-cli credential``) and which reaches every repo.
* On the lab the run's git reads a **minimal global config** the sidecar
writes (``GIT_CONFIG_GLOBAL`` → ``…/guest-gitea/gitconfig``, with
``GIT_CONFIG_NOSYSTEM=1``): the committer identity and nothing else — none
of the owner's ``~/.gitconfig``, whose credential helpers answer for the
Gitea host under both its names (``tea-cli credential``) and for
github.com (``gh auth git-credential``). Resetting one URL's helper, as
this did until 2026-11-15, left the other two in reach of a plain
``git push``.
* Every credential helper is also reset on git's command-line scope
(``GIT_CONFIG_COUNT`` — over the user's and the repo's own config).
* A run at ``ship`` level gets the guest's own token instead: minted once per
guest (``gitea admin user generate-access-token``, ``write:repository``),
kept on the host (``~/.config/ai-agent/guest-gitea/<user>.json``, 0600) —
the hub never sees it — and handed to the run's helper through its env.
* The projects it ships whose repo sits in someone else's namespace (the
owner's ``gabrielvidal/sherlock-project``) get the guest as a ``write``
collaborator, once (the admin token's job).
Best effort: Gitea down ⇒ the run starts without a token, and a push fails
with an auth error instead of going through as the owner.
"""
from __future__ import annotations
import json
import os
import pathlib
import re
import subprocess
import time
import urllib.request
GITEA_URL = os.environ.get("SIDECAR_GITEA_URL", "https://git.gabvdl.xyz").rstrip("/")
GITEA_HOST = GITEA_URL.split("://", 1)[-1]
GITEA_CONTAINER = os.environ.get("SIDECAR_GITEA_CONTAINER", "gitea")
ADMIN_TOKEN_FILE = pathlib.Path(os.path.expanduser(
os.environ.get("SIDECAR_GITEA_ADMIN_TOKEN", "~/.config/homelab-gitea-admin-token")))
STATE_DIR = pathlib.Path(os.path.expanduser(
os.environ.get("SIDECAR_GUEST_GIT_DIR", "~/.config/ai-agent/guest-gitea")))
PROJECTS_ROOT = pathlib.Path(os.path.expanduser(os.environ.get("SIDECAR_PROJECTS_DIR", "~/projects")))
TOKEN_ENV = "AIA_GITEA_TOKEN"
_USER_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,38}$")
_REMOTE_RE = re.compile(r"^https?://(?:[^@/]+@)?" + re.escape(GITEA_HOST)
+ r"/([\w.-]+)/([\w.-]+?)(?:\.git)?/?$")
GLOBAL_CONFIG = STATE_DIR / "gitconfig"
def _owner_identity() -> dict[str, str]:
"""The host's committer identity (a guest's commits are *authored* as
them — ``GIT_AUTHOR_*`` — and committed by the host's git user)."""
out = {}
for key in ("user.name", "user.email"):
try:
out[key] = _run(["git", "config", "--global", "--get", key], timeout=10)
except (RuntimeError, OSError, subprocess.SubprocessError):
pass
return out
def global_config() -> pathlib.Path | None:
"""Write (0600, atomically) the global git config a scoped run reads on
the lab and return its path; None when it can't be written — the run then
keeps the per-helper resets only."""
ident = _owner_identity()
lines = ["# Written by the ai-agent sidecar (guest_git.py) at each scoped launch:",
"# the only global git config a guest's run reads. No credential helper.",
"[user]"]
for key, name in (("user.name", "name"), ("user.email", "email")):
if ident.get(key):
value = ident[key].replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ")
lines.append(f'\t{name} = "{value}"')
lines += ["[init]", "\tdefaultBranch = main", "[credential]", "\thelper =", ""]
try:
STATE_DIR.mkdir(parents=True, exist_ok=True)
os.chmod(STATE_DIR, 0o700)
tmp = GLOBAL_CONFIG.with_suffix(f".{os.getpid()}.tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
f.write("\n".join(lines))
os.replace(tmp, GLOBAL_CONFIG)
return GLOBAL_CONFIG
except OSError:
return None
def git_env(user: str | None, token: str | None, isolate: bool = False) -> dict[str, str]:
"""The env a scoped run gets: every credential helper reset, then — with
a token — one for the Gitea host that answers with the guest's own
credentials. ``isolate`` (the lab): the minimal global config instead of
the owner's ``~/.gitconfig``, and no system config."""
key = f"credential.{GITEA_URL}.helper"
# An empty value resets the helper list built so far (system, global and
# repo config are all read before the command-line scope).
pairs = [("credential.helper", ""), (key, "")]
if user and token:
pairs.append((key, f'!f() {{ test "$1" = get || exit 0; echo username={user}; '
f'echo "password=${TOKEN_ENV}"; }}; f'))
env = {"GIT_CONFIG_COUNT": str(len(pairs)), "GIT_TERMINAL_PROMPT": "0"}
for i, (k, v) in enumerate(pairs):
env[f"GIT_CONFIG_KEY_{i}"], env[f"GIT_CONFIG_VALUE_{i}"] = k, v
if user and token:
env[TOKEN_ENV] = token
if isolate and (path := global_config()):
env["GIT_CONFIG_GLOBAL"] = str(path)
env["GIT_CONFIG_NOSYSTEM"] = "1"
return env
def _state(user: str) -> pathlib.Path:
return STATE_DIR / f"{user}.json"
def _load(user: str) -> dict:
try:
return json.loads(_state(user).read_text())
except (OSError, ValueError):
return {}
def _save(user: str, data: dict) -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
os.chmod(STATE_DIR, 0o700)
tmp = _state(user).with_suffix(".tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
json.dump(data, f)
os.replace(tmp, _state(user))
def _run(args: list[str], timeout: float = 30) -> str:
p = subprocess.run(args, capture_output=True, text=True, timeout=timeout,
stdin=subprocess.DEVNULL)
if p.returncode != 0:
raise RuntimeError((p.stderr or p.stdout).strip()[-300:])
return p.stdout.strip()
def _mint(user: str, email: str | None) -> str:
if email:
try:
_run(["tea-cli", "ensure-user", user, "--email", email], timeout=60)
except (RuntimeError, OSError, subprocess.SubprocessError):
pass # already there, or the mint below says why
return _run(["docker", "exec", "-u", "git", GITEA_CONTAINER, "gitea", "admin", "user",
"generate-access-token", "--username", user, "--token-name",
f"ai-agent-runs-{int(time.time())}", "--scopes", "write:repository", "--raw"])
def _repo_of(slug: str) -> tuple[str, str] | None:
d = PROJECTS_ROOT / slug
if not re.match(r"^[\w.-]+$", slug) or not (d / ".git").exists():
return None
try:
url = _run(["git", "-C", str(d), "remote", "get-url", "origin"], timeout=10)
except (RuntimeError, OSError, subprocess.SubprocessError):
return None
m = _REMOTE_RE.match(url)
return (m.group(1), m.group(2)) if m else None
def _add_collaborator(owner: str, repo: str, user: str) -> None:
token = ADMIN_TOKEN_FILE.read_text().strip()
req = urllib.request.Request(
f"{GITEA_URL}/api/v1/repos/{owner}/{repo}/collaborators/{user}",
data=json.dumps({"permission": "write"}).encode(), method="PUT",
headers={"Authorization": f"token {token}", "Content-Type": "application/json"})
urllib.request.urlopen(req, timeout=15).read()
def token_for(user: str, email: str | None, push: list[str]) -> str | None:
"""The guest's token (minted on first use) after making sure they can push
to each project in ``push``. None when it can't be had."""
if not _USER_RE.match(user or ""):
return None
data = _load(user)
try:
if not data.get("token"):
data = {"token": _mint(user, email), "repos": []}
_save(user, data)
for slug in push:
r = _repo_of(slug)
if not r or r[0] == user or "/".join(r) in data["repos"]:
continue
_add_collaborator(*r, user)
data["repos"].append("/".join(r))
_save(user, data)
except Exception:
pass
return data.get("token")
def run_env(git: dict | None, isolate: bool = False) -> dict[str, str]:
"""``scope.git`` (``{user, email, push}``) → the run's git env
(``isolate``: see :func:`git_env`)."""
if not isinstance(git, dict):
return git_env(None, None, isolate)
push = [p for p in git.get("push") or [] if isinstance(p, str)]
token = token_for(str(git.get("user") or ""), git.get("email"), push) if push else None
return git_env(str(git.get("user") or ""), token, isolate)
def forget(user: str) -> None:
"""A deleted guest's token file goes (the Gitea token itself stays until
the account is cleaned up there)."""
if _USER_RE.match(user or ""):
_state(user).unlink(missing_ok=True)