Files
ai-agent/backend/test_gate.py
gabrielvidalandClaude Opus 5.5 118b6db0df feat(plugins): the lab Chrome leaves the core for the lab-chrome plugin
Settings → Browser, the conversation's Browser dock (noVNC live view and
take-over) and the container's on-demand life move into the lab-chrome
live plugin (ai-agent-plugins). The core keeps the Chrome chip (the
harness capability chrome) and gains three generic hooks:

- sockets[] + aiAgentPlugin.openSocket(id): a frame's websocket, opened by
  the host with the reader's cookies and relayed over postMessage to
  WS /api/plugins/{pid}/sockets/{sid}, which bridges only to the declared
  upstream (owner only, the gate's handshake rules, never the guest host;
  operator approval). GET …/sockets/{sid}/probe → {up, open, lastActiveAt}
  for the plugin's handlers.
- provides chrome.lab (plugins/chrome_bridge.py): {op: status} → the chip
  default and whether guests' runs keep --chrome; {op: ensure} before a
  lab --chrome run launches (spawn and resume).
- ui.slots[].size on app.modal (full = near full screen, frame filling it);
  conversation.gizmos' update and hub/conversations rows carry chrome.

Gone: backend/chrome/, /api/chrome*, schemas/chrome.py, the SSE chrome
event, the lab.integrations permission, BrowserDock/BrowserSettings/store,
the Browser header button and eye switch, @novnc/novnc. /settings/browser
redirects to /settings/plugin/lab-chrome; carryover.chrome moves
/data/chrome.json into the plugin's config.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:18:31 +01:00

236 lines
13 KiB
Python

