fix: reject conflicting auth sources with 400 instead of silently preferring ?token= (#27)
Problem Description / 问题描述
EN: When both an Authorization: Bearer TOKEN_A header and a ?token=TOKEN_B query parameter are provided in the same request, the TokenQuerystringMiddleware silently strips the Authorization header and replaces it with the query token value. This hides client misconfiguration and makes auth problems harder to debug.
中文: 当请求同时包含 Authorization: Bearer TOKEN_A 请求头和 ?token=TOKEN_B 查询参数时,TokenQuerystringMiddleware 会静默替换掉请求头中的 token,改用查询参数中的值。这会掩盖客户端的配置错误,增加调试难度。
Root Cause Analysis / 根因分析
The bug is in TokenQuerystringMiddleware.__call__() in src/openapi_mcp_sdk/main.py (lines 163-170, before this fix). When a ?token= query parameter is present, the middleware unconditionally:
- Strips ALL existing
Authorizationheaders fromscope["headers"] - Injects a new
Authorization: Bearer {query_token}header
This means ?token= always wins, silently discarding any Authorization header the client may have set intentionally.
Fix / 修复方案
Before performing the header replacement, the middleware now checks whether an Authorization header already exists. If both ?token= and Authorization are present, the middleware short-circuits and returns an HTTP 400 response with a JSON body:
{
"error": "conflicting_auth",
"message": "Both ?token= query parameter and Authorization header are present. Use only one authentication source."
}
This is a minimal, backward-compatible change:
- Requests with only
?token=work exactly as before - Requests with only
Authorizationheader work exactly as before - Only requests with both sources now get a clear rejection instead of silent override
Tests / 测试
Added tests/pytest/test_token_querystring.py with 7 test cases:
| Test | What it verifies |
|---|---|
test_query_token_only_sets_auth_header |
?token= alone is promoted to Authorization header |
test_header_only_passes_through |
Authorization header alone passes through unchanged |
test_conflicting_auth_returns_400 |
Both present → 400 with conflicting_auth error |
test_conflicting_auth_response_is_json |
Response has application/json content-type |
test_no_auth_passes_through |
No auth at all → middleware does not interfere |
test_non_http_scope_passes_through |
Non-HTTP scopes (websocket) pass through |
test_query_token_with_other_params_preserved |
Other query params survive when ?token= is stripped |
Tests use mocked ASGI calls to test the middleware in isolation.
Impact / 影响范围
- Scope: Only affects
TokenQuerystringMiddlewareinmain.py - Breaking change: No — previously the conflicting case was undefined behavior (silent override). Now it returns a clear error. Clients relying on the silent override should remove one auth source.
- Security: Positive — prevents accidental token confusion where the wrong token silently wins.