Scaffold FastAPI + MySQL + Keycloak service with devcontainer

Sets up the project skeleton:

- FastAPI app factory with lifespan, request-id middleware, and RFC 9457
  problem+json error handlers
- Async SQLAlchemy 2.0 over MySQL (asyncmy), with a constraint naming
  convention in place before the first migration and async Alembic
- Keycloak as a pure resource server: OIDC discovery, cached JWKS with
  rotation-aware refresh, and require_roles dependencies
- Devcontainer running MySQL 8.4 and Keycloak 26.7 as compose siblings,
  with the realm (clients, roles, test users) imported on first boot
- Test suite covering the endpoints plus the token validator itself,
  exercised against a locally generated RSA keypair
- uv packaging, ruff, mypy --strict, pre-commit, Gitea CI, prod Dockerfile

Two Keycloak-in-containers traps are handled explicitly and documented in
the README: the issuer/internal-URL split (the browser sees localhost:8080,
the API sees keycloak:8080) and the audience mapper that stops Keycloak
issuing tokens with aud=account.

The devices resource is a placeholder proving the routing -> auth -> ORM ->
migration path end to end; replace it with the real domain.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
gnickensandClaude Opus 5 committed 2026-09-10 12:46:52 -04:00
commit 0526d34e42
52 files changed
+4433

No files matched your search

