Files
ai-agent/backend/test_guest_cli.py
gabrielvidalandClaude Opus 5.5 c7da0f5008 feat(authz): roles, scoped credentials and one permission table for every route
- authz/catalog.py: 42 named permissions in groups and tiers (person, admin,
  host); authz/roles.py: built-in Operator (the owner), Admin (assignable with
  team mode), Member, Guest, Viewer + custom clones, in roles.json
- a person = role + allow/deny overrides (authz/policy.py); users.json's old
  switches (cli, mcp, createProjects, scratchBash, codeMode,
  computers.enabled) migrate once to exactly what they allowed, backup kept
- authz/scopes.py: what a credential acting for someone keeps (cli,
  worker.read|run, bot, phone) — a scope only narrows
- authz/routes.py: (method, path) -> permission for all 310 /api routes; the
  gate asks Caller.allows() for every caller kind, replacing GUEST_ROUTES,
  CLI_ROUTES and the worker READ/RUN_ROUTES regex lists
- golden route x caller matrix (authz/matrix.golden.txt, test_authz_matrix)
- the claude bot reads the admin app minus people/security/the machine; the
  phone key reads its unread notifications only
- loopback without the host token is logged (loopback_tokenless), refusals
  are perm_denied lines; the hub's own MCP calls send the token
- /api/roles CRUD, /api/me and /api/users carry role/allow/deny/perms
- worker-bound scheduled items and conversation-meta respect the binding

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 17:59:05 +01:00

209 lines
11 KiB
Python

