144 lines
7.3 KiB
Python
144 lines
7.3 KiB
Python
"""The public transport must enforce bearer auth and tool scopes."""
|
|
from contextlib import closing
|
|
import asyncio
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
from urllib.parse import parse_qs, urlparse
|
|
|
|
from fastapi.testclient import TestClient
|
|
|
|
|
|
def _request(client, token=None):
|
|
headers = {"MCP-Protocol-Version": "2025-11-25", "Mcp-Method": "tools/list",
|
|
"Accept": "application/json, text/event-stream"}
|
|
if token:
|
|
headers["Authorization"] = "Bearer " + token
|
|
return client.post("/mcp", headers=headers, json={
|
|
"jsonrpc": "2.0", "id": 1, "method": "tools/list",
|
|
"params": {"_meta": {"io.modelcontextprotocol/protocolVersion": "2025-11-25",
|
|
"io.modelcontextprotocol/clientInfo": {"name": "test", "version": "1"},
|
|
"io.modelcontextprotocol/clientCapabilities": {}}}})
|
|
|
|
|
|
def test_transport_requires_token_and_filters_tools(tmp_path, monkeypatch):
|
|
import db
|
|
monkeypatch.setattr(db, "DB_PATH", tmp_path / "mcp.db")
|
|
db.init_db()
|
|
db.create_user("alice@example.test", "hash")
|
|
db.admin_verify_user("alice@example.test")
|
|
|
|
from mcp_identity import InfosmetaOAuthProvider
|
|
from external_mcp import create_mcp_app
|
|
provider = InfosmetaOAuthProvider("https://testserver", "https://testserver/mcp")
|
|
with closing(db._conn()) as conn, conn:
|
|
token = provider._issue(conn, client_id="ai-client", username="alice@example.test",
|
|
scopes=["norms:read"], resource=provider.resource)
|
|
app = create_mcp_app(provider, allowed_hosts=["testserver"])
|
|
with TestClient(app, base_url="https://testserver") as client:
|
|
denied = _request(client)
|
|
assert denied.status_code == 401
|
|
assert "resource_metadata" in denied.headers["www-authenticate"]
|
|
allowed = _request(client, token.access_token)
|
|
assert allowed.status_code == 200, allowed.text
|
|
names = {tool["name"] for tool in allowed.json()["result"]["tools"]}
|
|
assert "find_ksr" in names
|
|
assert "list_files" not in names
|
|
|
|
|
|
def test_oauth_discovery_pkce_and_tool_call(tmp_path, monkeypatch):
|
|
import db
|
|
monkeypatch.setattr(db, "DB_PATH", tmp_path / "mcp.db")
|
|
monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
|
|
monkeypatch.setenv("SESSION_SECRET", "test-only-mcp-secret")
|
|
db.init_db()
|
|
db.create_user("alice@example.test", "hash")
|
|
db.admin_verify_user("alice@example.test")
|
|
db.create_user("bob@example.test", "hash")
|
|
db.admin_verify_user("bob@example.test")
|
|
db.ensure_session("bob@example.test", "bob-tab")
|
|
from mcp_identity import InfosmetaOAuthProvider
|
|
from external_mcp import create_mcp_app
|
|
provider = InfosmetaOAuthProvider("https://testserver", "https://testserver/mcp")
|
|
app = create_mcp_app(provider, allowed_hosts=["testserver"])
|
|
verifier = "v" * 43
|
|
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=")
|
|
with TestClient(app, base_url="https://testserver") as client:
|
|
meta = client.get("/.well-known/oauth-authorization-server")
|
|
assert meta.status_code == 200
|
|
registration = client.post("/register", json={
|
|
"client_name": "Test AI", "redirect_uris": ["http://localhost:9876/callback"],
|
|
"scope": "files:read account:read stove:estimate",
|
|
"grant_types": ["authorization_code", "refresh_token"],
|
|
"response_types": ["code"],
|
|
})
|
|
assert registration.status_code == 201, registration.text
|
|
client_id = registration.json()["client_id"]
|
|
client_secret = registration.json()["client_secret"]
|
|
auth = client.get("/authorize", params={
|
|
"response_type": "code", "client_id": client_id,
|
|
"redirect_uri": "http://localhost:9876/callback",
|
|
"code_challenge": challenge, "code_challenge_method": "S256",
|
|
"scope": "files:read account:read stove:estimate", "resource": "https://testserver/mcp", "state": "xyz",
|
|
}, follow_redirects=False)
|
|
assert auth.status_code == 302, auth.text
|
|
ticket = parse_qs(urlparse(auth.headers["location"]).query)["ticket"][0]
|
|
callback = asyncio.run(provider.confirm(ticket, "alice@example.test", approved=True))
|
|
code = parse_qs(urlparse(callback).query)["code"][0]
|
|
token = client.post("/token", data={
|
|
"grant_type": "authorization_code", "client_id": client_id,
|
|
"client_secret": client_secret,
|
|
"code": code, "code_verifier": verifier,
|
|
"redirect_uri": "http://localhost:9876/callback",
|
|
"resource": "https://testserver/mcp",
|
|
})
|
|
assert token.status_code == 200, token.text
|
|
bearer = token.json()["access_token"]
|
|
call = client.post("/mcp", headers={
|
|
"Authorization": "Bearer " + bearer,
|
|
"MCP-Protocol-Version": "2025-11-25",
|
|
"Mcp-Method": "tools/call", "Mcp-Name": "list_files",
|
|
"Accept": "application/json, text/event-stream",
|
|
}, json={"jsonrpc": "2.0", "id": 2, "method": "tools/call",
|
|
"params": {"name": "list_files", "arguments": {}}})
|
|
assert call.status_code == 200, call.text
|
|
assert call.json()["result"]["isError"] is False
|
|
assert "files" in call.json()["result"]["content"][0]["text"]
|
|
foreign = client.post("/mcp", headers={
|
|
"Authorization": "Bearer " + bearer,
|
|
"MCP-Protocol-Version": "2025-11-25",
|
|
"Mcp-Method": "tools/call", "Mcp-Name": "list_files",
|
|
"Accept": "application/json, text/event-stream",
|
|
}, json={"jsonrpc": "2.0", "id": 3, "method": "tools/call",
|
|
"params": {"name": "list_files", "arguments": {"tab_id": "bob-tab"}}})
|
|
assert foreign.status_code == 200
|
|
assert foreign.json()["result"]["isError"] is True
|
|
limits = client.post("/mcp", headers={
|
|
"Authorization": "Bearer " + bearer,
|
|
"MCP-Protocol-Version": "2025-11-25",
|
|
"Mcp-Method": "tools/call", "Mcp-Name": "get_limits",
|
|
"Accept": "application/json, text/event-stream",
|
|
}, json={"jsonrpc": "2.0", "id": 4, "method": "tools/call",
|
|
"params": {"name": "get_limits", "arguments": {}}})
|
|
assert limits.status_code == 200, limits.text
|
|
assert limits.json()["result"]["isError"] is False, limits.text
|
|
stove = client.post("/mcp", headers={
|
|
"Authorization": "Bearer " + bearer,
|
|
"MCP-Protocol-Version": "2025-11-25",
|
|
"Mcp-Method": "tools/call", "Mcp-Name": "stove_estimate",
|
|
"Accept": "application/json, text/event-stream",
|
|
}, json={"jsonrpc": "2.0", "id": 5, "method": "tools/call",
|
|
"params": {"name": "stove_estimate", "arguments": {"stove": {}}}})
|
|
assert stove.status_code == 200, stove.text
|
|
payload = stove.json()["result"]
|
|
assert payload["isError"] is True, stove.text
|
|
assert json.loads(payload["content"][0]["text"])["error"] == "invalid_request"
|
|
replay = client.post("/token", data={
|
|
"grant_type": "authorization_code", "client_id": client_id,
|
|
"client_secret": client_secret,
|
|
"code": code, "code_verifier": verifier,
|
|
"redirect_uri": "http://localhost:9876/callback",
|
|
"resource": "https://testserver/mcp",
|
|
})
|
|
assert replay.status_code == 400
|