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

未關閉 適合新手
#3,885 3 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

維護者通常 1 天內回覆

還沒有人認領這個 Issue。

  • #3901 來自 @MrSpy00 —— 已關閉,未合併
  • #3914 來自 @EnesKartal —— 已關閉,未合併
  • #3930 來自 @NUAAwqy —— 已關閉,未合併
  • #3940 來自 @Echolonius —— 已關閉,未合併

評估

難度
2/5
預估耗時
1-3 小時
新手友好度
82/100
Issue 類型
缺陷
描述清晰度
描述清楚
活躍度
活躍
技術堆疊
python

研究方向

閱讀 src/mcp/server/auth/handlers/register.py 中的 RegistrationHandler.handle,從現有的 private_key_jwt 拒絕邏輯開始,然後是 grant_types/response_types 檢查。確認 src/mcp/shared/auth.py:118 處的 union 允許 null 通過,並用範例腳本的三個 payload 重現。在這些檢查之後加入 redirect_uris 防護,並加入一個回歸測試,斷言 {"redirect_uris": null} 會得到 400 invalid_client_metadata;完成意味著 null 和 [] 行為一致,且現有的 auth 測試仍然通過。注意回報者提出可以提供 PR,所以先檢查是否已有人認領。

由索引模型根據 Issue 內容生成。

描述

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.

主要語言
Python
星號
25k
分支
4.2k
平均合併
10 分鐘
30 天內合併 PR
1

環境準備

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

modelcontextprotocol/python-sdk 的其他 Issue

查看 modelcontextprotocol/python-sdk 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。