Files
ai-agent/backend/test_mcp.py

771 lines
42 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The hub as an MCP server (mcpserver/): OAuth 2.1 with dynamic registration
and PKCE, the owner's approval (admin host or push), a guest's own, and the
``/mcp`` tools reaching the API as the connection's caller — never more.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import base64
import hashlib
import os
import pathlib
import secrets
import tempfile
import unittest
import urllib.parse
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",
"MCP_PATH": TMP / "mcp.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",
"MCP_PUBLIC_URL": "https://claude.example.test",
"AI_AGENT_VIEW_URL": "https://admin.example.test",
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
os.environ[k] = str(v)
for slug in ("film", "secret"):
(TMP / "projects" / slug).mkdir(parents=True)
from fastapi.testclient import TestClient # noqa: E402
import conversations.routes as conv_routes # noqa: E402
import main # noqa: E402
import runs.routes as run_routes # noqa: E402
from mcpserver import routes as mroutes # noqa: E402
from mcpserver import tools as mtools # noqa: E402
from users import deliver # noqa: E402
from users.caller import SESSION_COOKIE # noqa: E402
DEPS = main.app.state.ai
OWNER_H = {"X-Internal-Auth": "tok"}
GUEST_HOST = "https://claude.example.test"
REDIRECT = "https://claude.ai/api/mcp/auth_callback"
class _TestHub(mtools.aa.Hub):
"""The tools' loopback hub, through the TestClient (still a trusted
caller to the gate: the internal token stands in for loopback)."""
def call(self, method, path, body=None, query=None, timeout=30):
q = {k: v for k, v in (query or {}).items() if v not in (None, "")}
r = TestClient(main.app).request(method, path, params=q, json=body,
headers={**OWNER_H, **self.headers})
if r.status_code >= 400:
raise mtools.aa.HubError(r.status_code, mtools.aa._detail(r.text))
return r.json() if r.text else {}
def _card(sid, **meta):
return {"id": f"-p/{sid}.jsonl", "sessionId": sid, "endedAt": "2026-10-10T00:00:00Z",
"cost": 1.0, "meta": {"archived": False, "state": "finished", **meta}}
def _pkce():
verifier = secrets.token_urlsafe(48)
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()
).rstrip(b"=").decode()
return verifier, challenge
class Mcp(unittest.TestCase):
def setUp(self):
for u in DEPS.users.all():
DEPS.users.delete(u["id"])
DEPS.security_state.set_locked(False)
DEPS.mcp._data = {k: {} for k in ("clients", "pending", "codes", "grants", "tokens",
"settings")}
mroutes._pushes.clear()
mroutes._registrations.clear()
self.dom = DEPS.users.create("dom@example.com", "Dom", mcp=True,
projects={"film": "chat"}, models=["sonnet"])
self.claire = DEPS.users.create("claire@example.com", "Claire",
projects={"secret": "chat"})
self.pub = TestClient(main.app, base_url=GUEST_HOST)
orig = mtools.hub_for
mtools.hub_for = lambda grant, headers=None: (
type("RO", (mtools.ReadOnlyHub, _TestHub), {})
if grant.get("scope") == "read" else _TestHub)(base="http://t", headers=headers)
self.addCleanup(setattr, mtools, "hub_for", orig)
# Conversations: one of the owner's, one of Dom's.
cards = [_card(str(uuid.uuid4()), title="owner work"),
_card(str(uuid.uuid4()), title="dom work", owner="dom", projects=["film"])]
orig_cards = conv_routes._conversation_cards
conv_routes._conversation_cards = lambda deps, full: cards
self.addCleanup(setattr, conv_routes, "_conversation_cards", orig_cards)
# ── helpers ──────────────────────────────────────────────────────────────
def register(self, uris=(REDIRECT,), method="none"):
r = self.pub.post("/oauth/register", json={"client_name": "Claude",
"redirect_uris": list(uris),
"token_endpoint_auth_method": method})
self.assertEqual(r.status_code, 201, r.text)
return r.json()
def authorize(self, client, challenge, scope=""):
r = self.pub.get("/oauth/authorize", params={
"response_type": "code", "client_id": client["client_id"],
"redirect_uri": REDIRECT, "state": "st8", "code_challenge": challenge,
"code_challenge_method": "S256", "scope": scope,
"resource": "https://claude.example.test/mcp"}, follow_redirects=False)
self.assertEqual(r.status_code, 302, r.text)
loc = r.headers["location"]
self.assertTrue(loc.startswith("/connect/"), loc)
return loc.split("/connect/", 1)[1]
def code_of(self, redirect):
q = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(redirect).query))
self.assertEqual(q.get("state"), "st8")
return q["code"]
def exchange(self, client, code, verifier):
return self.pub.post("/oauth/token", data={
"grant_type": "authorization_code", "code": code, "redirect_uri": REDIRECT,
"client_id": client["client_id"], "code_verifier": verifier})
def owner_token(self, scope="full"):
client = self.register()
verifier, challenge = _pkce()
rid = self.authorize(client, challenge)
r = TestClient(main.app).post(f"/api/mcp/pending/{rid}", headers=OWNER_H,
json={"approve": True, "scope": scope})
self.assertEqual(r.status_code, 200, r.text)
t = self.exchange(client, self.code_of(r.json()["redirect"]), verifier)
self.assertEqual(t.status_code, 200, t.text)
return client, t.json()
def from_ip(self, ip):
"""Requests now come from ``ip`` (the per-address caps)."""
orig = mroutes._ip
mroutes._ip = lambda request: ip
self.addCleanup(setattr, mroutes, "_ip", orig)
def no_delivery(self):
orig = deliver.recipients
deliver.recipients = lambda *a, **kw: []
self.addCleanup(setattr, deliver, "recipients", orig)
def push(self, rid, scope="full"):
"""Ask for the phone approval: (the page's answer, the ask it raised)."""
r = self.pub.post(f"/oauth/consent/{rid}", json={"action": "push", "scope": scope})
self.assertEqual(r.status_code, 200, r.text)
return r.json(), DEPS.notify_store.get(DEPS.mcp.pending(rid)["askId"])
def refresh(self, client, token):
return self.pub.post("/oauth/token", data={"grant_type": "refresh_token",
"refresh_token": token,
"client_id": client["client_id"]})
def rpc(self, token, method, params=None, mid=1):
r = self.pub.post("/mcp", headers={"Authorization": f"Bearer {token}"},
json={"jsonrpc": "2.0", "id": mid, "method": method,
"params": params or {}})
return r
def tool(self, token, name, **args):
r = self.rpc(token, "tools/call", {"name": name, "arguments": args})
self.assertEqual(r.status_code, 200, r.text)
return r.json()
# ── discovery ────────────────────────────────────────────────────────────
def test_discovery_points_at_the_public_host(self):
pr = self.pub.get("/.well-known/oauth-protected-resource/mcp").json()
self.assertEqual(pr["resource"], "https://claude.example.test/mcp")
meta = self.pub.get("/.well-known/oauth-authorization-server",
headers={"Host": "evil.example"}).json()
self.assertEqual(meta["token_endpoint"], "https://claude.example.test/oauth/token")
self.assertEqual(meta["code_challenge_methods_supported"], ["S256"])
def test_mcp_without_a_token_is_a_401_challenge(self):
r = self.pub.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"})
self.assertEqual(r.status_code, 401)
self.assertIn('resource_metadata="https://claude.example.test/.well-known/'
'oauth-protected-resource/mcp"', r.headers["www-authenticate"])
r = self.rpc("aia_mcp_nope", "tools/list")
self.assertEqual(r.status_code, 401)
self.assertIn('error="invalid_token"', r.headers["www-authenticate"])
# ── registration + authorize ─────────────────────────────────────────────
def test_registration_refuses_dangerous_redirects(self):
for bad in ("javascript:alert(1)", "http://evil.example/cb", "https://x/cb#frag"):
r = self.pub.post("/oauth/register", json={"redirect_uris": [bad]})
self.assertEqual(r.status_code, 400, bad)
for ok in ("http://127.0.0.1:3333/cb", "http://localhost/cb", "http://[::1]:8123/cb",
"cursor://anysphere/oauth", "com.example.app:/oauth",
"https://claude.ai/api/mcp/auth_callback?x=1"):
self.assertEqual(self.pub.post("/oauth/register",
json={"redirect_uris": [ok]}).status_code, 201, ok)
def test_registration_refuses_a_redirect_two_parsers_read_two_ways(self):
# `\` is `/` to a browser: these go to evil.example, while urlsplit
# says claude.ai / localhost — the page would vouch for the wrong host.
for bad in ("https://evil.example\\@claude.ai/cb",
"http://evil.example\\@localhost/cb",
"https://claude.ai@evil.example/cb", # userinfo
"https://user:pw@claude.ai/cb",
"https://claude.ai/\tcb", "https://claude.ai/c b", "https://claude.ai/cb\n",
" https://claude.ai/cb",
"https://CLAUDE.ai/cb", "https://clаude.ai/cb", # upper case; a Cyrillic а
"https://claude.ai:x/cb", "https:///cb", "https://claude.ai\\.evil.example/cb",
"JavaScript:alert(1)", "cursor://a\\@b/cb", "cursor://u@h/cb"):
r = self.pub.post("/oauth/register", json={"redirect_uris": [bad]})
self.assertEqual(r.status_code, 400, repr(bad))
self.assertFalse(mroutes._redirect_ok(bad), repr(bad))
def test_an_old_registration_with_a_bad_redirect_gets_no_request(self):
bad = "https://evil.example\\@claude.ai/cb"
cid, _ = DEPS.mcp.register(name="Claude", redirect_uris=[bad], auth_method="none")
r = self.pub.get("/oauth/authorize", params={
"response_type": "code", "client_id": cid, "redirect_uri": bad,
"code_challenge": _pkce()[1], "code_challenge_method": "S256"},
follow_redirects=False)
self.assertEqual(r.status_code, 400)
self.assertEqual(DEPS.mcp.pending_list(), [])
def test_registration_and_token_bodies_are_capped(self):
big = "x" * (mroutes.MAX_REGISTER_BODY + 1)
r = self.pub.post("/oauth/register", json={"redirect_uris": [REDIRECT], "pad": big})
self.assertEqual(r.status_code, 413)
client = self.register()
r = self.pub.post("/oauth/token", data={"grant_type": "refresh_token",
"refresh_token": "x" * mroutes.MAX_TOKEN_BODY,
"client_id": client["client_id"]})
self.assertEqual(r.status_code, 413)
r = self.pub.post("/oauth/revoke", data={"token": "x" * mroutes.MAX_TOKEN_BODY})
self.assertEqual(r.status_code, 413)
def test_registrations_are_capped_per_address(self):
self.from_ip("203.0.113.9")
codes = [self.pub.post("/oauth/register", json={"redirect_uris": [REDIRECT]}).status_code
for _ in range(mroutes.REG_PER_IP + 1)]
self.assertEqual(codes, [201] * mroutes.REG_PER_IP + [429])
self.from_ip("203.0.113.10") # somebody else still registers
self.register()
def test_authorize_never_redirects_to_an_unregistered_uri(self):
client = self.register()
_, challenge = _pkce()
r = self.pub.get("/oauth/authorize", params={
"response_type": "code", "client_id": client["client_id"],
"redirect_uri": "https://evil.example/cb", "code_challenge": challenge,
"code_challenge_method": "S256"}, follow_redirects=False)
self.assertEqual(r.status_code, 400)
r = self.pub.get("/oauth/authorize", params={
"response_type": "code", "client_id": client["client_id"],
"redirect_uri": REDIRECT}, follow_redirects=False)
self.assertEqual(r.status_code, 302)
self.assertIn("error=invalid_request", r.headers["location"]) # no PKCE
def test_an_unknown_address_gets_no_redirect_before_consent(self):
"""Anyone may register any https address: a refused request must not
turn our host into a link that sends a browser there."""
evil = "https://evil.example/cb"
client = self.pub.post("/oauth/register", json={"redirect_uris": [evil]}).json()
for params in ({"response_type": "token"}, # not `code`
{"response_type": "code"}, # no PKCE
{"response_type": "code", "code_challenge": _pkce()[1],
"code_challenge_method": "S256", "resource": "https://other.example"}):
r = self.pub.get("/oauth/authorize", params={
"client_id": client["client_id"], "redirect_uri": evil, **params},
follow_redirects=False)
self.assertEqual(r.status_code, 400, params)
self.assertNotIn("location", r.headers)
# …and a denial on the page sends nobody there either.
r = self.pub.get("/oauth/authorize", params={
"response_type": "code", "client_id": client["client_id"], "redirect_uri": evil,
"code_challenge": _pkce()[1], "code_challenge_method": "S256"},
follow_redirects=False)
rid = r.headers["location"].split("/connect/", 1)[1]
out = self.pub.post(f"/oauth/consent/{rid}", json={"action": "deny"}).json()
self.assertEqual((out["status"], out["redirect"]), ("denied", None))
def test_requests_waiting_are_capped_per_address(self):
client = self.register()
self.from_ip("203.0.113.9")
for _ in range(mroutes.PENDING_PER_IP):
self.authorize(client, _pkce()[1])
r = self.pub.get("/oauth/authorize", params={
"response_type": "code", "client_id": client["client_id"],
"redirect_uri": REDIRECT, "state": "st8", "code_challenge": _pkce()[1],
"code_challenge_method": "S256"}, follow_redirects=False)
self.assertIn("error=temporarily_unavailable", r.headers["location"])
self.from_ip("203.0.113.10") # one address can't lock the owner's own request out
self.authorize(client, _pkce()[1])
# ── the owner's approval ─────────────────────────────────────────────────
def test_the_owner_flow_end_to_end(self):
client, tok = self.owner_token()
self.assertEqual(tok["scope"], "full")
init = self.rpc(tok["access_token"], "initialize",
{"protocolVersion": "2025-06-18", "capabilities": {},
"clientInfo": {"name": "Claude", "version": "1"}}).json()
self.assertEqual(init["result"]["protocolVersion"], "2025-06-18")
names = {t["name"] for t in self.rpc(tok["access_token"], "tools/list")
.json()["result"]["tools"]}
self.assertTrue({"start_conversation", "run_agent", "browse"} <= names)
# Send later is the scheduled-conversations plugin's commands now
self.assertFalse(names & {"schedule_conversation", "cancel_scheduled"})
self.assertEqual(self.rpc(tok["access_token"], "notifications/initialized").status_code,
200)
def test_a_code_works_once_and_only_with_its_verifier(self):
client = self.register()
verifier, challenge = _pkce()
rid = self.authorize(client, challenge)
r = TestClient(main.app).post(f"/api/mcp/pending/{rid}", headers=OWNER_H,
json={"approve": True})
code = self.code_of(r.json()["redirect"])
self.assertEqual(self.exchange(client, code, _pkce()[0]).status_code, 400)
self.assertEqual(self.exchange(client, code, verifier).status_code, 400) # burnt
def test_the_public_host_cannot_approve_for_the_owner(self):
client = self.register()
_, challenge = _pkce()
rid = self.authorize(client, challenge)
r = self.pub.post(f"/api/mcp/pending/{rid}", json={"approve": True})
self.assertEqual(r.status_code, 401)
r = self.pub.post(f"/oauth/consent/{rid}", json={"action": "guest"})
self.assertEqual(r.status_code, 401) # nobody signed in
self.assertEqual(self.pub.get(f"/oauth/consent/{rid}").json()["status"], "pending")
# ── the phone: number matching ───────────────────────────────────────────
def test_the_number_on_the_page_approves_with_the_scope_picked_there(self):
client = self.register()
verifier, challenge = _pkce()
rid = self.authorize(client, challenge)
self.no_delivery()
v, ask = self.push(rid, scope="read")
self.assertTrue(v["pushed"])
self.assertRegex(v["matchNumber"], r"^[1-9][0-9]$")
self.assertEqual(len(set(ask["options"])), 3)
self.assertIn(v["matchNumber"], ask["options"])
self.assertIn("claude.ai", ask["body"])
self.assertIn("read-only", ask["body"])
self.assertNotIn(v["matchNumber"], ask["body"])
# the poll never repeats the number
waiting = self.pub.get(f"/oauth/consent/{rid}").json()
self.assertEqual((waiting["status"], waiting.get("matchNumber")), ("pending", None))
self.assertNotIn(v["matchNumber"], str(self.pub.get(f"/oauth/consent/{rid}").text))
DEPS.notify_store.answer_ask(ask["id"], ask["options"].index(v["matchNumber"]), None)
done = self.pub.get(f"/oauth/consent/{rid}").json()
self.assertEqual(done["status"], "approved")
t = self.exchange(client, self.code_of(done["redirect"]), verifier).json()
self.assertEqual(t["scope"], "read")
def test_a_wrong_number_refuses_and_closes_the_request(self):
client = self.register()
rid = self.authorize(client, _pkce()[1])
self.no_delivery()
v, ask = self.push(rid)
wrong = next(o for o in ask["options"] if o != v["matchNumber"])
DEPS.notify_store.answer_ask(ask["id"], None, wrong)
done = self.pub.get(f"/oauth/consent/{rid}").json()
self.assertEqual(done["status"], "denied")
self.assertIn("error=access_denied", done["redirect"])
self.assertNotIn("code=", done["redirect"])
self.assertEqual(self.pub.get(f"/oauth/consent/{rid}").status_code, 404)
self.assertEqual(DEPS.mcp._data["codes"], {})
def test_only_the_number_approves_never_just_any_answer(self):
"""What approved before: any answer that didn't start with "deny" —
an old button's label, or no label at all (an out-of-range index)."""
for index, label in ((None, "Allow"), (None, "Read only"), (7, None), (None, ""),
(None, "allow 42")):
rid = self.authorize(self.register(), _pkce()[1])
self.no_delivery()
mroutes._pushes.clear()
_, ask = self.push(rid)
DEPS.notify_store.answer_ask(ask["id"], index, label)
done = self.pub.get(f"/oauth/consent/{rid}").json()
self.assertEqual(done["status"], "denied", (index, label))
self.assertEqual(DEPS.mcp._data["codes"], {}, (index, label))
def test_pushes_are_capped_per_address_and_per_day(self):
self.no_delivery()
def push_from(ip):
self.from_ip(ip)
rid = self.authorize(self.register(), _pkce()[1])
return self.pub.post(f"/oauth/consent/{rid}", json={"action": "push"}).status_code
self.assertEqual([push_from("203.0.113.9") for _ in range(mroutes.PUSH_PER_IP + 1)],
[200] * mroutes.PUSH_PER_IP + [429])
# …which leaves room for the owner's own, from his address
self.assertEqual(push_from("198.51.100.7"), 200)
# whoever asks, a few in ten minutes at most
mroutes._pushes.clear()
codes = [push_from(f"203.0.113.{i}") for i in range(mroutes.PUSH_BURST + 1)]
self.assertEqual(codes, [200] * mroutes.PUSH_BURST + [429])
# …and a hard stop per day, however spread out
import time as _t
mroutes._pushes[:] = [(_t.time() - 3600 - i, f"192.0.2.{i}")
for i in range(mroutes.PUSH_DAILY)]
DEPS.mcp._data["pending"].clear()
self.assertEqual(push_from("198.51.100.8"), 429)
def test_an_approval_hands_its_code_to_the_approver_only(self):
"""Somebody who knows the request's id (whoever started it) polls it:
they must never see the code an approval elsewhere minted."""
client = self.register()
verifier, challenge = _pkce()
rid = self.authorize(client, challenge)
seen = []
orig = mroutes._approved
def spy(request, rid_, r, via): # between the decision and the answer
seen.append(self.pub.get(f"/oauth/consent/{rid}").status_code)
self.assertNotIn(rid, DEPS.mcp._data["pending"])
return orig(request, rid_, r, via)
mroutes._approved = spy
self.addCleanup(setattr, mroutes, "_approved", orig)
r = TestClient(main.app).post(f"/api/mcp/pending/{rid}", headers=OWNER_H,
json={"approve": True})
self.assertEqual(seen, [404])
self.assertEqual(self.exchange(client, self.code_of(r.json()["redirect"]),
verifier).status_code, 200)
# a second decision finds nothing
r = TestClient(main.app).post(f"/api/mcp/pending/{rid}", headers=OWNER_H,
json={"approve": True})
self.assertEqual(r.status_code, 409)
def test_the_owner_approval_refuses_a_cross_site_post(self):
rid = self.authorize(self.register(), _pkce()[1])
r = TestClient(main.app).post(f"/api/mcp/pending/{rid}", json={"approve": True},
headers={**OWNER_H, "Origin": "https://evil.example"})
self.assertEqual(r.status_code, 403)
def test_deny_sends_the_app_back_with_access_denied(self):
client = self.register()
_, challenge = _pkce()
rid = self.authorize(client, challenge)
r = self.pub.post(f"/oauth/consent/{rid}", json={"action": "deny"})
self.assertIn("error=access_denied", r.json()["redirect"])
self.assertEqual(self.pub.get(f"/oauth/consent/{rid}").status_code, 404)
# ── scopes, refresh, revoke ──────────────────────────────────────────────
def test_a_read_connection_gets_read_tools_only(self):
_, tok = self.owner_token(scope="read")
tools = self.rpc(tok["access_token"], "tools/list").json()["result"]["tools"]
self.assertTrue(tools and all(t["annotations"]["readOnlyHint"] for t in tools))
r = self.rpc(tok["access_token"], "tools/call",
{"name": "start_conversation", "arguments": {"prompt": "x"}}).json()
self.assertEqual(r["error"]["code"], -32602)
def test_refresh_rolls_and_revoke_ends_it(self):
client, tok = self.owner_token()
r = self.pub.post("/oauth/token", data={"grant_type": "refresh_token",
"refresh_token": tok["refresh_token"],
"client_id": client["client_id"]})
self.assertEqual(r.status_code, 200, r.text)
new = r.json()
self.assertNotEqual(new["access_token"], tok["access_token"])
gid = DEPS.mcp.grants()[0]["id"]
c = TestClient(main.app)
self.assertEqual(c.delete(f"/api/mcp/connections/{gid}", headers=OWNER_H).status_code, 200)
self.assertEqual(self.rpc(new["access_token"], "tools/list").status_code, 401)
r = self.pub.post("/oauth/token", data={"grant_type": "refresh_token",
"refresh_token": new["refresh_token"],
"client_id": client["client_id"]})
self.assertEqual(r.status_code, 400)
def test_revoking_a_refresh_token_ends_the_connection(self):
client, tok = self.owner_token()
self.assertEqual(self.rpc(tok["access_token"], "tools/list").status_code, 200)
self.pub.post("/oauth/revoke", data={"token": tok["refresh_token"]})
self.assertEqual(DEPS.mcp.grants(), [])
self.assertEqual(self.rpc(tok["access_token"], "tools/list").status_code, 401)
def test_revoking_an_access_token_ends_only_that_token(self):
client, tok = self.owner_token()
self.pub.post("/oauth/revoke", data={"token": tok["access_token"]})
self.assertEqual(self.rpc(tok["access_token"], "tools/list").status_code, 401)
self.assertEqual(self.refresh(client, tok["refresh_token"]).status_code, 200)
def _age_rolled(self):
"""The grace a rolled refresh token keeps is over."""
for r in DEPS.mcp._data["tokens"].values():
if r.get("rolledAt"):
r["rolledAt"] -= 3600
def test_a_rolled_refresh_token_used_again_ends_the_connection(self):
"""Two parties hold the chain: the app, and whoever copied a token."""
client, tok = self.owner_token()
new = self.refresh(client, tok["refresh_token"]).json()
# racing requests on the same token are fine for a minute
self.assertEqual(self.refresh(client, tok["refresh_token"]).status_code, 200)
self.assertEqual(self.rpc(new["access_token"], "tools/list").status_code, 200)
self._age_rolled()
self.assertEqual(self.refresh(client, tok["refresh_token"]).status_code, 400)
self.assertEqual(DEPS.mcp.grants(), [])
self.assertEqual(self.rpc(new["access_token"], "tools/list").status_code, 401)
self.assertEqual(self.refresh(client, new["refresh_token"]).status_code, 400)
def test_a_refresh_whose_answer_was_lost_can_be_retried(self):
"""The app never got the new pair (nothing of it was ever used): the
old token is served again, and the pair that went nowhere dies."""
client, tok = self.owner_token()
lost = self.refresh(client, tok["refresh_token"]).json()
self._age_rolled()
again = self.refresh(client, tok["refresh_token"])
self.assertEqual(again.status_code, 200, again.text)
self.assertEqual(self.rpc(lost["access_token"], "tools/list").status_code, 401)
self.assertEqual(self.refresh(client, lost["refresh_token"]).status_code, 400)
self.assertEqual(self.rpc(again.json()["access_token"], "tools/list").status_code, 200)
self.assertEqual(len(DEPS.mcp.grants()), 1)
def test_token_records_per_connection_are_capped(self):
from mcpserver import store as mstore
client, tok = self.owner_token()
last = tok
for _ in range(mstore.MAX_TOKENS_PER_GRANT * 2): # an app rolling in a loop
last = self.refresh(client, last["refresh_token"]).json()
self.assertLessEqual(len(DEPS.mcp._data["tokens"]), mstore.MAX_TOKENS_PER_GRANT)
self.assertEqual(self.rpc(last["access_token"], "tools/list").status_code, 200)
# …or hammering one token inside its grace: the oldest records go,
# that token among them, and the newest pair still works.
codes = [self.refresh(client, last["refresh_token"]) for _ in
range(mstore.MAX_TOKENS_PER_GRANT * 2)]
self.assertLessEqual(len(DEPS.mcp._data["tokens"]), mstore.MAX_TOKENS_PER_GRANT)
newest = [c.json() for c in codes if c.status_code == 200][-1]
self.assertEqual(self.rpc(newest["access_token"], "tools/list").status_code, 200)
self.assertEqual(len(DEPS.mcp.grants()), 1)
def test_a_connection_with_no_user_is_never_the_owners(self):
from mcpserver.caller import mcp_caller
from users.cli import Refused
for uid in ("", " ", None):
with self.assertRaises(Refused):
mcp_caller(DEPS, uid)
self.assertTrue(mcp_caller(DEPS, "owner").is_owner)
_, tok = self.owner_token()
next(iter(DEPS.mcp._data["grants"].values()))["user"] = ""
self.assertEqual(self.rpc(tok["access_token"], "tools/list").status_code, 403)
r = TestClient(main.app).get("/api/cron", headers={**OWNER_H, "X-AIA-MCP-User": ""})
self.assertEqual(r.status_code, 403)
def test_a_confidential_client_must_present_its_secret(self):
client = self.register(method="client_secret_post")
r = self.pub.post("/oauth/token", data={"grant_type": "refresh_token",
"refresh_token": "x",
"client_id": client["client_id"]})
self.assertEqual(r.status_code, 401)
self.assertEqual(r.json()["error"], "invalid_client")
def test_tool_groups_switched_off_disappear(self):
_, tok = self.owner_token()
DEPS.mcp.set_settings({"groups": ["read"]})
self.addCleanup(DEPS.mcp.set_settings, {"groups": ["read", "run", "agents"]})
names = {t["name"] for t in self.rpc(tok["access_token"], "tools/list")
.json()["result"]["tools"]}
self.assertNotIn("start_conversation", names)
self.assertIn("list_conversations", names)
def test_a_spawn_is_stamped_with_the_app(self):
_, tok = self.owner_token()
sid = "44444444-4444-4444-8444-444444444444"
orig = run_routes._send_message
run_routes._send_message = lambda deps, prompt, **kw: {"sessionId": sid, "pid": 1}
self.addCleanup(setattr, run_routes, "_send_message", orig)
out = self.tool(tok["access_token"], "start_conversation", prompt="hello")
self.assertFalse(out["result"]["isError"], out)
self.assertIn(sid, out["result"]["content"][0]["text"])
self.assertEqual(DEPS.meta_store.get(sid)["via"]["app"], "Claude")
from conversations.cards import _conv_meta
self.assertEqual(_conv_meta(DEPS, {"sessionId": sid})["via"]["kind"], "mcp")
# ── bound to a worker (workers/bound.py) ──────────────────────────────────
def bind(self, worker="orus", scope="full"):
"""An owner connection, bound to the Orus Mac (Work): (token, grant id)."""
DEPS.worker_store.put({"id": "orus", "name": "Orus Macbook", "url": "http://w:8790",
"token": "t", "account": "work", "claudeMode": "own"})
DEPS.profile_store.assign_worker(DEPS.worker_store.get("orus"), "work")
self.addCleanup(DEPS.profile_store.forget_worker, "orus")
self.addCleanup(DEPS.worker_store.delete, "orus")
_, tok = self.owner_token(scope=scope)
gid = DEPS.mcp.grants()[0]["id"]
r = TestClient(main.app).patch(f"/api/mcp/connections/{gid}", headers=OWNER_H,
json={"worker": worker})
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual((r.json()["worker"], r.json()["workerName"]), ("orus", "Orus Macbook"))
return tok["access_token"], gid
def work_cards(self):
"""One Work conversation that ran on the Mac, one Personal one."""
self.mac_sid, self.lab_sid = str(uuid.uuid4()), str(uuid.uuid4())
DEPS.meta_store.update(self.mac_sid, {"worker": "orus", "account": "work"})
cards = [_card(self.mac_sid, title="mac work", profile="work", worker="orus"),
_card(self.lab_sid, title="lab personal", profile="personal")]
conv_routes._conversation_cards = lambda deps, full: cards
def test_a_bound_connection_keeps_the_workers_tools(self):
tok, _ = self.bind()
names = {t["name"] for t in self.rpc(tok, "tools/list").json()["result"]["tools"]}
self.assertIn("start_conversation", names)
# no scheduling on a bound connection: no core tool, no plugin tool
self.assertFalse(names & {"inbox", "read_document", "run_agent", "run_cron_job",
"set_cron_job", "work_on_goal", "schedule_conversation",
"cancel_scheduled"})
self.assertFalse({n for n in names if n.startswith("plugin_")})
out = self.tool(tok, "browse", kind="scheduled")["result"]
self.assertTrue(out["isError"])
out = self.tool(tok, "browse", kind="memories")["result"]
self.assertTrue(out["isError"])
out = self.tool(tok, "browse", kind="workers")["result"]
self.assertFalse(out["isError"], out)
def test_a_bound_connection_reads_its_workers_profile_only(self):
tok, _ = self.bind()
self.work_cards()
text = self.tool(tok, "list_conversations")["result"]["content"][0]["text"]
self.assertIn("mac work", text)
self.assertNotIn("lab personal", text)
out = self.tool(tok, "get_conversation", id=self.lab_sid)["result"]
self.assertTrue(out["isError"], out)
def test_a_bound_connection_runs_on_its_worker_only(self):
tok, _ = self.bind()
sid = "55555555-5555-4555-8555-555555555555"
calls = []
orig = run_routes._send_message
run_routes._send_message = lambda deps, prompt, **kw: (
calls.append(kw) or {"sessionId": sid, "pid": 1})
self.addCleanup(setattr, run_routes, "_send_message", orig)
out = self.tool(tok, "start_conversation", prompt="hello")["result"]
self.assertFalse(out["isError"], out)
self.assertEqual(calls[-1]["worker"], "orus")
out = self.tool(tok, "start_conversation", prompt="hello", worker="local")["result"]
self.assertTrue(out["isError"], out)
def test_a_read_only_bound_connection_cannot_start_runs(self):
tok, gid = self.bind(scope="read")
names = {t["name"] for t in self.rpc(tok, "tools/list").json()["result"]["tools"]}
self.assertNotIn("start_conversation", names)
# Even past the tool list, the gate keeps it to its read routes.
grant = DEPS.mcp.grant(gid)
hub = mtools.hub_for(grant, {"x-aia-as-worker": "orus", "x-aia-as-worker-mode": "read"})
with self.assertRaises(mtools.aa.HubError):
hub.post("/api/spawn", {"prompt": "x"})
def test_unbinding_gives_every_profile_back(self):
tok, gid = self.bind()
self.work_cards()
r = TestClient(main.app).patch(f"/api/mcp/connections/{gid}", headers=OWNER_H,
json={"worker": ""})
self.assertEqual((r.status_code, r.json()["worker"]), (200, ""))
text = self.tool(tok, "list_conversations")["result"]["content"][0]["text"]
self.assertIn("lab personal", text)
def test_only_an_owners_connection_binds_and_only_to_his_workers(self):
tok, gid = self.bind()
c = TestClient(main.app)
DEPS.worker_store.put({"id": "guestbox", "name": "Dom's", "owner": "dom",
"url": "http://g", "token": "t"})
self.addCleanup(DEPS.worker_store.delete, "guestbox")
for w in ("guestbox", "nope"):
r = c.patch(f"/api/mcp/connections/{gid}", headers=OWNER_H, json={"worker": w})
self.assertEqual(r.status_code, 400, w)
_, r, client, verifier = self.guest_token(self.dom)
self.exchange(client, self.code_of(r.json()["redirect"]), verifier)
dom_gid = next(g["id"] for g in DEPS.mcp.grants() if g["user"] == self.dom["id"])
r = c.patch(f"/api/mcp/connections/{dom_gid}", headers=OWNER_H, json={"worker": "orus"})
self.assertEqual(r.status_code, 400)
def test_a_bound_connection_whose_worker_is_gone_gets_nothing(self):
tok, _ = self.bind()
DEPS.worker_store.delete("orus")
out = self.tool(tok, "list_conversations")["result"]
self.assertTrue(out["isError"], out)
# ── guests ───────────────────────────────────────────────────────────────
def guest_token(self, user, scope="full"):
client = self.register()
verifier, challenge = _pkce()
rid = self.authorize(client, challenge)
c = TestClient(main.app, base_url=GUEST_HOST)
c.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(user["id"]))
view = c.get(f"/oauth/consent/{rid}").json()
r = c.post(f"/oauth/consent/{rid}", json={"action": "guest", "scope": scope})
return view, r, client, verifier
def test_a_guest_connects_as_themselves(self):
view, r, client, verifier = self.guest_token(self.dom)
self.assertEqual(view["guest"], {"name": "Dom", "allowed": True})
self.assertEqual(r.status_code, 200, r.text)
tok = self.exchange(client, self.code_of(r.json()["redirect"]), verifier).json()
names = {t["name"] for t in self.rpc(tok["access_token"], "tools/list")
.json()["result"]["tools"]}
self.assertIn("start_conversation", names)
self.assertFalse(names & {"run_agent", "past_conversations", "read_document"})
out = self.tool(tok["access_token"], "list_conversations")["result"]
text = out["content"][0]["text"]
self.assertIn("dom work", text)
self.assertNotIn("owner work", text)
out = self.tool(tok["access_token"], "browse", kind="cron")["result"]
self.assertTrue(out["isError"])
def test_a_guest_without_the_switch_cannot_connect(self):
view, r, *_ = self.guest_token(self.claire)
self.assertEqual(view["guest"]["allowed"], False)
self.assertEqual(r.status_code, 403)
def test_switching_a_guest_off_cuts_their_connection(self):
_, r, client, verifier = self.guest_token(self.dom)
tok = self.exchange(client, self.code_of(r.json()["redirect"]), verifier).json()
DEPS.users.update(self.dom["id"], {"mcp": False})
self.assertEqual(self.rpc(tok["access_token"], "tools/list").status_code, 403)
def test_deleting_a_guest_ends_their_connections(self):
self.owner_token()
# (a guest of this test's own: a deleted id is retired for good)
eve = DEPS.users.create("eve@example.com", "Eve", mcp=True,
projects={"film": "chat"}, models=["sonnet"])
_, r, client, verifier = self.guest_token(eve)
tok = self.exchange(client, self.code_of(r.json()["redirect"]), verifier).json()
self.assertEqual(self.rpc(tok["access_token"], "tools/list").status_code, 200)
r = TestClient(main.app).delete(f"/api/users/{eve['id']}", headers=OWNER_H)
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual([g["user"] for g in DEPS.mcp.grants()], ["owner"])
self.assertEqual(self.rpc(tok["access_token"], "tools/list").status_code, 401)
self.assertEqual(self.refresh(client, tok["refresh_token"]).status_code, 400)
def test_a_guest_sees_and_ends_only_their_own_connections(self):
self.owner_token()
_, r, client, verifier = self.guest_token(self.dom)
self.exchange(client, self.code_of(r.json()["redirect"]), verifier)
c = TestClient(main.app, base_url=GUEST_HOST)
c.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(self.dom["id"]))
mine = c.get("/api/me/ai-apps").json()
self.assertEqual(mine["endpoint"], "https://claude.example.test/mcp")
self.assertEqual([g["user"] for g in mine["connections"]], ["dom"])
owners = [g["id"] for g in DEPS.mcp.grants(user="owner")]
self.assertEqual(c.delete(f"/api/me/ai-apps/{owners[0]}").status_code, 404)
gid = mine["connections"][0]["id"]
self.assertEqual(c.delete(f"/api/me/ai-apps/{gid}").status_code, 200)
self.assertEqual(c.get("/api/me/ai-apps").json()["connections"], [])
claire = TestClient(main.app, base_url=GUEST_HOST)
claire.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(self.claire["id"]))
self.assertFalse(claire.get("/api/me/ai-apps").json()["allowed"])
def test_the_header_grants_nothing_to_an_untrusted_caller(self):
r = self.pub.get("/api/conversations", headers={"X-AIA-MCP-User": "owner"})
self.assertEqual(r.status_code, 401)
r = TestClient(main.app).get("/api/projects", headers={**OWNER_H,
"X-AIA-MCP-User": "dom"})
self.assertEqual({p["name"] for p in r.json()["projects"]}, {"film"}, r.text)
r = TestClient(main.app).get("/api/cron", headers={**OWNER_H, "X-AIA-MCP-User": "dom"})
self.assertEqual(r.status_code, 403)
if __name__ == "__main__":
unittest.main()