"""A guest's `ai-agent` CLI (users/cli.py): a call the guard brokers for a
guest's run is that guest — the CLI's narrow route list, their own
conversations and projects, children of that run only — and never the owner.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import os
import pathlib
import tempfile
import unittest
import uuid
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",
"PROJECTS_DIR": TMP / "projects", "SECURITY_STATE_PATH": TMP / "sec.json",
"SECURITY_LOG_PATH": TMP / "sec.jsonl",
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
"GUEST_PUBLIC_URL": "https://claude.example.test",
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
os.environ[k] = str(v)
for slug in ("film", "other", "secret"):
(TMP / "projects" / slug).mkdir(parents=True)
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
import runs.routes as run_routes # noqa: E402
from runs import children # noqa: E402
from users import deliver # noqa: E402
from users.runs import CLI_SKILL # noqa: E402
DEPS = main.app.state.ai
OWNER_H = {"X-Internal-Auth": "tok"} # the trusted loopback, as in the tests' client
OWNER_RUN = "22222222-2222-4222-8222-222222222222"
class GuestCli(unittest.TestCase):
def setUp(self):
for u in DEPS.users.all():
DEPS.users.delete(u["id"])
self.dom = DEPS.users.create("dom@example.com", "Dom", cli=True,
projects={"film": "chat", "other": "chat"},
models=["sonnet", "haiku"])
DEPS.users.create("claire@example.com", "Claire", cli=True,
projects={"secret": "chat"})
DEPS.security_state.set_locked(False)
self.run = str(uuid.uuid4()) # dom's live run
DEPS.meta_store.update(self.run, {"owner": "dom", "runAs": "dom", "projects": ["film"],
"state": "running"})
DEPS.meta_store.update(OWNER_RUN, {"runAs": "owner"})
self.c = TestClient(main.app)
def cli(self, sid=None):
return {**OWNER_H, "X-AIA-As-Session": sid or self.run}
def _capture(self):
calls, pings = [], []
orig, ping = run_routes._send_message, deliver.owner_ping_start
run_routes._send_message = lambda deps, prompt, **kw: (
calls.append((prompt, kw)) or {"sessionId": "33333333-3333-4333-8333-333333333333",
"pid": 1})
deliver.owner_ping_start = lambda *a, **kw: pings.append(a)
self.addCleanup(setattr, run_routes, "_send_message", orig)
self.addCleanup(setattr, deliver, "owner_ping_start", ping)
return calls, pings
# ── who the call is ──────────────────────────────────────────────────────
def test_a_brokered_call_sees_only_the_guests_projects(self):
r = self.c.get("/api/projects", headers=self.cli())
self.assertEqual(r.status_code, 200, r.text)
slugs = {p["name"] for p in r.json()["projects"]}
self.assertEqual(slugs, {"film", "other"})
# their links open the guest app
self.assertEqual(r.headers.get("x-aia-view-url"), "https://claude.example.test")
def test_only_the_cli_routes_answer(self):
for path in ("/api/users", "/api/cron", "/api/me/computers", "/api/usage/budget"):
r = self.c.get(path, headers=self.cli())
self.assertEqual(r.status_code, 403, path)
r = self.c.put("/api/me", json={"name": "Owner"}, headers=self.cli())
self.assertEqual(r.status_code, 403)
self.assertEqual(self.c.get("/api/me", headers=self.cli()).json()["role"], "guest")
def test_the_switch_is_per_guest(self):
DEPS.users.update("dom", {"cli": False})
r = self.c.get("/api/projects", headers=self.cli())
self.assertEqual(r.status_code, 403)
self.assertEqual(r.json()["detail"]["kind"], "guest_cli")
def test_locked_or_disabled_guests_are_refused(self):
DEPS.security_state.set_locked(True)
self.assertEqual(self.c.get("/api/projects", headers=self.cli()).json()["detail"]["kind"],
"guests_locked")
DEPS.security_state.set_locked(False)
DEPS.users.update("dom", {"disabled": True})
self.assertEqual(self.c.get("/api/projects", headers=self.cli()).status_code, 403)
def test_an_unknown_or_bad_session_is_never_the_owner(self):
r = self.c.get("/api/users", headers=self.cli("44444444-4444-4444-8444-444444444444"))
self.assertEqual(r.status_code, 403)
self.assertEqual(self.c.get("/api/users", headers=self.cli("nope")).status_code, 400)
def test_an_owner_run_stays_the_owner(self):
self.assertEqual(self.c.get("/api/users", headers=self.cli(OWNER_RUN)).status_code, 200)
def test_the_header_grants_nothing_to_an_untrusted_caller(self):
r = self.c.get("/api/projects", headers={"X-AIA-As-Session": self.run})
self.assertEqual(r.status_code, 403)
self.assertEqual(r.json()["detail"], "forbidden")
# ── children ─────────────────────────────────────────────────────────────
def test_new_starts_a_child_of_the_run_in_its_project(self):
calls, pings = self._capture()
r = self.c.post("/api/spawn", json={"prompt": "split this off", "parent": OWNER_RUN,
"cwd": "/", "account": "work", "worker": "mac"},
headers=self.cli())
self.assertEqual(r.status_code, 200, r.text)
prompt, kw = calls[0]
self.assertTrue(prompt.startswith('<ai-agent-from user="dom"'))
self.assertEqual((kw["cwd"], kw["worker"], kw["harness"], kw["run_as"]),
("~/projects/film", "local", "claude", "dom"))
stamp = kw["stamp"]
self.assertEqual((stamp["owner"], stamp["projects"]), ("dom", ["film"]))
# the parent is the run the call came from, whatever the body said
self.assertEqual(stamp["spawnedBy"]["sessionId"], self.run)
self.assertEqual(stamp["spawnedBy"]["depth"], 1)
# the child gets the CLI too: the skill first, the line that explains it
self.assertEqual(kw["scope"]["skills"][0], CLI_SKILL)
self.assertIn("`ai-agent` CLI", kw["scope"]["systemPrompt"])
self.assertEqual(pings, []) # the parent's start already pinged the owner
def test_a_child_may_run_in_another_project_they_chat_in(self):
calls, _ = self._capture()
r = self.c.post("/api/spawn", json={"prompt": "x", "projects": ["other"]},
headers=self.cli())
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(calls[0][1]["cwd"], "~/projects/other")
r = self.c.post("/api/spawn", json={"prompt": "x", "projects": ["secret"]},
headers=self.cli())
self.assertEqual(r.status_code, 403)
def test_children_keep_the_owners_limits(self):
self._capture()
DEPS.meta_store.update(self.run, {"spawnedBy": {"sessionId": OWNER_RUN, "depth": 2,
"at": "2099-01-01T00:00:00.000Z"}})
r = self.c.post("/api/spawn", json={"prompt": "x"}, headers=self.cli())
self.assertEqual(r.status_code, 409)
self.assertEqual(r.json()["detail"]["kind"], "child_depth")
def test_a_scope_without_the_switch_has_no_cli(self):
calls, _ = self._capture()
g = TestClient(main.app, base_url="https://claude.example.test")
DEPS.users.update("dom", {"cli": False})
g.cookies.set("aia_session", DEPS.auth.open_session("dom"))
r = g.post("/api/spawn", json={"prompt": "x", "projects": ["film"]})
self.assertEqual(r.status_code, 200, r.text)
scope = calls[0][1]["scope"]
self.assertNotIn(CLI_SKILL, scope.get("skills") or [])
self.assertNotIn("`ai-agent` CLI", scope["systemPrompt"])
self.assertNotIn("spawnedBy", calls[0][1]["stamp"]) # a browser spawn has no parent
def test_an_owner_caller_still_cannot_parent_a_guests_conversation(self):
with self.assertRaises(Exception) as e:
children.stamp_for(DEPS, self.run)
self.assertEqual(e.exception.status_code, 403)
# ── title / archive ──────────────────────────────────────────────────────
def test_title_and_archive_their_own_only(self):
r = self.c.post("/api/conversation-meta", json={"id": self.run, "title": "Mine",
"titleSource": "user"},
headers=self.cli())
self.assertEqual(r.status_code, 200, r.text)
m = DEPS.meta_store.get(self.run)
self.assertEqual((m["title"], m["titleSource"]), ("Mine", "agent"))
r = self.c.post("/api/conversation-meta", json={"id": self.run, "account": "work"},
headers=self.cli())
self.assertEqual(r.status_code, 403)
r = self.c.post("/api/conversation-meta", json={"id": OWNER_RUN, "archived": True},
headers=self.cli())
self.assertEqual(r.status_code, 404)
def test_a_browser_guest_archives_their_own_only(self):
# conversations.edit is the Guest role's since roles (authz/, 2026-11-23):
# the same two fields as their CLI, on their own conversations only.
g = TestClient(main.app, base_url="https://claude.example.test")
g.cookies.set("aia_session", DEPS.auth.open_session("dom"))
r = g.post("/api/conversation-meta", json={"id": self.run, "archived": True})
self.assertEqual(r.status_code, 200, r.text)
r = g.post("/api/conversation-meta", json={"id": self.run, "projects": ["secret"]})
self.assertEqual(r.status_code, 403)
r = g.post("/api/conversation-meta", json={"id": OWNER_RUN, "archived": True})
self.assertEqual(r.status_code, 404)
DEPS.users.update("dom", {"deny": ["conversations.edit"]})
r = g.post("/api/conversation-meta", json={"id": self.run, "archived": False})
self.assertEqual(r.status_code, 403)
if __name__ == "__main__":
unittest.main()