ckb/tests/unit/test_mcp_server.py
Michał Kopeć aca5237ad2 Template 1.28.9: backport 2.0.8 mcp server tests to the 1.x line
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:07:53 +01:00

163 lines
7.3 KiB
Python

"""The mcp server's own policy: confirmation codes, allowed hosts, OAuth
identity. Needs the MCP SDK (`pip install -r .agents/modules/mcp/server/
requirements.txt`, in a virtualenv); skipped without it, so the stdlib-only
smoke test stays green. Run: <venv>/bin/python -m unittest tests.unit.test_mcp_server"""
import asyncio
import importlib
import os
import shutil
import sys
import tempfile
import time
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SERVER_DIR = ROOT / ".agents/modules/mcp/server"
FIX = ROOT / "tests/fixtures/minimal-kb"
try:
import mcp # noqa: F401
HAVE_SDK = True
except ImportError:
HAVE_SDK = False
@unittest.skipUnless(HAVE_SDK, "MCP SDK not installed")
class Server(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
kb = Path(cls.tmp.name) / "kb"
shutil.copytree(str(FIX), str(kb))
cls.saved_env = dict(os.environ)
os.environ.update({"CKB_ROOT": str(kb), "CKB_MCP_TRANSPORT": "http", "CKB_MCP_AUTH": "none",
"CKB_MCP_NAME": "test-kb", "CKB_MCP_PUBLIC_URL": "https://kb.example.com"})
for k in ("CKB_MCP_ALLOWED_HOSTS", "CKB_MCP_CONFIRM", "CKB_MCP_CONFIRM_SECRET"):
os.environ.pop(k, None)
sys.path.insert(0, str(SERVER_DIR))
sys.modules.pop("server", None)
cls.s = importlib.import_module("server")
from mcp.server.mcpserver.exceptions import ToolError
cls.ToolError = ToolError
cls.author = cls.s.Author("Ann", "ann@example.com")
@classmethod
def tearDownClass(cls):
os.environ.clear()
os.environ.update(cls.saved_env)
cls.tmp.cleanup()
def gate(self, payload, confirmation=None, kb="test-kb"):
return self.s._gate("add_to_inbox", kb, self.author, payload, None, confirmation, "Add it?")
# ---- confirmation codes ------------------------------------------------
def test_code_confirms_exactly_one_write(self):
first = self.gate({"title": "a"})
self.assertEqual(first["status"], "confirmation_required")
code = first["confirmation"]
self.assertIsNone(self.gate({"title": "a"}, code)) # the write goes ahead
with self.assertRaisesRegex(self.ToolError, "already used"):
self.gate({"title": "a"}, code) # a replay does not
def test_code_is_bound_to_the_payload_and_expires(self):
code = self.gate({"title": "a"})["confirmation"]
with self.assertRaisesRegex(self.ToolError, "invalid or expired"):
self.gate({"title": "b"}, code)
old = self.s._code("add_to_inbox", self.author, {"title": "a"}, int(time.time()) - self.s.CONFIRM_TTL - 5)
with self.assertRaisesRegex(self.ToolError, "invalid or expired"):
self.gate({"title": "a"}, old)
forged = code.split(".")[0] + "." + "0" * 24
with self.assertRaisesRegex(self.ToolError, "invalid or expired"):
self.gate({"title": "a"}, forged)
def test_wrong_kb_is_refused_before_anything_else(self):
with self.assertRaisesRegex(self.ToolError, "not 'other-kb'"):
self.gate({"title": "a"}, kb="other-kb")
def test_redact_masks_every_secret(self):
self.assertEqual(self.s._redact("GET /tok123/mcp tok123", ["tok123"]), "GET /***/mcp ***")
# ---- allowed hosts (DNS rebinding) -------------------------------------
def test_allowed_hosts_default_and_override(self):
hosts = self.s.allowed_hosts()
self.assertIn("kb.example.com", hosts)
self.assertIn(f"127.0.0.1:{self.s.PORT}", hosts)
self.assertNotIn("*", hosts)
os.environ["CKB_MCP_ALLOWED_HOSTS"] = "a.example, b.example:8443"
try:
self.assertEqual(self.s.allowed_hosts(), ["a.example", "b.example:8443"])
os.environ["CKB_MCP_ALLOWED_HOSTS"] = "*"
self.assertEqual(self.s.allowed_hosts(), ["*"])
finally:
os.environ.pop("CKB_MCP_ALLOWED_HOSTS")
def test_foreign_host_header_is_rejected_over_http(self):
try:
from starlette.testclient import TestClient
except Exception as e: # pragma: no cover - depends on the SDK's HTTP client
self.skipTest(f"no starlette TestClient: {e}")
body = {"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": "2025-06-18", "capabilities": {},
"clientInfo": {"name": "t", "version": "1"}}}
headers = {"Accept": "application/json, text/event-stream", "Content-Type": "application/json"}
with TestClient(self.s.http_app()) as client:
evil = client.post(self.s.MCP_PATH, json=body, headers={**headers, "Host": "attacker.example"})
good = client.post(self.s.MCP_PATH, json=body, headers={**headers, "Host": "kb.example.com"})
self.assertIn(evil.status_code, (400, 403, 421))
self.assertEqual(good.status_code, 200, good.text[:300])
@unittest.skipUnless(HAVE_SDK, "MCP SDK not installed")
class OAuthEmail(unittest.TestCase):
"""An `email` claim is identity only when the IdP says it is verified."""
@classmethod
def setUpClass(cls):
sys.path.insert(0, str(SERVER_DIR))
cls.auth = importlib.import_module("auth")
import jwt
from cryptography.hazmat.primitives.asymmetric import rsa
cls.jwt = jwt
cls.key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
def verifier(self, **extra):
env = {"CKB_MCP_OAUTH_ISSUER": "https://idp.example", "CKB_MCP_OAUTH_JWKS_URL": "https://idp.example/jwks",
"CKB_MCP_OAUTH_ALLOWED": "@corp.com", **extra}
v = self.auth.OAuthVerifier(env, "https://kb.example.com/mcp")
public = self.key.public_key()
class Keys: # stands in for PyJWKClient: no network
def get_signing_key_from_jwt(self, token):
return type("K", (), {"key": public})()
v._jwks = Keys()
return v
def token(self, **claims):
base = {"iss": "https://idp.example", "aud": "https://kb.example.com/mcp", "sub": "u-1",
"exp": int(time.time()) + 300}
return self.jwt.encode({**base, **claims}, self.key, algorithm="RS256")
def verify(self, v, token):
return asyncio.run(v.verify_token(token))
def test_unverified_email_does_not_pass_the_allowed_list(self):
self.assertIsNone(self.verify(self.verifier(), self.token(email="eve@corp.com")))
self.assertIsNone(self.verify(self.verifier(), self.token(email="eve@corp.com", email_verified=False)))
def test_verified_email_passes(self):
tok = self.verify(self.verifier(), self.token(email="ann@corp.com", email_verified=True))
self.assertIsNotNone(tok)
self.assertEqual(tok.claims["email"], "ann@corp.com")
def test_trust_email_opt_out(self):
self.assertIsNotNone(self.verify(self.verifier(CKB_MCP_OAUTH_TRUST_EMAIL="1"), self.token(email="ann@corp.com")))
def test_wrong_audience_and_expired_tokens_are_rejected(self):
v = self.verifier(CKB_MCP_OAUTH_TRUST_EMAIL="1")
self.assertIsNone(self.verify(v, self.token(email="ann@corp.com", aud="https://other.example/mcp")))
self.assertIsNone(self.verify(v, self.token(email="ann@corp.com", exp=int(time.time()) - 60)))
if __name__ == "__main__":
unittest.main()