mirror of
https://github.com/turnstonelabs/turnstone.git
synced 2026-08-12 23:12:23 -06:00
5a3f46a1fa
Wires the structured-error envelopes produced by Phase 7b's pool
dispatcher (mcp_consent_required / mcp_insufficient_scope /
mcp_*_forbidden / mcp_token_undecryptable_key_unknown /
mcp_oauth_url_insecure) through to the user-facing dashboard, and
adds a per-user settings panel for managing MCP server consents.
Changes
- ``_dispatch_pool_sync`` and ``_dispatch_pool_resource_sync`` wrap
structured-error string returns as ``RuntimeError(json_str)`` via
``_is_structured_error()`` so the session-layer ``except Exception``
branch fires uniformly across tool / resource / prompt dispatchers
(the prompt path's ``isinstance(result, str)`` shortcut works only
because prompts return ``list[dict]`` on success). Without this,
the consent UX silently does not render for tool / resource calls.
- ``_structured_error`` extended with an optional ``consent_url``
field; ``_build_consent_url`` produces ``/v1/api/mcp/oauth/start``
query strings (path-relative; the dashboard appends ``return_url``
at click time). Wired to all 12 ``mcp_consent_required`` and the
``mcp_insufficient_scope`` emit sites.
- New endpoints ``GET /v1/api/mcp/oauth/connections`` and
``DELETE /v1/api/mcp/oauth/connections/{server_name}`` registered
on both ``turnstone-server`` and ``turnstone-console``. The DELETE
handler runs local delete + audit + 204 first, then schedules the
RFC 7009 upstream revoke as a fire-and-forget ``asyncio.create_task``
with strong-ref tracking via ``_revoke_upstream_tasks`` (mirrors
the ``_pg_refresh_drain_tasks`` pattern). Soft cap of 256 concurrent
in-flight revokes prevents pile-up under coordinated mass-revoke;
the audit detail records ``upstream_revoke_outcome`` as
``scheduled | no_refresh_token | no_http_client | shed_by_cap``.
- ``ASMetadata`` extended with ``revocation_endpoint`` parsed from
RFC 8414 metadata. ``revoke_token_at_as`` helper posts the form
body under ``asyncio.timeout`` (not ``asyncio.wait_for``) and
never raises; ``_attempt_upstream_revoke`` is wrapped in an outer
``try/except Exception`` so unhandled exceptions don't surface as
``Task exception was never retrieved``.
- ``/v1/api/mcp/oauth/start`` accepts an optional ``scopes=`` query
param; tokens are validated against RFC 6749 §3.3 grammar via
``is_valid_scope_token`` (promoted to ``mcp_http_parsers``),
capped at ``_MAX_INSUFFICIENT_SCOPE_REPORTED`` (32), and unioned
with the configured server scopes for the step-up consent flow.
- Storage primitive ``list_mcp_user_token_metadata_by_user`` projects
the metadata columns at the SQL boundary so ciphertext blobs never
cross the wire on the settings-list path. New
``MCPUserTokenMetadataRow`` TypedDict in ``_protocol.py``;
``MCPTokenStore.list_user_token_metadata`` re-types to the existing
``MCPUserTokenMetadata`` shape.
- Dashboard renderer (``app.js``): ``tryParseMcpError`` detects the
envelope shape on ``tool_result`` SSE events with ``is_error=True``
and ``buildMcpErrorEmbed`` renders an action card mirroring the
existing ``buildMediaEmbed`` pattern. Three categories: actionable
(consent_required / insufficient_scope) with a ``Connect`` button
that opens ``/v1/api/mcp/oauth/start`` in a popup with a scheme
guard, forbidden (mcp_*_forbidden) with a static notice, operator
(key-mismatch / url-insecure) with an operator-action notice.
- New gear button in the appbar opens an MCP-connections settings
modal driven by ``loadMcpConnections`` / ``confirmRevokeMcp``
(two-step revoke confirmation matching the existing delete-ws
pattern). Pending-consent badge tracks unresolved consent prompts
in this tab; cleared after the connections list returns. Console
proxy collision-checked: the IIFE only prepends a node-id pill to
``header.firstChild``, so the right-anchored gear button is safe.
Bearer-leak invariant
- No ``exc_info=True`` on any new path that can carry a chained
``httpx.Request`` (revoke handler, dispatch sites, exec sites).
The two pre-existing ``exc_info=True`` calls in
``_exec_read_resource`` / ``_exec_use_prompt`` were replaced with
structured-field logs as a Phase 8 sibling fix.
Tests
- 440 pytest passes on both Python 3.13 (.venv) and 3.11
(/tmp/venv311); ruff + mypy clean.
- 5 new test files: ``test_mcp_consent_url_sibling_audit`` (structural
gate that every ``code="mcp_consent_required"`` / ``mcp_insufficient_scope``
site carries ``consent_url=``), ``test_mcp_oauth_connections``,
``test_mcp_oauth_revoke``, ``test_mcp_token_store_metadata``,
``test_session_mcp_dispatch_error``.
- End-to-end regression coverage for the bug-1 sibling pattern:
``test_call_tool_sync_raises_on_structured_error_envelope``,
``test_read_resource_sync_raises_on_structured_error_envelope``,
``test_get_prompt_sync_raises_on_structured_error_envelope``, plus
``test_call_tool_sync_does_not_wrap_non_structured_string`` as the
defensive gate (only ``mcp_*`` envelopes are wrapped).
Hard invariants honored
- Static path byte-identical for ``auth_type ∈ {none, static}``: the
wrap fires only when the dispatcher returns a structured-mcp-error
string, which only happens on the oauth_user pool path.
- ``asyncio.timeout`` (not ``asyncio.wait_for``) on every new
AS / SDK / pool-loop await per Python 3.11 anyio cancel-scope
hazard.
- Scope cap ``_MAX_INSUFFICIENT_SCOPE_REPORTED = 32`` enforced at
every output / merge site.
- Cross-user isolation on the revoke endpoint: a non-owner DELETE
returns 404 with the same body shape as a never-existed row;
``http_client_mock.post.assert_not_called()`` pins this in 3 tests.
Deferred (not Phase 8 blockers)
- perf-2 (``asyncio.gather`` parallelisation in revoke handler) —
superseded by perf-1's fire-and-forget pattern.
- q-4 (prompt-path ``isinstance(str)`` vs sibling ``_is_structured_error``
asymmetry) — already documented in the function docstring.
- q-9 (``_pendingConsentServers`` → ``_serversNeedingConsent``
rename) — pure naming taste.
627 lines
24 KiB
Python
627 lines
24 KiB
Python
"""Discovery tests for the per-(user, server) MCP OAuth flow.
|
|
|
|
Covers PRM (RFC 9728) and AS metadata (RFC 8414) discovery, including:
|
|
- override URL takes precedence
|
|
- PRM happy path: server URL -> .well-known/oauth-protected-resource
|
|
-> ``authorization_servers[0]``
|
|
- PRM 401 + ``WWW-Authenticate: Bearer resource_metadata="..."`` follows
|
|
the URL.
|
|
- AS metadata without S256 -> :class:`MCPOAuthDiscoveryError`.
|
|
- SSRF rejection on AS issuer URL.
|
|
- In-memory cache hit/miss + persistent cache write to
|
|
``mcp_servers.oauth_as_issuer_cached``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import time
|
|
from typing import Any
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
from turnstone.core.mcp_oauth import (
|
|
ASMetadata,
|
|
MCPOAuthDiscoveryError,
|
|
_parse_prm_url_from_www_authenticate,
|
|
discover_authorization_server,
|
|
)
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _mk_response(
|
|
status_code: int = 200,
|
|
json_body: Any = None,
|
|
headers: dict[str, str] | None = None,
|
|
) -> MagicMock:
|
|
"""Build a MagicMock that quacks like ``httpx.Response``."""
|
|
resp = MagicMock(spec=httpx.Response)
|
|
resp.status_code = status_code
|
|
resp.headers = headers or {}
|
|
resp.content = (str(json_body) if json_body is not None else "").encode("utf-8")
|
|
if json_body is not None:
|
|
resp.json.return_value = json_body
|
|
else:
|
|
resp.json.side_effect = ValueError("no body")
|
|
resp.text = str(json_body) if json_body is not None else ""
|
|
return resp
|
|
|
|
|
|
def _good_as_metadata_doc() -> dict[str, Any]:
|
|
return {
|
|
"issuer": "https://as.example.com",
|
|
"authorization_endpoint": "https://as.example.com/authorize",
|
|
"token_endpoint": "https://as.example.com/token",
|
|
"jwks_uri": "https://as.example.com/jwks",
|
|
"code_challenge_methods_supported": ["S256"],
|
|
"token_endpoint_auth_methods_supported": ["none", "client_secret_basic"],
|
|
"registration_endpoint": "https://as.example.com/register",
|
|
}
|
|
|
|
|
|
def _public_addr_patch():
|
|
return patch("socket.getaddrinfo", return_value=[(2, 1, 6, "", ("93.184.216.34", 0))])
|
|
|
|
|
|
def _mk_storage_mock(server_id: str = "srv-id") -> MagicMock:
|
|
storage = MagicMock()
|
|
storage.update_mcp_server.return_value = True
|
|
return storage
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# PRM parser
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestParsePRMUrl:
|
|
def test_extracts_resource_metadata_url(self) -> None:
|
|
header = (
|
|
'Bearer error="invalid_token", '
|
|
'resource_metadata="https://srv.example.com/.well-known/oauth-protected-resource"'
|
|
)
|
|
url = _parse_prm_url_from_www_authenticate(header)
|
|
assert url == "https://srv.example.com/.well-known/oauth-protected-resource"
|
|
|
|
def test_returns_none_when_absent(self) -> None:
|
|
assert _parse_prm_url_from_www_authenticate('Bearer realm="x"') is None
|
|
|
|
def test_handles_empty_header(self) -> None:
|
|
assert _parse_prm_url_from_www_authenticate("") is None
|
|
|
|
def test_handles_escaped_quote_in_value(self) -> None:
|
|
"""RFC 7230 quoted-string allows ``\\"`` — naive ``[^"]+`` truncates.
|
|
|
|
A malicious or buggy resource server could send an embedded
|
|
escaped quote; the parser must yield the unescaped value, not
|
|
the prefix up to the escaped quote.
|
|
"""
|
|
header = 'Bearer resource_metadata="https://srv.example.com/with\\"quote"'
|
|
url = _parse_prm_url_from_www_authenticate(header)
|
|
assert url == 'https://srv.example.com/with"quote'
|
|
|
|
def test_handles_escaped_backslash(self) -> None:
|
|
header = 'Bearer resource_metadata="https://srv.example.com/back\\\\slash"'
|
|
url = _parse_prm_url_from_www_authenticate(header)
|
|
assert url == "https://srv.example.com/back\\slash"
|
|
|
|
def test_unterminated_quoted_string_returns_none(self) -> None:
|
|
# Closing quote missing — naive regex would still match, but
|
|
# the proper parser should reject malformed input.
|
|
header = 'Bearer resource_metadata="https://srv.example.com/no-close'
|
|
assert _parse_prm_url_from_www_authenticate(header) is None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# discover_authorization_server happy paths
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestDiscoveryOverride:
|
|
def test_override_url_skips_prm(self) -> None:
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(return_value=_mk_response(200, _good_as_metadata_doc()))
|
|
storage = _mk_storage_mock()
|
|
|
|
async def _run():
|
|
with _public_addr_patch():
|
|
return await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url="https://as.example.com",
|
|
cached_issuer=None,
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
)
|
|
|
|
meta = asyncio.run(_run())
|
|
assert isinstance(meta, ASMetadata)
|
|
assert meta.token_endpoint == "https://as.example.com/token"
|
|
# Only the AS metadata URL was hit, not PRM.
|
|
called_urls = [c.args[0] for c in client.get.call_args_list]
|
|
assert all("oauth-authorization-server" in u for u in called_urls)
|
|
|
|
|
|
class TestDiscoveryPRM:
|
|
def test_prm_happy_path(self) -> None:
|
|
async def _get(url, *args, **kwargs):
|
|
if url.endswith("/oauth-protected-resource"):
|
|
return _mk_response(
|
|
200,
|
|
{
|
|
"resource": "https://mcp.example.com",
|
|
"authorization_servers": ["https://as.example.com"],
|
|
},
|
|
)
|
|
if url.endswith("/oauth-authorization-server"):
|
|
return _mk_response(200, _good_as_metadata_doc())
|
|
raise AssertionError(f"unexpected URL: {url}")
|
|
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(side_effect=_get)
|
|
storage = _mk_storage_mock()
|
|
|
|
async def _run():
|
|
with _public_addr_patch():
|
|
return await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url=None,
|
|
cached_issuer=None,
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
)
|
|
|
|
meta = asyncio.run(_run())
|
|
assert meta.issuer == "https://as.example.com"
|
|
|
|
def test_prm_401_follows_www_authenticate(self) -> None:
|
|
async def _get(url, *args, **kwargs):
|
|
if url == "https://mcp.example.com/.well-known/oauth-protected-resource":
|
|
return _mk_response(
|
|
401,
|
|
headers={
|
|
"www-authenticate": (
|
|
'Bearer error="invalid_token", '
|
|
"resource_metadata="
|
|
'"https://meta.example.com/prm"'
|
|
)
|
|
},
|
|
json_body=None,
|
|
)
|
|
if url == "https://meta.example.com/prm":
|
|
return _mk_response(
|
|
200,
|
|
{
|
|
"authorization_servers": ["https://as.example.com"],
|
|
},
|
|
)
|
|
if url.endswith("/oauth-authorization-server"):
|
|
return _mk_response(200, _good_as_metadata_doc())
|
|
raise AssertionError(f"unexpected URL: {url}")
|
|
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(side_effect=_get)
|
|
storage = _mk_storage_mock()
|
|
|
|
async def _run():
|
|
with _public_addr_patch():
|
|
return await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url=None,
|
|
cached_issuer=None,
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
)
|
|
|
|
meta = asyncio.run(_run())
|
|
assert meta.token_endpoint == "https://as.example.com/token"
|
|
|
|
def test_prm_401_without_resource_metadata_raises(self) -> None:
|
|
async def _get(url, *args, **kwargs):
|
|
return _mk_response(401, headers={"www-authenticate": "Basic realm=x"})
|
|
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(side_effect=_get)
|
|
storage = _mk_storage_mock()
|
|
|
|
async def _run():
|
|
with _public_addr_patch():
|
|
await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url=None,
|
|
cached_issuer=None,
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
)
|
|
|
|
with pytest.raises(MCPOAuthDiscoveryError, match="resource_metadata"):
|
|
asyncio.run(_run())
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# AS metadata validation
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestASMetadataValidation:
|
|
def test_no_s256_raises(self) -> None:
|
|
doc = _good_as_metadata_doc()
|
|
doc["code_challenge_methods_supported"] = ["plain"]
|
|
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(return_value=_mk_response(200, doc))
|
|
storage = _mk_storage_mock()
|
|
|
|
async def _run():
|
|
with _public_addr_patch():
|
|
await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url="https://as.example.com",
|
|
cached_issuer=None,
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
)
|
|
|
|
with pytest.raises(MCPOAuthDiscoveryError, match="S256"):
|
|
asyncio.run(_run())
|
|
|
|
def test_missing_endpoints_raises(self) -> None:
|
|
doc = _good_as_metadata_doc()
|
|
del doc["token_endpoint"]
|
|
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(return_value=_mk_response(200, doc))
|
|
storage = _mk_storage_mock()
|
|
|
|
async def _run():
|
|
with _public_addr_patch():
|
|
await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url="https://as.example.com",
|
|
cached_issuer=None,
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
)
|
|
|
|
with pytest.raises(MCPOAuthDiscoveryError, match="missing required"):
|
|
asyncio.run(_run())
|
|
|
|
def test_third_party_endpoint_rejected(self) -> None:
|
|
doc = _good_as_metadata_doc()
|
|
doc["token_endpoint"] = "https://attacker.example.com/token"
|
|
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(return_value=_mk_response(200, doc))
|
|
storage = _mk_storage_mock()
|
|
|
|
async def _run():
|
|
with _public_addr_patch():
|
|
await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url="https://as.example.com",
|
|
cached_issuer=None,
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
)
|
|
|
|
with pytest.raises(MCPOAuthDiscoveryError, match="token_endpoint"):
|
|
asyncio.run(_run())
|
|
|
|
def test_ssrf_on_override_rejected(self) -> None:
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock()
|
|
storage = _mk_storage_mock()
|
|
|
|
async def _run():
|
|
# Resolve to private 10.x — SSRF guard fires before any HTTP call.
|
|
with patch(
|
|
"socket.getaddrinfo",
|
|
return_value=[(2, 1, 6, "", ("10.0.0.1", 0))],
|
|
):
|
|
await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url="https://internal.corp.example.com",
|
|
cached_issuer=None,
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
)
|
|
|
|
with pytest.raises(MCPOAuthDiscoveryError):
|
|
asyncio.run(_run())
|
|
client.get.assert_not_called()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Caching
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestMetadataCache:
|
|
def test_cache_miss_then_hit(self) -> None:
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(return_value=_mk_response(200, _good_as_metadata_doc()))
|
|
storage = _mk_storage_mock()
|
|
cache: dict[str, tuple[ASMetadata, float]] = {}
|
|
|
|
async def _run():
|
|
with _public_addr_patch():
|
|
first = await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url="https://as.example.com",
|
|
cached_issuer=None,
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
metadata_cache=cache,
|
|
)
|
|
second = await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url="https://as.example.com",
|
|
cached_issuer="https://as.example.com",
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
metadata_cache=cache,
|
|
)
|
|
return first, second
|
|
|
|
first, second = asyncio.run(_run())
|
|
assert first.token_endpoint == second.token_endpoint
|
|
# First call hit AS metadata; second call hit the cache.
|
|
assert client.get.call_count == 1
|
|
|
|
def test_cache_expiry_refetches(self) -> None:
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(return_value=_mk_response(200, _good_as_metadata_doc()))
|
|
storage = _mk_storage_mock()
|
|
# Pre-populate cache with a very stale entry.
|
|
stale_meta = ASMetadata(
|
|
issuer="https://as.example.com",
|
|
authorization_endpoint="https://as.example.com/authorize",
|
|
token_endpoint="https://as.example.com/token",
|
|
registration_endpoint=None,
|
|
revocation_endpoint=None,
|
|
jwks_uri=None,
|
|
code_challenge_methods_supported=("S256",),
|
|
token_endpoint_auth_methods_supported=(),
|
|
)
|
|
cache = {"https://as.example.com": (stale_meta, time.monotonic() - 10**6)}
|
|
|
|
async def _run():
|
|
with _public_addr_patch():
|
|
return await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url="https://as.example.com",
|
|
cached_issuer=None,
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
metadata_cache=cache,
|
|
)
|
|
|
|
meta = asyncio.run(_run())
|
|
# Stale entry was bypassed -> we hit the network.
|
|
assert client.get.call_count == 1
|
|
assert meta.token_endpoint == "https://as.example.com/token"
|
|
|
|
def test_persistent_cache_write_on_first_resolution(self) -> None:
|
|
async def _get(url, *args, **kwargs):
|
|
if url.endswith("/oauth-protected-resource"):
|
|
return _mk_response(200, {"authorization_servers": ["https://as.example.com"]})
|
|
return _mk_response(200, _good_as_metadata_doc())
|
|
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(side_effect=_get)
|
|
storage = _mk_storage_mock()
|
|
|
|
async def _run():
|
|
with _public_addr_patch():
|
|
return await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url=None,
|
|
cached_issuer=None,
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
)
|
|
|
|
asyncio.run(_run())
|
|
# update_mcp_server was called once with the cached issuer.
|
|
storage.update_mcp_server.assert_called_once_with(
|
|
"srv-id", oauth_as_issuer_cached="https://as.example.com"
|
|
)
|
|
|
|
def test_persistent_cache_skip_when_already_cached(self) -> None:
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(return_value=_mk_response(200, _good_as_metadata_doc()))
|
|
storage = _mk_storage_mock()
|
|
|
|
async def _run():
|
|
with _public_addr_patch():
|
|
return await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url=None,
|
|
cached_issuer="https://as.example.com",
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
)
|
|
|
|
asyncio.run(_run())
|
|
storage.update_mcp_server.assert_not_called()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# sec-3 — cached_issuer re-validated on read
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestCachedIssuerSSRFRevalidation:
|
|
"""A cached issuer URL must still pass SSRF validation on every read.
|
|
|
|
Defense-in-depth: an admin who points ``oauth_as_issuer_cached`` at a
|
|
private address (or a hostname that has rebound to one) should not
|
|
bypass the guard just because the value was already in the row.
|
|
"""
|
|
|
|
def test_cached_issuer_rejected_clears_row_and_falls_through_to_prm(self) -> None:
|
|
async def _get(url: str, *args: Any, **kwargs: Any) -> MagicMock:
|
|
if url.endswith("/oauth-protected-resource"):
|
|
return _mk_response(200, {"authorization_servers": ["https://as.example.com"]})
|
|
if url.endswith("/oauth-authorization-server"):
|
|
return _mk_response(200, _good_as_metadata_doc())
|
|
raise AssertionError(f"unexpected URL: {url}")
|
|
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(side_effect=_get)
|
|
storage = _mk_storage_mock()
|
|
|
|
# cached_issuer points at a private host. SSRF guard fires on
|
|
# the cached value first, the row is cleared, and PRM
|
|
# discovery runs as a fallback.
|
|
async def _run() -> Any:
|
|
with patch(
|
|
"socket.getaddrinfo",
|
|
# Private resolution for "internal.corp", public for everything else.
|
|
side_effect=lambda host, *a, **kw: [
|
|
(2, 1, 6, "", ("10.0.0.1" if "internal" in host else "93.184.216.34", 0))
|
|
],
|
|
):
|
|
return await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url=None,
|
|
cached_issuer="https://internal.corp.example.com",
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
)
|
|
|
|
meta = asyncio.run(_run())
|
|
assert meta.token_endpoint == "https://as.example.com/token"
|
|
# The bad cached_issuer was cleared from the row.
|
|
clear_calls = [
|
|
c
|
|
for c in storage.update_mcp_server.call_args_list
|
|
if c.kwargs.get("oauth_as_issuer_cached") is None
|
|
]
|
|
assert clear_calls, "cached_issuer should have been cleared"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# revocation_endpoint parsing (RFC 8414)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestASMetadataRevocationEndpoint:
|
|
def test_as_metadata_parses_revocation_endpoint(self) -> None:
|
|
doc = _good_as_metadata_doc()
|
|
doc["revocation_endpoint"] = "https://as.example.com/revoke"
|
|
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(return_value=_mk_response(200, doc))
|
|
storage = _mk_storage_mock()
|
|
|
|
async def _run() -> ASMetadata:
|
|
with _public_addr_patch():
|
|
return await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url="https://as.example.com",
|
|
cached_issuer=None,
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
)
|
|
|
|
meta = asyncio.run(_run())
|
|
assert meta.revocation_endpoint == "https://as.example.com/revoke"
|
|
|
|
def test_as_metadata_revocation_endpoint_absent(self) -> None:
|
|
doc = _good_as_metadata_doc()
|
|
doc.pop("revocation_endpoint", None)
|
|
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(return_value=_mk_response(200, doc))
|
|
storage = _mk_storage_mock()
|
|
|
|
async def _run() -> ASMetadata:
|
|
with _public_addr_patch():
|
|
return await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url="https://as.example.com",
|
|
cached_issuer=None,
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
)
|
|
|
|
meta = asyncio.run(_run())
|
|
assert meta.revocation_endpoint is None
|
|
|
|
def test_as_metadata_revocation_endpoint_rejected_when_cross_origin(self) -> None:
|
|
doc = _good_as_metadata_doc()
|
|
doc["revocation_endpoint"] = "https://attacker.example.com/revoke"
|
|
|
|
client = MagicMock(spec=httpx.AsyncClient)
|
|
client.get = AsyncMock(return_value=_mk_response(200, doc))
|
|
storage = _mk_storage_mock()
|
|
|
|
async def _run() -> ASMetadata:
|
|
with _public_addr_patch():
|
|
return await discover_authorization_server(
|
|
server_name="srv-x",
|
|
server_url="https://mcp.example.com/sse",
|
|
override_url="https://as.example.com",
|
|
cached_issuer=None,
|
|
http_client=client,
|
|
storage=storage,
|
|
server_id="srv-id",
|
|
trusted_hosts=frozenset(),
|
|
)
|
|
|
|
with pytest.raises(MCPOAuthDiscoveryError, match="revocation_endpoint"):
|
|
asyncio.run(_run())
|