Files
ai-agent/backend/test_security.py
gabrielvidalandClaude Opus 5.5 97478dcb52 refactor(ship): the deploy broker leaves the core for the ship live plugin
backend/ship/ (store, service, routes), /api/ship/* (authz + golden
matrix), DEPS.deploy_hosts, the guard's ship-deploy catch (_SHIP / ship())
and the guest prompt's hardcoded ship-deploy line are gone: the managed ship
plugin (ai-agent-plugins) decides who deploys where and its skill supplies
the instructions. carryover.ship copies /data/deploy-hosts.json into the
plugin's shared dir once (then ….migrated). GUARD_SHIP_TIMEOUT_S becomes
GUARD_BROKER_TIMEOUT_S — the ai-agent CLI broker still needs it.

Kept: sidecar/ship.py (the ship.run bridge's /ship/deploy), deploycmd.py,
DeployWidget / DeployGizmo, the ship project level. openapi.json is not
re-dumped here (the coordinator does it after Batch 1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:53:29 +01:00

160 lines
7.7 KiB
Python

"""Settings → Security (security/): the log, the pushes, *Lock guests*, the
edge tripwire and the guard hook's events.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import os
import pathlib
import tempfile
import unittest
from unittest import mock
TMP = pathlib.Path(tempfile.mkdtemp())
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
"PROFILES_PATH": TMP / "profiles.json",
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
"NOTIF_READ_PATH": TMP / "nr.json",
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
"SECURITY_LOG_PATH": TMP / "sec.jsonl", "SECURITY_STATE_PATH": TMP / "sec.json",
"PROJECTS_DIR": TMP / "projects",
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
os.environ[k] = str(v)
(TMP / "projects" / "film").mkdir(parents=True)
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from security import service # noqa: E402
from users.caller import SESSION_COOKIE # noqa: E402
DEPS = main.app.state.ai
OWNER_H = {"X-Internal-Auth": "tok"}
class Security(unittest.TestCase):
def setUp(self):
for u in DEPS.users.all():
DEPS.users.delete(u["id"])
DEPS.security_state.set_locked(False)
from security.store import DEFAULT_PUSH_KINDS
DEPS.security_state.set_push_kinds(list(DEFAULT_PUSH_KINDS))
DEPS.security_log.path.unlink(missing_ok=True)
self.dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"})
self.c = TestClient(main.app)
self.pushes = []
p = mock.patch("notifications.service._create_notify",
lambda deps, d: self.pushes.append(d) or d)
p.start()
self.addCleanup(p.stop)
def guest(self, cookie=None):
c = TestClient(main.app, base_url="https://claude.example.test")
c.cookies.set(SESSION_COOKIE, cookie or DEPS.auth.open_session(self.dom["id"]))
return c
def kinds(self):
return [e["kind"] for e in DEPS.security_log.events()]
def test_the_log_is_the_owners(self):
self.assertEqual(self.guest().get("/api/security/log").status_code, 403)
self.assertEqual(self.c.get("/api/security/log", headers=OWNER_H).status_code, 200)
self.assertEqual(self.c.post("/api/security/lock-guests", json={"locked": True})
.status_code, 403) # untrusted peer, no token
def test_lock_guests_drops_sessions_and_refuses_sign_in(self):
g = self.guest()
self.assertEqual(g.get("/api/me").status_code, 200)
r = self.c.post("/api/security/lock-guests", json={"locked": True}, headers=OWNER_H)
self.assertEqual(r.status_code, 200, r.text)
self.assertTrue(r.json()["guestsLocked"])
self.assertEqual(r.json()["sessionsDropped"], 1)
# the session is gone; a fresh one is refused while locked
g2 = self.guest()
self.assertEqual(g2.get("/api/me").json()["detail"]["kind"], "guests_locked")
anon = TestClient(main.app, base_url="https://claude.example.test")
r = anon.post("/api/auth/request-link", json={"email": "dom@example.com"})
self.assertEqual(r.status_code, 403)
self.c.post("/api/security/lock-guests", json={"locked": False}, headers=OWNER_H)
self.assertEqual(self.guest().get("/api/me").status_code, 200)
self.assertEqual(self.kinds()[:2], ["guests_unlocked", "guests_locked"])
def test_edge_request_without_authelia_is_logged_once(self):
from core import auth
edge = frozenset({"testclient"})
with mock.patch.object(auth, "_resolved", lambda: (edge, edge)):
c = TestClient(main.app, base_url="https://admin.example.test")
for _ in range(3):
self.assertEqual(c.get("/api/me").status_code, 401)
self.assertEqual(self.kinds(), ["edge_anonymous"])
self.assertEqual(len(self.pushes), 1)
self.assertIn("/api/me", self.pushes[0]["message"])
self.assertEqual(self.pushes[0]["sessionId"], "") # the owner's alone
def test_a_new_device_stands_out(self):
DEPS.security_state.see_device("dom", "1.2.3.4", "Firefox")
self.assertEqual(DEPS.security_state.see_device("dom", "1.2.3.4", "Firefox"),
{"ip": False, "ua": False, "first": False})
seen = DEPS.security_state.see_device("dom", "5.6.7.8", "Firefox")
self.assertTrue(seen["ip"] and not seen["ua"])
self.assertTrue(DEPS.security_state.see_device("eve", "9.9.9.9", "x")["first"])
def test_guard_events_are_logged_and_pushed_as_picked(self):
sid = "aaaaaaaa-0000-0000-0000-000000000001"
DEPS.meta_store.update(sid, {"runAs": "dom"})
r = self.c.post("/api/security/events", headers=OWNER_H, json={
"kind": "guard_block", "sessionId": sid, "tool": "Bash",
"rule": "persistence.shell-rc", "input": "echo x >> ~/.bashrc"})
self.assertEqual(r.status_code, 200, r.text)
ev = DEPS.security_log.events()[0]
self.assertEqual((ev["kind"], ev["who"], ev["sid"]), ("guard_block", "dom", sid))
self.assertEqual(len(self.pushes), 1)
# the owner turns that push off: logged, not pushed
self.c.put("/api/security/settings", headers=OWNER_H,
json={"pushKinds": ["new_device"]})
self.c.post("/api/security/events", headers=OWNER_H, json={
"kind": "guard_owner", "tool": "Bash", "input": "rm -rf ~"})
self.assertEqual(len(self.pushes), 1)
self.assertEqual(self.kinds()[0], "guard_owner")
self.assertEqual(self.c.post("/api/security/events", headers=OWNER_H,
json={"kind": "whatever"}).status_code, 400)
def test_sandbox_denials_push_once_per_burst(self):
sid = "aaaaaaaa-0000-0000-0000-000000000002"
for _ in range(5):
service.record(DEPS, "sandbox_denial", who="dom", sid=sid, detail="curl x")
self.assertEqual(self.kinds().count("sandbox_burst"), 1)
self.assertEqual(len(self.pushes), 1)
def test_state(self):
service.record(DEPS, "guest_login", who="dom")
r = self.c.get("/api/security/state", headers=OWNER_H).json()
self.assertEqual(r["counts24h"]["guest_login"], 1)
self.assertFalse(r["guestsLocked"])
self.assertIn("guard_block", r["pushable"])
class ShipMovedToPlugin(unittest.TestCase):
"""The deploy broker is the ``ship`` live plugin since 2026-11-26: no
core route answers a deploy any more (the plugin's ``deploy`` action
calls the ``ship.run`` hub bridge)."""
def test_core_ship_routes_are_gone(self):
c = TestClient(main.app)
# 405: only the SPA's GET catch-all matches the path now
self.assertIn(c.post("/api/ship/deploy", headers=OWNER_H,
json={"sessionId": "x", "host": None}).status_code, (404, 405))
self.assertIn(c.put("/api/ship/hosts/film", headers=OWNER_H,
json={"hosts": []}).status_code, (404, 405))
self.assertNotIn("projects", c.get("/api/ship/hosts", headers=OWNER_H).text[:200])
self.assertFalse(hasattr(DEPS, "deploy_hosts"))
if __name__ == "__main__":
unittest.main()