Files
ai-agent/backend/test_plugin_endpoints.py
gabrielvidalandClaude Fable 5.2 efdd83de18 Merge main (batch plugin reads, #32) into hub-mcp-plugin
The endpoint-only guard moves into plugins/batch.resolve_call — the one rule
set the action route, its GET and the batch read share since #32 — so an
endpoint's action is refused on all three. OpenAPI, the orval types and the
permissions matrix regenerated on the merged tree.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 13:54:01 +01:00

607 lines
34 KiB
Python

"""The platform points the hub-mcp plugin was built on (2026-11-28, when the
MCP server left the core): ``endpoints[]`` (HTTP a plugin answers on the hub's
own address — plugins/endpoints.py), the ``hub.api`` bridge and its act-as
header (plugins/hubapi.py, plugins/actas.py), ``notify.ask`` and
``security.record`` (plugins/hubsignals.py), and the carry-over of core's
``mcp.json`` and of the retired ``mcp.connect`` permission.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
from __future__ import annotations
import json
import os
import pathlib
import tempfile
import unittest
from unittest.mock import patch
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",
"UI_STATE_PATH": TMP / "ui.json", "NOTIF_READ_PATH": TMP / "nr.json",
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
"ROLES_PATH": TMP / "roles.json", "PLUGINS_DIR": TMP / "plugins",
"PROJECTS_DIR": TMP / "projects", "SECURITY_STATE_PATH": TMP / "sec.json",
"SECURITY_LOG_PATH": TMP / "sec.jsonl", "TOOLS_TOKEN_KEY": TMP / "tools.key",
"INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "",
"GUEST_HOSTS": "guest.example.test",
"GUEST_PUBLIC_URL": "https://guest.example.test",
"AI_AGENT_VIEW_URL": "https://admin.example.test",
"PLUGINS_SEED_DIR": "", "PI_TRANSCRIPTS_DIR": ""}.items():
os.environ[k] = str(v)
import httpx # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from plugins import carryover, endpoints, hubapi, manifest # noqa: E402
from plugins.store import OWNER_UID, PluginStore # noqa: E402
from toolproxy import access # noqa: E402
from users.caller import SESSION_COOKIE # noqa: E402
DEPS = main.app.state.ai
OWNER_H = {"X-Internal-Auth": "tok"}
GUEST_HOST = {"Host": "guest.example.test"}
SID = "aaaaaaaa-1111-4111-8111-111111111111"
HANDLER = r'''import json, os, sys
p = json.load(sys.stdin)
req = p.get("request") or {}
rest = req.get("rest") or ""
if rest == "html":
out = {"headers": {"Content-Type": "text/html"}, "body": "<p>hi</p>"}
elif rest == "hdr":
out = {"status": 401, "headers": {"WWW-Authenticate": "Bearer x", "Set-Cookie": "a=b",
"X-Evil": "1", "Cache-Control": "no-store"},
"json": {"error": "unauthorized"}}
elif rest == "redir":
out = {"status": 302, "headers": {"Location": "https://claude.ai/cb?code=1"}}
elif rest == "noloc":
out = {"status": 302}
elif rest == "svg":
out = {"headers": {"Content-Type": "image/svg+xml"}, "body": "<svg/>"}
elif rest == "err":
out = {"_error": {"status": 409, "kind": "taken", "message": "nope"}}
elif rest == "crash":
print("the secret stack trace", file=sys.stderr)
sys.exit(3)
elif rest == "junk":
print("not json")
sys.exit(0)
else:
out = {"json": {"payload": p, "urls": json.loads(os.environ.get("AIA_HUB_URLS") or "null"),
"cli": os.environ.get("AIA_CLI_DIR"),
"uid": json.loads(os.environ["AIA_USER_CONTEXT"])["uid"]}}
print(json.dumps(out))
'''
ENDPOINTS = [
{"id": "page", "path": "/x/ep/*", "methods": ["GET", "POST"], "action": "http", "browser": True},
{"id": "mcp", "path": "/mcp", "methods": ["POST"], "action": "http", "maxBodyKb": 1},
{"id": "meta", "path": "/.well-known/oauth-protected-resource", "action": "http"},
{"id": "admin", "path": "/x/ep/admin-only", "action": "http", "surfaces": ["admin"]},
{"id": "slow", "path": "/oauth/*", "methods": ["POST"], "action": "http", "perIpPerMin": 2},
]
def _write(root: pathlib.Path, mf: dict | None = None, pid: str = "ep") -> pathlib.Path:
root.mkdir(parents=True, exist_ok=True)
(root / "h.py").write_text(HANDLER)
base = {"schema": 1, "id": pid, "name": "Ep", "actions": {"http": {"script": "h.py"}},
"endpoints": ENDPOINTS, "managed": {"defaultForGuests": False},
"capabilities": ["hub.api", "notify.ask", "security.record"]}
base.update(mf or {})
(root / "plugin.json").write_text(json.dumps(base))
return root
class _WithPlugin(unittest.TestCase):
"""A hub with the ``ep`` plugin installed for the owner."""
mf: dict | None = None
def setUp(self):
self.td = tempfile.TemporaryDirectory()
td = pathlib.Path(self.td.name)
self.store = PluginStore(td / "data")
self.store.install(OWNER_UID, str(_write(td / "src", self.mf)), is_owner=True, approve=True)
self.patch = patch.object(DEPS, "plugin_store", self.store)
self.patch.start()
endpoints._registry = None
endpoints._hits.clear()
self.tc = TestClient(main.app)
def tearDown(self):
self.patch.stop()
endpoints._registry = None
self.td.cleanup()
def token(self) -> dict:
return {"Authorization": "Bearer " + access.mint_handler(OWNER_UID, "ep", ttl=600)}
class TestManifest(unittest.TestCase):
def _mf(self, eps, pid="ep"):
with tempfile.TemporaryDirectory() as td:
return manifest.validate_manifest(_write(pathlib.Path(td), {"endpoints": eps}, pid))
def test_endpoints_are_normalized_operator_only_and_in_the_fingerprint(self):
mf = self._mf(ENDPOINTS)
self.assertEqual([e["id"] for e in mf["endpoints"]], ["page", "mcp", "meta", "admin", "slow"])
self.assertEqual(mf["endpoints"][2], {
"id": "meta", "path": "/.well-known/oauth-protected-resource", "methods": ["GET"],
"action": "http", "maxBodyKb": 64, "perIpPerMin": 120,
"surfaces": ["admin", "public"], "browser": False})
self.assertTrue(manifest.requires_operator(mf))
other = self._mf([{**ENDPOINTS[0], "methods": ["GET"]}, *ENDPOINTS[1:]])
self.assertNotEqual(manifest.capability_fingerprint(mf), manifest.capability_fingerprint(other))
label = next(i["label"] for i in manifest.capability_summary(mf) if i["kind"] == "endpoints")
self.assertIn("POST /mcp", label)
self.assertIn("internet", label)
def test_no_endpoints_leaves_the_fingerprint_alone(self):
with tempfile.TemporaryDirectory() as td:
root = _write(pathlib.Path(td))
raw = json.loads((root / "plugin.json").read_text())
del raw["endpoints"]
(root / "plugin.json").write_text(json.dumps(raw))
mf = manifest.validate_manifest(root)
self.assertNotIn("endpoints", mf)
self.assertNotIn("endpoints", json.dumps(manifest.capability_summary(mf)))
def test_only_its_own_prefix_and_the_protocol_paths(self):
for path in ("/api/x", "/proxy/tools/x", "/x/other/page", "/settings", "/", "/assets/a.js",
"/x/ep/../../api", "/x/ep//a", "x/ep/a", "/x/ep/a b", "/mcpx", "/mcp/*",
"/oauth", "/.well-known", "/x/*"):
with self.assertRaises(manifest.ManifestError, msg=path):
self._mf([{"id": "a", "path": path, "action": "http"}])
for path in ("/x/ep", "/x/ep/a/*", "/mcp", "/oauth/token", "/oauth/*",
"/.well-known/openid-configuration"):
self.assertEqual(self._mf([{"id": "a", "path": path, "action": "http"}])
["endpoints"][0]["path"], path)
def test_bad_declarations(self):
ok = {"id": "a", "path": "/x/ep/a", "action": "http"}
for bad in ({**ok, "action": "nope"}, {**ok, "methods": ["TRACE"]},
{**ok, "surfaces": ["owner"]}, {**ok, "maxBodyKb": 9000},
{**ok, "perIpPerMin": 0}, {**ok, "what": 1}, {**ok, "id": "Bad Id"}):
with self.assertRaises(manifest.ManifestError, msg=bad):
self._mf([bad])
with self.assertRaises(manifest.ManifestError):
self._mf([ok, {**ok, "id": "b"}])
with self.assertRaises(manifest.ManifestError):
self._mf([{**ok, "id": f"e{i}", "path": f"/x/ep/{i}"} for i in range(17)])
def test_an_endpoints_action_is_wired_to_nothing_else(self):
ok = [{"id": "a", "path": "/x/ep/a", "action": "http"}]
for extra in ({"commands": {"go": {"action": "http", "summary": "s"}}},
{"webhooks": [{"id": "in", "mode": "action", "action": "http"}]},
{"exports": ["http"]},
{"settings": {"testAction": "http"}}):
with tempfile.TemporaryDirectory() as td, \
self.assertRaises(manifest.ManifestError, msg=extra) as cm:
manifest.validate_manifest(_write(pathlib.Path(td), {"endpoints": ok, **extra}))
self.assertIn("answers an endpoint", " ".join(cm.exception.errors), extra)
class TestDispatch(_WithPlugin):
def test_nobody_claims_it(self):
self.assertEqual(self.tc.get("/x/none/page").status_code, 404)
self.assertEqual(self.tc.get("/.well-known/security.txt").status_code, 404)
self.store.update(OWNER_UID, "ep", enabled=False)
endpoints._registry = None
self.assertEqual(self.tc.get("/x/ep/hello").status_code, 404)
def test_the_handler_sees_what_the_host_vouches_for(self):
r = self.tc.post("/x/ep/a/b?x=1&y=2", content="hello", headers={
"Authorization": "Bearer t", "Cookie": "aia_session=zzz", "Remote-User": "gabriel",
"Content-Type": "text/plain", "X-Forwarded-For": "9.9.9.9"})
self.assertEqual(r.status_code, 200, r.text)
out = r.json()
req = out["payload"]["request"]
self.assertEqual((out["payload"]["trigger"], out["payload"]["endpoint"]), ("endpoint", "page"))
self.assertEqual((req["method"], req["path"], req["rest"], req["query"], req["body"]),
("POST", "/x/ep/a/b", "a/b", "x=1&y=2", "hello"))
self.assertEqual(req["headers"], {"authorization": "Bearer t", "content-type": "text/plain",
"accept": "*/*", "user-agent": "testclient"})
self.assertEqual((req["surface"], req["origin"]), ("admin", "https://admin.example.test"))
self.assertIsNone(req["caller"]) # an untrusted peer with no credential
self.assertEqual(out["urls"], {"admin": "https://admin.example.test",
"public": "https://guest.example.test"})
self.assertEqual(out["uid"], OWNER_UID) # the handler runs as the owner, whoever asked
self.assertTrue(out["cli"] and pathlib.Path(out["cli"], "ai_agent.py").is_file())
def test_bytes_that_are_not_text(self):
r = self.tc.post("/x/ep/a", content=b"\xff\xfe\x00", headers={"Content-Type": "application/octet-stream"})
req = r.json()["payload"]["request"]
self.assertNotIn("body", req)
self.assertEqual(req["bodyBase64"], "//4A")
def test_the_owner_and_a_guest_are_named_by_the_host(self):
owner = self.tc.get("/x/ep/a", headers=OWNER_H).json()["payload"]["request"]["caller"]
self.assertEqual((owner["uid"], owner["isOwner"], owner["active"]), (OWNER_UID, True, True))
u = DEPS.users.create("dom@example.com", "Dom")
self.addCleanup(DEPS.users.delete, u["id"])
g = TestClient(main.app)
g.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(u["id"]))
who = g.get("/x/ep/a", headers=GUEST_HOST).json()["payload"]["request"]
self.assertEqual((who["surface"], who["origin"]), ("public", "https://guest.example.test"))
self.assertEqual((who["caller"]["uid"], who["caller"]["isOwner"], who["caller"]["active"]),
(u["id"], False, False))
self.store.set_grant(u["id"], "ep", enabled=True)
self.assertTrue(g.get("/x/ep/a", headers=GUEST_HOST).json()["payload"]["request"]["caller"]["active"])
# their cookie means nothing off the guest host, and the host token nothing on it
self.assertIsNone(g.get("/x/ep/a").json()["payload"]["request"]["caller"])
self.assertIsNone(self.tc.get("/x/ep/a", headers={**OWNER_H, **GUEST_HOST})
.json()["payload"]["request"]["caller"])
with patch.object(DEPS.security_state, "guests_locked", lambda: True):
self.assertIsNone(g.get("/x/ep/a", headers=GUEST_HOST).json()["payload"]["request"]["caller"])
# the owner looking through their eyes is named as such: not their own act
self.assertNotIn("impersonatedBy", who["caller"])
imp = TestClient(main.app)
imp.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(u["id"], impersonator="owner"))
seen = imp.get("/x/ep/a", headers=GUEST_HOST).json()["payload"]["request"]["caller"]
self.assertEqual((seen["uid"], seen["impersonatedBy"]), (u["id"], "owner"))
def test_methods_surfaces_and_head(self):
r = self.tc.get("/mcp")
self.assertEqual((r.status_code, r.headers["allow"]), (405, "POST"))
self.assertEqual(self.tc.get("/x/ep/admin-only").json()["payload"]["endpoint"], "admin")
self.assertEqual(self.tc.get("/x/ep/admin-only", headers=GUEST_HOST).status_code, 404)
h = self.tc.head("/x/ep/html")
self.assertEqual((h.status_code, h.content), (200, b""))
self.assertEqual(self.tc.put("/x/ep/a").status_code, 405)
def test_never_on_the_owners_internet_address(self):
with patch("users.caller.OWNER_HOSTS", frozenset({"hub.example.test"})):
self.assertEqual(self.tc.post("/mcp", content="{}", headers={"Host": "hub.example.test"}).status_code, 404)
def test_the_answer_goes_through_the_allowlists(self):
r = self.tc.get("/x/ep/hdr")
self.assertEqual((r.status_code, r.json()), (401, {"error": "unauthorized"}))
self.assertEqual(r.headers["www-authenticate"], "Bearer x")
self.assertEqual(r.headers["cache-control"], "no-store")
self.assertNotIn("set-cookie", r.headers)
self.assertNotIn("x-evil", r.headers)
self.assertEqual(r.headers["x-content-type-options"], "nosniff")
html = self.tc.get("/x/ep/html")
self.assertEqual(html.text, "<p>hi</p>")
self.assertTrue(html.headers["content-type"].startswith("text/html"))
csp = html.headers["content-security-policy"]
self.assertIn("default-src 'none'", csp)
self.assertNotIn("script-src", csp)
self.assertIn("form-action 'self'", csp)
svg = self.tc.get("/x/ep/svg")
self.assertEqual((svg.headers["content-type"], svg.headers["content-disposition"]),
("application/octet-stream", "attachment"))
redir = self.tc.get("/x/ep/redir", follow_redirects=False)
self.assertEqual((redir.status_code, redir.headers["location"]), (302, "https://claude.ai/cb?code=1"))
self.assertEqual(self.tc.get("/x/ep/noloc", follow_redirects=False).status_code, 502)
self.assertEqual(self.tc.get("/x/ep/junk").status_code, 502)
def test_a_handlers_own_error_keeps_its_words_a_crash_does_not(self):
r = self.tc.get("/x/ep/err")
self.assertEqual((r.status_code, r.json()), (409, {"error": {"message": "nope", "kind": "taken"}}))
c = self.tc.get("/x/ep/crash")
self.assertEqual(c.status_code, 502)
self.assertNotIn("secret", c.text)
def test_body_cap_and_rate(self):
self.assertEqual(self.tc.post("/mcp", content="x" * 1025).status_code, 413)
self.assertEqual(self.tc.post("/mcp", content="x" * 1024).status_code, 200)
codes = [self.tc.post("/oauth/token", content="a=1").status_code for _ in range(3)]
self.assertEqual(codes, [200, 200, 429])
def test_a_page_refuses_another_sites_post(self):
evil = {"Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site"}
self.assertEqual(self.tc.post("/x/ep/a", content="x", headers=evil).status_code, 403)
# …but an API path has no browser behind it: its own credential is the gate
self.assertEqual(self.tc.post("/mcp", content="x", headers=evil).status_code, 200)
same = {"Origin": "http://testserver", "Sec-Fetch-Site": "same-origin"}
self.assertEqual(self.tc.post("/x/ep/a", content="x", headers=same).status_code, 200)
def test_an_endpoints_action_answers_http_only(self):
# Its payload says who the browser is — the host's word. Through the
# action routes it would be the caller's own: a guest granted the
# plugin posting "the caller is the owner" to the consent handler.
forged = {"trigger": "endpoint", "endpoint": "page",
"request": {"method": "POST", "rest": "a", "caller": {"uid": "owner", "isOwner": True}}}
u = DEPS.users.create("dom@example.com", "Dom")
self.addCleanup(DEPS.users.delete, u["id"])
self.store.set_grant(u["id"], "ep", enabled=True)
g = TestClient(main.app, base_url="https://guest.example.test")
g.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(u["id"]))
self.assertEqual(g.get("/api/plugins").status_code, 200) # the plugin is theirs…
r = g.post("/api/plugins/ep/actions/http", json=forged,
headers={"Origin": "https://guest.example.test"})
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (403, "endpoint_only"))
# …and the owner's own call is no different: only the dispatcher runs it
r = self.tc.post("/api/plugins/ep/actions/http", json=forged, headers=OWNER_H)
self.assertEqual(r.status_code, 403)
r = self.tc.post("/proxy/tools/plugins/ep/actions/http", json=forged, headers=self.token())
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (403, "endpoint_only"))
# …nor do the read doors (a GET, a batch read), even for an action marked readOnly
td = pathlib.Path(self.td.name)
self.store.install(OWNER_UID, str(_write(td / "ro", {
"actions": {"http": {"script": "h.py", "readOnly": True}},
"endpoints": [{"id": "page", "path": "/x/ro/*", "action": "http"}],
"capabilities": []}, pid="ro")), is_owner=True, approve=True)
self.store.set_grant(u["id"], "ro", enabled=True)
r = g.get("/api/plugins/ro/actions/http", params={"payload": json.dumps(forged)})
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (403, "endpoint_only"))
r = g.post("/api/plugins/batch-read", headers={"Origin": "https://guest.example.test"},
json={"items": [{"key": "k", "pluginId": "ro", "action": "http", "payload": forged}]})
self.assertEqual(r.status_code, 200, r.text)
self.assertNotIn("payload", json.dumps(r.json()["results"]["k"]))
self.assertEqual((r.json()["results"]["k"]["ok"], r.json()["results"]["k"]["status"]), (False, 403))
def test_two_plugins_one_path(self):
td = pathlib.Path(self.td.name)
self.store.install(OWNER_UID, str(_write(td / "src2", {
"endpoints": [{"id": "mcp", "path": "/mcp", "methods": ["POST"], "action": "http"}],
"capabilities": []}, pid="aa")), is_owner=True, approve=True)
endpoints._registry = None
self.assertEqual(self.tc.post("/mcp", content="x").json()["payload"]["endpoint"], "mcp")
self.assertEqual(endpoints.shadowed_for(DEPS, "ep"),
[{"plugin": "ep", "endpoint": "mcp", "path": "/mcp", "by": "aa"}])
info = self.tc.get("/api/plugins/ep/info", headers=OWNER_H).json()
self.assertEqual(info["shadowedEndpoints"][0]["by"], "aa")
self.assertEqual(len(info["endpoints"]), 5)
class TestHubApi(_WithPlugin):
def setUp(self):
super().setUp()
# the bridge calls the hub's own API over loopback: in-process here
client = httpx.AsyncClient(transport=httpx.ASGITransport(app=main.app),
base_url="http://127.0.0.1:8080")
p = patch.object(hubapi, "_http", lambda: client)
p.start()
self.addCleanup(p.stop)
self.url = "/proxy/tools/plugins/ep/hub"
def test_only_the_plugins_own_handlers_with_the_capability(self):
self.assertEqual(self.tc.get(f"{self.url}/api/me").status_code, 401)
other = {"Authorization": "Bearer " + access.mint_handler(OWNER_UID, "other", ttl=600)}
self.assertEqual(self.tc.get(f"{self.url}/api/me", headers=other).status_code, 403)
td = pathlib.Path(self.td.name)
self.store.install(OWNER_UID, str(_write(td / "nocap", {"capabilities": [], "endpoints": []},
pid="nocap")), is_owner=True, approve=True)
tok = {"Authorization": "Bearer " + access.mint_handler(OWNER_UID, "nocap", ttl=600)}
r = self.tc.get("/proxy/tools/plugins/nocap/hub/api/me", headers=tok)
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (403, "capability"))
def test_the_owner_as_his_cli_is(self):
r = self.tc.get(f"{self.url}/api/me", headers=self.token())
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(r.json()["role"], "owner")
def test_as_a_guest_only_while_the_plugin_is_theirs(self):
u = DEPS.users.create("dom@example.com", "Dom")
self.addCleanup(DEPS.users.delete, u["id"])
h = {**self.token(), "X-AIA-As-User": u["id"]}
r = self.tc.get(f"{self.url}/api/me", headers=h)
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (403, "not_granted"))
self.store.set_grant(u["id"], "ep", enabled=True)
me = self.tc.get(f"{self.url}/api/me", headers=h)
self.assertEqual((me.status_code, me.json()["id"], me.json()["role"]), (200, u["id"], "guest"))
# the CLI's routes, nothing wider: a guest's settings stay their browser's
self.assertEqual(self.tc.get(f"{self.url}/api/users", headers=h).status_code, 403)
self.assertEqual(self.tc.get(f"{self.url}/api/ui-state/x", headers=h).status_code, 403)
with patch.object(DEPS.security_state, "guests_locked", lambda: True):
r = self.tc.get(f"{self.url}/api/me", headers=h)
self.assertEqual(r.json()["detail"]["kind"], "guests_locked")
gone = self.tc.get(f"{self.url}/api/me", headers={**self.token(), "X-AIA-As-User": "nobody"})
self.assertEqual((gone.status_code, gone.json()["detail"]["kind"]), (403, "guest_gone"))
# disabled may come back (the plugin keeps their connections); gone never does
DEPS.users.update(u["id"], {"disabled": True})
self.assertEqual(self.tc.get(f"{self.url}/api/me", headers=h).json()["detail"]["kind"],
"guest_disabled")
# sent but empty is a call for nobody — never quietly the owner's
empty = self.tc.get(f"{self.url}/api/me", headers={**self.token(), "X-AIA-As-User": ""})
self.assertEqual(empty.status_code, 400)
def test_the_act_as_header_alone_names_no_plugin(self):
# straight at the API, as a trusted peer: a guest needs the plugin named and theirs
u = DEPS.users.create("dom@example.com", "Dom")
self.addCleanup(DEPS.users.delete, u["id"])
r = self.tc.get("/api/me", headers={**OWNER_H, "X-AIA-As-User": u["id"]})
self.assertEqual(r.status_code, 400)
r = self.tc.get("/api/me", headers={**OWNER_H, "X-AIA-As-User": u["id"], "X-AIA-Via-Plugin": "ep"})
self.assertEqual(r.json()["detail"]["kind"], "not_granted")
# and it is a downgrade only: an untrusted peer gains nothing by sending it
self.assertEqual(self.tc.get("/api/me", headers={"X-AIA-As-User": u["id"],
"X-AIA-Via-Plugin": "ep"}).status_code, 403)
def test_read_only(self):
h = {**self.token(), "X-AIA-Read-Only": "1"}
self.assertEqual(self.tc.get(f"{self.url}/api/me", headers=h).status_code, 200)
r = self.tc.post(f"{self.url}/api/conversation-meta", json={"id": "x"}, headers=h)
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (403, "read_only"))
def test_via_stamps_once(self):
DEPS.meta_store.update(SID, {"title": "t"})
r = self.tc.post(f"{self.url}/via", json={"sessionId": SID, "app": "Claude.ai", "connection": "mcpg_1"},
headers=self.token())
self.assertEqual(r.json()["via"], {"kind": "plugin", "plugin": "ep", "app": "Claude.ai",
"connection": "mcpg_1"})
again = self.tc.post(f"{self.url}/via", json={"sessionId": SID, "app": "Other"}, headers=self.token())
self.assertEqual((again.json()["existing"], DEPS.meta_store.peek(SID)["via"]["app"]), (True, "Claude.ai"))
self.assertEqual(self.tc.post(f"{self.url}/via", json={"sessionId": "nope"},
headers=self.token()).status_code, 400)
missing = "bbbbbbbb-2222-4222-8222-222222222222"
self.assertEqual(self.tc.post(f"{self.url}/via", json={"sessionId": missing},
headers=self.token()).status_code, 404)
from telemetry.views import run_origin
self.assertEqual(run_origin(DEPS.meta_store.peek(SID)), "mcp")
class TestSignals(_WithPlugin):
url = "/proxy/tools/plugins/ep/hub"
def test_an_ask_is_its_plugins(self):
r = self.tc.post(f"{self.url}/ask", headers=self.token(), json={
"question": "Claude.ai wants full access. Tap the number.", "options": ["12", "57", "83"],
"url": "https://admin.example.test/x/ep/connect/r1", "type": "auth", "timeoutSecs": 900})
self.assertEqual(r.status_code, 200, r.text)
aid = r.json()["id"]
self.assertEqual(DEPS.notify_store.get(aid)["plugin"], "ep")
st = self.tc.get(f"{self.url}/ask/{aid}", headers=self.token()).json()
self.assertEqual((st["status"], st["answer"]), ("pending", None))
DEPS.notify_store.answer_ask(aid, 1, None)
st = self.tc.get(f"{self.url}/ask/{aid}", headers=self.token()).json()
self.assertEqual((st["status"], st["answer"]), ("answered", "57"))
# somebody else's ask — an agent's question — is not this plugin's to read or close
other = DEPS.notify_store.create_ask("Deploy?", ["Yes", "No"])["id"]
self.assertEqual(self.tc.get(f"{self.url}/ask/{other}", headers=self.token()).status_code, 404)
self.assertEqual(self.tc.post(f"{self.url}/ask/{other}/close", json={}, headers=self.token()).status_code, 404)
self.assertEqual(DEPS.notify_store.ask_status(other)["status"], "pending")
def test_closing_an_ask_answered_elsewhere(self):
aid = self.tc.post(f"{self.url}/ask", headers=self.token(),
json={"question": "Q", "options": ["1", "2"]}).json()["id"]
r = self.tc.post(f"{self.url}/ask/{aid}/close", json={"note": "Allowed on the admin host"},
headers=self.token())
self.assertEqual(r.status_code, 200)
ask = DEPS.notify_store.ask_status(aid)
self.assertEqual((ask["status"], ask["answer"]), ("answered", "Allowed on the admin host"))
def test_bad_asks(self):
for body in ({"question": "", "options": ["a", "b"]}, {"question": "q", "options": ["a"]},
{"question": "q", "options": ["a", "b", "c", "d"]}, {"question": "q"}):
self.assertEqual(self.tc.post(f"{self.url}/ask", json=body, headers=self.token()).status_code, 400)
def test_a_security_line(self):
r = self.tc.post(f"{self.url}/security", headers=self.token(), json={
"event": "connected", "detail": "Claude.ai (full) → claude.ai", "who": "owner",
"ip": "203.0.113.7", "push": True})
self.assertEqual(r.status_code, 200, r.text)
ev = DEPS.security_log.events(limit=1)[0]
self.assertEqual((ev["kind"], ev["detail"], ev["who"], ev["ip"]),
("plugin_event", "Ep: Claude.ai (full) → claude.ai", "owner", "203.0.113.7"))
self.assertEqual(ev["data"], {"plugin": "ep", "event": "connected"})
self.assertEqual(self.tc.post(f"{self.url}/security", json={"event": "Bad Event"},
headers=self.token()).status_code, 400)
def test_the_push_is_the_owners_choice(self):
pushed = []
with patch("security.service._push", lambda deps, ev: pushed.append(ev["kind"])):
body = {"event": "connected", "detail": "d", "push": True}
self.tc.post(f"{self.url}/security", json=body, headers=self.token())
self.assertEqual(pushed, []) # not among his kinds
DEPS.security_state.set_push_kinds(["plugin_event"])
self.addCleanup(DEPS.security_state.set_push_kinds, [])
self.tc.post(f"{self.url}/security", json=body, headers=self.token())
self.tc.post(f"{self.url}/security", json={**body, "push": False}, headers=self.token())
self.assertEqual(pushed, ["plugin_event"])
class TestCarryOver(unittest.TestCase):
OLD = {
"clients": {"mcpc_1": {"name": "Claude", "redirectUris": ["https://claude.ai/cb"]}},
"pending": {"mcpr_1": {"client": "mcpc_1"}}, "codes": {"h": {"grant": "x"}},
"grants": {"mcpg_own": {"id": "mcpg_own", "user": "owner", "name": "Claude", "scope": "full"},
"mcpg_mac": {"id": "mcpg_mac", "user": "owner", "name": "Claude Code",
"scope": "full", "worker": "orus"},
"mcpg_dom": {"id": "mcpg_dom", "user": "dom", "name": "ChatGPT", "scope": "read"}},
"tokens": {"t1": {"grant": "mcpg_own", "kind": "access"},
"t2": {"grant": "mcpg_mac", "kind": "access"},
"t3": {"grant": "mcpg_mac", "kind": "refresh"},
"t4": {"grant": "mcpg_dom", "kind": "refresh"}},
"settings": {"groups": ["read"], "maxWaitS": 40}}
def setUp(self):
self.td = tempfile.TemporaryDirectory()
self.root = pathlib.Path(self.td.name)
self.store = PluginStore(self.root / "data")
self.legacy = self.root / "mcp.json"
self.legacy.write_text(json.dumps(self.OLD))
self.made = []
def tearDown(self):
for uid in self.made:
DEPS.users.delete(uid)
self.td.cleanup()
def _guest(self, email, **kw):
u = DEPS.users.create(email, email.split("@")[0], **kw)
self.made.append(u["id"])
return u["id"]
def _install(self):
self.store.install(OWNER_UID, str(_write(self.root / "src", {"endpoints": []}, pid="hub-mcp")),
is_owner=True, approve=True)
def test_it_waits_for_the_plugin(self):
self.assertFalse(carryover.hub_mcp(self.store, DEPS.users, legacy=str(self.legacy)))
self.assertFalse((self.store.shared_data_dir("hub-mcp") / "mcp.json").exists())
def test_connections_carry_over_but_the_ones_bound_to_a_worker(self):
self._install()
self.assertTrue(carryover.hub_mcp(self.store, None, legacy=str(self.legacy)))
dst = self.store.shared_data_dir("hub-mcp") / "mcp.json"
out = json.loads(dst.read_text())
self.assertEqual(sorted(out["grants"]), ["mcpg_dom", "mcpg_own"])
self.assertEqual(sorted(out["tokens"]), ["t1", "t4"]) # the bound one's tokens went with it
self.assertEqual((out["pending"], out["codes"]), ({}, {}))
self.assertEqual((out["clients"], out["settings"]), (self.OLD["clients"], self.OLD["settings"]))
self.assertEqual(dst.stat().st_mode & 0o777, 0o600)
self.assertTrue(self.legacy.is_file()) # the old file stays
# once: what the plugin has since is never overwritten
dst.write_text(json.dumps({"grants": {}}))
self.assertFalse(carryover.hub_mcp(self.store, None, legacy=str(self.legacy)))
self.assertEqual(json.loads(dst.read_text()), {"grants": {}})
def test_whoever_could_connect_ai_apps_gets_the_grant(self):
self._install()
allowed = self._guest("allow@example.com", allow=["cli.use"])
member = self._guest("member@example.com", role="member")
denied = self._guest("denied@example.com", role="member")
plain = self._guest("plain@example.com")
# the old permission, as the records of before the move carried it
raw = {u["id"]: dict(u) for u in DEPS.users.all()}
raw[allowed]["allow"] = ["mcp.connect"]
raw[denied]["deny"] = ["mcp.connect"]
class Users:
def all(self):
return list(raw.values())
carryover.hub_mcp(self.store, Users(), legacy=str(self.legacy))
on = {uid: bool(self.store.resolve_active_for_caller(uid, "hub-mcp")[0])
for uid in (allowed, member, denied, plain)}
self.assertEqual(on, {allowed: True, member: True, denied: False, plain: False})
class TestRetired(unittest.TestCase):
def test_the_mcp_routes_and_permissions_are_gone(self):
tc = TestClient(main.app)
from authz import routes as authz_routes
for path in ("/api/mcp", "/api/me/ai-apps", "/api/mcp/settings"):
self.assertEqual(authz_routes.matcher(main.app).lookup("GET", path), (None, None), path)
self.assertNotIn("connections", tc.get(path, headers=OWNER_H).text)
from authz import catalog, policy
self.assertNotIn("mcp.connect", catalog.ALL)
self.assertNotIn("mcp.manage", catalog.ALL)
self.assertIn("mcp", policy.RETIRED_SWITCHES)
# nothing answers the MCP paths until a plugin claims them
endpoints._registry = None
self.assertEqual(tc.post("/mcp", content="{}").status_code, 404)
self.assertEqual(tc.get("/.well-known/oauth-authorization-server").status_code, 404)
def test_who_was_pushed_about_connections_is_pushed_about_plugin_events(self):
from security.store import SecurityState
with tempfile.TemporaryDirectory() as td:
p = pathlib.Path(td) / "security.json"
p.write_text(json.dumps({"guestsLocked": False, "pushKinds": ["mcp_connected", "new_device"],
"offered": ["cross_site", "owner_login", "remote_passkey_added",
"remote_passkey_invited"], "devices": {}}))
self.assertEqual(SecurityState(str(p)).get()["pushKinds"], ["new_device", "plugin_event"])
if __name__ == "__main__":
unittest.main()