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>
223 lines
9.9 KiB
Python
223 lines
9.9 KiB
Python
"""
|
|
``POST /ship/deploy`` — publish a project's build to the zipgo host for a run
|
|
that can't: a guest's sandboxed run has neither the owner's SSH key nor the
|
|
network to reach raspy2 (docs/security.md → "Deploy broker").
|
|
|
|
The hub decides *whether* (the guest holds ``ship`` on the project, the host
|
|
is one the project may use — backend ``ship/``); this does *how*, with a fixed
|
|
command: ``zipgo deploy <copy of project/dir>/ -d <host> --ssh <target>``.
|
|
Nothing the guest wrote runs here — no npm script, no deploy.sh, no git hook —
|
|
and nothing they wrote *steers* it either:
|
|
|
|
* zipgo never works on the project. The build is first **copied** into a
|
|
folder of the sidecar's (:func:`stage`): opened component by component
|
|
without following links, so nothing can be swapped under the copy, and
|
|
links are copied as links, never read through. zipgo reads files by path
|
|
more than once (its precompress pass, the build's ``.zipgoconfig.json``) —
|
|
on the live tree a link put there between the check and the read would
|
|
ship an owner's file to the guest's site.
|
|
* a symlink in the copy must stay inside the copy, or the deploy is refused
|
|
(zipgo's compression pass reads through links).
|
|
* zipgo runs from ``/``, not from the project: it looks for ``.zipgo.json``
|
|
and a ``package.json`` ``zipgo`` key upward from where it starts, and a
|
|
project's own ``.zipgo.json`` ``targets`` map would rename the owner's
|
|
``--ssh`` target to any host his key reaches.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import shlex
|
|
import shutil
|
|
import stat
|
|
import subprocess
|
|
import tempfile
|
|
|
|
from fastapi import APIRouter, Header, HTTPException
|
|
from pydantic import BaseModel
|
|
|
|
from config import RUN_ENV_STRIP
|
|
from validate import _auth
|
|
|
|
PROJECTS_ROOT = pathlib.Path(os.path.expanduser(
|
|
os.environ.get("SIDECAR_PROJECTS_DIR", "~/projects"))).resolve()
|
|
ZIPGO = shlex.split(os.environ.get("SIDECAR_ZIPGO_CMD", "zipgo"))
|
|
# Where `zipgo deploy` sends sites: SIDECAR_SHIP_TARGET, else the homelab's
|
|
# root .zipgo.json `target` (what every project's deploy.sh passes as --ssh).
|
|
ZIPGO_CONFIG = pathlib.Path(os.path.expanduser(
|
|
os.environ.get("SIDECAR_ZIPGO_CONFIG", "~/homelab/.zipgo.json")))
|
|
SHIP_TIMEOUT_S = float(os.environ.get("SIDECAR_SHIP_TIMEOUT_S", "240"))
|
|
MAX_FILES = 20000
|
|
# Where a build is copied before zipgo sees it: the sidecar's own, never
|
|
# /tmp (a run can write there — a `.zipgo.json` above the copy, the copy itself).
|
|
STAGE_ROOT = pathlib.Path(os.path.expanduser(
|
|
os.environ.get("SIDECAR_SHIP_STAGE_DIR", "~/.cache/ai-agent/ship")))
|
|
MAX_BYTES = int(os.environ.get("SIDECAR_SHIP_MAX_BYTES", str(2 * 1024 ** 3)))
|
|
# zipgo's start folder: nothing above it can carry a `.zipgo.json`.
|
|
ZIPGO_CWD = "/"
|
|
_NOFOLLOW = os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC
|
|
|
|
_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")
|
|
_HOST_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$")
|
|
_DIR_RE = re.compile(r"^[\w.-]+(/[\w.-]+)*$")
|
|
_LOG_TAIL = 4000
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
class ShipBody(BaseModel):
|
|
project: str
|
|
host: str
|
|
dir: str = "dist"
|
|
|
|
|
|
def target() -> str | None:
|
|
t = os.environ.get("SIDECAR_SHIP_TARGET", "").strip()
|
|
if t:
|
|
return t
|
|
try:
|
|
return (json.loads(ZIPGO_CONFIG.read_text()).get("target") or "").strip() or None
|
|
except (OSError, ValueError, AttributeError):
|
|
return None
|
|
|
|
|
|
def build_dir(project: str, sub: str) -> pathlib.Path:
|
|
"""``<projects>/<project>/<sub>``, which must be a directory inside the
|
|
project holding no symlink that leads out of it."""
|
|
if not _SLUG_RE.match(project or "") or ".." in project:
|
|
raise HTTPException(400, f"invalid project: {project!r}")
|
|
if not _DIR_RE.match(sub or "") or ".." in sub.split("/"):
|
|
raise HTTPException(400, f"invalid build dir: {sub!r}")
|
|
root = (PROJECTS_ROOT / project).resolve()
|
|
if root.parent != PROJECTS_ROOT or not root.is_dir():
|
|
raise HTTPException(404, f"no project {project!r}")
|
|
d = (root / sub).resolve()
|
|
if root not in d.parents or not d.is_dir():
|
|
raise HTTPException(400, f"{sub}/ isn't a directory inside {project} — build it first")
|
|
n = 0
|
|
for dirpath, dirnames, filenames in os.walk(d, followlinks=False):
|
|
for name in dirnames + filenames:
|
|
n += 1
|
|
p = pathlib.Path(dirpath) / name
|
|
if p.is_symlink():
|
|
real = p.resolve()
|
|
if real != root and root not in real.parents:
|
|
raise HTTPException(400, f"{p.relative_to(root)} links outside the project")
|
|
if n > MAX_FILES:
|
|
raise HTTPException(400, f"{sub}/ holds more than {MAX_FILES} files")
|
|
return d
|
|
|
|
|
|
def _copy_tree(src_fd: int, dst: pathlib.Path, seen: dict) -> None:
|
|
"""Copy the directory open at ``src_fd`` into ``dst``: every entry is
|
|
opened relative to its parent's descriptor with ``O_NOFOLLOW``, so a path
|
|
swapped for a link mid-copy fails instead of being followed. Links are
|
|
recreated, never read through; sockets, pipes and devices are skipped."""
|
|
with os.scandir(src_fd) as it:
|
|
names = sorted(e.name for e in it)
|
|
for name in names:
|
|
seen["files"] += 1
|
|
if seen["files"] > MAX_FILES:
|
|
raise HTTPException(400, f"the build holds more than {MAX_FILES} files")
|
|
st = os.stat(name, dir_fd=src_fd, follow_symlinks=False)
|
|
out = dst / name
|
|
if stat.S_ISLNK(st.st_mode):
|
|
os.symlink(os.readlink(name, dir_fd=src_fd), out)
|
|
elif stat.S_ISDIR(st.st_mode):
|
|
fd = os.open(name, _NOFOLLOW | os.O_DIRECTORY, dir_fd=src_fd)
|
|
try:
|
|
out.mkdir(mode=0o755)
|
|
_copy_tree(fd, out, seen)
|
|
finally:
|
|
os.close(fd)
|
|
elif stat.S_ISREG(st.st_mode):
|
|
fd = os.open(name, _NOFOLLOW | os.O_NONBLOCK, dir_fd=src_fd)
|
|
try:
|
|
real = os.fstat(fd)
|
|
if not stat.S_ISREG(real.st_mode):
|
|
continue
|
|
seen["bytes"] += real.st_size
|
|
if seen["bytes"] > MAX_BYTES:
|
|
raise HTTPException(400, f"the build is over {MAX_BYTES // 1024 ** 2} MB")
|
|
with os.fdopen(os.dup(fd), "rb") as src, open(out, "wb") as dest:
|
|
shutil.copyfileobj(src, dest, 1024 * 1024)
|
|
os.chmod(out, 0o755 if real.st_mode & 0o111 else 0o644)
|
|
os.utime(out, ns=(real.st_atime_ns, real.st_mtime_ns))
|
|
finally:
|
|
os.close(fd)
|
|
|
|
|
|
def stage(project: str, sub: str) -> pathlib.Path:
|
|
"""A private copy of ``<project>/<sub>`` to deploy from; the caller
|
|
removes its parent folder. Refused (400) when a link in it leaves it."""
|
|
fd = os.open(PROJECTS_ROOT / project, _NOFOLLOW | os.O_DIRECTORY)
|
|
try:
|
|
for part in sub.split("/"):
|
|
try:
|
|
nxt = os.open(part, _NOFOLLOW | os.O_DIRECTORY, dir_fd=fd)
|
|
except OSError:
|
|
raise HTTPException(400, f"{sub}/ isn't a plain directory inside {project}")
|
|
os.close(fd)
|
|
fd = nxt
|
|
STAGE_ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
work = pathlib.Path(tempfile.mkdtemp(prefix=f"{project}-", dir=STAGE_ROOT))
|
|
try:
|
|
site = work / "site"
|
|
site.mkdir(mode=0o755)
|
|
try:
|
|
_copy_tree(fd, site, {"files": 0, "bytes": 0})
|
|
except OSError as e:
|
|
# a file that became a link, a folder that vanished: mid-build, or a try
|
|
raise HTTPException(400, f"the build changed while it was read "
|
|
f"({e.strerror or type(e).__name__}) — build it "
|
|
f"again, then deploy")
|
|
top = site.resolve()
|
|
for dirpath, dirnames, filenames in os.walk(site, followlinks=False):
|
|
for name in dirnames + filenames:
|
|
p = pathlib.Path(dirpath) / name
|
|
if p.is_symlink():
|
|
real = p.resolve()
|
|
if real != top and top not in real.parents:
|
|
raise HTTPException(
|
|
400, f"{p.relative_to(site)} links outside the build")
|
|
return site
|
|
except BaseException:
|
|
shutil.rmtree(work, ignore_errors=True)
|
|
raise
|
|
finally:
|
|
os.close(fd)
|
|
|
|
|
|
@router.post("/ship/deploy")
|
|
def ship_deploy(body: ShipBody, authorization: str | None = Header(default=None)) -> dict:
|
|
_auth(authorization)
|
|
host = (body.host or "").strip().lower()
|
|
if not _HOST_RE.match(host):
|
|
raise HTTPException(400, f"invalid host: {body.host!r}")
|
|
sub = (body.dir or "dist").strip().strip("/")
|
|
build_dir(body.project, sub) # the early, well-worded refusals
|
|
dest = target()
|
|
if not dest:
|
|
raise HTTPException(503, "no zipgo target (SIDECAR_SHIP_TARGET / ~/homelab/.zipgo.json)")
|
|
site = stage(body.project, sub) # what zipgo works on: ours, checked
|
|
args = [*ZIPGO, "deploy", f"{site}/", "-d", host, "--ssh", dest]
|
|
env = {k: v for k, v in os.environ.items() if k not in RUN_ENV_STRIP}
|
|
try:
|
|
p = subprocess.run(args, cwd=ZIPGO_CWD, env=env, capture_output=True, text=True,
|
|
timeout=SHIP_TIMEOUT_S, stdin=subprocess.DEVNULL)
|
|
except subprocess.TimeoutExpired:
|
|
raise HTTPException(504, f"zipgo deploy took longer than {SHIP_TIMEOUT_S:.0f}s")
|
|
except OSError as e:
|
|
raise HTTPException(500, f"can't run zipgo: {e}")
|
|
finally:
|
|
shutil.rmtree(site.parent, ignore_errors=True)
|
|
# the guest reads this: their folder's name, not where the copy sat
|
|
out = (p.stdout + p.stderr).replace(f"{site}/", f"{sub}/").replace(str(site), sub)[-_LOG_TAIL:]
|
|
if p.returncode != 0:
|
|
raise HTTPException(502, {"message": f"zipgo deploy failed ({p.returncode})",
|
|
"output": out})
|
|
return {"ok": True, "url": f"https://{host}", "output": out}
|