DCR `RegistrationHandler` accepts `{"redirect_uris": null}` and returns `201 Created` for `authorization_code` clients

Offen Anfängerfreundlich
#3,885 3 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Maintainer antworten meist innerhalb von 1 Tag

Dieses Issue hat noch niemand übernommen.

  • #3901 von @MrSpy00 — ohne Merge geschlossen
  • #3914 von @EnesKartal — ohne Merge geschlossen
  • #3930 von @NUAAwqy — ohne Merge geschlossen
  • #3940 von @Echolonius — ohne Merge geschlossen

Bewertung

Schwierigkeit
2/5
Geschätzter Aufwand
1-3 Stunden
Anfängerfreundlichkeit
82/100
Issue-Typ
Bug
Klarheit
Klar beschrieben
Aktivitätsstatus
Aktiv
Tech-Stack
python
Bereich
authentication

Rechercherichtung

Lies RegistrationHandler.handle in src/mcp/server/auth/handlers/register.py, beginnend bei der bestehenden private_key_jwt-Ablehnung, dann den Prüfungen für grant_types/response_types. Bestätige, dass die Union bei src/mcp/shared/auth.py:118 null durchlässt, und reproduziere es mit den drei Payloads des Beispielskripts. Füge nach diesen Prüfungen die redirect_uris-Absicherung hinzu sowie einen Regressionstest, der für {"redirect_uris": null} 400 invalid_client_metadata erwartet; erledigt bedeutet, dass null und [] sich gleich verhalten und bestehende Auth-Tests weiterhin bestehen. Beachte, dass der Reporter einen PR anbietet, also prüfe zuerst, ob es bereits eine Beanspruchung gibt.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

bug v1 v2
Initial Checks
Release line

2.x (current stable)

Description

POST /register (mcp.server.auth.handlers.register.RegistrationHandler.handle) properly rejects requests where redirect_uris is omitted (400 invalid_client_metadata) or empty (redirect_uris: [], 400 invalid_client_metadata), but accepts {"redirect_uris": null} and returns 201 Created, minting a client_id and client_secret and persisting a client with redirect_uris=None via provider.register_client(...).

Root cause
  1. OAuthClientMetadata.redirect_uris (src/mcp/shared/auth.py:118) is typed list[AnyUrl] | None = Field(..., min_length=1) so non-redirect flows (such as pre-registered jwt-bearer clients) can construct OAuthClientMetadata(redirect_uris=None).
  2. Because None satisfies the union and bypasses min_length=1, an explicit JSON "redirect_uris": null passes OAuthClientMetadata.model_validate_json(body).
  3. RegistrationHandler.handle() (src/mcp/server/auth/handlers/register.py) requires "authorization_code" in grant_types and "code" in response_types (and explicitly refuses jwt-bearer), yet never checks if not client_metadata.redirect_uris:.
Impact
  • Violates RFC 7591 §2 ("Clients using flows with redirection MUST register their redirection URI values").
  • Mirrors the exact invariant already enforced for private_key_jwt in RegistrationHandler.handle() (lines 53–64): mints credentials and stores a client record whose every /authorize request will fail OAuthClientInformationFull.validate_redirect_uri() with InvalidRedirectUriError.
Suggested fix

Keep OAuthClientMetadata.redirect_uris: list[AnyUrl] | None unchanged (so non-redirect client models continue working), and add an explicit check in RegistrationHandler.handle() after the grant_types/response_types checks:

if not client_metadata.redirect_uris:
    return PydanticJSONResponse(
        content=RegistrationErrorResponse(
            error="invalid_client_metadata",
            error_description="redirect_uris is required for authorization_code grant",
        ),
        status_code=400,
    )

I have a minimal fix + regression test verified locally (pytest, ruff, pyright) and would be happy to submit a PR if this is confirmed.

Example Code
import asyncio
import httpx2
from pydantic import AnyHttpUrl
from starlette.applications import Starlette

from mcp.server.auth.provider import OAuthAuthorizationServerProvider
from mcp.server.auth.routes import create_auth_routes
from mcp.server.auth.settings import ClientRegistrationOptions
from mcp.shared.auth import OAuthClientInformationFull


class DummyProvider(OAuthAuthorizationServerProvider):
    def __init__(self):
        self.clients: dict[str, OAuthClientInformationFull] = {}

    async def get_client(self, client_id: str) -> OAuthClientInformationFull | None:
        return self.clients.get(client_id)

    async def register_client(self, client_info: OAuthClientInformationFull) -> None:
        self.clients[client_info.client_id] = client_info


async def main() -> None:
    provider = DummyProvider()
    routes = create_auth_routes(
        provider=provider,
        issuer_url=AnyHttpUrl("https://auth.example.com"),
        client_registration_options=ClientRegistrationOptions(enabled=True),
    )
    app = Starlette(routes=routes)
    transport = httpx2.ASGITransport(app=app)
    async with httpx2.AsyncClient(transport=transport, base_url="https://auth.example.com") as client:
        for label, payload in [
            ("missing", {"client_name": "c"}),
            ("empty", {"redirect_uris": [], "client_name": "c"}),
            ("null", {"redirect_uris": None, "client_name": "c"}),
        ]:
            resp = await client.post("/register", json=payload)
            print(label, resp.status_code, resp.json())
    print("registered clients:", len(provider.clients))


asyncio.run(main())
# Actual output:
# missing 400 {'error': 'invalid_client_metadata', 'error_description': 'redirect_uris: Field required'}
# empty 400 {'error': 'invalid_client_metadata', 'error_description': 'redirect_uris: List should have at least 1 item after validation, not 0'}
# null 201 {'response_types': ['code'], 'client_name': 'c', 'token_endpoint_auth_method': 'client_secret_post', 'grant_types': ['authorization_code', 'refresh_token'], 'application_type': 'native', 'client_id': '...', 'client_secret': '...', 'client_id_issued_at': ..., 'client_secret_expires_at': 0}
# registered clients: 1
Python & MCP Python SDK
Python 3.14.8, macOS
modelcontextprotocol/python-sdk main @ 77001c96 (2.3.1.dev20+77001c96)

AI disclosure: AI assistance was used to help investigate and draft this issue; the reproduction and observed output were verified locally.

Vorherrschende Sprache
Python
Sterne
25k
Forks
4.2k
Ø Merge
10 Min.
Gemergte PRs (30 T.)
1

Entwicklungsumgebung

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus modelcontextprotocol/python-sdk

Alle Issues in modelcontextprotocol/python-sdk

Ähnliche Issues

Weitere Issues zu Python

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.