Files
ai-agent/backend/test_plugin_relay.py
gabrielvidalandClaude Opus 5.5 77a545444f feat(relay): a dial-out worker's public token passes on the guest host
The Orus devbox (a dial-out worker, off the personal tailnet) can't reach
ai-agent.lab: its MCP server through the hub failed with a TLS error.
GET hub/machines now gives a link worker the guest host's tools URL and
public: true; relay tokens carry public (mint / PUT), and the guest host lets
only those through (anything else there, a wrong token included, is a 404).
The owner's internet address still never serves the relay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:06:52 +01:00

377 lines
17 KiB
Python

"""``relay.serve`` (plugins/relay.py, the mcp-servers plugin's hub gateway,
2026-11-26): the plugin's route / token bridges, and the public relay a
machine's harness talks MCP Streamable HTTP through — against a real fake
upstream, so an event stream is seen to arrive event by event."""
from __future__ import annotations
import http.server
import json
import pathlib
import socket
import tempfile
import threading
import time
import types
import unittest
from unittest.mock import patch
import httpx
import uvicorn
from fastapi import FastAPI
from fastapi.testclient import TestClient
import main
from plugins import relay
from plugins.store import OWNER_UID, PluginStore
from toolproxy import access
SECRET = "Bearer s3cr3t-upstream-key"
class Upstream(http.server.ThreadingHTTPServer):
"""A fake MCP server: ``/mcp`` answers ``initialize`` with JSON (and a
session id), ``tools/call`` with an event stream that waits on ``gate``
between its two events; GET is a long-lived stream; ``/denied`` a 401."""
daemon_threads = True
def __init__(self):
super().__init__(("127.0.0.1", 0), UpstreamHandler)
self.gate = threading.Event()
self.seen: list[dict] = []
class UpstreamHandler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *a): # quiet
pass
def _note(self, body=b""):
self.server.seen.append({"method": self.command, "path": self.path,
"headers": {k.lower(): v for k, v in self.headers.items()},
"body": body.decode() if body else ""})
def _json(self, status, obj, extra=None):
raw = json.dumps(obj).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
for k, v in (extra or {}).items():
self.send_header(k, v)
self.end_headers()
self.wfile.write(raw)
def _events(self, first: bytes, second: bytes):
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Mcp-Session-Id", "sess-1")
self.send_header("Connection", "close")
self.end_headers()
self.wfile.write(first)
self.wfile.flush()
self.server.gate.wait(10)
self.wfile.write(second)
self.wfile.flush()
self.close_connection = True
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(n) if n else b""
self._note(body)
if self.path.startswith("/denied"):
self.send_response(401)
self.send_header("WWW-Authenticate", 'Bearer resource_metadata="https://up/.well-known/x"')
self.send_header("Content-Length", "0")
self.end_headers()
return
msg = json.loads(body or b"{}")
if msg.get("method") == "initialize":
self._json(200, {"jsonrpc": "2.0", "id": msg.get("id"), "result": {"ok": True}},
{"Mcp-Session-Id": "sess-1", "MCP-Protocol-Version": "2025-06-18",
"X-Upstream-Secret": "leak"})
return
self._events(b'event: message\ndata: {"n": 1}\n\n', b'event: message\ndata: {"n": 2}\n\n')
def do_GET(self):
self._note()
self._events(b"data: one\n\n", b"data: two\n\n")
def do_DELETE(self):
self._note()
self.send_response(204)
self.end_headers()
def _free_port() -> int:
s = socket.socket()
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close()
return port
class RelayCase(unittest.TestCase):
"""A plugin ``mcpx`` holding ``relay.serve``, installed for the owner."""
caps = ["relay.serve"]
def setUp(self):
self.td = tempfile.TemporaryDirectory()
root = pathlib.Path(self.td.name)
src = root / "src"
src.mkdir()
(src / "plugin.json").write_text(json.dumps(
{"schema": 1, "id": "mcpx", "name": "M", "capabilities": self.caps}))
self.store = PluginStore(root / "plugins")
self.store.install(OWNER_UID, str(src), is_owner=True, approve=True)
self.handler = {"Authorization": f"Bearer {access.mint_handler(OWNER_UID, 'mcpx', ttl=600)}"}
def tearDown(self):
self.td.cleanup()
class TestBridges(RelayCase):
def setUp(self):
super().setUp()
self.p = patch.object(main.app.state.ai, "plugin_store", self.store)
self.p.start()
self.tc = TestClient(main.app)
def tearDown(self):
self.p.stop()
super().tearDown()
def test_a_route_keeps_its_secrets(self):
r = self.tc.put("/proxy/tools/plugins/mcpx/hub/relay/routes/linear", headers=self.handler,
json={"upstream": "https://u:pw@mcp.linear.app/mcp?k=secret",
"headers": {"Authorization": SECRET}})
self.assertEqual(r.status_code, 200, r.text)
listed = self.tc.get("/proxy/tools/plugins/mcpx/hub/relay/routes", headers=self.handler).json()
self.assertEqual([x["name"] for x in listed], ["linear"])
self.assertEqual(listed[0]["upstream"], "https://mcp.linear.app/mcp")
self.assertEqual(listed[0]["headerNames"], ["Authorization"])
self.assertNotIn("s3cr3t", json.dumps(listed) + r.text)
f = self.store.root / "relay" / "mcpx.json"
self.assertEqual(f.stat().st_mode & 0o777, 0o600)
self.assertTrue(self.tc.delete("/proxy/tools/plugins/mcpx/hub/relay/routes/linear",
headers=self.handler).json()["ok"])
self.assertEqual(self.tc.get("/proxy/tools/plugins/mcpx/hub/relay/routes", headers=self.handler).json(), [])
def test_bad_routes_are_refused(self):
for body in ({"upstream": "ftp://x"}, {"upstream": "https://x", "headers": {"Host": "y"}},
{"upstream": "https://x", "headers": {"X": "a\r\nb"}}, {"upstream": "https://x#f"}):
r = self.tc.put("/proxy/tools/plugins/mcpx/hub/relay/routes/x", headers=self.handler, json=body)
self.assertEqual(r.status_code, 400, body)
r = self.tc.put("/proxy/tools/plugins/mcpx/hub/relay/routes/..bad", headers=self.handler,
json={"upstream": "https://x"})
self.assertEqual(r.status_code, 400)
def test_a_token_is_shown_once(self):
r = self.tc.post("/proxy/tools/plugins/mcpx/hub/relay/tokens", headers=self.handler,
json={"label": "Orus devbox", "routes": ["linear"]})
self.assertEqual(r.status_code, 200, r.text)
tok = r.json()
self.assertTrue(tok["token"].startswith(f"aiar1.{tok['id']}."))
listed = self.tc.get("/proxy/tools/plugins/mcpx/hub/relay/tokens", headers=self.handler).json()
self.assertEqual(listed[0]["id"], tok["id"])
self.assertEqual(listed[0]["routes"], ["linear"])
self.assertNotIn(tok["token"].split(".")[2], json.dumps(listed))
raw = (self.store.root / "relay" / "mcpx.json").read_text()
self.assertNotIn(tok["token"], raw)
r = self.tc.put(f"/proxy/tools/plugins/mcpx/hub/relay/tokens/{tok['id']}", headers=self.handler,
json={"routes": ["linear", "sentry"]})
self.assertEqual(r.json()["token"]["routes"], ["linear", "sentry"])
self.assertEqual(self.tc.put("/proxy/tools/plugins/mcpx/hub/relay/tokens/0123456789abcdef",
headers=self.handler, json={"label": "x"}).status_code, 404)
self.assertTrue(self.tc.delete(f"/proxy/tools/plugins/mcpx/hub/relay/tokens/{tok['id']}",
headers=self.handler).json()["ok"])
def test_only_the_plugins_own_handlers(self):
guest = {"Authorization": f"Bearer {access.mint_handler('cel', 'mcpx', ttl=600)}"}
other = {"Authorization": f"Bearer {access.mint_handler(OWNER_UID, 'other', ttl=600)}"}
for h in (guest, other, {}):
r = self.tc.get("/proxy/tools/plugins/mcpx/hub/relay/routes", headers=h)
self.assertIn(r.status_code, (401, 403, 404), r.text)
class TestBridgesWithoutTheCapability(RelayCase):
caps = []
def test_refused(self):
with patch.object(main.app.state.ai, "plugin_store", self.store):
r = TestClient(main.app).get("/proxy/tools/plugins/mcpx/hub/relay/routes", headers=self.handler)
self.assertEqual(r.status_code, 403)
class TestPublicRelay(RelayCase):
"""The relay served by a real uvicorn (so its streaming is the server's)."""
@classmethod
def make_app(cls):
app = FastAPI()
app.include_router(relay.router)
app.state.ai = types.SimpleNamespace(plugin_store=None, hub=types.SimpleNamespace(publish=lambda e: None))
return app
@classmethod
def setUpClass(cls):
cls.up = Upstream()
threading.Thread(target=cls.up.serve_forever, daemon=True).start()
cls.app = cls.make_app()
cls.port = _free_port()
cls.server = uvicorn.Server(uvicorn.Config(cls.app, host="127.0.0.1", port=cls.port,
lifespan="off", log_level="warning"))
threading.Thread(target=cls.server.run, daemon=True).start()
for _ in range(200):
if cls.server.started:
break
time.sleep(0.02)
@classmethod
def tearDownClass(cls):
cls.server.should_exit = True
cls.up.shutdown()
def setUp(self):
super().setUp()
self.ps = patch.object(self.app.state.ai, "plugin_store", self.store)
self.ps.start()
self.addCleanup(self.ps.stop)
self.up.gate.clear()
self.up.seen.clear()
st = relay.store_for(self.app.state.ai)
base = f"http://127.0.0.1:{self.up.server_address[1]}"
st.put_route("mcpx", "linear", f"{base}/mcp", {"Authorization": SECRET})
st.put_route("mcpx", "denied", f"{base}/denied", {})
self.tok = st.mint("mcpx", "lab", ["linear", "denied"])["token"]
self.url = f"http://127.0.0.1:{self.port}/proxy/tools/relay/mcpx"
self.h = {"Authorization": f"Bearer {self.tok}", "Accept": "application/json, text/event-stream",
"Content-Type": "application/json"}
def test_a_json_answer_passes_back_its_session(self):
r = httpx.post(f"{self.url}/linear", headers={**self.h, "X-Other": "nope", "Cookie": "c=1"},
json={"jsonrpc": "2.0", "id": 1, "method": "initialize"}, timeout=10)
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(r.json()["result"], {"ok": True})
self.assertEqual(r.headers["mcp-session-id"], "sess-1")
self.assertEqual(r.headers["mcp-protocol-version"], "2025-06-18")
self.assertNotIn("x-upstream-secret", r.headers)
seen = self.up.seen[-1]["headers"]
self.assertEqual(seen["authorization"], SECRET) # the route's, not the caller's
self.assertNotIn("x-other", seen)
self.assertNotIn("cookie", seen)
self.assertEqual(seen.get("accept-encoding"), "identity")
self.assertEqual(relay.store_for(self.app.state.ai).routes("mcpx")[1]["lastStatus"], 200)
def test_an_event_stream_arrives_event_by_event(self):
with httpx.Client(timeout=httpx.Timeout(5.0)) as c:
with c.stream("POST", f"{self.url}/linear", headers={**self.h, "Mcp-Session-Id": "sess-1"},
json={"jsonrpc": "2.0", "id": 2, "method": "tools/call"}) as r:
self.assertEqual(r.status_code, 200)
self.assertTrue(r.headers["content-type"].startswith("text/event-stream"))
self.assertEqual(r.headers.get("x-accel-buffering"), "no")
self.assertNotIn("content-encoding", r.headers)
lines = r.iter_lines()
got = [next(lines), next(lines)]
# the upstream is still holding its second event back: what
# came is the first one alone, not a buffered whole
self.assertEqual(got, ["event: message", 'data: {"n": 1}'])
self.assertFalse(self.up.gate.is_set())
self.up.gate.set()
rest = [x for x in lines if x]
self.assertEqual(rest, ["event: message", 'data: {"n": 2}'])
self.assertEqual(self.up.seen[-1]["headers"]["mcp-session-id"], "sess-1")
def test_a_get_stream_and_a_delete(self):
with httpx.Client(timeout=httpx.Timeout(5.0)) as c:
with c.stream("GET", f"{self.url}/linear/sub/path?cursor=7",
headers={**self.h, "Accept": "text/event-stream", "Last-Event-ID": "41"}) as r:
self.assertEqual(r.status_code, 200)
first = next(r.iter_lines())
self.assertEqual(first, "data: one")
self.up.gate.set()
seen = self.up.seen[-1]
self.assertEqual((seen["method"], seen["path"]), ("GET", "/mcp/sub/path?cursor=7"))
self.assertEqual(seen["headers"]["last-event-id"], "41")
r = httpx.delete(f"{self.url}/linear", headers={**self.h, "Mcp-Session-Id": "sess-1"}, timeout=10)
self.assertEqual(r.status_code, 204)
self.assertEqual(self.up.seen[-1]["method"], "DELETE")
def test_an_upstream_401_is_the_relays_own_403(self):
# 403, never 401: a 401 sends an MCP client looking for the hub's own OAuth
r = httpx.post(f"{self.url}/denied", headers=self.h, json={"method": "initialize"}, timeout=10)
self.assertEqual(r.status_code, 403)
self.assertNotIn("www-authenticate", r.headers)
self.assertEqual(r.json()["error"], "relay_unauthorized")
self.assertIn("sign in again", r.json()["message"])
def test_a_wrong_token_or_route_is_refused(self):
body = {"method": "initialize"}
bad = {**self.h, "Authorization": f"Bearer {self.tok[:-2]}xx"}
self.assertEqual(httpx.post(f"{self.url}/linear", headers=bad, json=body).status_code, 403)
no = {k: v for k, v in self.h.items() if k != "Authorization"}
self.assertEqual(httpx.post(f"{self.url}/linear", headers=no, json=body).status_code, 403)
# a token that doesn't list the route
only = relay.store_for(self.app.state.ai).mint("mcpx", "x", ["denied"])["token"]
r = httpx.post(f"{self.url}/linear", headers={**self.h, "Authorization": f"Bearer {only}"}, json=body)
self.assertEqual(r.status_code, 403)
# a route the token lists but nobody made
st = relay.store_for(self.app.state.ai)
ghost = st.mint("mcpx", "x", ["ghost"])["token"]
r = httpx.post(f"{self.url}/ghost", headers={**self.h, "Authorization": f"Bearer {ghost}"}, json=body)
self.assertEqual(r.status_code, 404)
# another plugin's path
r = httpx.post(f"http://127.0.0.1:{self.port}/proxy/tools/relay/other/linear", headers=self.h, json=body)
self.assertEqual(r.status_code, 403)
self.assertEqual(len([s for s in self.up.seen if s["method"] == "POST"]), 0)
def test_a_disabled_plugin_has_no_relay(self):
self.store.update(OWNER_UID, "mcpx", enabled=False)
r = httpx.post(f"{self.url}/linear", headers=self.h, json={"method": "initialize"})
self.assertEqual(r.status_code, 404)
def test_the_guest_host_gets_a_404(self):
with patch("users.caller.GUEST_HOSTS", {"ai-agent.example"}):
r = httpx.post(f"{self.url}/linear", headers={**self.h, "Host": "ai-agent.example"},
json={"method": "initialize"})
self.assertEqual(r.status_code, 404)
self.assertEqual(self.up.seen, [])
def test_a_dial_out_workers_public_token_passes_on_the_guest_host_only(self):
st = relay.store_for(self.app.state.ai)
pub = st.mint("mcpx", "devbox", ["linear"], public=True)["token"]
h = {**self.h, "Authorization": f"Bearer {pub}"}
body = {"jsonrpc": "2.0", "id": 1, "method": "initialize"}
with patch("users.caller.GUEST_HOSTS", {"ai-agent.example"}):
r = httpx.post(f"{self.url}/linear", headers={**h, "Host": "ai-agent.example"},
json=body, timeout=10)
self.assertEqual(r.status_code, 200, r.text)
# a wrong token there is a 404 too: the guest host shows nothing
bad = {**h, "Host": "ai-agent.example", "Authorization": f"Bearer {pub[:-2]}xx"}
self.assertEqual(httpx.post(f"{self.url}/linear", headers=bad, json=body).status_code, 404)
with patch("users.caller.OWNER_HOSTS", {"hub.example"}):
r = httpx.post(f"{self.url}/linear", headers={**h, "Host": "hub.example"}, json=body)
self.assertEqual(r.status_code, 404)
self.assertTrue([t for t in st.tokens("mcpx") if t["label"] == "devbox"][0]["public"])
tid = [t for t in st.tokens("mcpx") if t["label"] == "devbox"][0]["id"]
st.update_token("mcpx", tid, public=False)
with patch("users.caller.GUEST_HOSTS", {"ai-agent.example"}):
r = httpx.post(f"{self.url}/linear", headers={**h, "Host": "ai-agent.example"}, json=body)
self.assertEqual(r.status_code, 404)
class TestPublicRelayThroughTheApp(TestPublicRelay):
"""The same, through the whole app — its middlewares (the gate, the
request metrics) must not buffer an event stream either."""
@classmethod
def make_app(cls):
return main.app
if __name__ == "__main__":
unittest.main()