|
| 1 | +"""Serve the Protected Resource Metadata identifiers verbatim. |
| 2 | +
|
| 3 | +The core SDK stores and compares the issuer / resource identifier byte-for-byte |
| 4 | +(RFC 8414 §3.3, RFC 9728 §3.3). The upstream MCP machinery that serves the PRM |
| 5 | +document types ``authorization_servers`` and ``resource`` as |
| 6 | +``pydantic.AnyHttpUrl``, which normalizes an empty-path authority by appending a |
| 7 | +trailing slash (``https://auth.example.com`` -> ``https://auth.example.com/``). |
| 8 | +A client that follows that advertised value literally then does discovery and |
| 9 | +audience checks against the slashed form and is rejected by the strict |
| 10 | +comparison ("issuer mismatch"), and a token minted for the advertised |
| 11 | +``resource`` fails the verbatim ``aud`` check. |
| 12 | +
|
| 13 | +This module post-processes the served PRM response so the two identifier fields |
| 14 | +carry exactly the operator-configured strings, without touching any other field |
| 15 | +(scopes, bearer methods, cache headers, CORS) the upstream route emits. |
| 16 | +""" |
| 17 | + |
| 18 | +import json |
| 19 | +from collections.abc import Awaitable, Callable, MutableSequence |
| 20 | +from typing import Any |
| 21 | + |
| 22 | +from starlette.routing import BaseRoute, Route |
| 23 | + |
| 24 | +_PRM_PATH_PREFIX = "/.well-known/oauth-protected-resource" |
| 25 | + |
| 26 | +_Scope = dict[str, Any] |
| 27 | +_Message = dict[str, Any] |
| 28 | +_Receive = Callable[[], Awaitable[_Message]] |
| 29 | +_Send = Callable[[_Message], Awaitable[None]] |
| 30 | +_ASGIApp = Callable[[_Scope, _Receive, _Send], Awaitable[None]] |
| 31 | + |
| 32 | + |
| 33 | +def _rewrite_body(body: bytes, *, issuer: str, resource: str) -> bytes: |
| 34 | + """Return the PRM JSON body with the configured identifiers set verbatim. |
| 35 | +
|
| 36 | + Rewrites only the entries that match the configured identifier up to a |
| 37 | + trailing-slash normalization: in ``authorization_servers`` the element equal |
| 38 | + to ``issuer`` or ``issuer + "/"`` is swapped for the verbatim ``issuer`` and |
| 39 | + every other entry is left in place, so a multi-AS advertisement keeps its |
| 40 | + extra entries. ``resource`` is set verbatim. |
| 41 | +
|
| 42 | + Any body that is not a JSON object (e.g. a CORS preflight with an empty |
| 43 | + body) is returned unchanged. |
| 44 | + """ |
| 45 | + try: |
| 46 | + doc = json.loads(body) |
| 47 | + except (ValueError, TypeError): |
| 48 | + return body |
| 49 | + if not isinstance(doc, dict): |
| 50 | + return body |
| 51 | + changed = False |
| 52 | + servers = doc.get("authorization_servers") |
| 53 | + if isinstance(servers, list): |
| 54 | + rewritten = [issuer if entry in (issuer, issuer + "/") else entry for entry in servers] |
| 55 | + if rewritten != servers: |
| 56 | + doc["authorization_servers"] = rewritten |
| 57 | + changed = True |
| 58 | + if "resource" in doc and doc["resource"] != resource: |
| 59 | + doc["resource"] = resource |
| 60 | + changed = True |
| 61 | + if not changed: |
| 62 | + return body |
| 63 | + return json.dumps(doc, separators=(",", ":")).encode("utf-8") |
| 64 | + |
| 65 | + |
| 66 | +def _wrap_app(inner: _ASGIApp, *, issuer: str, resource: str) -> _ASGIApp: |
| 67 | + """Wrap an ASGI app so a JSON PRM body is rewritten before it is sent. |
| 68 | +
|
| 69 | + The PRM document is small and always flushed in a single body frame, so |
| 70 | + the wrapper buffers the whole body, rewrites it, then emits the (possibly |
| 71 | + resized) response in one shot. |
| 72 | + """ |
| 73 | + |
| 74 | + async def app(scope: _Scope, receive: _Receive, send: _Send) -> None: |
| 75 | + if scope.get("type") != "http": |
| 76 | + await inner(scope, receive, send) |
| 77 | + return |
| 78 | + |
| 79 | + start: _Message | None = None |
| 80 | + chunks: list[bytes] = [] |
| 81 | + |
| 82 | + async def capture(message: _Message) -> None: |
| 83 | + nonlocal start |
| 84 | + message_type = message["type"] |
| 85 | + if message_type == "http.response.start": |
| 86 | + # Defer the start frame until the body is assembled so the |
| 87 | + # Content-Length header can be corrected for the rewrite. |
| 88 | + start = message |
| 89 | + return |
| 90 | + if message_type == "http.response.body": |
| 91 | + chunks.append(message.get("body", b"")) |
| 92 | + if message.get("more_body", False): |
| 93 | + return |
| 94 | + if start is None: |
| 95 | + # An ASGI server must send http.response.start before any |
| 96 | + # http.response.body frame; guard explicitly rather than |
| 97 | + # asserting, since ``assert`` is stripped under ``python -O``. |
| 98 | + raise RuntimeError("http.response.body received before http.response.start") |
| 99 | + new_body = _rewrite_body(b"".join(chunks), issuer=issuer, resource=resource) |
| 100 | + headers = [ |
| 101 | + (key, value) |
| 102 | + for (key, value) in start.get("headers", []) |
| 103 | + if key.lower() != b"content-length" |
| 104 | + ] |
| 105 | + headers.append((b"content-length", str(len(new_body)).encode("latin-1"))) |
| 106 | + await send({**start, "headers": headers}) |
| 107 | + await send({"type": "http.response.body", "body": new_body}) |
| 108 | + return |
| 109 | + await send(message) |
| 110 | + |
| 111 | + await inner(scope, receive, capture) |
| 112 | + |
| 113 | + return app |
| 114 | + |
| 115 | + |
| 116 | +def rewrite_prm_routes_verbatim( |
| 117 | + routes: MutableSequence[BaseRoute], *, issuer: str, resource: str |
| 118 | +) -> None: |
| 119 | + """Wrap, in place, every Protected Resource Metadata route in ``routes``. |
| 120 | +
|
| 121 | + Matches routes registered under ``/.well-known/oauth-protected-resource`` |
| 122 | + (RFC 9728 §3) and swaps their ASGI app for one that advertises ``issuer`` |
| 123 | + and ``resource`` verbatim. |
| 124 | + """ |
| 125 | + for route in routes: |
| 126 | + if isinstance(route, Route) and ( |
| 127 | + route.path == _PRM_PATH_PREFIX or route.path.startswith(_PRM_PATH_PREFIX + "/") |
| 128 | + ): |
| 129 | + route.app = _wrap_app(route.app, issuer=issuer, resource=resource) |
0 commit comments