Files
ai-agent/backend/test_remote_access.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

489 lines
22 KiB
Python

"""The owner's internet address (remoteaccess/, docs/remote-access.md): on an
``OWNER_HOSTS`` host only the owner's own short session is anyone — no
Authelia user, host token or guest cookie — the session's hard and idle
limits, *Internet access* off, signing out, and the machine-only paths
refused there.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import os
import pathlib
import tempfile
import time
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_HOSTS": "hub.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
import main # noqa: E402
from remoteaccess import routes # noqa: E402
from remoteaccess import sessions as rs # noqa: E402
from remoteaccess import webauthn as wa # noqa: E402
from security import service # noqa: E402
from test_webauthn import Authenticator # noqa: E402
from workers import guests as guests_mod # noqa: E402
from users.caller import SESSION_COOKIE # noqa: E402
DEPS = main.app.state.ai
HUB = "https://hub.example.test"
ADMIN = "https://admin.example.test"
EDGE = frozenset({"testclient"}) # TestClient's peer address, as Traefik's
OWNER_EDGE = {"Remote-User": "gabriel"} # the owner through Authelia, on the admin host
class RemoteBase(unittest.TestCase):
def setUp(self):
for u in DEPS.users.all():
DEPS.users.delete(u["id"])
DEPS.security_state.set_locked(False)
DEPS.security_state.set_remote_locked(False)
DEPS.owner_sessions.close_all()
DEPS.security_log.path.unlink(missing_ok=True)
service._edge_seen.clear()
service._cross_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.hub = TestClient(main.app, base_url=HUB)
self.admin = TestClient(main.app, base_url=ADMIN)
def kinds(self):
return [e["kind"] for e in DEPS.security_log.events()]
def signed_in(self) -> str:
token = DEPS.owner_sessions.open("203.0.113.7", "Mozilla/5.0 (Macintosh)", "passkey")
self.hub.cookies.set(rs.COOKIE, token, domain="hub.example.test")
return token
class NobodyThere(RemoteBase):
def test_without_a_session_only_the_sign_in_answers(self):
r = self.hub.get("/api/conversations")
self.assertEqual(r.status_code, 401)
self.assertEqual(r.json()["detail"]["kind"], "login_required")
self.assertEqual(self.hub.get("/api/auth/methods").status_code, 200)
self.assertEqual(self.hub.get("/api/health").status_code, 200)
def test_an_authelia_user_is_nobody_there(self):
# Through Traefik on the admin host this is the owner…
self.assertEqual(self.admin.get("/api/me", headers={"Remote-User": "gabriel"})
.json()["role"], "owner")
# …on the internet address, a header anyone can send.
r = self.hub.get("/api/me", headers={"Remote-User": "gabriel"})
self.assertEqual(r.status_code, 401)
# and no tripwire noise: it is not the admin host
self.assertNotIn("edge_anonymous", self.kinds())
def test_the_host_token_is_nobody_there(self):
for h in ({"X-Internal-Auth": "tok"}, {"Authorization": "Bearer tok"}):
self.assertEqual(self.hub.get("/api/me", headers=h).status_code, 401)
def test_a_guest_cookie_is_nobody_there(self):
dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"})
tok = DEPS.auth.open_session(dom["id"])
self.hub.cookies.set(SESSION_COOKIE, tok, domain="hub.example.test")
self.assertEqual(self.hub.get("/api/me").status_code, 401)
# …nor, beside the owner's session, a way to become that guest
self.signed_in()
self.assertEqual(self.hub.get("/api/me").json()["role"], "owner")
def test_a_forged_cookie_is_nobody(self):
self.hub.cookies.set(rs.COOKIE, "made-up", domain="hub.example.test")
self.assertEqual(self.hub.get("/api/me").status_code, 401)
def test_trailing_dot_and_case_are_the_same_host(self):
for host in ("hub.example.test.", "HUB.example.test"):
r = self.hub.get("/api/me", headers={"Host": host, "X-Internal-Auth": "tok"})
self.assertEqual(r.status_code, 401, host)
class Session(RemoteBase):
def test_the_owner_with_a_session(self):
self.signed_in()
me = self.hub.get("/api/me").json()
self.assertEqual((me["role"], me["surface"]), ("owner", "remote"))
self.assertEqual(self.hub.get("/api/remote").json()["here"], True)
def test_idle_past_the_limit_signs_out(self):
token = self.signed_in()
rec = DEPS.owner_sessions._data["sessions"][rs._hash(token)]
rec["seen"] = time.time() - rs.OWNER_SESSION_IDLE_S - 5
self.assertEqual(self.hub.get("/api/me").status_code, 401)
self.assertEqual(DEPS.owner_sessions.list(), [])
def test_the_hard_end_signs_out_however_busy(self):
token = self.signed_in()
rec = DEPS.owner_sessions._data["sessions"][rs._hash(token)]
rec["exp"] = time.time() - 1
self.assertEqual(self.hub.get("/api/me").status_code, 401)
def test_use_keeps_it_alive_but_never_past_its_end(self):
token = self.signed_in()
rec = DEPS.owner_sessions._data["sessions"][rs._hash(token)]
exp = rec["exp"]
rec["seen"] = time.time() - rs.OWNER_SESSION_IDLE_S + 60
self.assertEqual(self.hub.get("/api/me").status_code, 200)
rec = DEPS.owner_sessions._data["sessions"][rs._hash(token)]
self.assertGreater(rec["seen"], time.time() - 5)
self.assertEqual(rec["exp"], exp)
def test_signing_out(self):
self.signed_in()
self.assertEqual(self.hub.post("/api/auth/logout").status_code, 200)
self.assertEqual(DEPS.owner_sessions.list(), [])
self.assertEqual(self.hub.get("/api/me").status_code, 401)
def test_sessions_listed_and_one_signed_out_from_the_admin_host(self):
self.signed_in()
rows = self.admin.get("/api/remote", headers=OWNER_EDGE).json()
self.assertEqual(len(rows["sessions"]), 1)
self.assertFalse(rows["sessions"][0]["current"])
self.assertTrue(self.hub.get("/api/remote").json()["sessions"][0]["current"])
sid = rows["sessions"][0]["id"]
r = self.admin.delete(f"/api/remote/sessions/{sid}", headers=OWNER_EDGE)
self.assertEqual(r.json()["sessions"], [])
self.assertEqual(self.hub.get("/api/me").status_code, 401)
def test_a_page_elsewhere_cannot_post_as_the_owner(self):
self.signed_in()
r = self.hub.post("/api/remote/lock", json={"locked": True},
headers={"Origin": "https://evil.gabvdl.xyz"})
self.assertEqual(r.status_code, 403)
self.assertFalse(DEPS.security_state.remote_locked())
def test_a_body_without_content_type_is_refused(self):
self.signed_in()
r = self.hub.post("/api/remote/lock", content=b'{"locked": true}')
self.assertEqual(r.status_code, 415)
class InternetAccessOff(RemoteBase):
def test_off_drops_every_session_and_refuses_sign_in(self):
self.signed_in()
r = self.hub.post("/api/remote/lock", json={"locked": True})
self.assertEqual(r.status_code, 200)
self.assertEqual(r.json()["locked"], True)
r = self.hub.get("/api/me")
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (403, "remote_locked"))
self.assertIn("remote_locked", self.kinds())
# a session opened anyhow while off is still nobody
self.signed_in()
self.assertEqual(self.hub.get("/api/me").status_code, 403)
def test_back_on_only_from_the_admin_host(self):
DEPS.security_state.set_remote_locked(True)
r = self.admin.post("/api/remote/lock", json={"locked": False},
headers=OWNER_EDGE)
self.assertEqual(r.json()["locked"], False)
self.signed_in()
r = self.hub.post("/api/remote/lock", json={"locked": False})
self.assertEqual(r.status_code, 403)
def test_the_admin_host_is_unaffected(self):
DEPS.security_state.set_remote_locked(True)
self.assertEqual(self.admin.get("/api/me", headers={"Remote-User": "gabriel"})
.json()["role"], "owner")
def test_security_state_says_so(self):
DEPS.security_state.set_remote_locked(True)
st = self.admin.get("/api/security/state", headers=OWNER_EDGE).json()
self.assertTrue(st["remoteLocked"])
class Passkeys(RemoteBase):
"""The whole round trip with a software authenticator (test_webauthn)."""
def setUp(self):
super().setUp()
for pk in DEPS.owner_passkeys.all():
DEPS.owner_passkeys.remove(pk["id"])
DEPS.owner_passkeys.cancel_invites()
routes._pending.clear()
routes._refused_seen.clear()
from workers import guests
guests.BAD.__init__()
self.a = Authenticator()
def invite(self) -> str:
r = self.admin.post("/api/remote/passkeys/invite", headers=OWNER_EDGE)
self.assertEqual(r.status_code, 200, r.text)
url = r.json()["url"]
self.assertTrue(url.startswith("https://hub.example.test/remote/add-passkey#"))
return url.split("#", 1)[1]
def add(self, invite: str, a=None, origin=HUB) -> "object":
a = a or self.a
r = self.hub.post("/api/remote/passkey/add/options", json={"invite": invite})
if r.status_code != 200:
return r
o = r.json()
self.assertEqual(o["publicKey"]["rp"]["id"], "hub.example.test")
made = a.create(wa.unb64u(o["publicKey"]["challenge"]), origin=origin,
rp="hub.example.test")
return self.hub.post("/api/remote/passkey/add", json={
"ticket": o["ticket"], "invite": invite, "id": wa.b64u(a.cid),
"clientDataJSON": wa.b64u(made["client_data_json"]),
"attestationObject": wa.b64u(made["attestation_object"]), "name": "Pixel 9"})
def login(self, a=None, origin=HUB, ticket=None) -> "object":
a = a or self.a
r = self.hub.post("/api/remote/passkey/login/options")
if r.status_code != 200:
return r
o = r.json()
got = a.get(wa.unb64u(o["publicKey"]["challenge"]), origin=origin, rp="hub.example.test")
return self.hub.post("/api/remote/passkey/login", json={
"ticket": ticket or o["ticket"], "id": wa.b64u(a.cid),
"clientDataJSON": wa.b64u(got["client_data_json"]),
"authenticatorData": wa.b64u(got["authenticator_data"]),
"signature": wa.b64u(got["signature"]),
"userHandle": DEPS.owner_passkeys.user_handle})
def test_add_then_sign_in(self):
r = self.add(self.invite())
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(self.hub.get("/api/me").json()["role"], "owner")
self.assertEqual([p["name"] for p in DEPS.owner_passkeys.all()], ["Pixel 9"])
kinds = self.kinds()
self.assertIn("remote_passkey_added", kinds)
self.assertIn("owner_login", kinds)
titles = [p.get("title") for p in self.pushes]
self.assertTrue(any("passkey was added" in (t or "") for t in titles), titles)
self.assertTrue(any("signed in from the internet" in (t or "") for t in titles), titles)
# signed out, then in again with the same passkey
self.hub.post("/api/auth/logout")
self.assertEqual(self.hub.get("/api/me").status_code, 401)
r = self.login()
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(self.hub.get("/api/me").json()["role"], "owner")
def test_the_cookie_is_host_only_strict_and_short(self):
r = self.add(self.invite())
c = r.headers["set-cookie"]
self.assertTrue(c.startswith("__Host-aia_owner="), c)
for part in ("HttpOnly", "Secure", "SameSite=strict", "Path=/",
f"Max-Age={rs.OWNER_SESSION_TTL_S}"):
self.assertIn(part.lower(), c.lower())
self.assertNotIn("domain=", c.lower())
def test_a_link_is_good_once(self):
inv = self.invite()
self.assertEqual(self.add(inv).status_code, 200)
self.assertEqual(self.add(inv, a=Authenticator()).status_code, 410)
def test_a_new_link_voids_the_last(self):
old = self.invite()
self.invite()
self.assertEqual(self.add(old).status_code, 410)
def test_a_wrong_link_is_refused(self):
self.assertEqual(self.add("not-a-link").status_code, 410)
def test_a_link_is_made_on_the_admin_host_only(self):
self.add(self.invite())
r = self.hub.post("/api/remote/passkeys/invite")
self.assertEqual(r.status_code, 403)
def test_a_passkey_made_for_another_page_is_refused(self):
r = self.add(self.invite(), origin="https://guest.example.test")
self.assertEqual(r.status_code, 400)
self.assertEqual(DEPS.owner_passkeys.all(), [])
def test_sign_in_refusals(self):
self.add(self.invite())
self.hub.post("/api/auth/logout")
# a page elsewhere relaying the ceremony
r = self.login(origin="https://evil.example.test")
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (401, "passkey_refused"))
# a passkey that isn't one of his
self.assertEqual(self.login(a=Authenticator()).status_code, 401)
# a ticket used twice / made up
self.assertEqual(self.login(ticket="made-up").status_code, 409)
self.assertEqual(self.hub.get("/api/me").status_code, 401)
self.assertIn("owner_login_refused", self.kinds())
def test_too_many_failures_lock_the_address(self):
self.add(self.invite())
self.hub.post("/api/auth/logout")
other = Authenticator()
codes = [self.login(a=other).status_code for _ in range(guests_mod.BadTokens.LIMIT + 2)]
self.assertIn(429, codes)
self.assertEqual(self.login().status_code, 429) # even the right passkey, for now
def test_removed_passkey_no_longer_signs_in(self):
self.add(self.invite())
self.hub.post("/api/auth/logout")
pid = DEPS.owner_passkeys.all()[0]["id"]
r = self.admin.delete(f"/api/remote/passkeys/{pid}", headers=OWNER_EDGE)
self.assertEqual(r.json()["passkeys"], [])
self.assertEqual(self.login().status_code, 401)
def test_internet_access_off_refuses_ceremonies(self):
inv = self.invite()
DEPS.security_state.set_remote_locked(True)
r = self.hub.post("/api/remote/passkey/login/options")
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (403, "remote_locked"))
self.assertEqual(self.add(inv).status_code, 403)
self.assertTrue(self.hub.get("/api/auth/methods").json()["locked"])
def test_only_on_the_internet_address(self):
guest = TestClient(main.app, base_url="https://guest.example.test")
for c in (guest, self.admin):
self.assertEqual(c.post("/api/remote/passkey/login/options").status_code, 404)
self.assertTrue(self.hub.get("/api/auth/methods").json()["passkey"])
self.assertFalse(guest.get("/api/auth/methods").json().get("passkey"))
class ReviewFixes(Passkeys):
"""What the 2026-11-24 review found: revocation that didn't revoke, a
sign-out a planted cookie could void, "admin host only" a run could
reach, a ticket pool one address could drain, a link the off switch
left open, a Chrome view that outlived its session."""
def test_removing_a_passkey_ends_its_sessions(self):
self.add(self.invite()) # signed in by that passkey
self.assertEqual(self.hub.get("/api/me").status_code, 200)
pid = DEPS.owner_passkeys.all()[0]["id"]
self.admin.delete(f"/api/remote/passkeys/{pid}", headers=OWNER_EDGE)
self.assertEqual(self.hub.get("/api/me").status_code, 401)
def test_a_planted_guest_cookie_cannot_void_sign_out(self):
self.add(self.invite())
dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"})
self.hub.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(dom["id"]),
domain="hub.example.test")
self.hub.post("/api/auth/logout")
self.assertEqual(DEPS.owner_sessions.list(), [])
self.hub.cookies.set(SESSION_COOKIE, "made-up", domain="hub.example.test")
self.add(self.invite(), a=Authenticator())
self.hub.post("/api/auth/logout")
self.assertEqual(DEPS.owner_sessions.list(), [])
def test_an_impersonation_still_goes_back_to_the_owner(self):
self.add(self.invite())
dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"})
self.hub.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(dom["id"], impersonator="owner"),
domain="hub.example.test")
self.assertEqual(self.hub.get("/api/me").json()["role"], "guest")
self.hub.post("/api/auth/logout") # *Back to admin*
self.assertEqual(len(DEPS.owner_sessions.list()), 1)
def test_links_and_back_on_need_authelia_not_the_host_token(self):
for h in ({"X-Internal-Auth": "tok"}, {}):
# a host-side caller: what a run started from a stolen session could use
r = self.admin.post("/api/remote/passkeys/invite", headers=h)
self.assertIn(r.status_code, (401, 403), h)
DEPS.security_state.set_remote_locked(True)
with mock.patch("core.auth._resolved", lambda: (EDGE | {"127.0.0.1"}, frozenset())):
r = self.admin.post("/api/remote/lock", json={"locked": False},
headers={"X-Internal-Auth": "tok"})
self.assertEqual(r.status_code, 403)
self.assertTrue(DEPS.security_state.remote_locked())
def test_one_address_cannot_drain_the_tickets(self):
self.add(self.invite())
self.hub.post("/api/auth/logout")
mine = self.hub.post("/api/remote/passkey/login/options",
headers={"X-Real-Ip": "203.0.113.7"}).json()
for _ in range(routes._PENDING_PER_IP * 3):
self.hub.post("/api/remote/passkey/login/options", headers={"X-Real-Ip": "198.51.100.9"})
self.assertIn(mine["ticket"], routes._pending)
self.assertLessEqual(sum(p["ip"] == "198.51.100.9" for p in routes._pending.values()),
routes._PENDING_PER_IP)
def test_switching_off_cancels_an_open_link(self):
inv = self.invite()
self.admin.post("/api/remote/lock", json={"locked": True}, headers=OWNER_EDGE)
self.admin.post("/api/remote/lock", json={"locked": False}, headers=OWNER_EDGE)
self.assertEqual(self.add(inv).status_code, 410)
def test_making_a_link_pushes(self):
self.invite()
self.assertTrue(any("link to add a passkey" in (p.get("title") or "") for p in self.pushes))
def test_an_open_plugin_socket_closes_with_its_session(self):
import asyncio
from plugins import sockets as plugin_sockets
from starlette.websockets import WebSocketDisconnect
class Upstream:
def __init__(self):
self.gone = asyncio.Event()
async def send(self, data):
pass
async def close(self):
self.gone.set()
def __aiter__(self):
return self
async def __anext__(self):
await self.gone.wait()
raise StopAsyncIteration
async def connect(*a, **k):
return Upstream()
rec = {"id": "lab-chrome", "enabled": True, "manifest": {
"id": "lab-chrome", "sockets": [{"id": "vnc", "url": "ws://chrome:6080/websockify"}]}}
self.add(self.invite())
with mock.patch("websockets.connect", connect), \
mock.patch.object(plugin_sockets, "REMOTE_RECHECK_S", 0.05), \
mock.patch.object(plugin_sockets, "_owner_rec", lambda deps, pid: rec):
# (TestClient's websocket sends neither the base URL's host nor its cookies)
token = self.hub.cookies.get(rs.COOKIE)
with self.hub.websocket_connect("/api/plugins/lab-chrome/sockets/vnc", headers={
"Origin": HUB, "Host": "hub.example.test",
"Cookie": f"{rs.COOKIE}={token}"}) as ws:
DEPS.owner_sessions.close_all()
with self.assertRaises(WebSocketDisconnect) as cm:
ws.receive_bytes()
self.assertEqual(cm.exception.code, 4403)
class MachinesOnly(RemoteBase):
def test_owner_worker_tokens_refused_on_the_internet_address(self):
from claudeproxy import routes as cp
w = {"id": "wmac", "name": "Mac"}
with mock.patch.object(cp.service, "worker_for_token", lambda store, tok: w), \
mock.patch.object(cp.guests, "ip_locked", lambda req: False), \
mock.patch.object(cp.guests, "bad_token", lambda *a, **k: None):
class Req:
headers = {"host": "hub.example.test", "authorization": "Bearer x"}
app = main.app
got, err = cp._worker(Req())
self.assertIsNone(got)
self.assertIsNotNone(err)
if __name__ == "__main__":
unittest.main()