Skip to content

Commit cf96d57

Browse files
bokelleyclaude
andauthored
feat(server): let PrincipalResolverError carry a stable error code (#1633)
PrincipalResolverError(403, code="identity_org_mismatch") answers 403 {"error": "identity_org_mismatch"} on MCP and A2A. Codes must match ^[a-z][a-z0-9_]{0,63}$; anything else falls back to the generic body. Exception text is never sent, and the default bodies are unchanged. Fixes #1623 Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent b5234e2 commit cf96d57

4 files changed

Lines changed: 171 additions & 7 deletions

File tree

‎docs/principal-resolution.md‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,21 @@ Returning `Principal` authenticates the request. Returning `None` applies the
5656
usual missing-bearer policy, including explicitly configured discovery and
5757
`allow_unauthenticated` behavior. Raising `PrincipalResolverError(401)` or
5858
`PrincipalResolverError(403)` rejects regardless of that opt-in. Responses contain
59-
only generic `unauthenticated`/`forbidden` error bodies. A 401 carries the shared
60-
Bearer challenge; 403 does not. Other resolver exceptions and invalid return
59+
only generic `unauthenticated`/`forbidden` error bodies unless the resolver
60+
supplies a stable code. A 401 carries the shared Bearer challenge; 403 does not.
61+
62+
When your integrators branch on documented rejection codes, pass one as `code`:
63+
64+
```python
65+
raise PrincipalResolverError(403, code="identity_org_mismatch")
66+
# -> 403 {"error": "identity_org_mismatch"}
67+
```
68+
69+
`code` must match `^[a-z][a-z0-9_]{0,63}$`. It is a fixed identifier from your
70+
documented set, never a message or a value derived from the request. A code that
71+
doesn't match falls back to the generic body for that status, and the auth log
72+
records only the coarse reason `invalid_code`, never the value. Exception text
73+
is never sent. Without `code` the bodies are unchanged. Other resolver exceptions and invalid return
6174
values fail closed with generic 401; auth logs contain only coarse reason codes,
6275
never callback exception text or credential values.
6376

‎src/adcp/server/auth.py‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ async def validate_token(token: str) -> Principal | None:
7474
import inspect
7575
import json
7676
import logging
77+
import re
7778
import warnings
7879
from collections.abc import Awaitable, Callable, Collection, Mapping, Sequence
7980
from contextvars import ContextVar
@@ -267,17 +268,24 @@ def __call__(self, request: AuthRequest) -> Awaitable[Principal | None]: ...
267268
"""
268269

269270

271+
_RESOLVER_ERROR_CODE = re.compile(r"[a-z][a-z0-9_]{0,63}")
272+
273+
270274
class PrincipalResolverError(Exception):
271-
"""Intentional resolver rejection. Only the status is sent to the caller.
275+
"""Intentional resolver rejection. Only the status and code reach the caller.
272276
273277
401 means identity was not established; 403 means it is forbidden by the
274-
resolver's policy. Responses use fixed generic bodies, never exception text.
278+
resolver's policy. Responses never include exception text. The body is
279+
``{"error": code}`` when ``code`` is a stable machine-readable identifier
280+
matching ``^[a-z][a-z0-9_]{0,63}$`` (for example ``identity_org_mismatch``),
281+
otherwise the generic ``unauthenticated``/``forbidden`` body.
275282
"""
276283

277-
def __init__(self, status_code: Literal[401, 403] = 401) -> None:
284+
def __init__(self, status_code: Literal[401, 403] = 401, *, code: str | None = None) -> None:
278285
if status_code not in (401, 403):
279286
raise ValueError("PrincipalResolverError status_code must be 401 or 403")
280287
self.status_code = status_code
288+
self.code = code
281289
super().__init__("Principal resolution rejected")
282290

283291

@@ -313,10 +321,17 @@ async def _resolve_request_principal(
313321

314322

315323
def _resolver_rejection(error: PrincipalResolverError) -> JSONResponse:
324+
code = error.code
325+
if code is not None and not (
326+
isinstance(code, str) and _RESOLVER_ERROR_CODE.fullmatch(code) is not None
327+
):
328+
# Never echo a code that could carry free text; log no value either.
329+
logger.warning("principal resolver code rejected", extra={"reason": "invalid_code"})
330+
code = None
316331
if error.status_code == 403:
317-
return JSONResponse({"error": "forbidden"}, status_code=403)
332+
return JSONResponse({"error": code or "forbidden"}, status_code=403)
318333
return JSONResponse(
319-
{"error": "unauthenticated"},
334+
{"error": code or "unauthenticated"},
320335
status_code=401,
321336
headers={"WWW-Authenticate": _WWW_AUTHENTICATE_CHALLENGE},
322337
)

‎tests/test_auth_principal_resolver.py‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,128 @@ def resolve(request: AuthRequest) -> Any:
268268
assert not errors
269269

270270

271+
@pytest.mark.asyncio
272+
@pytest.mark.parametrize("leg", ["mcp", "a2a"])
273+
@pytest.mark.parametrize("status", [401, 403])
274+
@pytest.mark.parametrize("code", ["identity_org_mismatch", "network_policy_denied", "x"])
275+
async def test_resolver_rejection_carries_a_stable_code(
276+
leg: str, status: Any, code: str, caplog: pytest.LogCaptureFixture
277+
) -> None:
278+
def resolve(request: AuthRequest) -> Principal | None:
279+
error = PrincipalResolverError(status, code=code)
280+
error.args = ("private-token",)
281+
raise error
282+
283+
config = BearerTokenAuth(validate_token=lambda token: None, resolve_principal=resolve)
284+
with caplog.at_level(logging.DEBUG, logger="adcp.server.auth"):
285+
async with httpx.AsyncClient(
286+
transport=httpx.ASGITransport(app=resolver_app(leg, config)), base_url="http://test"
287+
) as client:
288+
response = await client.post("/", json=CALL)
289+
assert response.status_code == status
290+
assert response.json() == {"error": code}
291+
assert ("www-authenticate" in response.headers) == (status == 401)
292+
assert "private-token" not in caplog.text + response.text
293+
294+
295+
@pytest.mark.asyncio
296+
@pytest.mark.parametrize("leg", ["mcp", "a2a"])
297+
@pytest.mark.parametrize("status", [401, 403])
298+
@pytest.mark.parametrize(
299+
"code",
300+
[
301+
"",
302+
"Identity_org_mismatch",
303+
"1dentity",
304+
"_identity",
305+
"identity-org-mismatch",
306+
"identity org mismatch",
307+
"identity_org_mismatch\n",
308+
"a" * 65,
309+
"token=private-token",
310+
42,
311+
],
312+
)
313+
async def test_resolver_rejection_falls_back_on_an_unsafe_code(
314+
leg: str, status: Any, code: Any, caplog: pytest.LogCaptureFixture
315+
) -> None:
316+
def resolve(request: AuthRequest) -> Principal | None:
317+
raise PrincipalResolverError(status, code=code)
318+
319+
config = BearerTokenAuth(validate_token=lambda token: None, resolve_principal=resolve)
320+
with caplog.at_level(logging.DEBUG, logger="adcp.server.auth"):
321+
async with httpx.AsyncClient(
322+
transport=httpx.ASGITransport(app=resolver_app(leg, config)), base_url="http://test"
323+
) as client:
324+
response = await client.post("/", json=CALL)
325+
assert response.status_code == status
326+
assert response.json() == {"error": "forbidden" if status == 403 else "unauthenticated"}
327+
assert ("www-authenticate" in response.headers) == (status == 401)
328+
rejected = [r for r in caplog.records if getattr(r, "reason", None) == "invalid_code"]
329+
assert len(rejected) == 1
330+
assert rejected[0].args == ()
331+
if code not in ("", "a" * 65):
332+
assert str(code) not in caplog.text + response.text
333+
334+
335+
@pytest.mark.asyncio
336+
async def test_combined_server_resolver_code_on_both_transports() -> None:
337+
class Seller(ADCPHandler):
338+
advertised_tools = {"get_products"}
339+
340+
async def get_products(self, params: Any, context: Any = None) -> dict[str, Any]:
341+
raise AssertionError("a rejected caller must not reach the handler")
342+
343+
async def resolve(request: AuthRequest) -> Principal | None:
344+
raise PrincipalResolverError(403, code="identity_org_mismatch")
345+
346+
app = _build_mcp_and_a2a_app(
347+
Seller(),
348+
name="seller",
349+
port=3001,
350+
host="127.0.0.1",
351+
instructions=None,
352+
test_controller=None,
353+
validation=None,
354+
stateless_http=True,
355+
enable_dns_rebinding_protection=False,
356+
context_factory=auth_context_factory,
357+
auth=BearerTokenAuth(validate_token=lambda token: None, resolve_principal=resolve),
358+
)
359+
params = {"buying_mode": "brief", "brief": "video"}
360+
mcp = {
361+
"jsonrpc": "2.0",
362+
"id": 1,
363+
"method": "tools/call",
364+
"params": {"name": "get_products", "arguments": params},
365+
}
366+
a2a = {
367+
"jsonrpc": "2.0",
368+
"id": 1,
369+
"method": "SendMessage",
370+
"params": {
371+
"message": {
372+
"messageId": "m1",
373+
"role": "ROLE_USER",
374+
"parts": [{"data": {"skill": "get_products", "parameters": params}}],
375+
}
376+
},
377+
}
378+
async with LifespanManager(app):
379+
async with httpx.AsyncClient(
380+
transport=httpx.ASGITransport(app=app), base_url="http://test", follow_redirects=True
381+
) as client:
382+
for path, body in [("/mcp", mcp), ("/", a2a)]:
383+
response = await client.post(
384+
path,
385+
json=body,
386+
headers={"accept": "application/json, text/event-stream", "A2A-Version": "1.0"},
387+
)
388+
assert response.status_code == 403, response.text
389+
assert response.json() == {"error": "identity_org_mismatch"}
390+
assert "www-authenticate" not in response.headers
391+
392+
271393
@pytest.mark.asyncio
272394
@pytest.mark.parametrize("leg", ["mcp", "a2a"])
273395
@pytest.mark.parametrize("allow", [False, True])

‎tests/type_checks/principal_resolver.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,17 @@ async def __call__(self, request: AuthRequest) -> Principal | None:
4242

4343
unauthorized = PrincipalResolverError(401)
4444
forbidden = PrincipalResolverError(403)
45+
46+
# A stable machine-readable code answers 403 {"error": "identity_org_mismatch"}.
47+
coded = PrincipalResolverError(403, code="identity_org_mismatch")
48+
coded_unauthenticated = PrincipalResolverError(401, code="identity_required")
49+
code: str | None = coded.code
50+
51+
52+
def resolve_with_code(request: AuthRequest) -> Principal | None:
53+
if request.state.get("verified_proxy_org") != request.headers.get("x-org"):
54+
raise PrincipalResolverError(403, code="identity_org_mismatch")
55+
return None
56+
57+
58+
BearerTokenAuth(validate_token=lambda token: None, resolve_principal=resolve_with_code)

0 commit comments

Comments
 (0)