fix: resolve all ruff lint errors and type checker warnings

- Use Annotated[str, Form()] for FastAPI dependencies (FAST002)
- Add missing type annotations across src/ and tests/ (ANN001/003/201/202)
- Reduce function arguments via request.form() reads (PLR0913)
- Combine return paths to reduce return statements (PLR0911)
- Use anyio.Path for async-safe filesystem operations (ASYNC240)
- Extract constants, helpers, and dict comprehensions for clarity
- Move inline imports to top-level (PLC0415)
- Use raw strings for regex match patterns (RUF043)
- Fix redundant get_session_user call in delete_user (not-iterable)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Johan Lundberg 2026-03-31 15:48:46 +02:00
parent 2b652ff603
commit 01e3382aaf
No known key found for this signature in database
GPG key ID: A6C152738D03C7D1
23 changed files with 258 additions and 214 deletions

View file

@ -2,48 +2,41 @@ import json
import secrets
from base64 import b64encode
from datetime import UTC, datetime
from typing import Any
from urllib.parse import parse_qs, urlparse
from argon2 import PasswordHasher
from cryptojwt.jwk.jwk import key_from_jwk_dict
from cryptojwt.jws.jws import JWS
from fastapi import FastAPI
from httpx import AsyncClient
from porchlight.authn.password import PasswordService
from porchlight.models import PasswordCredential, User
from tests.conftest import get_csrf_token
CLIENT_ID = "e2e-rp"
CLIENT_SECRET = "e2e-secret-0123456789abcdef" # 30+ chars
REDIRECT_URI = "http://localhost:9000/callback"
async def test_full_authorization_code_flow(client: AsyncClient) -> None:
"""End-to-end test of the complete OIDC Authorization Code flow.
Exercises: discovery, client registration, authorization request,
password login, authorization completion, token exchange, ID token
validation (JWKS + JWT signature), and userinfo.
"""
# -- Setup: register RP client and create user --
app = client._transport.app # type: ignore[union-attr]
async def _setup_rp_and_user(app: FastAPI) -> None:
"""Register an RP client and create a test user with password."""
oidc_server = app.state.oidc_server
user_repo = app.state.user_repo
cred_repo = app.state.credential_repo
client_id = "e2e-rp"
client_secret = "e2e-secret-0123456789abcdef" # 30+ chars
redirect_uri = "http://localhost:9000/callback"
state = secrets.token_urlsafe(16)
nonce = secrets.token_urlsafe(16)
oidc_server.context.cdb[client_id] = {
"client_id": client_id,
"client_secret": client_secret,
"redirect_uris": [(redirect_uri, {})],
oidc_server.context.cdb[CLIENT_ID] = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"redirect_uris": [(REDIRECT_URI, {})],
"response_types_supported": ["code"],
"token_endpoint_auth_method": "client_secret_basic",
"scope": ["openid", "profile", "email"],
"allowed_scopes": ["openid", "profile", "email"],
"client_salt": secrets.token_hex(8),
}
oidc_server.keyjar.add_symmetric(client_id, client_secret)
oidc_server.keyjar.add_symmetric(CLIENT_ID, CLIENT_SECRET)
user = User(
userid="lusab-bansen",
@ -60,13 +53,16 @@ async def test_full_authorization_code_flow(client: AsyncClient) -> None:
svc = PasswordService(hasher=PasswordHasher(time_cost=1, memory_cost=8192))
await cred_repo.create_password(PasswordCredential(user_id=user.userid, password_hash=svc.hash("testpass")))
# -- Step 1: Authorization request (unauthenticated) → redirect to /login --
async def _login_and_authorize(client: AsyncClient, state: str, nonce: str) -> str:
"""Perform authorization request, login, consent, and return the auth code."""
# Step 1: Authorization request (unauthenticated) -> redirect to /login
auth_res = await client.get(
"/authorization",
params={
"response_type": "code",
"client_id": client_id,
"redirect_uri": redirect_uri,
"client_id": CLIENT_ID,
"redirect_uri": REDIRECT_URI,
"scope": "openid profile email",
"state": state,
"nonce": nonce,
@ -76,7 +72,7 @@ async def test_full_authorization_code_flow(client: AsyncClient) -> None:
assert auth_res.status_code in (302, 303), f"Expected redirect to /login, got {auth_res.status_code}"
assert "/login" in auth_res.headers["location"]
# -- Step 2: Password login → HX-Redirect to /authorization/complete --
# Step 2: Password login -> HX-Redirect to /authorization/complete
token = await get_csrf_token(client)
login_res = await client.post(
"/login/password",
@ -89,14 +85,14 @@ async def test_full_authorization_code_flow(client: AsyncClient) -> None:
f"Expected HX-Redirect to /authorization/complete, got '{hx_redirect}'"
)
# -- Step 3: Complete authorization → redirect to consent --
# Step 3: Complete authorization -> redirect to consent
complete_res = await client.get("/authorization/complete", follow_redirects=False)
assert complete_res.status_code in (302, 303), (
f"Expected redirect to /consent, got {complete_res.status_code}: {complete_res.text}"
)
assert "/consent" in complete_res.headers["location"]
# -- Step 3b: Approve consent → redirect to callback with code + state --
# Step 3b: Approve consent -> redirect to callback with code + state
token = await get_csrf_token(client)
consent_res = await client.post(
"/consent",
@ -117,15 +113,18 @@ async def test_full_authorization_code_flow(client: AsyncClient) -> None:
code = callback_params["code"][0]
assert len(code) > 0
return code
# -- Step 4: Token exchange → access_token, id_token, token_type --
auth_header = b64encode(f"{client_id}:{client_secret}".encode()).decode()
async def _exchange_token(client: AsyncClient, code: str) -> dict[str, Any]:
"""Exchange authorization code for tokens."""
auth_header = b64encode(f"{CLIENT_ID}:{CLIENT_SECRET}".encode()).decode()
token_res = await client.post(
"/token",
data={
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirect_uri,
"redirect_uri": REDIRECT_URI,
},
headers={
"Authorization": f"Basic {auth_header}",
@ -138,45 +137,59 @@ async def test_full_authorization_code_flow(client: AsyncClient) -> None:
assert "access_token" in token_data
assert "id_token" in token_data
assert token_data["token_type"].lower() == "bearer"
return token_data
access_token = token_data["access_token"]
id_token_jwt = token_data["id_token"]
# -- Step 5: Validate ID token — fetch JWKS, verify JWT signature --
async def _validate_id_token(client: AsyncClient, id_token_jwt: str, nonce: str) -> str:
"""Validate the ID token via JWKS and return the sub claim."""
jwks_res = await client.get("/jwks")
assert jwks_res.status_code == 200
jwks = jwks_res.json()
assert "keys" in jwks
assert len(jwks["keys"]) > 0
# Decode the ID token header to find the key ID
id_token_header = json.loads(JWS()._decode(id_token_jwt.split(".")[0]))
id_token_header = json.loads(JWS()._decode(id_token_jwt.split(".", maxsplit=1)[0]))
kid = id_token_header.get("kid")
# Find the matching key in JWKS
matching_keys = [k for k in jwks["keys"] if k.get("kid") == kid]
assert len(matching_keys) == 1, f"Expected 1 matching key for kid={kid}, found {len(matching_keys)}"
key = key_from_jwk_dict(matching_keys[0])
# Verify JWT signature and decode payload
verifier = JWS()
payload = verifier.verify_compact(id_token_jwt, keys=[key])
id_token_payload = json.loads(payload) if isinstance(payload, (str, bytes)) else payload
assert id_token_payload["iss"] == "http://localhost:8000"
assert client_id in id_token_payload["aud"]
assert CLIENT_ID in id_token_payload["aud"]
assert id_token_payload["nonce"] == nonce
# sub is a pairwise identifier — just verify it exists and is non-empty
id_token_sub = id_token_payload["sub"]
assert isinstance(id_token_sub, str)
assert len(id_token_sub) > 0
return id_token_sub
async def test_full_authorization_code_flow(client: AsyncClient) -> None:
"""End-to-end test of the complete OIDC Authorization Code flow.
Exercises: discovery, client registration, authorization request,
password login, authorization completion, token exchange, ID token
validation (JWKS + JWT signature), and userinfo.
"""
app = client._transport.app # type: ignore[union-attr]
state = secrets.token_urlsafe(16)
nonce = secrets.token_urlsafe(16)
await _setup_rp_and_user(app)
code = await _login_and_authorize(client, state, nonce)
token_data = await _exchange_token(client, code)
id_token_sub = await _validate_id_token(client, token_data["id_token"], nonce)
# -- Step 6: UserInfo — GET /userinfo with Bearer token --
userinfo_res = await client.get(
"/userinfo",
headers={"Authorization": f"Bearer {access_token}"},
headers={"Authorization": f"Bearer {token_data['access_token']}"},
)
assert userinfo_res.status_code == 200, f"UserInfo failed: {userinfo_res.status_code} {userinfo_res.text}"