Add user-bound external MCP server and OAuth access

This commit is contained in:
anor
2026-11-27 17:12:15 +10:00
parent 9a8c2de750
commit 70ad8743d2
25 changed files with 1520 additions and 20 deletions
+34
View File
@@ -0,0 +1,34 @@
"""A remote MCP call must not borrow another user's process environment."""
import asyncio
from pathlib import Path
def test_explicit_context_overrides_process_environment(monkeypatch, tmp_path):
monkeypatch.setenv("SMETA_USER", "wrong-user")
monkeypatch.setenv("SMETA_TAB", "wrong-tab")
monkeypatch.setenv("SMETA_WORK_DIR", str(tmp_path / "wrong"))
import smeta_mcp
from mcp_context import ToolContext, bind_tool_context
own = tmp_path / "alice"
with bind_tool_context(ToolContext("alice", "alice-tab", own, "client-a", frozenset())):
assert smeta_mcp._user_tab() == ("alice", "alice-tab")
assert smeta_mcp._work_dir("alice", "alice-tab") == own
assert smeta_mcp._user_tab() == ("wrong-user", "wrong-tab")
def test_parallel_contexts_do_not_mix(monkeypatch, tmp_path):
monkeypatch.setenv("SMETA_USER", "wrong-user")
import smeta_mcp
from mcp_context import ToolContext, bind_tool_context
async def one(user):
with bind_tool_context(ToolContext(user, "tab", Path(tmp_path / user),
"client", frozenset())):
await asyncio.sleep(0)
return await asyncio.to_thread(smeta_mcp._user_tab)
async def both():
return await asyncio.gather(one("alice"), one("bob"))
assert asyncio.run(both()) == [
("alice", "tab"), ("bob", "tab")]
+91
View File
@@ -0,0 +1,91 @@
"""OAuth grant and revocation contract for the external MCP server."""
import asyncio
from urllib.parse import parse_qs, urlparse
from pydantic import AnyUrl
from mcp.server.auth.provider import AuthorizationParams
from mcp.shared.auth import OAuthClientInformationFull
def test_approved_client_receives_user_bound_token_and_revocation(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
provider = InfosmetaOAuthProvider("https://infosmeta.test", "https://infosmeta.test/mcp")
asyncio.run(provider.register_client(OAuthClientInformationFull(
client_id="client-a", client_name="Тестовый ИИ",
redirect_uris=[AnyUrl("http://localhost:9876/callback")],
token_endpoint_auth_method="none", scope="norms:read files:read")))
client = asyncio.run(provider.get_client("client-a"))
params = AuthorizationParams(state="state-a", scopes=["norms:read"],
code_challenge="a" * 43, redirect_uri=AnyUrl("http://localhost:9876/callback"),
redirect_uri_provided_explicitly=True, resource="https://infosmeta.test/mcp")
consent_url = asyncio.run(provider.authorize(client, params))
ticket = parse_qs(urlparse(consent_url).query)["ticket"][0]
callback_url = asyncio.run(provider.confirm(ticket, "alice@example.test", approved=True))
code = parse_qs(urlparse(callback_url).query)["code"][0]
grant = asyncio.run(provider.load_authorization_code(client, code))
token = asyncio.run(provider.exchange_authorization_code(client, grant))
access = asyncio.run(provider.load_access_token(token.access_token))
assert access.subject == "alice@example.test"
assert access.client_id == "client-a"
assert access.resource == "https://infosmeta.test/mcp"
assert access.scopes == ["norms:read"]
assert asyncio.run(provider.load_authorization_code(client, code)) is None
asyncio.run(provider.revoke_token(access))
assert asyncio.run(provider.load_access_token(token.access_token)) is None
def test_wrong_resource_is_rejected(tmp_path, monkeypatch):
import db
monkeypatch.setattr(db, "DB_PATH", tmp_path / "mcp.db")
db.init_db()
from mcp_identity import InfosmetaOAuthProvider
from mcp.server.auth.provider import AuthorizeError
provider = InfosmetaOAuthProvider("https://infosmeta.test", "https://infosmeta.test/mcp")
client = OAuthClientInformationFull(client_id="x", redirect_uris=[AnyUrl("http://localhost/cb")])
params = AuthorizationParams(state=None, scopes=["norms:read"],
code_challenge="a" * 43, redirect_uri=AnyUrl("http://localhost/cb"),
redirect_uri_provided_explicitly=True, resource="https://other.test/mcp")
try:
asyncio.run(provider.authorize(client, params))
except AuthorizeError as error:
assert error.error == "invalid_target"
else:
raise AssertionError("чужой resource должен быть отклонён")
def test_destructive_action_requires_browser_confirmation_once(tmp_path, monkeypatch):
import db
monkeypatch.setattr(db, "DB_PATH", tmp_path / "mcp.db")
db.init_db()
from mcp_identity import InfosmetaOAuthProvider
provider = InfosmetaOAuthProvider("https://infosmeta.test", "https://infosmeta.test/mcp")
url = asyncio.run(provider.prepare_action("alice@example.test", "client-a", "tab-a", "clear_files"))
ticket = parse_qs(urlparse(url).query)["ticket"][0]
try:
asyncio.run(provider.consume_action(ticket, "alice@example.test", "client-a", "tab-a", "clear_files"))
except PermissionError:
pass
else:
raise AssertionError("browser confirmation required")
try:
asyncio.run(provider.approve_action(ticket, "bob@example.test"))
except ValueError:
pass
else:
raise AssertionError("another user cannot confirm")
asyncio.run(provider.approve_action(ticket, "alice@example.test"))
asyncio.run(provider.consume_action(ticket, "alice@example.test", "client-a", "tab-a", "clear_files"))
try:
asyncio.run(provider.consume_action(ticket, "alice@example.test", "client-a", "tab-a", "clear_files"))
except PermissionError:
pass
else:
raise AssertionError("confirmation must be single-use")
+143
View File
@@ -0,0 +1,143 @@
"""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