Files
gabrielvidalandClaude Opus 5.5 ca228531d0 fix(relay): refuse with 403, never 401 — a 401 sends MCP clients to the hub's own OAuth
An MCP client that gets a 401 (even without WWW-Authenticate) looks for
/.well-known/oauth-protected-resource at the hub's origin, which the hub's own
MCP server answers. Every relay refusal (bad token, unlisted route, upstream
signed out) is now a 403 relay_auth / relay_unauthorized; the sidecar probe
reads the relay's message from either status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 21:49:58 +01:00

596 lines
25 KiB
Python

"""mcp_base: the generic half of the machine's MCP servers — the canonical
config, the managed store, apply / approve against an adapter, the listing
cache and report, the pty sign-in, the probes. No harness here: a fake
adapter stands in (the real ones are the harness plugins', tested there)."""
import hashlib
import http.server
import json
import os
import sys
import threading
import time
import pytest
from fastapi import HTTPException
import config
import mcp_base as m
REAL_ADAPTERS = m.adapters
class FakeAdapter(m.McpAdapter):
"""A harness whose servers are a dict per account; ``own`` = what's there."""
def __init__(self, harness_id="claude", accounts=("work",), caps=None, fail=None):
self.harness_id = harness_id
self._accounts = list(accounts)
self.caps = caps or {"login": True, "approve": True, "connectors": True,
"transports": ("http", "sse", "stdio")}
self.connector_hosts = ("claude.ai",)
self.servers: dict[str, dict] = {a: {} for a in accounts}
self.user: dict[str, set] = {a: set() for a in accounts}
self.calls: list = []
self.fail = fail or {}
self.approved: list = []
self.listing = None
def accounts(self):
return list(self._accounts)
def config_dir(self, account):
return f"/cfg/{self.harness_id}/{account}"
def own_names(self, account):
return set(self.servers[account]) | self.user[account]
def write(self, account, name, cfg):
self.calls.append(("write", account, name))
if self.fail.get("write"):
raise m.McpError(self.fail["write"])
self.servers[account][name] = cfg
def delete(self, account, name):
self.calls.append(("delete", account, name))
if self.fail.get("delete"):
raise m.McpError(self.fail["delete"])
self.servers[account].pop(name, None)
def list_account(self, account, managed):
if self.listing is not None:
return self.listing(account, managed)
return {"servers": [m.row(n, source="hub" if n in managed else "user", transport="http",
target=c.get("url", ""), status="connected")
for n, c in self.servers[account].items()], "listError": None}
def login_argv(self, account, name):
return [sys.executable, "mcp", "login", name], {"X": "1"}
def approve(self, account, name):
self.approved.append((account, name))
@pytest.fixture
def home(tmp_path, monkeypatch):
"""A machine: the state dir under tmp, the listing never in the background."""
monkeypatch.setenv("WORKER_STATE_DIR", str(tmp_path / "state"))
monkeypatch.setattr(m, "enabled", lambda: True)
monkeypatch.setattr(m, "refresh_soon", lambda: None)
monkeypatch.setattr(m, "_state", {"at": time.time(), "running": False, "logins": {}})
fake = FakeAdapter()
monkeypatch.setattr(m, "adapters", lambda: [fake])
return fake
HTTP = {"type": "http", "url": "https://mcp.linear.app/mcp",
"headers": {"Authorization": "Bearer lin_api_x"}}
# ── the canonical config ──────────────────────────────────────────────────────
def test_config_hash_is_the_specs():
want = hashlib.sha256(json.dumps(HTTP, sort_keys=True, separators=(",", ":"))
.encode()).hexdigest()[:16]
assert m.config_hash(HTTP) == want
assert m.config_hash(dict(reversed(list(HTTP.items())))) == want # key order free
def test_valid_config():
assert m.valid_config(HTTP)
assert m.valid_config({"type": "sse", "url": "http://x:1/sse"})
assert m.valid_config({"type": "stdio", "command": "npx", "args": ["-y", "x"],
"env": {"KEY": "v"}})
assert not m.valid_config({"type": "stdio", "command": "npx", "env": {"KEY": 1}})
assert not m.valid_config({"type": "stdio", "command": "a\nb"})
assert not m.valid_config({"type": "http", "url": "file:///etc"})
assert not m.valid_config({"type": "http", "url": "https://x", "headers": {"A": "b\nc"}})
assert not m.valid_config({"type": "ws", "url": "wss://x"})
def test_redact():
assert m.redact("https://penpot.lab/mcp/stream?userToken=SECRET (HTTP)") \
== "https://penpot.lab/mcp/stream (HTTP)"
assert m.redact("https://user:pw@h.example/p?q=1#f") == "https://h.example/p"
assert m.redact("npx -y mcp-remote https://mcp.notion.com/mcp?key=SECRET --token abc") \
== "npx … https://mcp.notion.com/mcp"
assert m.redact("/usr/local/bin/srv --key SECRET") == "srv"
once = m.redact("npx -y mcp-remote https://mcp.notion.com/mcp?key=SECRET")
assert m.redact(once) == once # idempotent
assert m.scrub("failed at https://h/x?token=SECRET (500)") == "failed at https://h/x (500)"
# ── the managed store ─────────────────────────────────────────────────────────
def test_managed_store_reads_the_claude_only_file(home):
p = m.managed_path()
p.parent.mkdir(parents=True)
p.write_text(json.dumps({"work": {"linear": "h1"}, "personal": {"a": "h2"},
"claude:personal": {"b": "h3"}}))
assert m.managed("claude:work") == {"linear": "h1"}
assert m.managed("claude:personal") == {"a": "h2", "b": "h3"}
m.set_managed("opencode:chatgpt-work", "x", "h4")
data = json.loads(p.read_text())
assert set(data) == {"claude:work", "claude:personal", "opencode:chatgpt-work"}
assert os.stat(p).st_mode & 0o777 == 0o600
m.set_managed("opencode:chatgpt-work", "x", None)
assert "opencode:chatgpt-work" not in json.loads(p.read_text())
# ── apply ─────────────────────────────────────────────────────────────────────
def test_apply_adds_tracks_replaces_removes(home):
a = home
out = m.apply(a, "work", [{"name": "linear", "config": HTTP, "hash": "h1"}], [])
assert out["results"] == {"linear": {"ok": True}}
assert a.calls == [("write", "work", "linear")]
assert m.managed("claude:work") == {"linear": "h1"}
assert "lin_api_x" not in json.dumps(out) # the report never has it
a.calls.clear() # same hash: nothing to do
m.apply(a, "work", [{"name": "linear", "config": HTTP, "hash": "h1"}], [])
assert a.calls == []
m.apply(a, "work", [{"name": "linear", "config": {**HTTP, "headers": {}}, "hash": "h2"}], [])
assert [c[0] for c in a.calls] == ["delete", "write"] # changed: delete, then write
assert m.managed("claude:work") == {"linear": "h2"}
a.calls.clear()
m.apply(a, "work", [], ["linear"])
assert a.calls == [("delete", "work", "linear")]
assert m.managed("claude:work") == {}
def test_apply_writes_again_what_went_missing(home):
a = home
m.apply(a, "work", [{"name": "linear", "config": HTTP, "hash": "h1"}], [])
a.servers["work"].clear() # someone removed it by hand
a.calls.clear()
m.apply(a, "work", [{"name": "linear", "config": HTTP, "hash": "h1"}], [])
assert a.calls == [("write", "work", "linear")]
def test_apply_hash_defaults_to_the_configs(home):
m.apply(home, "work", [{"name": "linear", "config": HTTP}], [])
assert m.managed("claude:work") == {"linear": m.config_hash(HTTP)}
def test_apply_never_touches_the_machines_own(home):
home.user["work"].add("linear")
out = m.apply(home, "work", [{"name": "linear", "config": HTTP, "hash": "h"}], ["linear"])
assert out["results"]["linear"]["conflict"] is True
assert home.calls == []
out = m.apply(home, "work", [], ["linear"])
assert out["results"] == {"linear": {"ok": True}} and home.calls == []
def test_apply_rejects_bad_input(home):
out = m.apply(home, "work", [{"name": "../x", "config": HTTP},
{"name": "ok", "config": {"type": "http", "url": "file:///etc"}},
{"name": "cmd", "config": {"type": "stdio", "command": "a\nb"}}],
[])
assert all(not r["ok"] for r in out["results"].values())
assert home.calls == []
def test_apply_refuses_a_transport_the_harness_lacks(home):
home.caps = {"transports": ("http", "stdio")}
home.harness_id = "agy"
out = m.apply(home, "work", [{"name": "s", "config": {"type": "sse", "url": "https://x/sse"}}],
[])
assert out["results"]["s"] == {"ok": False, "error": "agy takes http or stdio servers"}
assert home.calls == []
def test_apply_failure_keeps_it_unmanaged(home):
home.fail["write"] = "add-json failed"
out = m.apply(home, "work", [{"name": "linear", "config": HTTP, "hash": "h"}], [])
assert out["results"]["linear"] == {"ok": False, "error": "add-json failed"}
assert m.managed("claude:work") == {}
def test_apply_on_a_guests_computer(home, monkeypatch):
monkeypatch.setattr(m, "enabled", lambda: False)
with pytest.raises(HTTPException) as e:
m.apply(home, "work", [], [])
assert e.value.status_code == 403 and e.value.detail["kind"] == "forbidden"
assert m.report() is None
def test_resolve(home, monkeypatch):
assert m.resolve(None, "work") is home # no harness: claude
with pytest.raises(HTTPException) as e:
m.resolve("claude", "personal")
assert (e.value.status_code, e.value.detail["kind"]) == (400, "unknown_account")
with pytest.raises(HTTPException) as e:
m.resolve("pi", "work")
assert (e.value.status_code, e.value.detail["kind"]) == (400, "unknown_harness")
def test_approve(home):
out = m.approve(home, "work", "sentry")
assert out["ok"] and home.approved == [("work", "sentry")]
with pytest.raises(HTTPException) as e:
m.approve(home, "work", "bad name")
assert e.value.detail["kind"] == "bad_name"
home.caps = {"transports": ("http",)}
with pytest.raises(HTTPException) as e:
m.approve(home, "work", "sentry")
assert (e.value.status_code, e.value.detail["kind"]) == (409, "unsupported")
# ── the report ────────────────────────────────────────────────────────────────
def test_report_shape_and_order(home, monkeypatch):
oc = FakeAdapter("opencode", ["chatgpt-work"], caps={"transports": ("http", "sse", "stdio")})
agy = FakeAdapter("agy", ["google-personal"], caps={"transports": ("http", "stdio")})
import harness_loader
class D:
def __init__(self, hid, a):
self.harness_id, self._a = hid, a
def mcp_adapter(self):
return self._a
class Broken:
harness_id = "broken"
def mcp_adapter(self):
raise RuntimeError("boom")
class Old: # a driver with no MCP at all
harness_id = "pi"
monkeypatch.setattr(harness_loader, "drivers",
lambda: [D("agy", agy), Broken(), Old(), D("opencode", oc),
D("claude", home), D("none", None)])
monkeypatch.setattr(m, "adapters", REAL_ADAPTERS)
m.set_managed("claude:work", "linear", "h1")
r = m.report()
assert r["version"] == 2 and r["checkedAt"] and r["running"] is False
assert [x["key"] for x in r["logins"]] == ["claude:work", "agy:google-personal",
"opencode:chatgpt-work"]
c = r["logins"][0]
assert c["harness"] == "claude" and c["account"] == "work"
assert c["configDir"] == "/cfg/claude/work" and c["cwd"] == config.DEFAULT_CWD
assert c["caps"] == {"login": True, "approve": True, "connectors": True,
"transports": ["http", "sse", "stdio"]}
assert c["managed"] == {"linear": "h1"}
assert c["servers"] is None and c["listedAt"] is None and c["listError"] is None
g = r["logins"][1]
assert g["caps"] == {"login": False, "approve": False, "connectors": False,
"transports": ["http", "stdio"]}
json.dumps(r) # JSON all the way
def test_caps_drop_what_the_adapter_cant_do():
class A:
harness_id = "x"
caps = {"login": True, "approve": True, "transports": ("stdio", "ws")}
assert m.caps_of(A()) == {"login": False, "approve": False, "connectors": False,
"transports": ["stdio"]}
def test_listing_in_the_background_normalizes_rows(home, monkeypatch):
monkeypatch.setattr(m, "_state", {"at": 0.0, "running": False, "logins": {}})
seen = threading.Event()
def listing(account, managed):
seen.set()
return {"servers": [{"name": "penpot", "source": "user", "transport": "http",
"target": "https://penpot.lab/mcp?userToken=SECRET",
"status": "weird", "detail": "at https://x/y?token=SECRET"},
{"name": "linear", "source": "nope", "status": "connected"}],
"listError": None}
home.listing = listing
m.set_managed("claude:work", "linear", "h")
first = m.report()
assert first["logins"][0]["servers"] is None # never waits
assert seen.wait(2)
for _ in range(100):
if not m._state["running"]:
break
time.sleep(0.02)
rows = {r["name"]: r for r in m.report()["logins"][0]["servers"]}
assert "SECRET" not in json.dumps(rows)
assert rows["penpot"]["target"] == "https://penpot.lab/mcp"
assert rows["penpot"]["status"] == "unknown" and rows["penpot"]["managed"] is False
assert rows["linear"]["source"] == "other" and rows["linear"]["managed"] is True
m.patch_listing("claude:work", "penpot", status="connected", detail=None)
rows = {r["name"]: r for r in m.report()["logins"][0]["servers"]}
assert rows["penpot"]["status"] == "connected"
def test_one_broken_login_never_hides_the_others(home, monkeypatch):
def listing(account, managed):
raise RuntimeError("list blew up")
home.listing = listing
got = m.list_login(home, "work")
assert got["servers"] is None and got["listError"] == "list blew up"
def test_enabled_reads_the_link(monkeypatch):
import link
monkeypatch.setattr(config, "IS_WORKER", True)
monkeypatch.setattr(link, "config", lambda: None)
assert m.enabled() # a tailnet worker
monkeypatch.setattr(link, "config", lambda: {"hub": "h", "owner": True})
assert m.enabled() # the owner's devbox
monkeypatch.setattr(link, "config", lambda: {"hub": "h"})
assert not m.enabled() # a guest's computer
monkeypatch.setattr(config, "IS_WORKER", False)
assert m.enabled() # the host
# ── signing in ────────────────────────────────────────────────────────────────
AUTHORIZE = ("https://mcp.linear.app/authorize?response_type=code&client_id=c"
"&redirect_uri=http%3A%2F%2Flocalhost%3A54879%2Fcallback&state=S1&scope=read")
class FakeProc:
def __init__(self):
self.rc = None
def poll(self):
return self.rc
def kill(self):
if self.rc is None:
self.rc = -9
def wait(self, timeout=None):
return self.rc
def _spawner(text: str, procs: list, seen: list | None = None):
def spawn(args, env):
if seen is not None:
seen.append((args, env))
r, w = os.pipe()
os.write(w, text.encode())
os.close(w)
p = FakeProc()
procs.append(p)
return p, r
return spawn
def test_login_paste_back(home):
procs, seen = [], []
out = m.start_login(home, "work", "linear", spawn=_spawner(
f"Starting authentication…\r\nVisit this URL to authorize:\r\n {AUTHORIZE}\r\n"
"Or paste the redirect URL here: ", procs, seen))
assert seen[0][0][1:] == ["mcp", "login", "linear"] and seen[0][1] == {"X": "1"}
assert out["kind"] == "callback" and out["callbackPort"] == 54879
assert out["url"] == AUTHORIZE and out["harness"] == "claude" and out["account"] == "work"
assert out["expiresAt"] - out["startedAt"] == m.LOGIN_TTL_S
with pytest.raises(HTTPException) as e: # another port
m.finish_login(out["loginId"], "http://localhost:1234/callback?code=x&state=S1")
assert e.value.status_code == 400
with pytest.raises(HTTPException) as e: # another attempt's state
m.finish_login(out["loginId"], "http://localhost:54879/callback?code=x&state=S0")
assert "another sign-in" in e.value.detail["message"]
with pytest.raises(HTTPException): # not an address at all
m.finish_login(out["loginId"], "x#y")
hit = []
def get(url):
hit.append(url)
procs[0].rc = 0 # the CLI got it and exits
got = m.finish_login(out["loginId"],
" localhost:54879/callback?code=abc&state=S1&iss=https%3A%2F%2Fi \n",
get=get)
assert hit == ["http://127.0.0.1:54879/callback?code=abc&state=S1&iss=https%3A%2F%2Fi"]
assert got["ok"] and got["name"] == "linear" and got["harness"] == "claude"
with pytest.raises(HTTPException) as e: # it's over
m.finish_login(out["loginId"], "http://localhost:54879/callback?code=abc&state=S1")
assert e.value.status_code == 404 and e.value.detail["kind"] == "login_expired"
def test_login_failed_exchange(home):
procs = []
out = m.start_login(home, "work", "linear", spawn=_spawner(f"Visit:\n {AUTHORIZE}\n", procs))
def get(url):
procs[0].rc = 1
with pytest.raises(HTTPException) as e:
m.finish_login(out["loginId"], "http://localhost:54879/callback?code=a&state=S1", get=get)
assert e.value.status_code == 502 and e.value.detail["kind"] == "login_failed"
def test_login_connector_needs_no_paste(home):
procs = []
url = "https://claude.ai/api/organizations/o/mcp/start-auth/mcpsrv_1?product_surface=x"
out = m.start_login(home, "work", "claude.ai Linear", spawn=_spawner(
f"Visit this URL to authorize:\n {url}\n\nOnce authorized on claude.ai, …\n", procs))
assert out["kind"] == "connector" and out["url"] == url
assert out["callbackPort"] is None
def test_login_connector_host_is_the_adapters(home, monkeypatch):
monkeypatch.setattr(m, "URL_WAIT_S", 0.3)
home.connector_hosts = ()
procs = []
def spawn(args, env):
p, fd = _spawner("Visit https://claude.ai/x\n", procs)(args, env)
p.rc = 0
return p, fd
with pytest.raises(HTTPException) as e:
m.start_login(home, "work", "claude.ai Linear", spawn=spawn)
assert e.value.status_code == 502
def test_login_without_url(home, monkeypatch):
monkeypatch.setattr(m, "URL_WAIT_S", 0.3)
procs = []
def spawn(args, env):
p, fd = _spawner("Couldn't complete authentication\n", procs)(args, env)
p.rc = 1
return p, fd
with pytest.raises(HTTPException) as e:
m.start_login(home, "work", "linear", spawn=spawn)
assert e.value.status_code == 502 and "printed no sign-in link" in e.value.detail["message"]
def test_login_unsupported(home):
home.caps = {"transports": ("http",)}
with pytest.raises(HTTPException) as e:
m.start_login(home, "work", "linear", spawn=lambda *a: pytest.fail("spawned"))
assert (e.value.status_code, e.value.detail["kind"]) == (409, "unsupported")
def test_cancel_login(home):
procs = []
out = m.start_login(home, "work", "linear", spawn=_spawner(f"{AUTHORIZE}\n", procs))
assert m.cancel_login(out["loginId"]) and procs[0].rc == -9
assert not m.cancel_login(out["loginId"])
# ── probes ────────────────────────────────────────────────────────────────────
class _Handler(http.server.BaseHTTPRequestHandler):
seen: list = []
def log_message(self, *a):
pass
def _answer(self):
n = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(n) if n else b""
_Handler.seen.append((self.command, self.path, dict(self.headers), body))
if self.path == "/ok":
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Mcp-Session-Id", "sess-1")
self.end_headers()
self.wfile.write(b'{"jsonrpc":"2.0","id":1,"result":{}}')
elif self.path == "/sse":
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
self.wfile.write(b"event: message\ndata: {}\n\n")
elif self.path == "/auth":
self.send_response(401)
self.send_header("WWW-Authenticate", 'Bearer resource_metadata="x"')
self.end_headers()
elif self.path == "/relay":
b = json.dumps({"error": "relay_unauthorized",
"message": "signed out on the hub — sign in again in MCP servers"})
self.send_response(403) # the relay's refusals are 403s, never 401s
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(b.encode())))
self.end_headers()
self.wfile.write(b.encode())
elif self.path == "/away":
self.send_response(307)
self.send_header("Location", "http://other.invalid/steal")
self.end_headers()
elif self.path == "/moved":
self.send_response(308)
self.send_header("Location", "/ok")
self.end_headers()
else:
self.send_response(500)
self.end_headers()
do_POST = do_DELETE = _answer
@pytest.fixture
def server():
_Handler.seen = []
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
yield f"http://127.0.0.1:{srv.server_address[1]}"
srv.shutdown()
def test_probe_http(server):
assert m.probe_http(f"{server}/ok", {"Authorization": "Bearer T"}) == ("connected", None)
(verb, path, hdrs, body), (dverb, _, dhdrs, _) = _Handler.seen
assert (verb, path) == ("POST", "/ok")
msg = json.loads(body)
assert msg["method"] == "initialize" and msg["params"]["protocolVersion"] == "2025-06-18"
assert msg["params"]["clientInfo"]["name"] == "ai-agent"
assert hdrs["Accept"] == "application/json, text/event-stream"
assert hdrs["Authorization"] == "Bearer T"
assert dverb == "DELETE" and dhdrs["Mcp-Session-Id"] == "sess-1" # session closed
assert m.probe_http(f"{server}/sse") == ("connected", None)
assert m.probe_http(f"{server}/auth") == ("needs_auth", None)
assert m.probe_http(f"{server}/relay") == \
("needs_auth", "signed out on the hub — sign in again in MCP servers")
assert m.probe_http(f"{server}/boom") == ("failed", "HTTP 500")
assert m.probe_http("http://127.0.0.1:1/x", timeout=2)[0] == "failed"
def test_probe_http_redirects(server):
_Handler.seen = []
st, detail = m.probe_http(f"{server}/away", {"Authorization": "Bearer T"})
assert st == "failed" and "redirect not followed" in detail
assert [s[1] for s in _Handler.seen] == ["/away"] # never went to the other host
assert m.probe_http(f"{server}/moved") == ("connected", None) # same origin: followed
STDIO_OK = r"""
import json, sys
line = sys.stdin.readline()
req = json.loads(line)
print("not json, a log line", flush=True)
print(json.dumps({"jsonrpc": "2.0", "id": req["id"], "result": {"serverInfo": {"name": "x"}}}),
flush=True)
sys.stdin.read()
"""
def test_probe_stdio(tmp_path):
srv = tmp_path / "srv.py"
srv.write_text(STDIO_OK)
assert m.probe_stdio(sys.executable, [str(srv)], {"K": "v"}) == ("connected", None)
refuse = tmp_path / "refuse.py"
refuse.write_text("import sys,json; sys.stdin.readline(); print(json.dumps("
"{'jsonrpc':'2.0','id':1,'error':{'code':-1,'message':'bad key'}}"
"), flush=True)")
assert m.probe_stdio(sys.executable, [str(refuse)]) == ("failed", "bad key")
silent = tmp_path / "silent.py"
silent.write_text("import time; time.sleep(30)")
t0 = time.monotonic()
assert m.probe_stdio(sys.executable, [str(silent)], timeout=0.5) == \
("failed", "no answer in 0.5 s")
assert time.monotonic() - t0 < 5
assert m.probe_stdio(sys.executable, ["-c", "pass"])[1].startswith("exited before answering")
assert m.probe_stdio("/nonexistent/mcp-srv", []) == ("failed", "mcp-srv: command not found")
def test_probe_all(tmp_path, server):
srv = tmp_path / "srv.py"
srv.write_text(STDIO_OK)
got = m.probe_all({"a": {"type": "http", "url": f"{server}/ok"},
"b": {"type": "stdio", "command": sys.executable, "args": [str(srv)]},
"c": {"type": "nope"}})
assert got == {"a": ("connected", None), "b": ("connected", None),
"c": ("failed", "invalid server")}