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

162 lines
7.2 KiB
Python

"""The deploy broker's host half (ship.py): only a build dir inside the
project, deployed from a private copy that no link leaves, with the fixed
zipgo command run where no project file can steer it."""
import json
import os
import pathlib
import shutil
import pytest
from fastapi import HTTPException
import ship
@pytest.fixture
def projects(tmp_path, monkeypatch):
root = tmp_path / "projects"
(root / "site" / "dist").mkdir(parents=True)
(root / "site" / "dist" / "index.html").write_text("hi")
monkeypatch.setattr(ship, "PROJECTS_ROOT", root.resolve())
monkeypatch.setattr(ship, "STAGE_ROOT", tmp_path / "stage")
return root
def test_the_build_dir_must_stay_inside(projects):
assert ship.build_dir("site", "dist") == (projects / "site" / "dist").resolve()
for project, sub in (("site", "../site/dist"), ("../x", "dist"), ("site", "/etc"),
("nope", "dist"), ("site", "missing")):
with pytest.raises(HTTPException):
ship.build_dir(project, sub)
def test_a_symlink_out_of_the_project_is_refused(projects, tmp_path):
secret = tmp_path / "id_ed25519"
secret.write_text("KEY")
os.symlink(secret, projects / "site" / "dist" / "key.txt")
with pytest.raises(HTTPException) as e:
ship.build_dir("site", "dist")
assert "links outside" in str(e.value.detail)
def test_a_symlink_inside_the_build_is_fine(projects):
os.symlink("index.html", projects / "site" / "dist" / "alias.html")
assert ship.build_dir("site", "dist")
site = ship.stage("site", "dist")
assert (site / "alias.html").is_symlink() and (site / "alias.html").read_text() == "hi"
def test_the_copy_is_private_and_never_reads_through_a_link(projects, tmp_path):
dist = projects / "site" / "dist"
(dist / "assets").mkdir()
(dist / "assets" / "app.js").write_text("js")
os.chmod(dist / "assets" / "app.js", 0o755)
site = ship.stage("site", "dist")
assert tmp_path / "stage" in site.parents and projects not in site.parents
assert (site / "assets" / "app.js").read_text() == "js"
assert os.stat(site / "assets" / "app.js").st_mode & 0o777 == 0o755
assert os.stat(site / "index.html").st_mtime_ns == os.stat(dist / "index.html").st_mtime_ns
# the live tree changing afterwards doesn't reach what zipgo will read
secret = tmp_path / "id_ed25519"
secret.write_text("KEY")
(dist / "index.html").unlink()
os.symlink(secret, dist / "index.html")
assert (site / "index.html").read_text() == "hi"
# …and a tree that holds such a link when it is copied is refused: the
# link is copied as a link (never the key's bytes), then found
for link in (str(secret), "../../../id_ed25519", # absolute, relative
str(dist / "assets" / "app.js")): # the *live* project, not the copy
(dist / "index.html").unlink()
os.symlink(link, dist / "index.html")
with pytest.raises(HTTPException) as e:
ship.stage("site", "dist")
assert "links outside the build" in str(e.value.detail)
assert list((tmp_path / "stage").iterdir()) == [site.parent] # refused copies are removed
def test_a_build_dir_that_is_itself_a_link_is_refused(projects, tmp_path):
outside = tmp_path / "owner-files"
outside.mkdir()
(outside / "notes.txt").write_text("private")
shutil.rmtree(projects / "site" / "dist")
os.symlink(outside, projects / "site" / "dist")
with pytest.raises(HTTPException):
ship.stage("site", "dist")
# a link to a folder inside the project is not followed either
(projects / "site" / "build").mkdir()
os.unlink(projects / "site" / "dist")
os.symlink("build", projects / "site" / "dist")
with pytest.raises(HTTPException) as e:
ship.stage("site", "dist")
assert "plain directory" in str(e.value.detail)
def test_caps_on_the_copy(projects, monkeypatch):
monkeypatch.setattr(ship, "MAX_BYTES", 1)
with pytest.raises(HTTPException) as e:
ship.stage("site", "dist")
assert "MB" in str(e.value.detail)
monkeypatch.setattr(ship, "MAX_BYTES", 10 ** 9)
monkeypatch.setattr(ship, "MAX_FILES", 1)
(projects / "site" / "dist" / "b.txt").write_text("b")
with pytest.raises(HTTPException) as e:
ship.stage("site", "dist")
assert "more than 1 files" in str(e.value.detail)
def test_the_command_is_fixed(projects, monkeypatch, tmp_path):
seen = {}
class P:
returncode, stdout, stderr = 0, "synced", ""
monkeypatch.setattr(ship, "_auth", lambda a: None)
monkeypatch.setattr(ship, "target", lambda: "u@h:/srv/domains")
def run(args, **kw):
src = pathlib.Path(args[2])
seen.update(args=args, env=kw["env"], cwd=kw["cwd"], src=src,
files=sorted(p.name for p in src.iterdir()))
P.stdout = f"synced {src}/index.html"
return P()
monkeypatch.setattr(ship.subprocess, "run", run)
monkeypatch.setenv("SIDECAR_TOKEN", "secret")
# what a project could use to steer zipgo, were it run from the project
(projects / "site" / ".zipgo.json").write_text(json.dumps(
{"target": "evil@elsewhere:/x", "targets": {"u@h:/srv/domains": "evil@elsewhere:/x"}}))
(projects / "site" / "package.json").write_text(json.dumps(
{"zipgo": {"target": "evil@elsewhere:/x", "deploy": {"other.host": "dist"}}}))
out = ship.ship_deploy(ship.ShipBody(project="site", host="x.dom.gabvdl.xyz"), "Bearer t")
assert out["url"] == "https://x.dom.gabvdl.xyz"
assert seen["args"][1] == "deploy" and seen["args"][2].endswith("/site/")
assert seen["args"][3:] == ["-d", "x.dom.gabvdl.xyz", "--ssh", "u@h:/srv/domains"]
assert seen["files"] == ["index.html"]
# zipgo ran on the private copy, from a folder with no project config above it
assert projects not in seen["src"].parents and (tmp_path / "stage") in seen["src"].parents
assert seen["cwd"] == "/" and not os.path.exists("/.zipgo.json")
assert "SIDECAR_TOKEN" not in seen["env"]
# the copy is gone, and its path isn't in what the guest reads back
assert not any((tmp_path / "stage").iterdir())
assert out["output"] == "synced dist/index.html"
with pytest.raises(HTTPException):
ship.ship_deploy(ship.ShipBody(project="site", host="x;rm -rf ~"), "Bearer t")
@pytest.mark.skipif(not shutil.which("zipgo"), reason="zipgo isn't installed here")
def test_a_projects_zipgo_json_cannot_retarget_the_real_zipgo(projects, monkeypatch):
"""The reviewer's demo, with the real binary: run from the project, a
`.zipgo.json` `targets` entry named like the owner's target replaced it
(`invalid --ssh "REMAPPED-BY-PROJECT-FILE"`). Now zipgo never sees that
file — it goes on to the (unresolvable) target it was given."""
dest = "nobody@ship-test.invalid:/srv/domains"
(projects / "site" / ".zipgo.json").write_text(json.dumps(
{"targets": {dest: "REMAPPED-BY-PROJECT-FILE"}}))
monkeypatch.setattr(ship, "_auth", lambda a: None)
monkeypatch.setattr(ship, "target", lambda: dest)
monkeypatch.setattr(ship, "SHIP_TIMEOUT_S", 60)
with pytest.raises(HTTPException) as e:
ship.ship_deploy(ship.ShipBody(project="site", host="x.dom.gabvdl.xyz"), "Bearer t")
assert e.value.status_code == 502
assert "REMAPPED" not in json.dumps(e.value.detail)