View File
Whitespace-only changes.
+154
View File
@@ -0,0 +1,154 @@
"""Token-forging fixtures for exercising the validator against real crypto.
A locally generated RSA keypair stands in for Keycloak's realm keys, and the
provider's JWKS fetch is redirected at it. That makes it possible to mint
tokens that are genuinely signed -- and genuinely wrong in one specific way per
test -- without a running Keycloak.
"""
from __future__ import annotations
import datetime as dt
import json
from collections.abc import Callable, Iterator
from typing import Any
import jwt
import pytest
from cryptography.hazmat.primitives.asymmetric import rsa
from jwt.utils import base64url_encode
from v2x_server.core.config import Settings
TEST_KID = "test-key-1"
@pytest.fixture(scope="session")
def rsa_key() -> rsa.RSAPrivateKey:
return rsa.generate_private_key(public_exponent=65537, key_size=2048)
@pytest.fixture(scope="session")
def jwks(rsa_key: rsa.RSAPrivateKey) -> dict[str, Any]:
"""The public half, in the JWKS shape Keycloak would serve."""
public_numbers = rsa_key.public_key().public_numbers()
def _b64(value: int) -> str:
length = (value.bit_length() + 7) // 8
return base64url_encode(value.to_bytes(length, "big")).decode()
return {
"keys": [
{
"kty": "RSA",
"kid": TEST_KID,
"use": "sig",
"alg": "RS256",
"n": _b64(public_numbers.n),
"e": _b64(public_numbers.e),
}
]
}
@pytest.fixture
def auth_settings() -> Settings:
return Settings(
app_env="test",
keycloak_issuer="https://idp.test/realms/v2x",
keycloak_internal_url="https://idp.test",
keycloak_realm="v2x",
keycloak_audience="v2x-api",
)
@pytest.fixture
def make_token(rsa_key: rsa.RSAPrivateKey, auth_settings: Settings) -> Callable[..., str]:
"""Mint a signed token, overriding any claim or header field per test."""
def _make(
*,
kid: str | None = TEST_KID,
algorithm: str = "RS256",
key: Any = None,
expires_in: int = 300,
drop: tuple[str, ...] = (),
**claim_overrides: Any,
) -> str:
now = dt.datetime.now(tz=dt.UTC)
claims: dict[str, Any] = {
"sub": "11111111-1111-1111-1111-111111111111",
"iss": auth_settings.keycloak_issuer,
"aud": auth_settings.keycloak_audience,
"iat": now,
"exp": now + dt.timedelta(seconds=expires_in),
"preferred_username": "vera",
"email": "[email protected]",
"scope": "openid profile email",
"realm_access": {"roles": ["viewer"]},
"resource_access": {"v2x-api": {"roles": ["device.read"]}},
}
claims.update(claim_overrides)
for claim in drop:
claims.pop(claim, None)
headers = {"kid": kid} if kid else {}
return jwt.encode(
claims,
key if key is not None else rsa_key,
algorithm=algorithm,
headers=headers,
)
return _make
@pytest.fixture
def unsigned_token(auth_settings: Settings) -> str:
"""An `alg: none` token -- the classic downgrade attempt."""
now = dt.datetime.now(tz=dt.UTC)
header = base64url_encode(
json.dumps({"alg": "none", "typ": "JWT", "kid": TEST_KID}).encode()
).decode()
payload = base64url_encode(
json.dumps(
{
"sub": "attacker",
"iss": auth_settings.keycloak_issuer,
"aud": auth_settings.keycloak_audience,
"iat": int(now.timestamp()),
"exp": int((now + dt.timedelta(minutes=5)).timestamp()),
"realm_access": {"roles": ["admin"]},
}
).encode()
).decode()
return f"{header}.{payload}."
@pytest.fixture
def provider(auth_settings: Settings, jwks: dict[str, Any]) -> Iterator[Any]:
"""An OIDCProvider whose network calls are served from the fixtures above."""
import httpx
from v2x_server.auth.keycloak import OIDCProvider
certs_url = (
f"{auth_settings.keycloak_internal_url}"
f"/realms/{auth_settings.keycloak_realm}/protocol/openid-connect/certs"
)
def handler(request: httpx.Request) -> httpx.Response:
url = str(request.url)
if url.endswith("/.well-known/openid-configuration"):
return httpx.Response(
200,
json={
"issuer": auth_settings.keycloak_issuer,
"jwks_uri": certs_url,
},
)
if url.endswith("/protocol/openid-connect/certs"):
return httpx.Response(200, json=jwks)
return httpx.Response(404)
client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
yield OIDCProvider(auth_settings, client)
+170
View File
@@ -0,0 +1,170 @@
"""The validator must reject every category of bad token, not just expired ones.
Without these, `get_current_principal` could be accepting anything and the
endpoint tests -- which override authentication -- would never notice.
"""
from __future__ import annotations
import datetime as dt
from collections.abc import Callable
import pytest
from cryptography.hazmat.primitives.asymmetric import rsa
from v2x_server.auth.keycloak import OIDCProvider, TokenError
from v2x_server.auth.principal import Principal
async def test_accepts_a_valid_token(
provider: OIDCProvider, make_token: Callable[..., str]
) -> None:
claims = await provider.decode(make_token())
assert claims["sub"] == "11111111-1111-1111-1111-111111111111"
assert claims["preferred_username"] == "vera"
async def test_rejects_expired_token(
provider: OIDCProvider, make_token: Callable[..., str]
) -> None:
# Beyond the 30s leeway.
with pytest.raises(TokenError):
await provider.decode(make_token(expires_in=-120))
async def test_rejects_wrong_issuer(provider: OIDCProvider, make_token: Callable[..., str]) -> None:
with pytest.raises(TokenError):
await provider.decode(make_token(iss="https://evil.test/realms/v2x"))
async def test_rejects_wrong_audience(
provider: OIDCProvider, make_token: Callable[..., str]
) -> None:
# This is the failure Keycloak produces by default: without an audience
# mapper the token's aud is "account", not the API's client id.
with pytest.raises(TokenError):
await provider.decode(make_token(aud="account"))
async def test_rejects_unknown_key_id(
provider: OIDCProvider, make_token: Callable[..., str]
) -> None:
with pytest.raises(TokenError):
await provider.decode(make_token(kid="rotated-away"))
async def test_rejects_missing_key_id(
provider: OIDCProvider, make_token: Callable[..., str]
) -> None:
with pytest.raises(TokenError, match="no kid"):
await provider.decode(make_token(kid=None))
async def test_rejects_alg_none(provider: OIDCProvider, unsigned_token: str) -> None:
with pytest.raises(TokenError):
await provider.decode(unsigned_token)
async def test_rejects_token_signed_by_another_key(
provider: OIDCProvider, make_token: Callable[..., str]
) -> None:
attacker_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
with pytest.raises(TokenError):
await provider.decode(make_token(key=attacker_key))
async def test_rejects_tampered_payload(
provider: OIDCProvider, make_token: Callable[..., str]
) -> None:
header, payload, signature = make_token().split(".")
# Flip a character in the payload; the signature no longer covers it.
mutated = payload[:-2] + ("A" if payload[-2] != "A" else "B") + payload[-1]
with pytest.raises(TokenError):
await provider.decode(f"{header}.{mutated}.{signature}")
async def test_rejects_garbage(provider: OIDCProvider) -> None:
with pytest.raises(TokenError):
await provider.decode("not-a-jwt")
@pytest.mark.parametrize("claim", ["sub", "exp", "iat", "iss", "aud"])
async def test_rejects_token_missing_a_required_claim(
provider: OIDCProvider, make_token: Callable[..., str], claim: str
) -> None:
with pytest.raises(TokenError):
await provider.decode(make_token(drop=(claim,)))
class TestPrincipalMapping:
"""Claim shape -> Principal. The one place that knows Keycloak's layout."""
def test_maps_realm_and_client_roles(self) -> None:
principal = Principal.from_claims(
{
"sub": "abc",
"preferred_username": "vera",
"email": "[email protected]",
"realm_access": {"roles": ["viewer", "operator"]},
"resource_access": {"v2x-api": {"roles": ["device.read"]}},
"scope": "openid profile",
},
client_id="v2x-api",
)
assert principal.realm_roles == frozenset({"viewer", "operator"})
assert principal.client_roles == frozenset({"device.read"})
assert principal.roles == frozenset({"viewer", "operator", "device.read"})
assert principal.has_any_role("operator", "admin")
assert not principal.has_all_roles("operator", "admin")
def test_tolerates_absent_role_blocks(self) -> None:
principal = Principal.from_claims({"sub": "abc"}, client_id="v2x-api")
assert principal.roles == frozenset()
assert principal.username is None
def test_ignores_roles_for_other_clients(self) -> None:
principal = Principal.from_claims(
{
"sub": "abc",
"resource_access": {"some-other-client": {"roles": ["admin"]}},
},
client_id="v2x-api",
)
assert principal.client_roles == frozenset()
async def test_unknown_kid_triggers_a_refresh_once_the_floor_has_passed(
provider: OIDCProvider, make_token: Callable[..., str]
) -> None:
"""Key rotation must be survivable without restarting the process."""
await provider.decode(make_token()) # warm the cache
before = provider._jwks_fetched_at
# Age the cache past the minimum refresh interval.
provider._jwks_fetched_at -= 3600
with pytest.raises(TokenError):
await provider.decode(make_token(kid="unknown-kid"))
# A refetch happened: the timestamp moved forward again.
assert provider._jwks_fetched_at > before - 3600
async def test_unknown_kid_refresh_is_rate_limited(
provider: OIDCProvider, make_token: Callable[..., str]
) -> None:
"""A flood of junk tokens must not become load amplification on Keycloak."""
await provider.decode(make_token())
with pytest.raises(TokenError, match="rate-limited"):
await provider.decode(make_token(kid="unknown-kid"))
async def test_clock_skew_within_leeway_is_accepted(
provider: OIDCProvider, make_token: Callable[..., str]
) -> None:
"""A token issued a few seconds in the future should still pass."""
future = dt.datetime.now(tz=dt.UTC) + dt.timedelta(seconds=10)
claims = await provider.decode(make_token(iat=future, nbf=future))
assert claims["sub"]