"""The trusted-caller gate's 2026-11-15 hardening (core/auth.py,
docs/security.md → "Second pass"): cross-site requests refused for every
caller, the path the router matches, who an Authelia user is, the Chrome
websocket, and the two routes that sat outside the gate.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import json
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": "guest.example.test",
"OWNER_USERS": "gabriel", "READONLY_USERS": "bot",
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
os.environ[k] = str(v)
(TMP / "projects" / "film").mkdir(parents=True)
from fastapi.testclient import TestClient # noqa: E402
from starlette.websockets import WebSocketDisconnect # noqa: E402
import core.auth # noqa: E402
import main # noqa: E402
from security import service # noqa: E402
from security.store import SecurityState # noqa: E402
from users.caller import SESSION_COOKIE # noqa: E402
DEPS = main.app.state.ai
ADMIN = "https://admin.example.test"
EDGE = frozenset({"testclient"}) # TestClient's peer address, as Traefik's
class Gate(unittest.TestCase):
def setUp(self):
for u in DEPS.users.all():
DEPS.users.delete(u["id"])
DEPS.security_state.set_locked(False)
DEPS.security_log.path.unlink(missing_ok=True)
service._cross_seen.clear()
service._edge_seen.clear()
self.pushes = []
for target, repl in (
("notifications.service._create_notify",
lambda deps, d: self.pushes.append(d) or d),
("core.auth._resolved", lambda: (EDGE | {"127.0.0.1"}, EDGE))):
p = mock.patch(target, repl)
p.start()
self.addCleanup(p.stop)
self.c = TestClient(main.app, base_url=ADMIN)
def kinds(self):
return [e["kind"] for e in DEPS.security_log.events()]
def edge(self, user="gabriel", **extra):
return {"Remote-User": user, **extra}
# ── cross-site ───────────────────────────────────────────────────────────
def test_a_page_elsewhere_cannot_post_as_the_owner(self):
"""What `fetch(url, {method: "POST", mode: "no-cors", credentials:
"include", body: new Blob([json])})` sends from a guest's site: the
Authelia cookie (same-site), a foreign Origin, no Content-Type."""
r = self.c.post("/api/security/lock-guests", content=b'{"locked": true}',
headers=self.edge(Origin="https://evil.guest.example.test"))
self.assertEqual(r.status_code, 403)
self.assertFalse(DEPS.security_state.guests_locked())
self.assertEqual(self.kinds(), ["cross_site"])
self.assertEqual(len(self.pushes), 1) # pushed by default
# …once per origin per quiet window
self.c.post("/api/security/lock-guests", json={"locked": True},
headers=self.edge(Origin="https://evil.guest.example.test"))
self.assertEqual(self.kinds(), ["cross_site"])
def test_fetch_metadata_alone_refuses(self):
for site in ("same-site", "cross-site"):
r = self.c.post("/api/security/lock-guests", json={"locked": True},
headers=self.edge(**{"Sec-Fetch-Site": site}))
self.assertEqual(r.status_code, 403, site)
self.assertFalse(DEPS.security_state.guests_locked())
def test_the_app_itself_and_host_callers_pass(self):
r = self.c.post("/api/security/lock-guests", json={"locked": False},
headers=self.edge(Origin=ADMIN, **{"Sec-Fetch-Site": "same-origin"}))
self.assertEqual(r.status_code, 200)
# the CLI, a hook, Home Assistant: no Origin, no fetch metadata
cli = TestClient(main.app, client=("10.9.9.9", 5555))
r = cli.post("/api/security/lock-guests", json={"locked": False},
headers={"X-Internal-Auth": "tok"})
self.assertEqual(r.status_code, 200)
self.assertEqual(self.kinds().count("cross_site"), 0)
def test_reads_are_not_concerned(self):
r = self.c.get("/api/security/state",
headers=self.edge(Origin="https://evil.guest.example.test"))
self.assertEqual(r.status_code, 200)
def test_cross_site_guest_request_is_refused_and_named(self):
dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"})
g = TestClient(main.app, base_url="https://guest.example.test")
g.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(dom["id"]))
r = g.put("/api/me", json={"name": "x"}, headers={"Origin": "https://evil.example"})
self.assertEqual(r.status_code, 403)
ev = DEPS.security_log.events()[0]
self.assertEqual((ev["kind"], ev["who"]), ("cross_site", dom["id"]))
def test_a_browser_body_needs_a_content_type(self):
r = self.c.post("/api/security/lock-guests", content=b'{"locked": true}',
headers=self.edge(Origin=ADMIN))
self.assertEqual(r.status_code, 415)
self.assertFalse(DEPS.security_state.guests_locked())
# ── the path the router matches ──────────────────────────────────────────
def test_host_header_cannot_empty_the_gates_path(self):
"""Starlette rebuilds `request.url.path` from Host: `Host: x?` made it
'' and the gate waved the request through to the router."""
outsider = TestClient(main.app, client=("10.9.9.9", 5555))
for host in ("x?", "x#", "x/..?"):
r = outsider.get("/api/users", headers={"Host": host})
self.assertEqual(r.status_code, 403, host)
self.assertEqual(outsider.get("/api/users").status_code, 403)
# ── who an Authelia user is ──────────────────────────────────────────────
def test_only_named_authelia_users_are_the_owner(self):
self.assertEqual(self.c.get("/api/users", headers=self.edge("gabriel")).status_code, 200)
self.assertEqual(self.c.get("/api/users", headers=self.edge("Gabriel")).status_code, 200)
# another account Authelia let through: nobody
r = self.c.get("/api/users", headers=self.edge("celri"))
self.assertEqual(r.status_code, 401)
self.assertIn("edge_anonymous", self.kinds())
def test_the_bot_account_reads_and_never_writes(self):
# what the Admin role reads (authz/scopes.py "bot") — the app's pages…
self.assertEqual(self.c.get("/api/conversations", headers=self.edge("bot")).status_code, 200)
# …but not people, security or the machine's Claude logins
for path in ("/api/security/state", "/api/users", "/api/accounts"):
self.assertEqual(self.c.get(path, headers=self.edge("bot")).status_code, 403, path)
self.assertIn("perm_denied", self.kinds())
r = self.c.post("/api/security/lock-guests", json={"locked": True},
headers=self.edge("bot", Origin=ADMIN))
self.assertEqual(r.status_code, 403)
self.assertFalse(DEPS.security_state.guests_locked())
# ── anonymous bodies, the schema, the share target ───────────────────────
def test_an_anonymous_body_is_small_and_declared(self):
g = TestClient(main.app, base_url="https://guest.example.test")
big = json.dumps({"email": "a@b.c", "pad": "x" * (core.auth.ANON_BODY_MAX + 1)})
self.assertEqual(g.post("/api/auth/request-link", content=big,
headers={"Content-Type": "application/json"}).status_code, 413)
def chunks():
yield b'{"email": "a@b.c"}'
self.assertEqual(g.post("/api/auth/request-link", content=chunks(),
headers={"Content-Type": "application/json"}).status_code, 413)
self.assertNotEqual(g.post("/api/auth/request-link",
json={"email": "a@b.c"}).status_code, 413)
def test_a_guests_body_is_declared_and_bounded(self):
dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"})
g = TestClient(main.app, base_url="https://guest.example.test")
g.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(dom["id"]))
big = json.dumps({"value": "x" * (core.auth.GUEST_BODY_MAX + 1)})
hdr = {"Content-Type": "application/json"}
self.assertEqual(g.put("/api/ui-state/big", content=big, headers=hdr).status_code, 413)
self.assertEqual(g.put("/api/ui-state/big", content=iter([b"{}"]), headers=hdr).status_code, 413)
self.assertNotEqual(g.put("/api/me", json={"name": "Dom"}).status_code, 413)
self.assertNotEqual(g.delete("/api/ui-state/big").status_code, 413) # no body at all
self.assertNotEqual(g.post("/api/upload", content=b"x" * (core.auth.GUEST_BODY_MAX + 1),
headers={"Content-Type": "multipart/form-data; boundary=b"}
).status_code, 413)
def test_the_schema_is_not_served(self):
r = TestClient(main.app, base_url="https://guest.example.test").get("/openapi.json")
self.assertNotIn("paths", r.text)
self.assertIn("/api/spawn", main.app.openapi()["paths"]) # the orval dump still works
def test_share_parses_only_a_small_declared_body(self):
g = TestClient(main.app, base_url="https://guest.example.test", follow_redirects=False)
r = g.post("/share", data={"text": "hello"})
self.assertEqual((r.status_code, r.headers["location"]), (303, "/?q=hello"))
with mock.patch("starlette.requests.Request.form",
side_effect=AssertionError("parsed")):
r = g.post("/share", content=b"x" * (main._SHARE_BODY_MAX + 1),
headers={"Content-Type": "multipart/form-data; boundary=b"})
self.assertEqual((r.status_code, r.headers["location"]), (303, "/"))
# ── a plugin's websocket (the lab-chrome plugin's VNC) ───────────────────
def _ws_code(self, headers):
rec = {"id": "lab-chrome", "enabled": True, "manifest": {
"id": "lab-chrome", "sockets": [{"id": "vnc", "url": "ws://chrome:6080/websockify",
"subprotocols": ["binary"]}]}}
try:
with mock.patch("plugins.sockets._owner_rec", lambda deps, pid: rec), \
self.c.websocket_connect("/api/plugins/lab-chrome/sockets/vnc", headers=headers,
subprotocols=["binary"]):
return "accepted"
except WebSocketDisconnect as e:
return e.code
def test_plugin_socket_refuses_another_origin_and_other_accounts(self):
refused, own = 4403, "https://testserver" # TestClient's websocket host
self.assertEqual(self._ws_code(self.edge(Origin="https://evil.guest.example.test")), refused)
self.assertEqual(self._ws_code(self.edge("bot", Origin=own)), refused)
self.assertEqual(self._ws_code({"Origin": own}), refused) # no Authelia user
# the owner's own page gets past the check (4502: no Chrome container here)
with mock.patch("websockets.connect", side_effect=OSError("down")):
self.assertEqual(self._ws_code(self.edge(Origin=own)), 4502)
class PushDefault(unittest.TestCase):
def test_a_new_default_kind_is_switched_on_once(self):
path = TMP / "old-sec.json"
path.write_text(json.dumps({"guestsLocked": False, "pushKinds": ["guard_block"]}))
st = SecurityState(str(path))
self.assertEqual(st.get()["pushKinds"], ["cross_site", "guard_block", "owner_login", "remote_passkey_added",
"remote_passkey_invited"])
st.set_push_kinds(["guard_block"]) # the owner unticks it
self.assertEqual(SecurityState(str(path)).get()["pushKinds"], ["guard_block"])
if __name__ == "__main__":
unittest.main()