fix(oidc): return 400 instead of 500 on bad token requests

The token endpoint wrapped parse_request in try/except but
  called process_request and do_response unguarded, so a parseable-but-invalid request (e.g. a refresh_token grant missing client_id, or an
  unknown token) made idpyoidc raise and surfaced as a 500. Wrap both so failures return a clean 400 invalid_request and log the traceback
  server-side. Adds a regression test.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Johan Lundberg 2026-06-10 14:37:01 +02:00
parent 3c5451b9c2
commit b284cf596b
No known key found for this signature in database
GPG key ID: A6C152738D03C7D1
2 changed files with 42 additions and 3 deletions

View file

@ -126,6 +126,25 @@ async def test_token_endpoint_exchanges_code(client: AsyncClient) -> None:
assert data["token_type"].lower() == "bearer"
async def test_refresh_grant_failure_returns_400_not_500(client: AsyncClient) -> None:
"""A refresh_token request that idpyoidc cannot process (here: unknown token,
no client_id in body) must surface as a 400, not a server 500."""
_register_test_client(client)
client_secret = "test-secret-0123456789abcdef"
auth_header = b64encode(f"test-rp:{client_secret}".encode()).decode()
token_res = await client.post(
"/token",
data={"grant_type": "refresh_token", "refresh_token": "bogus-token"},
headers={
"Authorization": f"Basic {auth_header}",
"Content-Type": "application/x-www-form-urlencoded",
},
)
assert token_res.status_code == 400, f"Expected 400, got {token_res.status_code}: {token_res.text}"
assert "error" in token_res.json()
async def test_token_endpoint_invalid_code_returns_error(client: AsyncClient) -> None:
_register_test_client(client)
client_secret = "test-secret-0123456789abcdef"