Author SHA1 Message Date
kiskaadee 30d9a889a3 feat(security): harden authentication edge cases and verify deployment independence
- Reject forged, replayed, and expired CSRF state with HTTP 400 Bad Request
- Enforce cryptographic validation rejecting tampered ID token signatures and mismatched/missing nonces with HTTP 401 Unauthorized
- Reject missing, invalid, or mismatched PKCE code_verifier with HTTP 401 Unauthorized (InvalidCodeVerifierError)
- Invalidate expired ID tokens and session cookies returning HTTP 401 Unauthorized
- Enforce role-based access control blocking authenticated non-admin users from admin APIs with HTTP 403 Forbidden
- Eliminate legacy Remote-User trust ensuring session identity strictly governs authorization
- Document and verify dual deployment modes (Standalone Mode vs Homelab Production Mode behind Traefik TLS proxy)
- Add comprehensive security hardening regression suite (tests/test_security_hardening.py) and .env.example template
- Ensure clean multi-stage Docker build
2026-10-03 01:26:05 -05:00
kiskaadee e1f745608a feat(ui): integrate browser SSO authentication and admin logout
- Integrate React SPA admin layout with OIDC authentication check and unauthenticated login redirection
- Support authenticated session resolution via /birthday/api/auth/me and display user identity in admin navigation bar
- Add working Logout button calling /birthday/api/auth/logout to revoke session, clear HttpOnly cookie, and transition UI to unauthenticated state
- Update auth routes callback target to /birthday/admin and handle GET/POST logout redirects
- Add end-to-end browser acceptance tests using Playwright verifying complete interactive login and logout flow
2026-10-03 01:04:40 -05:00
kiskaadee 39ac42cfce feat(admin): migrate admin routes to group authorization and enforce negative Remote-User barrier
- Migrate all admin endpoints in backend/app/routes/admin.py to consume the group authorization dependency require_admin (bdinvite_admins group)
- Completely purge legacy Remote-User header dependency from admin route implementations and API documentation
- Enforce strict negative barrier rejecting requests containing Remote-User without a valid authenticated session with HTTP 401 Unauthorized
- Enforce access control verification: 401 for anonymous requests, 403 for non-admin authenticated users, 200 for bdinvite_admins members
- Update admin test suite and related fixtures in backend/tests/ to authenticate via session cookies and verify full admin functionality and negative barriers
2026-10-03 00:23:43 -05:00
kiskaadee 27015d0d72 feat(auth): implement FastAPI authentication and group authorization dependencies
- FastAPI dependency injection module in backend/app/auth/dependencies.py with get_current_identity, require_authenticated, and require_group factory
- Application admin policy require_admin = require_group("bdinvite_admins")
- Isolated verification and test suite in backend/tests/test_dependencies.py
2026-10-03 00:12:54 -05:00
kiskaadee 815a5847c6 feat(auth): implement browser session management and fixation protection
- Browser session contract with HttpOnly=True and SameSite
- Configurable Secure cookie flag
- Session fixation barrier rotating session ID on login
- Session lifecycle, expiration, and safe rejection of tampered cookies
- Logout endpoint (/birthday/api/auth/logout) revoking session and clearing cookie (Max-Age=0)
- Unit and integration tests in backend/tests/test_session_management.py
2026-10-02 23:39:59 -05:00
kiskaadee 35be202adc feat(auth): map verified OIDC claims to domain Identity and groups
- Extract standard claims (sub, email, name) and groups mapping into domain Identity model
- Support configurable groups_claim and dotted group_claim_path resolution
- Enforce Identity Origin Integrity in OIDCAuthAdapter against unvalidated request headers
- Verify claims extraction and session flows against pre-seeded live fixture users (admin and guest)
2026-10-02 23:15:16 -05:00
kiskaadee 0a4032a344 feat(auth): implement generic OIDC client with PKCE and cryptographic token verification 2026-10-02 23:03:46 -05:00
kiskaadee df498979d9 feat(auth): define AuthPort protocol and Identity domain model 2026-10-02 22:48:41 -05:00
26 changed files with 4548 additions and 105 deletions

No files matched your search

+55
View File
@@ -0,0 +1,55 @@
# ==============================================================================
# BDInvite Environment Configuration Template (.env.example)
#
# BDInvite supports two operational deployment modes configured via environment:
# 1. Direct Standalone Mode (local dev & testing with mock-oauth2-server or Keycloak)
# 2. Homelab Production Mode (behind Traefik TLS proxy with Authelia or OIDC IdP)
# ==============================================================================
# ------------------------------------------------------------------------------
# 1. General Service Configuration
# ------------------------------------------------------------------------------
SERVICE_NAME=bdinvite
SERVICE_DOMAIN=demos.roadtotech.me
BASE_PATH=/birthday
APP_PORT=8000
DATABASE_URL=sqlite:///./data/bdinvite.db
DATA_DIR=./data
# ------------------------------------------------------------------------------
# 2. OpenID Connect (OIDC) Authentication Settings
# ------------------------------------------------------------------------------
# Mode A: Standalone Mode (Default Local Development)
# OIDC_ISSUER=http://localhost:8088/default
# OIDC_CLIENT_ID=bdinvite-client
# OIDC_CLIENT_SECRET=bdinvite-secret
# OIDC_REDIRECT_URI=http://localhost:8000/birthday/api/auth/callback
# Mode B: Homelab Production Mode (Traefik TLS + Authelia / IdP)
# OIDC_ISSUER=https://auth.roadtotech.me
# OIDC_CLIENT_ID=bdinvite
# OIDC_CLIENT_SECRET=change-me-to-production-secret
# OIDC_REDIRECT_URI=https://demos.roadtotech.me/birthday/api/auth/callback
OIDC_ISSUER=http://localhost:8088/default
OIDC_CLIENT_ID=bdinvite-client
OIDC_CLIENT_SECRET=bdinvite-secret
OIDC_REDIRECT_URI=http://localhost:8000/birthday/api/auth/callback
OIDC_GROUPS_CLAIM=groups
# OIDC_GROUP_CLAIM_PATH=realm_access.roles
# ------------------------------------------------------------------------------
# 3. Browser Session Management Settings
# ------------------------------------------------------------------------------
SESSION_COOKIE_NAME=bdinvite_session
# Set SESSION_COOKIE_SECURE to true in production behind HTTPS/TLS reverse proxy.
# Set to false only for local standalone testing over plain HTTP.
SESSION_COOKIE_SECURE=false
# Session cookie SameSite attribute ("lax", "strict", "none")
SESSION_COOKIE_SAMESITE=lax
SESSION_COOKIE_PATH=/
# SESSION_COOKIE_DOMAIN=roadtotech.me
SESSION_EXPIRE_SECONDS=86400
+68
View File
@@ -0,0 +1,68 @@
"""Authentication package providing domain models, hexagonal ports, and OIDC client."""
from .dependencies import (
AdminUserDep,
AuthAdapterDep,
AuthenticatedUserDep,
CurrentIdentityDep,
get_auth_adapter,
get_current_identity,
require_admin,
require_authenticated,
require_group,
set_auth_adapter,
)
from .oidc import (
InvalidCodeVerifierError,
InvalidNonceError,
InvalidStateError,
OIDCAuthAdapter,
OIDCClient,
OIDCConfig,
OIDCDiscovery,
OIDCError,
OIDCTransaction,
SessionRecord,
TokenValidationError,
claims_to_identity,
extract_identity_from_claims,
generate_code_challenge,
generate_code_verifier,
generate_nonce,
generate_state,
resolve_claim_path,
)
from .port import AuthPort, Identity
__all__ = [
"AdminUserDep",
"AuthAdapterDep",
"AuthPort",
"AuthenticatedUserDep",
"CurrentIdentityDep",
"Identity",
"InvalidCodeVerifierError",
"InvalidNonceError",
"InvalidStateError",
"OIDCAuthAdapter",
"OIDCClient",
"OIDCConfig",
"OIDCDiscovery",
"OIDCError",
"OIDCTransaction",
"SessionRecord",
"TokenValidationError",
"claims_to_identity",
"extract_identity_from_claims",
"generate_code_challenge",
"generate_code_verifier",
"generate_nonce",
"generate_state",
"get_auth_adapter",
"get_current_identity",
"require_admin",
"require_authenticated",
"require_group",
"resolve_claim_path",
"set_auth_adapter",
]
+108
View File
@@ -0,0 +1,108 @@
"""FastAPI dependency injection module for authentication and authorization."""
from collections.abc import Callable
from typing import Annotated, Optional
from fastapi import Depends, HTTPException, Request, status
from ..config import settings
from .oidc import OIDCAuthAdapter, OIDCClient, OIDCConfig
from .port import Identity
_auth_adapter: Optional[OIDCAuthAdapter] = None
def get_auth_adapter() -> OIDCAuthAdapter:
"""Provide singleton or cached OIDCAuthAdapter for dependency injection."""
global _auth_adapter
if _auth_adapter is None:
client_config = OIDCConfig(
issuer=settings.OIDC_ISSUER,
client_id=settings.OIDC_CLIENT_ID,
client_secret=settings.OIDC_CLIENT_SECRET,
redirect_uri=settings.OIDC_REDIRECT_URI,
groups_claim=settings.OIDC_GROUPS_CLAIM,
group_claim_path=settings.OIDC_GROUP_CLAIM_PATH,
)
client = OIDCClient(client_config)
_auth_adapter = OIDCAuthAdapter(
client=client,
session_cookie_name=settings.SESSION_COOKIE_NAME,
cookie_secure=settings.SESSION_COOKIE_SECURE,
cookie_samesite=settings.SESSION_COOKIE_SAMESITE,
cookie_path=settings.SESSION_COOKIE_PATH,
cookie_domain=settings.SESSION_COOKIE_DOMAIN,
session_lifetime=float(settings.SESSION_EXPIRE_SECONDS),
)
return _auth_adapter
def set_auth_adapter(adapter: Optional[OIDCAuthAdapter]) -> None:
"""Override the active auth adapter (for test isolation and fixture injection)."""
global _auth_adapter
_auth_adapter = adapter
AuthAdapterDep = Annotated[OIDCAuthAdapter, Depends(get_auth_adapter)]
def get_current_identity(
request: Request,
adapter: OIDCAuthAdapter = Depends(get_auth_adapter),
) -> Optional[Identity]:
"""Resolve the active Identity from the session or adapter, or None if unauthenticated."""
if not isinstance(adapter, OIDCAuthAdapter):
adapter = get_auth_adapter()
return adapter.current_identity(request)
def require_authenticated(
identity: Optional[Identity] = Depends(get_current_identity),
) -> Identity:
"""Enforce authentication, raising HTTP 401 Unauthorized if anonymous."""
if identity is None or not isinstance(identity, Identity):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required",
headers={"WWW-Authenticate": "Bearer"},
)
return identity
def require_group(group_name: str) -> Callable[..., Identity]:
"""Dependency factory enforcing membership in a specified group.
Raises HTTP 401 Unauthorized if anonymous, and HTTP 403 Forbidden
if authenticated but missing the required group in identity.groups.
"""
def _require_group_dependency(
identity: Optional[Identity] = Depends(get_current_identity),
) -> Identity:
if identity is None or not isinstance(identity, Identity):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required",
headers={"WWW-Authenticate": "Bearer"},
)
if group_name not in identity.groups:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Forbidden: user is not a member of group '{group_name}'",
)
return identity
_require_group_dependency.__name__ = f"require_group_{group_name}"
_require_group_dependency.__qualname__ = (
f"require_group.<locals>.require_group_{group_name}"
)
return _require_group_dependency
# Application Authorization Policy:
require_admin: Callable[..., Identity] = require_group("bdinvite_admins")
# Type annotations for endpoint dependency injection
CurrentIdentityDep = Annotated[Optional[Identity], Depends(get_current_identity)]
AuthenticatedUserDep = Annotated[Identity, Depends(require_authenticated)]
AdminUserDep = Annotated[Identity, Depends(require_admin)]
File diff suppressed because it is too large. Load diff
+49
View File
@@ -0,0 +1,49 @@
"""Authentication port and identity abstractions for hexagonal architecture."""
from dataclasses import dataclass, field
from typing import Optional, Protocol, runtime_checkable
from fastapi import Request, Response
@dataclass(frozen=True)
class Identity:
"""Domain model representing a validated authenticated user identity.
Identity Origin Integrity Invariant:
An Identity instance must only represent validated authentication results
(such as from an authorized identity provider, cryptographically verified token,
or trusted authentication adapter). It must never be constructed directly
from raw, unvalidated client request headers.
"""
subject: str
email: str
name: Optional[str] = None
groups: list[str] = field(default_factory=list)
def __post_init__(self) -> None:
if self.groups is None: # type: ignore[reportUnnecessaryComparison]
object.__setattr__(self, "groups", [])
elif not isinstance(self.groups, list):
object.__setattr__(self, "groups", list(self.groups))
@runtime_checkable
class AuthPort(Protocol):
"""Hexagonal inbound/outbound port interface for authentication."""
def current_identity(self, request: Request) -> Optional[Identity]:
"""Extract and return the verified Identity from the incoming request.
Returns None if the request is unauthenticated or credentials are invalid.
"""
...
def login(self, request: Request) -> Response:
"""Handle or initiate the authentication flow (e.g. redirecting to an IdP)."""
...
def logout(self, request: Request) -> Response:
"""Handle session termination or logout redirection."""
...
+46
View File
@@ -1,9 +1,39 @@
from pathlib import Path from pathlib import Path
from typing import Literal
from pydantic_settings import BaseSettings, SettingsConfigDict from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings): class Settings(BaseSettings):
"""Application and deployment configuration supporting multi-mode deployment.
BDInvite supports two primary operational deployment modes via environment variables:
1. Direct Standalone Mode (Local Development & Testing):
- Runs directly or in lightweight container with direct port binding (e.g. 8000).
- Integrates directly with any standard OIDC identity provider (e.g. mock-oauth2-server,
local Keycloak, or Dex).
- Insecure session cookies (`SESSION_COOKIE_SECURE=False`) allow local HTTP testing.
- Example:
OIDC_ISSUER="http://localhost:8088/default"
OIDC_REDIRECT_URI="http://localhost:8000/birthday/api/auth/callback"
SESSION_COOKIE_SECURE=false
2. Homelab Production Mode (Reverse Proxy & Edge Ingress):
- Deployed behind Traefik reverse proxy terminating TLS on edge domain.
- Integrates with central Homelab OIDC Provider (such as Authelia, Keycloak, or Authentik).
- Secure session cookies (`SESSION_COOKIE_SECURE=True`) enforce HTTPS-only transmission.
- Zero trust in unvalidated client headers (e.g. legacy proxy headers are completely ignored).
- Example:
SERVICE_DOMAIN="demos.roadtotech.me"
OIDC_ISSUER="https://auth.roadtotech.me"
OIDC_CLIENT_ID="bdinvite"
OIDC_CLIENT_SECRET="<secret>"
OIDC_REDIRECT_URI="https://demos.roadtotech.me/birthday/api/auth/callback"
SESSION_COOKIE_SECURE=true
SESSION_COOKIE_NAME="bdinvite_session"
"""
SERVICE_NAME: str = "bdinvite" SERVICE_NAME: str = "bdinvite"
SERVICE_DOMAIN: str = "demos.roadtotech.me" SERVICE_DOMAIN: str = "demos.roadtotech.me"
BASE_PATH: str = "/birthday" BASE_PATH: str = "/birthday"
@@ -11,6 +41,22 @@ class Settings(BaseSettings):
DATABASE_URL: str = "sqlite:///./data/bdinvite.db" DATABASE_URL: str = "sqlite:///./data/bdinvite.db"
DATA_DIR: str = "./data" DATA_DIR: str = "./data"
# OIDC & Auth Settings
OIDC_ISSUER: str = "http://localhost:8088/default"
OIDC_CLIENT_ID: str = "bdinvite-client"
OIDC_CLIENT_SECRET: str | None = "bdinvite-secret"
OIDC_REDIRECT_URI: str = "http://localhost:8000/birthday/api/auth/callback"
OIDC_GROUPS_CLAIM: str = "groups"
OIDC_GROUP_CLAIM_PATH: str | None = None
# Browser Session Management Settings
SESSION_COOKIE_NAME: str = "bdinvite_session"
SESSION_COOKIE_SECURE: bool = False
SESSION_COOKIE_SAMESITE: Literal["lax", "strict", "none"] = "lax"
SESSION_COOKIE_PATH: str = "/"
SESSION_COOKIE_DOMAIN: str | None = None
SESSION_EXPIRE_SECONDS: int = 86400
model_config = SettingsConfigDict(env_file=".env", extra="ignore") model_config = SettingsConfigDict(env_file=".env", extra="ignore")
@property @property
+5 -4
View File
@@ -10,7 +10,7 @@ from fastapi.staticfiles import StaticFiles
from .config import settings from .config import settings
from .database import Base, SessionLocal, engine from .database import Base, SessionLocal, engine
from .routes import admin, config, rsvp from .routes import admin, auth, config, rsvp
from .services.config import seed_default_config from .services.config import seed_default_config
@@ -31,8 +31,8 @@ app = FastAPI(
"API REST para la invitación interactiva de cumpleaños con sistema RSVP.\n\n" "API REST para la invitación interactiva de cumpleaños con sistema RSVP.\n\n"
"### Arquitectura de Seguridad\n" "### Arquitectura de Seguridad\n"
"- **Rutas Públicas (`/birthday/api/*`)**: Acceso abierto para los invitados.\n" "- **Rutas Públicas (`/birthday/api/*`)**: Acceso abierto para los invitados.\n"
"- **Rutas Administrativas (`/birthday/api/admin/*`)**: Protegidas por **Authelia ForwardAuth** " "- **Rutas Administrativas (`/birthday/api/admin/*`)**: Protegidas por autenticación "
"a nivel de proxy inverso (Traefik). Cada endpoint valida de forma independiente la cabecera `Remote-User`." "OIDC y autorización basada en grupos (`bdinvite_admins`)."
), ),
openapi_tags=[ openapi_tags=[
{ {
@@ -45,7 +45,7 @@ app = FastAPI(
}, },
{ {
"name": "Admin", "name": "Admin",
"description": "Gestión de asistentes, descarga CSV y edición de contenido protegida por Authelia.", "description": "Gestión de asistentes, descarga CSV y edición de contenido protegida por autorización administrativa.",
}, },
], ],
lifespan=lifespan, lifespan=lifespan,
@@ -90,6 +90,7 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
# Register API routes with exact path prefixes per specification # Register API routes with exact path prefixes per specification
app.include_router(rsvp.router, prefix="/birthday/api") app.include_router(rsvp.router, prefix="/birthday/api")
app.include_router(config.router, prefix="/birthday/api") app.include_router(config.router, prefix="/birthday/api")
app.include_router(auth.router, prefix="/birthday/api/auth")
app.include_router(admin.router, prefix="/birthday/api/admin") app.include_router(admin.router, prefix="/birthday/api/admin")
+4
View File
@@ -1 +1,5 @@
"""API Route definitions.""" """API Route definitions."""
from . import admin, auth, config, rsvp
__all__ = ["admin", "auth", "config", "rsvp"]
+33 -33
View File
@@ -3,9 +3,10 @@ import io
from datetime import UTC, datetime from datetime import UTC, datetime
from typing import Annotated from typing import Annotated
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Response, status from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from ..auth import AdminUserDep, Identity, require_admin
from ..config import settings from ..config import settings
from ..database import get_db from ..database import get_db
from ..schemas import ( from ..schemas import (
@@ -21,38 +22,22 @@ from ..services.config import get_config, seed_default_config, update_config
from ..services.map_preview import generate_map_preview_image, resolve_google_maps_coordinates from ..services.map_preview import generate_map_preview_image, resolve_google_maps_coordinates
from ..services.rsvp import delete_rsvp, get_rsvps, update_rsvp from ..services.rsvp import delete_rsvp, get_rsvps, update_rsvp
router = APIRouter(tags=["Admin"]) router = APIRouter(tags=["Admin"], dependencies=[Depends(require_admin)])
AdminDep = AdminUserDep
def require_admin(
remote_user: Annotated[
str | None,
Header(
alias="Remote-User",
description="Identidad de usuario autenticada e inyectada por Authelia ForwardAuth en el proxy Traefik",
examples=["kiskaadee"],
),
] = None,
) -> str:
"""Security invariant: require verified Remote-User header from Authelia."""
if not remote_user:
raise HTTPException(
status_code=401,
detail="Not authenticated",
)
return remote_user
AdminDep = Annotated[str, Depends(require_admin)]
DbDep = Annotated[Session, Depends(get_db)] DbDep = Annotated[Session, Depends(get_db)]
ADMIN_401 = { ADMIN_RESPONSES = {
401: { 401: {
"description": "No autenticado. Se requiere la cabecera `Remote-User` provista por Authelia ForwardAuth." "description": "No autenticado. Se requiere una sesión válida o token de autorización.",
} },
403: {
"description": "Acceso prohibido. El usuario autenticado no pertenece al grupo administrativo.",
},
} }
@router.get( @router.get(
"/rsvps", "/rsvps",
response_model=RSVPListResponse, response_model=RSVPListResponse,
@@ -63,7 +48,7 @@ ADMIN_401 = {
), ),
responses={ responses={
200: {"model": RSVPListResponse, "description": "Lista de confirmaciones obtenida."}, 200: {"model": RSVPListResponse, "description": "Lista de confirmaciones obtenida."},
**ADMIN_401, **ADMIN_RESPONSES,
}, },
) )
def list_rsvps( def list_rsvps(
@@ -92,7 +77,7 @@ def list_rsvps(
responses={ responses={
204: {"description": "Registro eliminado con éxito."}, 204: {"description": "Registro eliminado con éxito."},
404: {"description": "Registro no encontrado."}, 404: {"description": "Registro no encontrado."},
**ADMIN_401, **ADMIN_RESPONSES,
}, },
) )
def delete_rsvp_endpoint( def delete_rsvp_endpoint(
@@ -119,7 +104,7 @@ def delete_rsvp_endpoint(
400: {"description": "Error de validación en los campos proporcionados."}, 400: {"description": "Error de validación en los campos proporcionados."},
404: {"description": "Registro no encontrado."}, 404: {"description": "Registro no encontrado."},
409: {"description": "El número de teléfono ya está registrado por otro asistente."}, 409: {"description": "El número de teléfono ya está registrado por otro asistente."},
**ADMIN_401, **ADMIN_RESPONSES,
}, },
) )
def update_rsvp_endpoint( def update_rsvp_endpoint(
@@ -157,7 +142,7 @@ def update_rsvp_endpoint(
"content": {"text/csv": {}}, "content": {"text/csv": {}},
"description": "Descarga del archivo CSV `rsvps.csv`.", "description": "Descarga del archivo CSV `rsvps.csv`.",
}, },
**ADMIN_401, **ADMIN_RESPONSES,
}, },
) )
def export_rsvps_csv( def export_rsvps_csv(
@@ -192,7 +177,7 @@ def export_rsvps_csv(
description="Retorna el objeto completo de configuración para poblar el formulario de administración.", description="Retorna el objeto completo de configuración para poblar el formulario de administración.",
responses={ responses={
200: {"model": InvitationConfigResponse, "description": "Configuración obtenida correctamente."}, 200: {"model": InvitationConfigResponse, "description": "Configuración obtenida correctamente."},
**ADMIN_401, **ADMIN_RESPONSES,
}, },
) )
def get_admin_config( def get_admin_config(
@@ -217,7 +202,22 @@ def get_admin_config(
), ),
responses={ responses={
200: {"model": InvitationConfigResponse, "description": "Configuración actualizada con éxito."}, 200: {"model": InvitationConfigResponse, "description": "Configuración actualizada con éxito."},
**ADMIN_401, **ADMIN_RESPONSES,
},
)
@router.patch(
"/config",
response_model=InvitationConfigResponse,
summary="Actualizar configuración de la invitación",
description=(
"Actualiza los valores de la configuración singleton del evento. "
"Si la URL de Google Maps cambió, valida y regenera automáticamente la vista previa del mapa. "
"Aplica validación de fecha ISO, hora en formato militar 24h y zona horaria válida IANA. "
"Los cambios toman efecto de inmediato sin requerir recarga del contenedor."
),
responses={
200: {"model": InvitationConfigResponse, "description": "Configuración actualizada con éxito."},
**ADMIN_RESPONSES,
}, },
) )
async def update_admin_config( async def update_admin_config(
@@ -263,7 +263,7 @@ async def update_admin_config(
), ),
responses={ responses={
200: {"model": GenerateMapPreviewResponse, "description": "Vista previa generada exitosamente."}, 200: {"model": GenerateMapPreviewResponse, "description": "Vista previa generada exitosamente."},
**ADMIN_401, **ADMIN_RESPONSES,
}, },
) )
async def regenerate_map_preview_endpoint( async def regenerate_map_preview_endpoint(
+111
View File
@@ -0,0 +1,111 @@
"""Authentication and browser session management API routes."""
from typing import Annotated, Optional
from fastapi import APIRouter, Depends, Query, Request, Response, status
from fastapi.responses import JSONResponse, RedirectResponse
from ..auth import OIDCAuthAdapter, OIDCClient, OIDCConfig
from ..config import settings
router = APIRouter(tags=["Auth"])
from ..auth.dependencies import (
AuthAdapterDep,
get_auth_adapter,
set_auth_adapter,
)
@router.get(
"/login",
summary="Initiate OIDC authentication flow",
description="Redirects user browser to the configured OIDC provider authorization endpoint.",
)
def login(request: Request, adapter: AuthAdapterDep) -> Response:
return adapter.login(request)
@router.get(
"/callback",
summary="Handle OIDC authentication callback",
description=(
"Processes authorization code and state from IdP. "
"Enforces session fixation barrier by issuing a fresh session identifier "
"and sets HttpOnly SameSite browser session cookie."
),
)
def callback(
request: Request,
adapter: AuthAdapterDep,
code: str = Query(..., description="Authorization code from IdP"),
state: str = Query(..., description="CSRF state parameter"),
) -> Response:
target_url = "/birthday/admin"
response = RedirectResponse(url=target_url, status_code=status.HTTP_302_FOUND)
adapter.handle_callback(
code=code,
state=state,
response=response,
request=request,
)
return response
@router.get(
"/logout",
summary="Logout user session (Browser redirect)",
description="Revokes the session on server/storage, clears browser cookie (Max-Age=0), and redirects.",
)
@router.post(
"/logout",
summary="Logout user session (API)",
description="Revokes the session on server/storage, clears browser cookie (Max-Age=0), and returns JSON confirmation.",
)
def logout(
request: Request,
adapter: AuthAdapterDep,
redirect_uri: Optional[str] = Query(None, description="Optional post-logout redirect URI"),
) -> Response:
accept_header = request.headers.get("accept", "")
if request.method == "POST" or "application/json" in accept_header:
json_resp = JSONResponse(
status_code=status.HTTP_200_OK,
content={"result": "SUCCESS", "message": "Session terminated successfully"},
)
return adapter.logout(request, response=json_resp)
target = redirect_uri or "/birthday/admin?logged_out=1"
redirect_resp = RedirectResponse(url=target, status_code=status.HTTP_302_FOUND)
return adapter.logout(request, response=redirect_resp)
@router.get(
"/session",
summary="Check authenticated browser session",
description="Resolves incoming session cookie to verified Identity. Returns None if unauthenticated.",
)
@router.get(
"/me",
summary="Check current identity",
description="Alias for /session returning verified Identity.",
)
def get_session(request: Request, adapter: AuthAdapterDep) -> Response:
identity = adapter.current_identity(request)
if identity is None:
return JSONResponse(
status_code=status.HTTP_200_OK,
content={"authenticated": False, "identity": None},
)
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"authenticated": True,
"identity": {
"subject": identity.subject,
"email": identity.email,
"name": identity.name,
"groups": identity.groups,
},
},
)
+1
View File
@@ -11,6 +11,7 @@ dependencies = [
"pydantic-settings>=2.0.0", "pydantic-settings>=2.0.0",
"pillow>=10.0.0", "pillow>=10.0.0",
"httpx>=0.27.0", "httpx>=0.27.0",
"pyjwt[crypto]>=2.8.0",
] ]
[dependency-groups] [dependency-groups]
+59
View File
@@ -41,3 +41,62 @@ def client(db_session):
with TestClient(app) as test_client: with TestClient(app) as test_client:
yield test_client yield test_client
app.dependency_overrides.clear() app.dependency_overrides.clear()
@pytest.fixture(scope="function")
def admin_identity():
from app.auth import Identity
return Identity(
subject="admin-001",
email="admin@example.com",
name="Admin User",
groups=["bdinvite_admins"],
)
@pytest.fixture(scope="function")
def guest_identity():
from app.auth import Identity
return Identity(
subject="guest-001",
email="guest@example.com",
name="Guest User",
groups=["guests"],
)
@pytest.fixture(scope="function")
def admin_session_cookie(admin_identity):
from app.auth import get_auth_adapter
adapter = get_auth_adapter()
session_id = adapter.establish_session(admin_identity)
return {adapter.session_cookie_name: session_id}
@pytest.fixture(scope="function")
def guest_session_cookie(guest_identity):
from app.auth import get_auth_adapter
adapter = get_auth_adapter()
session_id = adapter.establish_session(guest_identity)
return {adapter.session_cookie_name: session_id}
@pytest.fixture(scope="function")
def admin_client(db_session, admin_session_cookie):
def override_get_db():
try:
yield db_session
finally:
pass
app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as test_client:
for k, v in admin_session_cookie.items():
test_client.cookies.set(k, v)
yield test_client
app.dependency_overrides.clear()
+146 -41
View File
@@ -1,4 +1,37 @@
def test_admin_endpoints_require_remote_user(client): from unittest.mock import ANY, patch
import pytest
from fastapi.testclient import TestClient
from app.auth import Identity, get_auth_adapter
def test_remote_user_header_strictly_ignored(client: TestClient):
"""Negative gate: legacy Remote-User header without authenticated session must return 401."""
res = client.get("/birthday/api/admin/rsvps", headers={"Remote-User": "kiskaadee"})
assert res.status_code == 401
def test_admin_endpoints_require_authentication(client: TestClient):
"""Anonymous requests to admin endpoints must receive HTTP 401 Unauthorized."""
endpoints = [
("GET", "/birthday/api/admin/rsvps"),
("GET", "/birthday/api/admin/export"),
("GET", "/birthday/api/admin/config"),
("PUT", "/birthday/api/admin/config"),
("PATCH", "/birthday/api/admin/config"),
("POST", "/birthday/api/admin/map-preview/generate"),
("DELETE", "/birthday/api/admin/rsvps/1"),
("PATCH", "/birthday/api/admin/rsvps/1"),
]
for method, path in endpoints:
res = client.request(method, path)
assert res.status_code == 401, f"{method} {path} should require authentication"
assert res.headers.get("WWW-Authenticate") == "Bearer"
def test_admin_endpoints_require_remote_user(client: TestClient):
"""Backwards-compatible test: verify anonymous or legacy header calls are rejected with 401."""
endpoints = [ endpoints = [
"/birthday/api/admin/rsvps", "/birthday/api/admin/rsvps",
"/birthday/api/admin/export", "/birthday/api/admin/export",
@@ -6,60 +39,84 @@ def test_admin_endpoints_require_remote_user(client):
] ]
for path in endpoints: for path in endpoints:
res = client.get(path) res = client.get(path)
assert res.status_code == 401, f"GET {path} should require Remote-User header" assert res.status_code == 401, f"GET {path} should require authentication"
assert res.json() == {"detail": "Not authenticated"} res_legacy = client.get(path, headers={"Remote-User": "kiskaadee"})
assert res_legacy.status_code == 401, f"GET {path} with Remote-User must still be rejected"
def test_admin_list_and_search_rsvps(client): def test_admin_endpoints_forbidden_for_non_admin_users(client: TestClient, guest_session_cookie: dict[str, str]):
headers = {"Remote-User": "kiskaadee"} """Authenticated non-admin users must receive HTTP 403 Forbidden."""
for k, v in guest_session_cookie.items():
client.cookies.set(k, v)
endpoints = [
("GET", "/birthday/api/admin/rsvps"),
("GET", "/birthday/api/admin/export"),
("GET", "/birthday/api/admin/config"),
("PUT", "/birthday/api/admin/config"),
("PATCH", "/birthday/api/admin/config"),
("POST", "/birthday/api/admin/map-preview/generate"),
("DELETE", "/birthday/api/admin/rsvps/1"),
("PATCH", "/birthday/api/admin/rsvps/1"),
]
for method, path in endpoints:
res = client.request(method, path)
assert res.status_code == 403, f"{method} {path} should be forbidden for guest user"
assert "bdinvite_admins" in res.json().get("detail", "")
# Even if non-admin injects Remote-User header, session identity governs -> 403
res_spoof = client.get("/birthday/api/admin/rsvps", headers={"Remote-User": "admin"})
assert res_spoof.status_code == 403
def test_admin_list_and_search_rsvps(admin_client: TestClient):
"""Authenticated admin user can list and search RSVPs."""
# Initially 0 # Initially 0
res = client.get("/birthday/api/admin/rsvps", headers=headers) res = admin_client.get("/birthday/api/admin/rsvps")
assert res.status_code == 200 assert res.status_code == 200
assert res.json()["count"] == 0 assert res.json()["count"] == 0
# Add 3 invitees # Add 3 invitees
client.post( admin_client.post(
"/birthday/api/rsvp", "/birthday/api/rsvp",
json={"name": "Carlos Gomez", "phone": "300 111 2233", "email": "carlos@test.com"}, json={"name": "Carlos Gomez", "phone": "300 111 2233", "email": "carlos@test.com"},
) )
client.post( admin_client.post(
"/birthday/api/rsvp", "/birthday/api/rsvp",
json={"name": "Maria Perez", "phone": "315 222 3344", "email": "maria@test.com"}, json={"name": "Maria Perez", "phone": "315 222 3344", "email": "maria@test.com"},
) )
client.post( admin_client.post(
"/birthday/api/rsvp", "/birthday/api/rsvp",
json={"name": "Juan Gomez", "phone": "320 333 4455", "email": None}, json={"name": "Juan Gomez", "phone": "320 333 4455", "email": None},
) )
# List all # List all
res = client.get("/birthday/api/admin/rsvps", headers=headers) res = admin_client.get("/birthday/api/admin/rsvps")
assert res.status_code == 200 assert res.status_code == 200
data = res.json() data = res.json()
assert data["count"] == 3 assert data["count"] == 3
# Search by name # Search by name
res_search = client.get("/birthday/api/admin/rsvps?search=Gomez", headers=headers) res_search = admin_client.get("/birthday/api/admin/rsvps?search=Gomez")
assert res_search.status_code == 200 assert res_search.status_code == 200
search_data = res_search.json() search_data = res_search.json()
assert search_data["count"] == 2 assert search_data["count"] == 2
# Search by phone substring # Search by phone substring
res_phone = client.get("/birthday/api/admin/rsvps?search=315222", headers=headers) res_phone = admin_client.get("/birthday/api/admin/rsvps?search=315222")
assert res_phone.status_code == 200 assert res_phone.status_code == 200
assert res_phone.json()["count"] == 1 assert res_phone.json()["count"] == 1
assert res_phone.json()["rsvps"][0]["name"] == "Maria Perez" assert res_phone.json()["rsvps"][0]["name"] == "Maria Perez"
def test_admin_export_csv(client): def test_admin_export_csv(admin_client: TestClient):
headers = {"Remote-User": "kiskaadee"} """Authenticated admin user can export RSVPs as CSV."""
admin_client.post(
client.post(
"/birthday/api/rsvp", "/birthday/api/rsvp",
json={"name": "Sofia Vergara", "phone": "301 999 8877", "email": "sofia@hollywood.com"}, json={"name": "Sofia Vergara", "phone": "301 999 8877", "email": "sofia@hollywood.com"},
) )
res = client.get("/birthday/api/admin/export", headers=headers) res = admin_client.get("/birthday/api/admin/export")
assert res.status_code == 200 assert res.status_code == 200
assert res.headers["content-type"].startswith("text/csv") assert res.headers["content-type"].startswith("text/csv")
assert 'filename="rsvps.csv"' in res.headers["content-disposition"] assert 'filename="rsvps.csv"' in res.headers["content-disposition"]
@@ -70,72 +127,68 @@ def test_admin_export_csv(client):
assert "Sofia Vergara,3019998877,sofia@hollywood.com" in lines[1] assert "Sofia Vergara,3019998877,sofia@hollywood.com" in lines[1]
def test_admin_delete_rsvp(client): def test_admin_delete_rsvp(client: TestClient, admin_client: TestClient):
headers = {"Remote-User": "kiskaadee"} """Admin can delete RSVPs; anonymous requests are rejected."""
# Unauthorized without session
# Unauthorized without header
res_unauth = client.delete("/birthday/api/admin/rsvps/1") res_unauth = client.delete("/birthday/api/admin/rsvps/1")
assert res_unauth.status_code == 401 assert res_unauth.status_code == 401
# 404 for non-existent RSVP # 404 for non-existent RSVP
res_404 = client.delete("/birthday/api/admin/rsvps/9999", headers=headers) res_404 = admin_client.delete("/birthday/api/admin/rsvps/9999")
assert res_404.status_code == 404 assert res_404.status_code == 404
# Create an RSVP # Create an RSVP
client.post( admin_client.post(
"/birthday/api/rsvp", "/birthday/api/rsvp",
json={"name": "Lucas Silva", "phone": "300 444 5566", "email": "lucas@test.com"}, json={"name": "Lucas Silva", "phone": "300 444 5566", "email": "lucas@test.com"},
) )
list_res = client.get("/birthday/api/admin/rsvps", headers=headers) list_res = admin_client.get("/birthday/api/admin/rsvps")
assert list_res.status_code == 200 assert list_res.status_code == 200
rsvps = list_res.json()["rsvps"] rsvps = list_res.json()["rsvps"]
assert len(rsvps) == 1 assert len(rsvps) == 1
rsvp_id = rsvps[0]["id"] rsvp_id = rsvps[0]["id"]
# Delete successfully # Delete successfully
del_res = client.delete(f"/birthday/api/admin/rsvps/{rsvp_id}", headers=headers) del_res = admin_client.delete(f"/birthday/api/admin/rsvps/{rsvp_id}")
assert del_res.status_code == 204 assert del_res.status_code == 204
# Confirm deletion # Confirm deletion
list_after = client.get("/birthday/api/admin/rsvps", headers=headers) list_after = admin_client.get("/birthday/api/admin/rsvps")
assert list_after.json()["count"] == 0 assert list_after.json()["count"] == 0
def test_admin_update_rsvp(client): def test_admin_update_rsvp(client: TestClient, admin_client: TestClient):
headers = {"Remote-User": "kiskaadee"} """Admin can update RSVPs; anonymous requests are rejected."""
# Unauthorized without session
# Unauthorized without header
res_unauth = client.patch("/birthday/api/admin/rsvps/1", json={"name": "New Name"}) res_unauth = client.patch("/birthday/api/admin/rsvps/1", json={"name": "New Name"})
assert res_unauth.status_code == 401 assert res_unauth.status_code == 401
# 404 for non-existent RSVP # 404 for non-existent RSVP
res_404 = client.patch( res_404 = admin_client.patch(
"/birthday/api/admin/rsvps/9999", "/birthday/api/admin/rsvps/9999",
json={"name": "New Name"}, json={"name": "New Name"},
headers=headers,
) )
assert res_404.status_code == 404 assert res_404.status_code == 404
# Create two RSVPs # Create two RSVPs
client.post( admin_client.post(
"/birthday/api/rsvp", "/birthday/api/rsvp",
json={"name": "Person One", "phone": "300 111 2222", "email": "one@test.com"}, json={"name": "Person One", "phone": "300 111 2222", "email": "one@test.com"},
) )
client.post( admin_client.post(
"/birthday/api/rsvp", "/birthday/api/rsvp",
json={"name": "Person Two", "phone": "300 333 4444", "email": "two@test.com"}, json={"name": "Person Two", "phone": "300 333 4444", "email": "two@test.com"},
) )
list_res = client.get("/birthday/api/admin/rsvps", headers=headers) list_res = admin_client.get("/birthday/api/admin/rsvps")
rsvps = list_res.json()["rsvps"] rsvps = list_res.json()["rsvps"]
id_one = next(r["id"] for r in rsvps if r["name"] == "Person One") id_one = next(r["id"] for r in rsvps if r["name"] == "Person One")
id_two = next(r["id"] for r in rsvps if r["name"] == "Person Two") id_two = next(r["id"] for r in rsvps if r["name"] == "Person Two")
# Update Person One with valid new name and phone # Update Person One with valid new name and phone
patch_res = client.patch( patch_res = admin_client.patch(
f"/birthday/api/admin/rsvps/{id_one}", f"/birthday/api/admin/rsvps/{id_one}",
json={"name": "Person One Updated", "phone": "+57 300 999 8888", "email": "newone@test.com"}, json={"name": "Person One Updated", "phone": "+57 300 999 8888", "email": "newone@test.com"},
headers=headers,
) )
assert patch_res.status_code == 200 assert patch_res.status_code == 200
updated_data = patch_res.json() updated_data = patch_res.json()
@@ -144,18 +197,70 @@ def test_admin_update_rsvp(client):
assert updated_data["email"] == "newone@test.com" assert updated_data["email"] == "newone@test.com"
# Attempt to update Person One's phone to Person Two's phone -> 409 # Attempt to update Person One's phone to Person Two's phone -> 409
dup_res = client.patch( dup_res = admin_client.patch(
f"/birthday/api/admin/rsvps/{id_one}", f"/birthday/api/admin/rsvps/{id_one}",
json={"phone": "300 333 4444"}, json={"phone": "300 333 4444"},
headers=headers,
) )
assert dup_res.status_code == 409 assert dup_res.status_code == 409
# Validation error for invalid phone # Validation error for invalid phone
val_res = client.patch( val_res = admin_client.patch(
f"/birthday/api/admin/rsvps/{id_one}", f"/birthday/api/admin/rsvps/{id_one}",
json={"phone": "12345"}, json={"phone": "12345"},
headers=headers,
) )
assert val_res.status_code in (400, 422) assert val_res.status_code in (400, 422)
def test_admin_config_endpoints(admin_client: TestClient, client: TestClient):
"""Admin can retrieve and update config via PUT and PATCH; unauthenticated calls rejected."""
# Anonymous -> 401
assert client.get("/birthday/api/admin/config").status_code == 401
assert client.patch("/birthday/api/admin/config", json={}).status_code == 401
assert client.put("/birthday/api/admin/config", json={}).status_code == 401
# Admin GET config -> 200
res = admin_client.get("/birthday/api/admin/config")
assert res.status_code == 200
current_config = res.json()
assert current_config["honoree_name"] == "Isabelle Snow"
# Admin PATCH config -> 200
update_payload = {**current_config}
update_payload["honoree_name"] = "Isabelle Updated via PATCH"
patch_res = admin_client.patch("/birthday/api/admin/config", json=update_payload)
assert patch_res.status_code == 200
assert patch_res.json()["honoree_name"] == "Isabelle Updated via PATCH"
# Admin PUT config -> 200
update_payload["honoree_name"] = "Isabelle Updated via PUT"
put_res = admin_client.put("/birthday/api/admin/config", json=update_payload)
assert put_res.status_code == 200
assert put_res.json()["honoree_name"] == "Isabelle Updated via PUT"
@patch("app.routes.admin.resolve_google_maps_coordinates")
@patch("app.routes.admin.generate_map_preview_image")
def test_admin_map_preview_generate_endpoint(
mock_generate, mock_resolve, client: TestClient, admin_client: TestClient, tmp_path
):
"""Map preview generation requires admin; verifies successful generation."""
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
mock_generate.return_value = tmp_path / "map_preview.png"
# Anonymous -> 401
res_unauth = client.post(
"/birthday/api/admin/map-preview/generate",
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
)
assert res_unauth.status_code == 401
# Admin -> 200
res_admin = admin_client.post(
"/birthday/api/admin/map-preview/generate",
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
)
assert res_admin.status_code == 200
data = res_admin.json()
assert "/birthday/api/map-preview.png" in data["map_preview_url"]
assert data["lat"] == 34.1432
assert data["lng"] == -118.2551
+178
View File
@@ -0,0 +1,178 @@
import ast
from dataclasses import FrozenInstanceError
from pathlib import Path
from typing import Optional
import pytest
from fastapi import Request, Response
from fastapi.responses import RedirectResponse
from starlette.datastructures import Headers
from app.auth import AuthPort, Identity
class MockAuthAdapter:
"""Mock implementation of AuthPort for testing hexagonal boundary contract."""
def __init__(self, sessions: Optional[dict[str, Identity]] = None):
self.sessions = sessions or {}
def current_identity(self, request: Request) -> Optional[Identity]:
session_id = request.headers.get("X-Session-ID") or request.cookies.get("session_id")
if session_id and session_id in self.sessions:
return self.sessions[session_id]
return None
def login(self, request: Request) -> Response:
return RedirectResponse(url="https://auth.example.com/oauth/authorize", status_code=302)
def logout(self, request: Request) -> Response:
response = Response(content="logged out", status_code=200)
response.delete_cookie("session_id")
return response
class IncompleteAuthAdapter:
"""Incomplete adapter missing logout to test Protocol validation."""
def current_identity(self, request: Request) -> Optional[Identity]:
return None
def login(self, request: Request) -> Response:
return Response(content="login", status_code=200)
def create_mock_request(headers: Optional[dict[str, str]] = None, cookies: Optional[dict[str, str]] = None) -> Request:
"""Helper to build a Starlette/FastAPI Request instance with mock scope."""
header_list = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in (headers or {}).items()]
scope = {
"type": "http",
"method": "GET",
"path": "/test",
"headers": header_list,
"query_string": b"",
}
req = Request(scope)
if cookies:
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
header_list.append((b"cookie", cookie_header.encode("latin-1")))
req.scope["headers"] = header_list
return req
def test_identity_creation_defaults():
identity = Identity(subject="usr_123", email="user@example.com")
assert identity.subject == "usr_123"
assert identity.email == "user@example.com"
assert identity.name is None
assert identity.groups == []
def test_identity_creation_full():
identity = Identity(
subject="usr_456",
email="admin@example.com",
name="Admin User",
groups=["admins", "organizers"],
)
assert identity.subject == "usr_456"
assert identity.email == "admin@example.com"
assert identity.name == "Admin User"
assert identity.groups == ["admins", "organizers"]
def test_identity_none_groups_normalized():
identity = Identity(subject="usr_789", email="test@example.com", groups=None) # type: ignore[arg-type]
assert identity.groups == []
def test_identity_frozen_immutability():
identity = Identity(subject="usr_123", email="user@example.com")
with pytest.raises(FrozenInstanceError):
identity.subject = "usr_999" # type: ignore[misc]
with pytest.raises(FrozenInstanceError):
identity.email = "changed@example.com" # type: ignore[misc]
def test_identity_equality():
id1 = Identity(subject="usr_1", email="a@b.com", name="Alice", groups=["user"])
id2 = Identity(subject="usr_1", email="a@b.com", name="Alice", groups=["user"])
id3 = Identity(subject="usr_2", email="a@b.com", name="Alice", groups=["user"])
assert id1 == id2
assert id1 != id3
def test_auth_port_protocol_conformance():
adapter = MockAuthAdapter()
assert isinstance(adapter, AuthPort)
assert issubclass(MockAuthAdapter, AuthPort)
incomplete = IncompleteAuthAdapter()
assert not isinstance(incomplete, AuthPort)
assert not issubclass(IncompleteAuthAdapter, AuthPort)
def test_auth_port_behavior_with_mock():
expected_identity = Identity(
subject="sub_valid",
email="guest@example.com",
name="Guest User",
groups=["guests"],
)
adapter = MockAuthAdapter(sessions={"valid_token": expected_identity})
# Unauthenticated request
unauth_req = create_mock_request()
assert adapter.current_identity(unauth_req) is None
# Authenticated request via header
auth_req = create_mock_request(headers={"X-Session-ID": "valid_token"})
resolved = adapter.current_identity(auth_req)
assert resolved == expected_identity
assert resolved is not None
assert resolved.email == "guest@example.com"
# Login flow
login_resp = adapter.login(unauth_req)
assert isinstance(login_resp, Response)
assert login_resp.status_code == 302
assert login_resp.headers["location"] == "https://auth.example.com/oauth/authorize"
# Logout flow
logout_resp = adapter.logout(auth_req)
assert isinstance(logout_resp, Response)
assert logout_resp.status_code == 200
def test_architectural_isolation_zero_prohibited_imports():
"""Verify application domain files do not import OIDC, OAuth, JWT, cryptography, or proxy headers."""
backend_app_dir = Path(__file__).resolve().parent.parent / "app"
prohibited_keywords = {"oidc", "oauth", "jwt", "jose", "cryptography"}
# Files to inspect: routes, models, schemas, and auth port
domain_paths = [
backend_app_dir / "models.py",
backend_app_dir / "schemas.py",
backend_app_dir / "auth" / "port.py",
]
domain_paths.extend((backend_app_dir / "routes").glob("*.py"))
for py_file in domain_paths:
assert py_file.exists(), f"Expected domain file {py_file} to exist"
tree = ast.parse(py_file.read_text("utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
name_lower = alias.name.lower()
for prohibited in prohibited_keywords:
assert prohibited not in name_lower, (
f"Prohibited import '{alias.name}' found in {py_file}"
)
elif isinstance(node, ast.ImportFrom):
module_name = (node.module or "").lower()
for prohibited in prohibited_keywords:
assert prohibited not in module_name, (
f"Prohibited import from '{node.module}' found in {py_file}"
)
+156
View File
@@ -0,0 +1,156 @@
"""Automated Browser Acceptance Tests for Single Sign-On (SSO) Flow via Playwright.
Verifies Checkpoint 7 (CP7) requirements:
1. Browser navigates to /birthday/admin -> redirected to OIDC login form.
2. Form submitted with admin@example.com / password123.
3. Browser redirects back through callback -> receives HttpOnly cookie -> arrives on Admin Dashboard.
4. Admin Dashboard renders RSVPs table and authenticated user information.
5. Clicking Logout button revokes session -> returns to unauthenticated state.
"""
import json
import threading
import time
from typing import Generator
import httpx
import pytest
import uvicorn
from playwright.sync_api import BrowserContext, Page, sync_playwright
from app.config import settings
from app.database import Base, SessionLocal, engine
from app.models import RSVP
from app.services.config import seed_default_config
@pytest.fixture(scope="module")
def live_server() -> Generator[str, None, None]:
"""Start uvicorn server running FastAPI application in background daemon thread."""
# Ensure fresh DB tables and seed data
Base.metadata.create_all(bind=engine)
with SessionLocal() as db:
seed_default_config(db)
# Seed an RSVP item to guarantee the table renders records
test_rsvp = db.query(RSVP).filter_by(phone="3009998877").first()
if not test_rsvp:
test_rsvp = RSVP(
name="Invitado de Prueba",
phone="3009998877",
email="invitado@test.com",
)
db.add(test_rsvp)
db.commit()
config = uvicorn.Config(
"app.main:app",
host="127.0.0.1",
port=settings.APP_PORT,
log_level="warning",
)
server = uvicorn.Server(config)
thread = threading.Thread(target=server.run, daemon=True)
thread.start()
base_url = f"http://localhost:{settings.APP_PORT}"
# Poll until server is responding
ready = False
for _ in range(50):
try:
with httpx.Client() as client:
res = client.get(f"{base_url}/birthday/api/config", timeout=1.0)
if res.status_code == 200:
ready = True
break
except Exception:
time.sleep(0.1)
assert ready, f"Live server failed to start on {base_url}"
yield base_url
server.should_exit = True
thread.join(timeout=3.0)
@pytest.fixture(scope="module")
def browser_context():
"""Launch headless Chromium browser and provide an isolated context."""
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
yield context
context.close()
browser.close()
def test_browser_sso_complete_flow(live_server: str, browser_context: BrowserContext):
"""Execute complete end-to-end interactive browser authentication flow."""
page: Page = browser_context.new_page()
# 1. Unauthenticated navigation to /birthday/admin initiates login redirect
page.goto(f"{live_server}/birthday/admin")
# 2. Browser is redirected to OIDC provider login page
page.wait_for_url(lambda u: "8088" in u and "/authorize" in u, timeout=10000)
assert "8088" in page.url
# 3. Submit credentials on Mock OAuth2 Server login form
page.wait_for_selector("input[name='username']", timeout=5000)
page.fill("input[name='username']", "admin@example.com")
if page.locator("input[type='password']").count() > 0:
page.fill("input[type='password']", "password123")
if page.locator("textarea[name='claims']").count() > 0:
page.fill(
"textarea[name='claims']",
json.dumps({
"sub": "admin-001",
"email": "admin@example.com",
"name": "Admin User",
"groups": ["bdinvite_admins"],
}),
)
page.click("input[type='submit']")
# 4. Redirects through callback -> receives HttpOnly cookie -> arrives on Admin Dashboard
page.wait_for_url(lambda u: "/birthday/admin" in u and "8088" not in u, timeout=10000)
assert "/birthday/admin" in page.url
# Verify HttpOnly session cookie
cookies = browser_context.cookies("http://localhost:8000")
session_cookies = [c for c in cookies if c.get("name") == settings.SESSION_COOKIE_NAME]
assert len(session_cookies) >= 1, f"Missing {settings.SESSION_COOKIE_NAME} cookie"
session_cookie = session_cookies[0]
assert session_cookie.get("httpOnly") is True, "Session cookie must be HttpOnly"
same_site = session_cookie.get("sameSite")
assert same_site is not None and same_site.lower() in ["lax", "strict"]
# 5. Admin navigation header displays authenticated user info and working Logout button
page.wait_for_selector("[data-testid='user-info']", timeout=5000)
user_info_text = page.locator("[data-testid='user-info']").inner_text()
assert "admin@example.com" in user_info_text or "Admin User" in user_info_text
# 6. Admin Dashboard renders RSVPs table with live data
page.wait_for_selector("table", timeout=5000)
assert page.locator("table").is_visible()
# Confirm seeded attendee appears in the table
page.wait_for_selector("text=Invitado de Prueba", timeout=5000)
assert page.locator("text=Invitado de Prueba").is_visible()
# 7. Clicking "Logout" button revokes session and returns UI to unauthenticated state
logout_btn = page.locator("[data-testid='logout-btn']")
assert logout_btn.is_visible()
logout_btn.click()
# UI displays unauthenticated state
page.wait_for_selector("[data-testid='unauthenticated-state']", timeout=5000)
assert page.locator("[data-testid='unauthenticated-state']").is_visible()
# RSVPs table is no longer displayed
assert page.locator("table").count() == 0
page.close()
+8 -13
View File
@@ -10,19 +10,16 @@ def test_get_config_public(client):
assert data["countdown_label"] == "NOS VEMOS EN" assert data["countdown_label"] == "NOS VEMOS EN"
def test_get_config_admin(client): def test_get_config_admin(client, admin_client):
res_unauth = client.get("/birthday/api/admin/config") res_unauth = client.get("/birthday/api/admin/config")
assert res_unauth.status_code == 401 assert res_unauth.status_code == 401
res_auth = client.get( res_auth = admin_client.get("/birthday/api/admin/config")
"/birthday/api/admin/config",
headers={"Remote-User": "admin_user"},
)
assert res_auth.status_code == 200 assert res_auth.status_code == 200
assert res_auth.json()["honoree_name"] == "Isabelle Snow" assert res_auth.json()["honoree_name"] == "Isabelle Snow"
def test_update_config_requires_admin(client): def test_update_config_requires_admin(client, admin_client):
update_payload = { update_payload = {
"title": "Fiesta de Cumpleaños", "title": "Fiesta de Cumpleaños",
"invitation_text": "Estás invitado a la fiesta de", "invitation_text": "Estás invitado a la fiesta de",
@@ -46,15 +43,14 @@ def test_update_config_requires_admin(client):
"countdown_in_progress": "EN VIVO", "countdown_in_progress": "EN VIVO",
"countdown_finished": "TERMINADO", "countdown_finished": "TERMINADO",
} }
# Without Remote-User header -> 401 # Without session -> 401
res = client.put("/birthday/api/admin/config", json=update_payload) res = client.put("/birthday/api/admin/config", json=update_payload)
assert res.status_code == 401 assert res.status_code == 401
# With Remote-User header -> 200 # With admin session -> 200
res_auth = client.put( res_auth = admin_client.put(
"/birthday/api/admin/config", "/birthday/api/admin/config",
json=update_payload, json=update_payload,
headers={"Remote-User": "admin_user"},
) )
assert res_auth.status_code == 200 assert res_auth.status_code == 200
data = res_auth.json() data = res_auth.json()
@@ -68,7 +64,7 @@ def test_update_config_requires_admin(client):
assert res_pub.json()["title"] == "Fiesta de Cumpleaños" assert res_pub.json()["title"] == "Fiesta de Cumpleaños"
def test_update_config_invalid_timezone(client): def test_update_config_invalid_timezone(admin_client):
invalid_payload = { invalid_payload = {
"title": "Party", "title": "Party",
"invitation_text": "Invited", "invitation_text": "Invited",
@@ -92,10 +88,9 @@ def test_update_config_invalid_timezone(client):
"countdown_in_progress": "CURSO", "countdown_in_progress": "CURSO",
"countdown_finished": "FIN", "countdown_finished": "FIN",
} }
res = client.put( res = admin_client.put(
"/birthday/api/admin/config", "/birthday/api/admin/config",
json=invalid_payload, json=invalid_payload,
headers={"Remote-User": "admin_user"},
) )
assert res.status_code == 422 assert res.status_code == 422
+419
View File
@@ -0,0 +1,419 @@
"""Tests for FastAPI dependency injection and authorization policies (Checkpoint 5)."""
from collections.abc import Generator
from typing import Annotated, Optional
import pytest
from fastapi import APIRouter, Depends, FastAPI, HTTPException, status
from fastapi.testclient import TestClient
from starlette.requests import Request
from app.auth import (
AdminUserDep,
AuthenticatedUserDep,
CurrentIdentityDep,
Identity,
OIDCAuthAdapter,
OIDCClient,
OIDCConfig,
get_auth_adapter,
get_current_identity,
require_admin,
require_authenticated,
require_group,
set_auth_adapter,
)
FIXTURE_ISSUER = "http://localhost:8088/default"
FIXTURE_CLIENT_ID = "bdinvite-client"
FIXTURE_CLIENT_SECRET = "bdinvite-secret"
FIXTURE_REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
@pytest.fixture
def oidc_config() -> OIDCConfig:
return OIDCConfig(
issuer=FIXTURE_ISSUER,
client_id=FIXTURE_CLIENT_ID,
client_secret=FIXTURE_CLIENT_SECRET,
redirect_uri=FIXTURE_REDIRECT_URI,
)
@pytest.fixture
def oidc_client(oidc_config: OIDCConfig) -> OIDCClient:
return OIDCClient(oidc_config)
@pytest.fixture
def auth_adapter(oidc_client: OIDCClient) -> Generator[OIDCAuthAdapter, None, None]:
adapter = OIDCAuthAdapter(
client=oidc_client,
session_cookie_name="bdinvite_session",
cookie_secure=False,
cookie_samesite="lax",
session_lifetime=3600.0,
)
set_auth_adapter(adapter)
yield adapter
set_auth_adapter(None)
def create_request(
headers: dict[str, str] | None = None,
cookies: dict[str, str] | None = None,
) -> Request:
header_list: list[tuple[bytes, bytes]] = []
if headers:
for k, v in headers.items():
header_list.append((k.lower().encode("latin-1"), v.encode("latin-1")))
if cookies:
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
header_list.append((b"cookie", cookie_header.encode("latin-1")))
scope = {
"type": "http",
"method": "GET",
"path": "/test",
"headers": header_list,
"query_string": b"",
}
return Request(scope)
@pytest.fixture
def test_app(auth_adapter: OIDCAuthAdapter) -> FastAPI:
"""Isolated FastAPI test application mounted with test endpoints."""
app = FastAPI(title="Dependency Test App")
router = APIRouter()
@router.get("/me")
def me_endpoint(identity: CurrentIdentityDep):
if identity is None:
return {"authenticated": False, "identity": None}
return {
"authenticated": True,
"identity": {
"subject": identity.subject,
"email": identity.email,
"name": identity.name,
"groups": identity.groups,
},
}
@router.get("/authenticated")
def authenticated_endpoint(user: AuthenticatedUserDep):
return {
"subject": user.subject,
"email": user.email,
"groups": user.groups,
}
@router.get("/admin")
def admin_endpoint(admin: AdminUserDep):
return {
"subject": admin.subject,
"email": admin.email,
"groups": admin.groups,
}
require_staff = require_group("staff")
@router.get("/staff")
def staff_endpoint(user: Annotated[Identity, Depends(require_staff)]):
return {
"subject": user.subject,
"email": user.email,
"groups": user.groups,
}
app.include_router(router)
return app
@pytest.fixture
def client(test_app: FastAPI) -> Generator[TestClient, None, None]:
with TestClient(test_app) as c:
yield c
# ============================================================================
# Unit Tests (Direct Dependency Invocations)
# ============================================================================
def test_get_current_identity_anonymous(auth_adapter: OIDCAuthAdapter):
"""Anonymous request yields None on get_current_identity."""
req_empty = create_request()
assert get_current_identity(req_empty, adapter=auth_adapter) is None
# Default adapter fallback (when adapter argument is omitted)
assert get_current_identity(req_empty) is None
def test_get_current_identity_with_valid_session(auth_adapter: OIDCAuthAdapter):
"""Valid session cookie yields active Identity on get_current_identity."""
admin_id, session_id = auth_adapter.authenticate_and_establish_session(
"admin@example.com", "password123"
)
req = create_request(cookies={auth_adapter.session_cookie_name: session_id})
resolved = get_current_identity(req, adapter=auth_adapter)
assert resolved == admin_id
assert resolved is not None
assert resolved.email == "admin@example.com"
assert "bdinvite_admins" in resolved.groups
def test_get_current_identity_with_valid_bearer_token(
auth_adapter: OIDCAuthAdapter, oidc_client: OIDCClient
):
"""Valid Bearer token yields active Identity on get_current_identity."""
_, tokens = oidc_client.authenticate_user("guest@example.com", "guestpass456")
id_token = tokens["id_token"]
req = create_request(headers={"Authorization": f"Bearer {id_token}"})
resolved = get_current_identity(req, adapter=auth_adapter)
assert resolved is not None
assert resolved.email == "guest@example.com"
assert resolved.groups == ["guests"]
def test_require_authenticated_anonymous_raises_401():
"""Anonymous request (identity=None) raises HTTP 401 on require_authenticated."""
with pytest.raises(HTTPException) as exc_info:
require_authenticated(identity=None)
assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED
assert exc_info.value.detail == "Authentication required"
assert exc_info.value.headers is not None
assert exc_info.value.headers.get("WWW-Authenticate") == "Bearer"
def test_require_authenticated_success():
"""Authenticated user returns Identity from require_authenticated."""
identity = Identity(
subject="sub-123",
email="user@example.com",
groups=["guests"],
)
result = require_authenticated(identity=identity)
assert result == identity
def test_require_group_anonymous_raises_401():
"""Anonymous user raises HTTP 401 on require_group."""
group_dep = require_group("staff")
with pytest.raises(HTTPException) as exc_info:
group_dep(identity=None)
assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED
def test_require_group_missing_group_raises_403():
"""Authenticated user missing the required group raises HTTP 403 Forbidden."""
group_dep = require_group("staff")
user = Identity(
subject="sub-123",
email="user@example.com",
groups=["guests"],
)
with pytest.raises(HTTPException) as exc_info:
group_dep(identity=user)
assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN
assert "staff" in exc_info.value.detail
def test_require_group_success():
"""Authenticated user possessing the required group returns Identity."""
group_dep = require_group("staff")
user = Identity(
subject="sub-123",
email="user@example.com",
groups=["staff", "guests"],
)
result = group_dep(identity=user)
assert result == user
def test_require_admin_anonymous_raises_401():
"""Anonymous request raises HTTP 401 on require_admin."""
with pytest.raises(HTTPException) as exc_info:
require_admin(identity=None)
assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED
def test_require_admin_non_admin_raises_403():
"""Authenticated non-admin user raises HTTP 403 on require_admin."""
guest_user = Identity(
subject="guest-001",
email="guest@example.com",
groups=["guests"],
)
with pytest.raises(HTTPException) as exc_info:
require_admin(identity=guest_user)
assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN
assert "bdinvite_admins" in exc_info.value.detail
def test_require_admin_success():
"""Authenticated admin user successfully yields Identity object on require_admin."""
admin_user = Identity(
subject="admin-001",
email="admin@example.com",
groups=["bdinvite_admins"],
)
result = require_admin(identity=admin_user)
assert result == admin_user
assert result.subject == "admin-001"
assert result.email == "admin@example.com"
assert result.groups == ["bdinvite_admins"]
# ============================================================================
# FastAPI Integration Tests (End-to-End Dependency Injection via TestClient)
# ============================================================================
def test_api_anonymous_get_current_identity(client: TestClient):
"""Anonymous request to /me yields None identity."""
resp = client.get("/me")
assert resp.status_code == 200
data = resp.json()
assert data["authenticated"] is False
assert data["identity"] is None
def test_api_authenticated_user_get_current_identity(
client: TestClient, auth_adapter: OIDCAuthAdapter
):
"""Authenticated user with session cookie resolves Identity on /me."""
guest_id, session_id = auth_adapter.authenticate_and_establish_session(
"guest@example.com", "guestpass456"
)
client.cookies.set(auth_adapter.session_cookie_name, session_id)
resp = client.get("/me")
assert resp.status_code == 200
data = resp.json()
assert data["authenticated"] is True
assert data["identity"]["email"] == "guest@example.com"
assert data["identity"]["groups"] == ["guests"]
def test_api_require_authenticated_anonymous_returns_401(client: TestClient):
"""Anonymous request to /authenticated raises HTTP 401 Unauthorized."""
resp = client.get("/authenticated")
assert resp.status_code == 401
assert resp.headers.get("WWW-Authenticate") == "Bearer"
assert resp.json()["detail"] == "Authentication required"
def test_api_require_authenticated_with_session_returns_200(
client: TestClient, auth_adapter: OIDCAuthAdapter
):
"""Authenticated request to /authenticated returns 200 and Identity."""
_, session_id = auth_adapter.authenticate_and_establish_session(
"guest@example.com", "guestpass456"
)
client.cookies.set(auth_adapter.session_cookie_name, session_id)
resp = client.get("/authenticated")
assert resp.status_code == 200
data = resp.json()
assert data["email"] == "guest@example.com"
def test_api_require_admin_anonymous_returns_401(client: TestClient):
"""Anonymous request to /admin raises HTTP 401 Unauthorized."""
resp = client.get("/admin")
assert resp.status_code == 401
assert resp.headers.get("WWW-Authenticate") == "Bearer"
def test_api_require_admin_non_admin_returns_403(
client: TestClient, auth_adapter: OIDCAuthAdapter
):
"""Authenticated non-admin user (guest) raises HTTP 403 Forbidden on /admin."""
_, session_id = auth_adapter.authenticate_and_establish_session(
"guest@example.com", "guestpass456"
)
client.cookies.set(auth_adapter.session_cookie_name, session_id)
resp = client.get("/admin")
assert resp.status_code == 403
assert "bdinvite_admins" in resp.json()["detail"]
def test_api_require_admin_admin_returns_200(
client: TestClient, auth_adapter: OIDCAuthAdapter
):
"""Authenticated admin user (bdinvite_admins) succeeds with HTTP 200 on /admin."""
admin_id, session_id = auth_adapter.authenticate_and_establish_session(
"admin@example.com", "password123"
)
client.cookies.set(auth_adapter.session_cookie_name, session_id)
resp = client.get("/admin")
assert resp.status_code == 200
data = resp.json()
assert data["email"] == "admin@example.com"
assert data["groups"] == ["bdinvite_admins"]
def test_api_bearer_token_authentication_flow(
client: TestClient, oidc_client: OIDCClient
):
"""Bearer token in Authorization header successfully resolves through dependencies."""
# 1. Guest user Bearer token -> /authenticated succeeds, /admin fails with 403
_, guest_tokens = oidc_client.authenticate_user(
"guest@example.com", "guestpass456"
)
guest_headers = {"Authorization": f"Bearer {guest_tokens['id_token']}"}
resp_guest_auth = client.get("/authenticated", headers=guest_headers)
assert resp_guest_auth.status_code == 200
assert resp_guest_auth.json()["email"] == "guest@example.com"
resp_guest_admin = client.get("/admin", headers=guest_headers)
assert resp_guest_admin.status_code == 403
# 2. Admin user Bearer token -> /admin succeeds with 200
_, admin_tokens = oidc_client.authenticate_user("admin@example.com", "password123")
admin_headers = {"Authorization": f"Bearer {admin_tokens['id_token']}"}
resp_admin = client.get("/admin", headers=admin_headers)
assert resp_admin.status_code == 200
assert resp_admin.json()["email"] == "admin@example.com"
assert resp_admin.json()["groups"] == ["bdinvite_admins"]
def test_api_dependency_overrides(test_app: FastAPI, client: TestClient):
"""FastAPI dependency overrides function cleanly on get_current_identity."""
# 1. Override with mock admin identity
mock_admin = Identity(
subject="mock-admin",
email="mockadmin@example.com",
groups=["bdinvite_admins"],
)
test_app.dependency_overrides[get_current_identity] = lambda: mock_admin
resp = client.get("/admin")
assert resp.status_code == 200
assert resp.json()["email"] == "mockadmin@example.com"
# 2. Override with mock guest identity (missing bdinvite_admins)
mock_guest = Identity(
subject="mock-guest",
email="mockguest@example.com",
groups=["guests"],
)
test_app.dependency_overrides[get_current_identity] = lambda: mock_guest
resp = client.get("/admin")
assert resp.status_code == 403
# 3. Override with anonymous (None)
test_app.dependency_overrides[get_current_identity] = lambda: None
resp = client.get("/admin")
assert resp.status_code == 401
test_app.dependency_overrides.clear()
+388
View File
@@ -0,0 +1,388 @@
"""Tests for OIDC Identity & Group Extraction, Integrity Invariants, and Fixture Users."""
from dataclasses import FrozenInstanceError
import json
from urllib.parse import parse_qs, urlparse
import httpx
import pytest
from starlette.requests import Request
from app.auth import (
Identity,
OIDCAuthAdapter,
OIDCClient,
OIDCConfig,
TokenValidationError,
claims_to_identity,
extract_identity_from_claims,
resolve_claim_path,
)
FIXTURE_ISSUER = "http://localhost:8088/default"
FIXTURE_CLIENT_ID = "bdinvite-client"
FIXTURE_CLIENT_SECRET = "bdinvite-secret"
FIXTURE_REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
@pytest.fixture
def oidc_config() -> OIDCConfig:
return OIDCConfig(
issuer=FIXTURE_ISSUER,
client_id=FIXTURE_CLIENT_ID,
client_secret=FIXTURE_CLIENT_SECRET,
redirect_uri=FIXTURE_REDIRECT_URI,
)
@pytest.fixture
def oidc_client(oidc_config: OIDCConfig) -> OIDCClient:
return OIDCClient(oidc_config)
def create_request(
headers: dict[str, str] | None = None,
cookies: dict[str, str] | None = None,
) -> Request:
header_list: list[tuple[bytes, bytes]] = []
if headers:
for k, v in headers.items():
header_list.append((k.lower().encode("latin-1"), v.encode("latin-1")))
if cookies:
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
header_list.append((b"cookie", cookie_header.encode("latin-1")))
scope = {
"type": "http",
"method": "GET",
"path": "/birthday/api/admin/rsvps",
"headers": header_list,
"query_string": b"",
}
return Request(scope)
def obtain_auth_code_from_fixture(
authorization_url: str,
username: str,
claims: dict | None = None,
) -> tuple[str, str]:
parsed_url = urlparse(authorization_url)
auth_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"
query_params = parse_qs(parsed_url.query)
flat_params = {k: v[0] for k, v in query_params.items()}
post_data: dict[str, str] = {"username": username}
if claims:
post_data["claims"] = json.dumps(claims)
with httpx.Client() as client:
resp = client.post(
auth_endpoint,
params=flat_params,
data=post_data,
follow_redirects=False,
)
assert resp.status_code == 302
location = resp.headers["location"]
redirect_parsed = urlparse(location)
callback_params = parse_qs(redirect_parsed.query)
return callback_params["code"][0], callback_params["state"][0]
# ============================================================================
# 1. Identity Resolution & Mapping Unit Tests
# ============================================================================
def test_resolve_claim_path():
claims = {
"groups": ["group1", "group2"],
"realm_access": {"roles": ["admin", "editor"]},
"deep": {"nested": {"path": ["value"]}},
}
assert resolve_claim_path(claims, "groups") == ["group1", "group2"]
assert resolve_claim_path(claims, "realm_access.roles") == ["admin", "editor"]
assert resolve_claim_path(claims, "deep.nested.path") == ["value"]
assert resolve_claim_path(claims, "nonexistent") is None
assert resolve_claim_path(claims, "deep.wrong.path") is None
def test_claims_to_identity_standard_mapping():
claims = {
"sub": "user_101",
"email": "user@example.com",
"name": "Normal User",
"groups": ["engineering", "security"],
}
identity = claims_to_identity(claims)
assert isinstance(identity, Identity)
assert identity.subject == "user_101"
assert identity.email == "user@example.com"
assert identity.name == "Normal User"
assert identity.groups == ["engineering", "security"]
def test_claims_to_identity_custom_group_claim_path():
claims = {
"sub": "user_custom",
"email": "custom@example.com",
"roles": ["operator", "auditor"],
}
identity = extract_identity_from_claims(claims, groups_claim="roles")
assert identity.groups == ["operator", "auditor"]
# Nested path
nested_claims = {
"sub": "user_nested",
"email": "nested@example.com",
"resource_access": {"bdinvite": {"roles": ["admin"]}},
}
identity_nested = extract_identity_from_claims(
nested_claims, groups_claim="resource_access.bdinvite.roles"
)
assert identity_nested.groups == ["admin"]
def test_claims_to_identity_normalizes_group_types():
# Single string group
c1 = {"sub": "u1", "email": "u1@e.com", "groups": "only_one_group"}
assert claims_to_identity(c1).groups == ["only_one_group"]
# Comma-separated string
c2 = {"sub": "u2", "email": "u2@e.com", "groups": "admin, billing, support"}
assert claims_to_identity(c2).groups == ["admin", "billing", "support"]
# Non-string elements in list are stringified
c3 = {"sub": "u3", "email": "u3@e.com", "groups": [123, True, "staff"]}
assert claims_to_identity(c3).groups == ["123", "True", "staff"]
def test_claims_to_identity_missing_or_empty_groups_defaults_to_empty_list():
# Absent groups claim
c1 = {"sub": "u1", "email": "u1@e.com", "name": "No Groups"}
id1 = claims_to_identity(c1)
assert id1.groups == []
# groups is None
c2 = {"sub": "u2", "email": "u2@e.com", "groups": None}
id2 = claims_to_identity(c2)
assert id2.groups == []
# groups is empty list
c3 = {"sub": "u3", "email": "u3@e.com", "groups": []}
id3 = claims_to_identity(c3)
assert id3.groups == []
# groups is empty string
c4 = {"sub": "u4", "email": "u4@e.com", "groups": " "}
id4 = claims_to_identity(c4)
assert id4.groups == []
def test_claims_to_identity_requires_sub():
with pytest.raises(TokenValidationError) as exc_info:
claims_to_identity({"email": "nosub@example.com"})
assert "sub" in str(exc_info.value.detail).lower()
with pytest.raises(TokenValidationError) as exc_info:
claims_to_identity({"sub": " ", "email": "blanksub@example.com"})
assert "sub" in str(exc_info.value.detail).lower()
def test_claims_to_identity_email_and_name_fallbacks():
# Fallback to preferred_username
c1 = {"sub": "usr_abc", "preferred_username": "preferred@example.com"}
id1 = claims_to_identity(c1)
assert id1.email == "preferred@example.com"
assert id1.name is None
# Fallback to sub@local
c2 = {"sub": "usr_xyz"}
id2 = claims_to_identity(c2)
assert id2.email == "usr_xyz@local"
assert id2.name is None
# ============================================================================
# 2. Verification Against Seeded Fixture Users
# ============================================================================
def test_fixture_admin_user_password_grant(oidc_client: OIDCClient):
"""Verify authenticating admin@example.com resolves to Identity with bdinvite_admins group."""
identity, tokens = oidc_client.authenticate_user(
username="admin@example.com",
password="password123",
)
assert isinstance(identity, Identity)
assert identity.subject == "admin-001"
assert identity.email == "admin@example.com"
assert identity.name == "Admin User"
assert identity.groups == ["bdinvite_admins"]
assert "access_token" in tokens
assert "id_token" in tokens
def test_fixture_guest_user_password_grant(oidc_client: OIDCClient):
"""Verify authenticating guest@example.com resolves to Identity with guests group."""
identity, tokens = oidc_client.authenticate_user(
username="guest@example.com",
password="password123",
)
assert isinstance(identity, Identity)
assert identity.subject == "guest-001"
assert identity.email == "guest@example.com"
assert identity.name == "Guest User"
assert identity.groups == ["guests"]
assert "access_token" in tokens
assert "id_token" in tokens
@pytest.mark.asyncio
async def test_async_fixture_admin_and_guest_user(oidc_client: OIDCClient):
admin_id, _ = await oidc_client.aauthenticate_user("admin@example.com", "password123")
assert admin_id.subject == "admin-001"
assert admin_id.groups == ["bdinvite_admins"]
guest_id, _ = await oidc_client.aauthenticate_user("guest@example.com", "password123")
assert guest_id.subject == "guest-001"
assert guest_id.groups == ["guests"]
def test_fixture_admin_authorization_code_flow(oidc_client: OIDCClient):
"""Verify complete authorization code flow with admin fixture user."""
auth_url, tx = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="admin@example.com")
identity, tokens = oidc_client.process_callback(
code=code,
state=returned_state,
extra_params={"username": "admin@example.com"},
)
assert identity.subject == "admin-001"
assert identity.email == "admin@example.com"
assert identity.name == "Admin User"
assert identity.groups == ["bdinvite_admins"]
def test_fixture_guest_authorization_code_flow(oidc_client: OIDCClient):
"""Verify complete authorization code flow with guest fixture user."""
auth_url, tx = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="guest@example.com")
identity, tokens = oidc_client.process_callback(
code=code,
state=returned_state,
extra_params={"username": "guest@example.com"},
)
assert identity.subject == "guest-001"
assert identity.email == "guest@example.com"
assert identity.name == "Guest User"
assert identity.groups == ["guests"]
# ============================================================================
# 3. Identity Origin Integrity (Authoritative Provenance) Tests
# ============================================================================
def test_identity_origin_integrity_rejects_unvalidated_request_headers(
oidc_client: OIDCClient,
):
"""Verify that unvalidated request headers (e.g. X-User, X-Email, X-Groups)
CANNOT forge or inject an Identity. Application code must only trust
cryptographically verified authentication artifacts.
"""
adapter = OIDCAuthAdapter(client=oidc_client)
# 1. Attacker attempts to spoof admin identity via custom headers
spoof_req = create_request(
headers={
"X-User": "admin-001",
"X-User-Email": "admin@example.com",
"X-User-Name": "Admin User",
"X-Groups": "bdinvite_admins",
"X-Remote-User": "admin@example.com",
"X-Forwarded-User": "admin-001",
}
)
resolved = adapter.current_identity(spoof_req)
assert resolved is None, "Adapter must NEVER construct an Identity from raw unvalidated headers"
# 2. Attacker attempts to forge session cookie with fake ID
fake_session_req = create_request(cookies={"session_id": "forged_random_session_key"})
assert adapter.current_identity(fake_session_req) is None
# 3. Legitimate session established through verified callback succeeds
legit_identity = Identity(
subject="admin-001",
email="admin@example.com",
name="Admin User",
groups=["bdinvite_admins"],
)
session_id = adapter.establish_session(legit_identity)
valid_session_req = create_request(cookies={"session_id": session_id})
assert adapter.current_identity(valid_session_req) == legit_identity
def test_identity_origin_integrity_bearer_token_validation(oidc_client: OIDCClient):
"""Verify Bearer token in Authorization header is strictly cryptographically validated."""
adapter = OIDCAuthAdapter(client=oidc_client)
# 1. Genuine token from fixture user
_, tokens = oidc_client.authenticate_user("admin@example.com", "password123")
valid_id_token = tokens["id_token"]
req_with_valid_bearer = create_request(
headers={"Authorization": f"Bearer {valid_id_token}"}
)
resolved = adapter.current_identity(req_with_valid_bearer)
assert resolved is not None
assert resolved.subject == "admin-001"
assert resolved.email == "admin@example.com"
assert resolved.groups == ["bdinvite_admins"]
# 2. Tampered token signature fails verification and yields None
parts = valid_id_token.split(".")
tampered_sig = ("X" if parts[2][0] != "X" else "Y") + parts[2][1:]
tampered_token = f"{parts[0]}.{parts[1]}.{tampered_sig}"
req_with_tampered_bearer = create_request(
headers={"Authorization": f"Bearer {tampered_token}"}
)
assert adapter.current_identity(req_with_tampered_bearer) is None
# 3. Forged payload with valid signature prefix fails verification
req_garbage = create_request(headers={"Authorization": "Bearer not.a.valid.jwt"})
assert adapter.current_identity(req_garbage) is None
# ============================================================================
# 4. Identity Immutability Tests
# ============================================================================
def test_identity_frozen_immutability():
"""Verify that domain Identity instances cannot be mutated at runtime."""
identity = Identity(
subject="admin-001",
email="admin@example.com",
name="Admin User",
groups=["bdinvite_admins"],
)
with pytest.raises(FrozenInstanceError):
identity.subject = "hacker" # type: ignore[misc]
with pytest.raises(FrozenInstanceError):
identity.email = "hacker@example.com" # type: ignore[misc]
with pytest.raises(FrozenInstanceError):
identity.name = "Hacker" # type: ignore[misc]
with pytest.raises(FrozenInstanceError):
identity.groups = ["superusers"] # type: ignore[misc]
+9 -12
View File
@@ -10,8 +10,6 @@ from app.services.map_preview import (
validate_google_maps_url_format, validate_google_maps_url_format,
) )
ADMIN_HEADERS = {"Remote-User": "kiskaadee"}
def test_is_google_maps_host(): def test_is_google_maps_host():
assert is_google_maps_host("maps.app.goo.gl") assert is_google_maps_host("maps.app.goo.gl")
@@ -72,7 +70,7 @@ def test_deg2num():
@patch("app.routes.admin.resolve_google_maps_coordinates") @patch("app.routes.admin.resolve_google_maps_coordinates")
@patch("app.routes.admin.generate_map_preview_image") @patch("app.routes.admin.generate_map_preview_image")
def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client, tmp_path): def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client, admin_client, tmp_path):
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url") mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
mock_generate.return_value = tmp_path / "map_preview.png" mock_generate.return_value = tmp_path / "map_preview.png"
@@ -81,9 +79,8 @@ def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client
assert resp.status_code == 401 assert resp.status_code == 401
# Test with auth -> 200 # Test with auth -> 200
resp = client.post( resp = admin_client.post(
"/birthday/api/admin/map-preview/generate", "/birthday/api/admin/map-preview/generate",
headers=ADMIN_HEADERS,
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"}, json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
) )
assert resp.status_code == 200 assert resp.status_code == 200
@@ -97,19 +94,19 @@ def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client
@patch("app.routes.admin.resolve_google_maps_coordinates") @patch("app.routes.admin.resolve_google_maps_coordinates")
@patch("app.routes.admin.generate_map_preview_image") @patch("app.routes.admin.generate_map_preview_image")
def test_config_update_triggers_generator_only_when_map_url_changes(mock_generate, mock_resolve, client, tmp_path): def test_config_update_triggers_generator_only_when_map_url_changes(mock_generate, mock_resolve, admin_client, tmp_path):
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url") mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
mock_generate.return_value = tmp_path / "map_preview.png" mock_generate.return_value = tmp_path / "map_preview.png"
# Get current config # Get current config
current = client.get("/birthday/api/admin/config", headers=ADMIN_HEADERS).json() current = admin_client.get("/birthday/api/admin/config").json()
orig_map_url = current["map_url"] orig_map_url = current["map_url"]
assert orig_map_url == "https://maps.google.com/?q=Fresco+Ristorante+Glendale+CA" assert orig_map_url == "https://maps.google.com/?q=Fresco+Ristorante+Glendale+CA"
# 1. Update config WITHOUT changing map_url -> generator NOT called # 1. Update config WITHOUT changing map_url -> generator NOT called
update_payload = {**current} update_payload = {**current}
update_payload["honoree_name"] = "Updated Honoree" update_payload["honoree_name"] = "Updated Honoree"
resp = client.put("/birthday/api/admin/config", headers=ADMIN_HEADERS, json=update_payload) resp = admin_client.put("/birthday/api/admin/config", json=update_payload)
assert resp.status_code == 200 assert resp.status_code == 200
assert resp.json()["honoree_name"] == "Updated Honoree" assert resp.json()["honoree_name"] == "Updated Honoree"
mock_resolve.assert_not_called() mock_resolve.assert_not_called()
@@ -117,7 +114,7 @@ def test_config_update_triggers_generator_only_when_map_url_changes(mock_generat
# 2. Update config WITH new map_url -> generator CALLED # 2. Update config WITH new map_url -> generator CALLED
update_payload["map_url"] = "https://maps.google.com/?q=34.1432,-118.2551" update_payload["map_url"] = "https://maps.google.com/?q=34.1432,-118.2551"
resp = client.put("/birthday/api/admin/config", headers=ADMIN_HEADERS, json=update_payload) resp = admin_client.put("/birthday/api/admin/config", json=update_payload)
assert resp.status_code == 200 assert resp.status_code == 200
assert resp.json()["map_url"] == "https://maps.google.com/?q=34.1432,-118.2551" assert resp.json()["map_url"] == "https://maps.google.com/?q=34.1432,-118.2551"
assert resp.json()["map_preview_url"] == "/birthday/api/map-preview.png" assert resp.json()["map_preview_url"] == "/birthday/api/map-preview.png"
@@ -125,11 +122,11 @@ def test_config_update_triggers_generator_only_when_map_url_changes(mock_generat
mock_generate.assert_called_once_with(34.1432, -118.2551) mock_generate.assert_called_once_with(34.1432, -118.2551)
def test_config_update_rejects_invalid_map_url(client): def test_config_update_rejects_invalid_map_url(admin_client):
current = client.get("/birthday/api/admin/config", headers=ADMIN_HEADERS).json() current = admin_client.get("/birthday/api/admin/config").json()
bad_payload = {**current, "map_url": "https://invalid-non-google-url.com/something"} bad_payload = {**current, "map_url": "https://invalid-non-google-url.com/something"}
resp = client.put("/birthday/api/admin/config", headers=ADMIN_HEADERS, json=bad_payload) resp = admin_client.put("/birthday/api/admin/config", json=bad_payload)
assert resp.status_code == 422 assert resp.status_code == 422
+325
View File
@@ -0,0 +1,325 @@
"""Comprehensive unit and integration tests for Generic OIDC Client, PKCE & Cryptographic Verification."""
import base64
import json
import time
from urllib.parse import parse_qs, urlparse
import httpx
import pytest
from fastapi import HTTPException
from app.auth import (
AuthPort,
Identity,
InvalidNonceError,
InvalidStateError,
OIDCAuthAdapter,
OIDCClient,
OIDCConfig,
OIDCTransaction,
TokenValidationError,
generate_code_challenge,
generate_code_verifier,
generate_nonce,
generate_state,
)
FIXTURE_ISSUER = "http://localhost:8088/default"
FIXTURE_CLIENT_ID = "bdinvite-client"
FIXTURE_CLIENT_SECRET = "bdinvite-secret"
FIXTURE_REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
@pytest.fixture
def oidc_config() -> OIDCConfig:
return OIDCConfig(
issuer=FIXTURE_ISSUER,
client_id=FIXTURE_CLIENT_ID,
client_secret=FIXTURE_CLIENT_SECRET,
redirect_uri=FIXTURE_REDIRECT_URI,
)
@pytest.fixture
def oidc_client(oidc_config: OIDCConfig) -> OIDCClient:
return OIDCClient(oidc_config)
def obtain_auth_code_from_fixture(
authorization_url: str,
username: str = "testuser",
claims: dict | None = None,
) -> tuple[str, str]:
"""Helper to simulate user authentication against the Navikt mock-oauth2-server fixture."""
parsed_url = urlparse(authorization_url)
auth_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"
query_params = parse_qs(parsed_url.query)
flat_params = {k: v[0] for k, v in query_params.items()}
post_data: dict[str, str] = {"username": username}
if claims:
post_data["claims"] = json.dumps(claims)
with httpx.Client() as client:
resp = client.post(
auth_endpoint,
params=flat_params,
data=post_data,
follow_redirects=False,
)
assert resp.status_code == 302, f"Expected 302 redirect, got {resp.status_code}: {resp.text}"
location = resp.headers["location"]
redirect_parsed = urlparse(location)
callback_params = parse_qs(redirect_parsed.query)
assert "code" in callback_params, f"No code in callback redirect: {location}"
assert "state" in callback_params, f"No state in callback redirect: {location}"
return callback_params["code"][0], callback_params["state"][0]
def test_pkce_rfc7636_test_vector():
"""Verify that SHA-256 PKCE code_challenge derivation matches RFC 7636 Appendix B."""
rfc_verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
expected_challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
derived_challenge = generate_code_challenge(rfc_verifier)
assert derived_challenge == expected_challenge
def test_pkce_verifier_generation_entropy():
"""Verify generated code_verifier conforms to RFC 7636 unreserved character requirements and length."""
verifier = generate_code_verifier()
assert 43 <= len(verifier) <= 128
allowed_chars = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
assert all(c in allowed_chars for c in verifier)
def test_oidc_discovery_fetching(oidc_client: OIDCClient):
"""Verify dynamic discovery parsing from the live OIDC issuer."""
discovery = oidc_client.fetch_discovery()
assert discovery.issuer == FIXTURE_ISSUER
assert discovery.authorization_endpoint == f"{FIXTURE_ISSUER}/authorize"
assert discovery.token_endpoint == f"{FIXTURE_ISSUER}/token"
assert discovery.jwks_uri == f"{FIXTURE_ISSUER}/jwks"
assert discovery.end_session_endpoint == f"{FIXTURE_ISSUER}/endsession"
def test_authorization_request_contains_pkce_state_and_nonce(oidc_client: OIDCClient):
"""Verify authorization URL properly includes PKCE S256 challenge, state, and nonce."""
auth_url, transaction = oidc_client.create_authorization_url()
parsed = urlparse(auth_url)
assert parsed.scheme == "http"
assert parsed.path == "/default/authorize"
params = parse_qs(parsed.query)
assert params["client_id"] == [FIXTURE_CLIENT_ID]
assert params["response_type"] == ["code"]
assert params["redirect_uri"] == [FIXTURE_REDIRECT_URI]
assert params["scope"] == ["openid profile email"]
# Verify state, nonce, and PKCE parameters
assert params["state"] == [transaction.state]
assert params["nonce"] == [transaction.nonce]
assert params["code_challenge_method"] == ["S256"]
expected_challenge = generate_code_challenge(transaction.code_verifier)
assert params["code_challenge"] == [expected_challenge]
# Verify transaction is stored internally
assert transaction.state in oidc_client._transactions
def test_successful_code_exchange_and_id_token_validation(oidc_client: OIDCClient):
"""Verify complete end-to-end authorization code exchange, cryptographic verification, and Identity extraction."""
auth_url, transaction = oidc_client.create_authorization_url()
expected_claims = {
"email": "alex@roadtotech.me",
"name": "Alex Organizer",
"groups": ["organizers", "vip"],
}
code, returned_state = obtain_auth_code_from_fixture(
auth_url,
username="alex_sub_101",
claims=expected_claims,
)
assert returned_state == transaction.state
# Process callback
identity, tokens = oidc_client.process_callback(code=code, state=returned_state)
# Validate tokens payload
assert "access_token" in tokens
assert "id_token" in tokens
assert tokens["token_type"].lower() == "bearer"
# Validate Identity model creation
assert isinstance(identity, Identity)
assert identity.subject == "alex_sub_101"
assert identity.email == "alex@roadtotech.me"
assert identity.name == "Alex Organizer"
assert identity.groups == ["organizers", "vip"]
def test_rejection_of_invalid_state(oidc_client: OIDCClient):
"""Verify invalid, missing, and replayed states are rejected with HTTP 400 (CSRF protection)."""
# 1. Unrecognized state
with pytest.raises(InvalidStateError) as exc_info:
oidc_client.validate_state("non_existent_state_value")
assert exc_info.value.status_code == 400
# 2. None or empty state
with pytest.raises(InvalidStateError) as exc_info:
oidc_client.validate_state("")
assert exc_info.value.status_code == 400
# 3. Replay attack rejection: state must only be valid once
_, transaction = oidc_client.create_authorization_url()
first_validation = oidc_client.validate_state(transaction.state)
assert first_validation.state == transaction.state
with pytest.raises(InvalidStateError) as exc_info:
oidc_client.validate_state(transaction.state)
assert exc_info.value.status_code == 400
# 4. Expired state rejection
_, exp_transaction = oidc_client.create_authorization_url()
# Artificially expire the transaction
expired_tx = OIDCTransaction(
state=exp_transaction.state,
nonce=exp_transaction.nonce,
code_verifier=exp_transaction.code_verifier,
created_at=time.time() - 700.0,
expires_in=600.0,
)
oidc_client._transactions[expired_tx.state] = expired_tx
with pytest.raises(InvalidStateError) as exc_info:
oidc_client.validate_state(expired_tx.state)
assert exc_info.value.status_code == 400
def test_rejection_of_mismatched_nonce(oidc_client: OIDCClient):
"""Verify mismatched or missing nonce causes rejection with HTTP 401."""
auth_url, transaction = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="nonce_user")
validated_tx = oidc_client.validate_state(returned_state)
tokens = oidc_client.exchange_code(code=code, transaction_or_verifier=validated_tx)
id_token = tokens["id_token"]
# Validate with mismatched nonce
with pytest.raises(InvalidNonceError) as exc_info:
oidc_client.validate_id_token(id_token=id_token, nonce="completely_different_nonce")
assert exc_info.value.status_code == 401
# Validating with correct nonce succeeds
claims = oidc_client.validate_id_token(id_token=id_token, nonce=validated_tx.nonce)
assert claims["nonce"] == validated_tx.nonce
def test_rejection_of_tampered_id_token_signature(oidc_client: OIDCClient):
"""Verify tampered ID token signature or payload causes cryptographic rejection with HTTP 401."""
auth_url, transaction = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="tamper_user")
validated_tx = oidc_client.validate_state(returned_state)
tokens = oidc_client.exchange_code(code=code, transaction_or_verifier=validated_tx)
valid_id_token = tokens["id_token"]
# Valid token passes verification
oidc_client.validate_id_token(id_token=valid_id_token, nonce=validated_tx.nonce)
# 1. Tamper signature segment: change the last few characters of the signature
parts = valid_id_token.split(".")
assert len(parts) == 3
header_b64, payload_b64, sig_b64 = parts
tampered_sig = ("A" if sig_b64[-1] != "A" else "B") + sig_b64[1:]
tampered_token = f"{header_b64}.{payload_b64}.{tampered_sig}"
with pytest.raises(TokenValidationError) as exc_info:
oidc_client.validate_id_token(id_token=tampered_token, nonce=validated_tx.nonce)
assert exc_info.value.status_code == 401
# 2. Tamper payload segment: elevate permissions or change subject
payload_json = json.loads(base64.urlsafe_b64decode(payload_b64 + "==").decode("utf-8"))
payload_json["sub"] = "hacked_admin_user"
new_payload_b64 = (
base64.urlsafe_b64encode(json.dumps(payload_json).encode("utf-8"))
.decode("ascii")
.rstrip("=")
)
tampered_payload_token = f"{header_b64}.{new_payload_b64}.{sig_b64}"
with pytest.raises(TokenValidationError) as exc_info:
oidc_client.validate_id_token(id_token=tampered_payload_token, nonce=validated_tx.nonce)
assert exc_info.value.status_code == 401
def test_rejection_of_issuer_or_audience_mismatch(oidc_client: OIDCClient):
"""Verify tokens with unexpected issuer or audience are rejected with HTTP 401."""
auth_url, transaction = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="mismatch_user")
validated_tx = oidc_client.validate_state(returned_state)
tokens = oidc_client.exchange_code(code=code, transaction_or_verifier=validated_tx)
id_token = tokens["id_token"]
# Wrong client_id / audience expected
client_wrong_aud = OIDCClient(
OIDCConfig(
issuer=FIXTURE_ISSUER,
client_id="attacker-client",
client_secret=FIXTURE_CLIENT_SECRET,
redirect_uri=FIXTURE_REDIRECT_URI,
)
)
with pytest.raises(TokenValidationError) as exc_info:
client_wrong_aud.validate_id_token(id_token=id_token, nonce=validated_tx.nonce)
assert exc_info.value.status_code == 401
# Wrong issuer expected
client_wrong_iss = OIDCClient(
OIDCConfig(
issuer="http://rogue-idp.example.com",
client_id=FIXTURE_CLIENT_ID,
client_secret=FIXTURE_CLIENT_SECRET,
redirect_uri=FIXTURE_REDIRECT_URI,
)
)
# Pre-populate JWKS from fixture so key is available, but issuer check will fail
client_wrong_iss._jwk_set = oidc_client.get_jwks()
with pytest.raises(TokenValidationError) as exc_info:
client_wrong_iss.validate_id_token(id_token=id_token, nonce=validated_tx.nonce)
assert exc_info.value.status_code == 401
@pytest.mark.asyncio
async def test_async_oidc_flow(oidc_client: OIDCClient):
"""Verify asynchronous discovery, code exchange, and token validation."""
discovery = await oidc_client.afetch_discovery()
assert discovery.issuer == FIXTURE_ISSUER
auth_url, transaction = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="async_user")
identity, tokens = await oidc_client.aprocess_callback(code=code, state=returned_state)
assert identity.subject == "async_user"
assert "access_token" in tokens
assert "id_token" in tokens
def test_auth_adapter_protocol_conformance(oidc_client: OIDCClient):
"""Verify OIDCAuthAdapter adheres to the hexagonal AuthPort Protocol."""
adapter = OIDCAuthAdapter(client=oidc_client)
assert isinstance(adapter, AuthPort)
from fastapi import Request
mock_req = Request({"type": "http", "method": "GET", "path": "/test", "headers": []})
login_resp = adapter.login(mock_req)
assert login_resp.status_code == 302
assert "/default/authorize?" in login_resp.headers["location"]
+511
View File
@@ -0,0 +1,511 @@
"""Security Hardening and Deployment Independence verification tests (Checkpoint 8).
Validates adversarial edge cases:
1. Forged / invalid CSRF state returns HTTP 400 Bad Request.
2. Forged / tampered ID token signature returns HTTP 401 Unauthorized.
3. Mismatched or replayed nonce returns HTTP 401 Unauthorized.
4. Missing or invalid PKCE code_verifier returns HTTP 401 Unauthorized.
5. Expired ID token / expired session cookie returns HTTP 401 Unauthorized.
6. Authenticated non-admin user accessing admin APIs returns HTTP 403 Forbidden.
7. Legacy Remote-User header without a valid authenticated session returns HTTP 401 Unauthorized.
8. Deployment independence: Direct Standalone Mode vs Homelab Production Mode.
"""
import base64
import json
import time
from unittest.mock import MagicMock
from urllib.parse import parse_qs, urlparse
import httpx
import pytest
from fastapi.testclient import TestClient
from app.auth import (
Identity,
InvalidCodeVerifierError,
InvalidNonceError,
InvalidStateError,
OIDCAuthAdapter,
OIDCClient,
OIDCConfig,
OIDCTransaction,
SessionRecord,
TokenValidationError,
get_auth_adapter,
)
from app.config import Settings
FIXTURE_ISSUER = "http://localhost:8088/default"
FIXTURE_CLIENT_ID = "bdinvite-client"
FIXTURE_CLIENT_SECRET = "bdinvite-secret"
FIXTURE_REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
def _obtain_auth_code(
authorization_url: str,
username: str = "security_test_user",
claims: dict | None = None,
) -> tuple[str, str]:
"""Helper to simulate user authentication against the Navikt mock-oauth2-server fixture."""
parsed_url = urlparse(authorization_url)
auth_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"
query_params = parse_qs(parsed_url.query)
flat_params = {k: v[0] for k, v in query_params.items()}
post_data: dict[str, str] = {"username": username}
if claims:
post_data["claims"] = json.dumps(claims)
with httpx.Client() as http_client:
resp = http_client.post(
auth_endpoint,
params=flat_params,
data=post_data,
follow_redirects=False,
)
assert resp.status_code == 302, f"Expected 302 redirect, got {resp.status_code}: {resp.text}"
location = resp.headers["location"]
redirect_parsed = urlparse(location)
callback_params = parse_qs(redirect_parsed.query)
assert "code" in callback_params
assert "state" in callback_params
return callback_params["code"][0], callback_params["state"][0]
# ==============================================================================
# 1. Adversarial State Rejection (CSRF Mitigation) -> HTTP 400 Bad Request
# ==============================================================================
def test_forged_csrf_state_returns_400(client: TestClient):
"""Forged / unrecognized CSRF state returns HTTP 400 Bad Request."""
adapter = get_auth_adapter()
with pytest.raises(InvalidStateError):
adapter.client.validate_state("forged_state_xyz")
res = client.get(
"/birthday/api/auth/callback",
params={"code": "dummy_auth_code", "state": "forged_malicious_state_xyz"},
)
assert res.status_code == 400
assert "detail" in res.json()
def test_replayed_csrf_state_returns_400(client: TestClient):
"""Replaying an already-consumed CSRF state parameter returns HTTP 400 Bad Request."""
adapter = get_auth_adapter()
auth_url, _ = adapter.client.create_authorization_url()
code, returned_state = _obtain_auth_code(auth_url, username="replay_state_user")
# First callback succeeds and consumes state
res1 = client.get(
"/birthday/api/auth/callback",
params={"code": code, "state": returned_state},
follow_redirects=False,
)
assert res1.status_code == 302
# Second callback replaying the exact same state must return HTTP 400
res2 = client.get(
"/birthday/api/auth/callback",
params={"code": code, "state": returned_state},
)
assert res2.status_code == 400
assert "already consumed" in res2.json()["detail"].lower() or "invalid" in res2.json()["detail"].lower()
def test_expired_csrf_state_returns_400(client: TestClient):
"""Authentication transaction that exceeded its TTL returns HTTP 400 Bad Request."""
adapter = get_auth_adapter()
_, tx = adapter.client.create_authorization_url()
# Artificially expire the transaction
expired_tx = OIDCTransaction(
state=tx.state,
nonce=tx.nonce,
code_verifier=tx.code_verifier,
created_at=time.time() - 900.0,
expires_in=600.0,
)
adapter.client._transactions[tx.state] = expired_tx
res = client.get(
"/birthday/api/auth/callback",
params={"code": "any_code", "state": tx.state},
)
assert res.status_code == 400
assert "expired" in res.json()["detail"].lower()
# ==============================================================================
# 2. Forged / Tampered ID Token Signature -> HTTP 401 Unauthorized
# ==============================================================================
def test_tampered_id_token_signature_returns_401():
"""Tampered ID token signature raises TokenValidationError (HTTP 401)."""
adapter = get_auth_adapter()
auth_url, _ = adapter.client.create_authorization_url()
code, returned_state = _obtain_auth_code(auth_url, username="tamper_sig_user")
validated_tx = adapter.client.validate_state(returned_state)
tokens = adapter.client.exchange_code(code=code, transaction_or_verifier=validated_tx)
valid_id_token = tokens["id_token"]
parts = valid_id_token.split(".")
assert len(parts) == 3
header_b64, payload_b64, sig_b64 = parts
# Invert characters in the signature segment
tampered_sig = ("Z" if sig_b64[-1] != "Z" else "A") + sig_b64[1:]
tampered_token = f"{header_b64}.{payload_b64}.{tampered_sig}"
with pytest.raises(TokenValidationError) as exc_info:
adapter.client.validate_id_token(id_token=tampered_token, nonce=validated_tx.nonce)
assert exc_info.value.status_code == 401
def test_tampered_id_token_bearer_header_returns_401(client: TestClient):
"""Bearer request containing a forged / tampered ID token signature returns HTTP 401."""
adapter = get_auth_adapter()
auth_url, _ = adapter.client.create_authorization_url()
code, returned_state = _obtain_auth_code(auth_url, username="bearer_tamper_user")
validated_tx = adapter.client.validate_state(returned_state)
tokens = adapter.client.exchange_code(code=code, transaction_or_verifier=validated_tx)
valid_id_token = tokens["id_token"]
parts = valid_id_token.split(".")
tampered_token = f"{parts[0]}.{parts[1]}.tampered_signature_bytes_12345"
res = client.get(
"/birthday/api/admin/rsvps",
headers={"Authorization": f"Bearer {tampered_token}"},
)
assert res.status_code == 401
def test_alg_none_id_token_rejected_with_401():
"""ID token with 'alg': 'none' is rejected with HTTP 401."""
adapter = get_auth_adapter()
header = base64.urlsafe_b64encode(json.dumps({"alg": "none"}).encode()).decode().rstrip("=")
payload = base64.urlsafe_b64encode(
json.dumps({
"sub": "admin",
"iss": adapter.client.config.issuer,
"aud": adapter.client.config.client_id,
"exp": time.time() + 3600,
}).encode()
).decode().rstrip("=")
forged_token = f"{header}.{payload}."
with pytest.raises(TokenValidationError) as exc_info:
adapter.client.validate_id_token(forged_token)
assert exc_info.value.status_code == 401
# ==============================================================================
# 3. Mismatched or Replayed Nonce -> HTTP 401 Unauthorized
# ==============================================================================
def test_mismatched_nonce_returns_401():
"""ID token with mismatched nonce claim raises InvalidNonceError (HTTP 401)."""
adapter = get_auth_adapter()
auth_url, _ = adapter.client.create_authorization_url()
code, returned_state = _obtain_auth_code(auth_url, username="nonce_mismatch_user")
validated_tx = adapter.client.validate_state(returned_state)
tokens = adapter.client.exchange_code(code=code, transaction_or_verifier=validated_tx)
id_token = tokens["id_token"]
with pytest.raises(InvalidNonceError) as exc_info:
adapter.client.validate_id_token(id_token=id_token, nonce="completely_different_nonce_val")
assert exc_info.value.status_code == 401
assert "nonce" in exc_info.value.detail.lower()
def test_missing_nonce_when_expected_returns_401(monkeypatch):
"""ID token missing expected nonce claim raises InvalidNonceError (HTTP 401)."""
adapter = get_auth_adapter()
# Mock jwt.decode to return valid claims except missing the required nonce
mock_claims = {
"sub": "user123",
"email": "user@example.com",
"iss": adapter.client.config.issuer,
"aud": adapter.client.config.client_id,
"exp": time.time() + 3600,
}
monkeypatch.setattr("jwt.get_unverified_header", lambda token: {"alg": "RS256", "kid": "mock_kid"})
monkeypatch.setattr("jwt.decode", lambda *args, **kwargs: mock_claims)
mock_jwk = MagicMock()
mock_jwk.key = "mock_key"
mock_keys = MagicMock()
mock_keys.__getitem__.return_value = mock_jwk
monkeypatch.setattr(adapter.client, "get_jwks", lambda *args, **kwargs: mock_keys)
with pytest.raises(InvalidNonceError) as exc_info:
adapter.client.validate_id_token("dummy.jwt.token", nonce="expected_nonce_123")
assert exc_info.value.status_code == 401
assert "nonce" in exc_info.value.detail.lower()
# ==============================================================================
# 4. Missing or Invalid PKCE code_verifier -> HTTP 401 Unauthorized
# ==============================================================================
def test_missing_pkce_code_verifier_returns_401():
"""Missing or empty PKCE code_verifier raises InvalidCodeVerifierError (HTTP 401)."""
adapter = get_auth_adapter()
with pytest.raises(InvalidCodeVerifierError) as exc_info:
adapter.client.exchange_code(code="dummy_code", transaction_or_verifier="")
assert exc_info.value.status_code == 401
assert "code_verifier" in exc_info.value.detail.lower()
def test_invalid_pkce_code_verifier_against_idp_returns_401():
"""Invalid PKCE code_verifier rejected by IdP raises InvalidCodeVerifierError (HTTP 401)."""
adapter = get_auth_adapter()
auth_url, _ = adapter.client.create_authorization_url()
code, _ = _obtain_auth_code(auth_url, username="pkce_invalid_user")
# Mismatched 50-char string that does not hash to the code_challenge
wrong_verifier = "x" * 50
with pytest.raises(InvalidCodeVerifierError) as exc_info:
adapter.client.exchange_code(code=code, transaction_or_verifier=wrong_verifier)
assert exc_info.value.status_code == 401
@pytest.mark.asyncio
async def test_async_invalid_pkce_code_verifier_returns_401():
"""Asynchronous exchange with invalid PKCE code_verifier raises InvalidCodeVerifierError (HTTP 401)."""
adapter = get_auth_adapter()
with pytest.raises(InvalidCodeVerifierError) as exc_info:
await adapter.client.aexchange_code(code="dummy_code", transaction_or_verifier="")
assert exc_info.value.status_code == 401
# ==============================================================================
# 5. Expired ID Token / Expired Session Cookie -> HTTP 401 Unauthorized
# ==============================================================================
def test_expired_id_token_validation_returns_401(monkeypatch):
"""Expired ID token raises TokenValidationError (HTTP 401)."""
adapter = get_auth_adapter()
import jwt as pyjwt
monkeypatch.setattr("jwt.get_unverified_header", lambda token: {"alg": "RS256", "kid": "mock_kid"})
mock_jwk = MagicMock()
mock_jwk.key = "mock_key"
mock_keys = MagicMock()
mock_keys.__getitem__.return_value = mock_jwk
monkeypatch.setattr(adapter.client, "get_jwks", lambda *args, **kwargs: mock_keys)
def mock_decode(*args, **kwargs):
raise pyjwt.ExpiredSignatureError("Signature has expired")
monkeypatch.setattr("jwt.decode", mock_decode)
with pytest.raises(TokenValidationError) as exc_info:
adapter.client.validate_id_token("expired.jwt.token")
assert exc_info.value.status_code == 401
assert "expired" in exc_info.value.detail.lower()
def test_expired_session_cookie_returns_401(client: TestClient):
"""Expired session cookie is rejected with HTTP 401 Unauthorized on admin API."""
adapter = get_auth_adapter()
admin_id = Identity(
subject="admin-exp",
email="admin@example.com",
groups=["bdinvite_admins"],
)
# Establish session expired 100 seconds ago
session_id = "expired_sess_test_123"
past_time = time.time() - 100.0
record = SessionRecord(
session_id=session_id,
identity=admin_id,
created_at=past_time - 3600,
expires_at=past_time,
last_accessed=past_time,
)
adapter.sessions[session_id] = record
client.cookies.set(adapter.session_cookie_name, session_id)
res = client.get("/birthday/api/admin/rsvps")
assert res.status_code == 401
# Session record must be revoked
assert session_id not in adapter.sessions
def test_expired_session_cookie_on_auth_me_returns_unauthenticated(client: TestClient):
"""Expired session cookie returns unauthenticated status on /birthday/api/auth/me."""
adapter = get_auth_adapter()
guest_id = Identity(
subject="guest-exp",
email="guest@example.com",
groups=["guests"],
)
session_id = "expired_me_test_123"
past_time = time.time() - 50.0
adapter.sessions[session_id] = SessionRecord(
session_id=session_id,
identity=guest_id,
created_at=past_time - 3600,
expires_at=past_time,
)
client.cookies.set(adapter.session_cookie_name, session_id)
res = client.get("/birthday/api/auth/me")
assert res.status_code == 200
data = res.json()
assert data["authenticated"] is False
assert data["identity"] is None
# ==============================================================================
# 6. Authenticated Non-Admin User Accessing Admin APIs -> HTTP 403 Forbidden
# ==============================================================================
def test_authenticated_non_admin_returns_403(client: TestClient, guest_session_cookie):
"""Authenticated non-admin user (guest) accessing admin endpoints returns HTTP 403 Forbidden."""
for k, v in guest_session_cookie.items():
client.cookies.set(k, v)
# 1. GET RSVPs
res1 = client.get("/birthday/api/admin/rsvps")
assert res1.status_code == 403
assert "Forbidden" in res1.json()["detail"] or "bdinvite_admins" in res1.json()["detail"]
# 2. GET Config
res2 = client.get("/birthday/api/admin/config")
assert res2.status_code == 403
# 3. PUT Config
res3 = client.put("/birthday/api/admin/config", json={"title": "Hacked Title"})
assert res3.status_code == 403
# 4. Export CSV
res4 = client.get("/birthday/api/admin/export")
assert res4.status_code == 403
# 5. Map preview trigger
res5 = client.post("/birthday/api/admin/map-preview/generate", json={"map_url": "https://maps.google.com"})
assert res5.status_code == 403
# 6. Delete RSVP
res6 = client.delete("/birthday/api/admin/rsvps/1")
assert res6.status_code == 403
# ==============================================================================
# 7. Legacy Remote-User Header Without Valid Session -> HTTP 401 Unauthorized
# ==============================================================================
def test_legacy_remote_user_header_without_session_returns_401(client: TestClient):
"""Negative gate: legacy Remote-User header without valid session returns HTTP 401."""
# Direct Remote-User spoofing attempt
res = client.get(
"/birthday/api/admin/rsvps",
headers={"Remote-User": "admin@example.com"},
)
assert res.status_code == 401
# Alternative headers spoofing attempts
res_alt1 = client.get(
"/birthday/api/admin/config",
headers={"X-Remote-User": "admin", "X-Forwarded-User": "admin"},
)
assert res_alt1.status_code == 401
def test_legacy_remote_user_with_non_admin_session_returns_403(
client: TestClient, guest_session_cookie
):
"""Remote-User header sent alongside non-admin session is ignored; session governs -> 403."""
for k, v in guest_session_cookie.items():
client.cookies.set(k, v)
res = client.get(
"/birthday/api/admin/rsvps",
headers={"Remote-User": "admin@example.com"},
)
assert res.status_code == 403
# ==============================================================================
# 8. Deployment Independence: Standalone vs Homelab Production Mode
# ==============================================================================
def test_standalone_mode_configuration():
"""Verify Direct Standalone Mode environment settings and behavior."""
standalone_settings = Settings(
SERVICE_DOMAIN="localhost",
OIDC_ISSUER="http://localhost:8088/default",
OIDC_REDIRECT_URI="http://localhost:8000/birthday/api/auth/callback",
SESSION_COOKIE_SECURE=False,
SESSION_COOKIE_NAME="bdinvite_session",
)
assert standalone_settings.SESSION_COOKIE_SECURE is False
assert standalone_settings.OIDC_ISSUER == "http://localhost:8088/default"
# Adapter with secure=False should not set Secure flag on cookie
client = OIDCClient(
OIDCConfig(
issuer=standalone_settings.OIDC_ISSUER,
client_id=standalone_settings.OIDC_CLIENT_ID,
redirect_uri=standalone_settings.OIDC_REDIRECT_URI,
)
)
adapter = OIDCAuthAdapter(
client=client,
cookie_secure=standalone_settings.SESSION_COOKIE_SECURE,
session_cookie_name=standalone_settings.SESSION_COOKIE_NAME,
)
mock_resp = MagicMock()
adapter.set_session_cookie(mock_resp, "test_sess_123")
mock_resp.set_cookie.assert_called_once()
_, kwargs = mock_resp.set_cookie.call_args
assert kwargs["secure"] is False
assert kwargs["httponly"] is True
def test_homelab_production_mode_configuration():
"""Verify Homelab Production Mode environment settings and behavior."""
prod_settings = Settings(
SERVICE_DOMAIN="demos.roadtotech.me",
OIDC_ISSUER="https://auth.roadtotech.me",
OIDC_CLIENT_ID="bdinvite-prod",
OIDC_CLIENT_SECRET="secure-prod-secret",
OIDC_REDIRECT_URI="https://demos.roadtotech.me/birthday/api/auth/callback",
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_NAME="bdinvite_session",
SESSION_COOKIE_SAMESITE="lax",
)
assert prod_settings.SESSION_COOKIE_SECURE is True
assert prod_settings.SERVICE_DOMAIN == "demos.roadtotech.me"
assert prod_settings.OIDC_ISSUER == "https://auth.roadtotech.me"
# Adapter with secure=True must set Secure=True and HttpOnly=True
client = OIDCClient(
OIDCConfig(
issuer=prod_settings.OIDC_ISSUER,
client_id=prod_settings.OIDC_CLIENT_ID,
client_secret=prod_settings.OIDC_CLIENT_SECRET,
redirect_uri=prod_settings.OIDC_REDIRECT_URI,
)
)
adapter = OIDCAuthAdapter(
client=client,
cookie_secure=prod_settings.SESSION_COOKIE_SECURE,
session_cookie_name=prod_settings.SESSION_COOKIE_NAME,
)
mock_resp = MagicMock()
adapter.set_session_cookie(mock_resp, "test_prod_sess_456")
mock_resp.set_cookie.assert_called_once()
_, kwargs = mock_resp.set_cookie.call_args
assert kwargs["secure"] is True
assert kwargs["httponly"] is True
assert kwargs["samesite"] == "lax"
+401
View File
@@ -0,0 +1,401 @@
"""Tests for Browser Session Management and Session Fixation Protection (Checkpoint 4)."""
import time
from collections.abc import Generator
from urllib.parse import parse_qs, urlparse
import httpx
import pytest
from fastapi import Response
from fastapi.testclient import TestClient
from starlette.requests import Request
from app.auth import (
Identity,
OIDCAuthAdapter,
OIDCClient,
OIDCConfig,
SessionRecord,
)
from app.routes.auth import get_auth_adapter, set_auth_adapter
FIXTURE_ISSUER = "http://localhost:8088/default"
FIXTURE_CLIENT_ID = "bdinvite-client"
FIXTURE_CLIENT_SECRET = "bdinvite-secret"
FIXTURE_REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
@pytest.fixture
def oidc_config() -> OIDCConfig:
return OIDCConfig(
issuer=FIXTURE_ISSUER,
client_id=FIXTURE_CLIENT_ID,
client_secret=FIXTURE_CLIENT_SECRET,
redirect_uri=FIXTURE_REDIRECT_URI,
)
@pytest.fixture
def oidc_client(oidc_config: OIDCConfig) -> OIDCClient:
return OIDCClient(oidc_config)
@pytest.fixture
def auth_adapter(oidc_client: OIDCClient) -> Generator[OIDCAuthAdapter, None, None]:
adapter = OIDCAuthAdapter(
client=oidc_client,
session_cookie_name="bdinvite_session",
cookie_secure=False,
cookie_samesite="lax",
session_lifetime=3600.0,
)
set_auth_adapter(adapter)
yield adapter
set_auth_adapter(None)
def create_request(
headers: dict[str, str] | None = None,
cookies: dict[str, str] | None = None,
) -> Request:
header_list: list[tuple[bytes, bytes]] = []
if headers:
for k, v in headers.items():
header_list.append((k.lower().encode("latin-1"), v.encode("latin-1")))
if cookies:
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
header_list.append((b"cookie", cookie_header.encode("latin-1")))
scope = {
"type": "http",
"method": "GET",
"path": "/birthday/api/auth/session",
"headers": header_list,
"query_string": b"",
}
return Request(scope)
def obtain_auth_code_from_fixture(authorization_url: str, username: str) -> tuple[str, str]:
parsed_url = urlparse(authorization_url)
auth_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"
query_params = parse_qs(parsed_url.query)
flat_params = {k: v[0] for k, v in query_params.items()}
with httpx.Client() as client:
resp = client.post(
auth_endpoint,
params=flat_params,
data={"username": username},
follow_redirects=False,
)
assert resp.status_code == 302, f"Failed auth code post: {resp.text}"
location = resp.headers["location"]
redirect_parsed = urlparse(location)
callback_params = parse_qs(redirect_parsed.query)
return callback_params["code"][0], callback_params["state"][0]
# ============================================================================
# 1. Browser Session Contract & Security Invariant Tests
# ============================================================================
def test_session_cookie_issued_with_httponly_and_samesite(auth_adapter: OIDCAuthAdapter):
"""Security Invariant: The session cookie MUST have HttpOnly=True and SameSite.
Client-side JavaScript must never have access to raw tokens or session identifiers.
"""
identity = Identity(
subject="admin-001",
email="admin@example.com",
name="Admin User",
groups=["bdinvite_admins"],
)
response = Response()
session_id = auth_adapter.establish_session(identity)
auth_adapter.set_session_cookie(response, session_id)
set_cookie = response.headers.get("set-cookie", "")
assert auth_adapter.session_cookie_name in set_cookie
assert session_id in set_cookie
assert "HttpOnly" in set_cookie, "Session cookie MUST enforce HttpOnly=True"
assert "SameSite=lax" in set_cookie or "samesite=lax" in set_cookie.lower()
def test_configurable_secure_flag():
"""Verify configurable Secure cookie flag: False in test/dev, True in production."""
# 1. Development/test environment: Secure=False allows HTTP testing
dev_adapter = OIDCAuthAdapter(
client=OIDCClient(OIDCConfig(issuer=FIXTURE_ISSUER, client_id=FIXTURE_CLIENT_ID)),
cookie_secure=False,
)
resp_dev = Response()
s_dev = dev_adapter.establish_session(Identity(subject="dev", email="dev@local"))
dev_adapter.set_session_cookie(resp_dev, s_dev)
assert "secure" not in resp_dev.headers.get("set-cookie", "").lower()
# 2. Production environment: Secure=True enforces HTTPS transmission
prod_adapter = OIDCAuthAdapter(
client=OIDCClient(OIDCConfig(issuer=FIXTURE_ISSUER, client_id=FIXTURE_CLIENT_ID)),
cookie_secure=True,
)
resp_prod = Response()
s_prod = prod_adapter.establish_session(Identity(subject="prod", email="prod@local"))
prod_adapter.set_session_cookie(resp_prod, s_prod)
set_cookie_prod = resp_prod.headers.get("set-cookie", "").lower()
assert "secure" in set_cookie_prod, "Production session cookie MUST enforce Secure=True"
# ============================================================================
# 2. Session Fixation Barrier Tests
# ============================================================================
def test_session_fixation_barrier_rotates_session_id(auth_adapter: OIDCAuthAdapter):
"""Session Fixation Barrier:
Successful authentication MUST generate a fresh, new session identifier.
An existing pre-authentication session identifier must NEVER be promoted into an
authenticated session (pre_auth_session_id != post_auth_session_id).
"""
# 1. Pre-authentication state: client possesses an anonymous or pre-auth session ID
pre_auth_session_id = auth_adapter.create_anonymous_session()
assert pre_auth_session_id is not None
# Pre-auth request resolves to anonymous
req_pre = create_request(cookies={auth_adapter.session_cookie_name: pre_auth_session_id})
assert auth_adapter.current_identity(req_pre) is None
# 2. User successfully authenticates
identity = Identity(
subject="admin-001",
email="admin@example.com",
name="Admin User",
groups=["bdinvite_admins"],
)
post_auth_session_id = auth_adapter.establish_session(
identity=identity,
pre_auth_session_id=pre_auth_session_id,
)
# 3. Assert Session Fixation Barrier guarantees
assert post_auth_session_id != pre_auth_session_id, (
f"Session Fixation violation: pre-auth ID was promoted! "
f"{pre_auth_session_id} == {post_auth_session_id}"
)
# 4. Old pre-auth session ID is strictly invalid and resolves to None
assert auth_adapter.current_identity(req_pre) is None
# 5. New post-auth session ID resolves to the authenticated user
req_post = create_request(cookies={auth_adapter.session_cookie_name: post_auth_session_id})
resolved = auth_adapter.current_identity(req_post)
assert resolved == identity
def test_session_fixation_barrier_via_callback(
auth_adapter: OIDCAuthAdapter,
oidc_client: OIDCClient,
):
"""Verify session fixation barrier through complete callback processing."""
auth_url, _ = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="guest@example.com")
# Attacker sets fixed pre-auth session cookie on victim
pre_auth_session_id = "pre_auth_attacker_fixed_session_key"
req = create_request(cookies={auth_adapter.session_cookie_name: pre_auth_session_id})
resp = Response()
identity, post_auth_session_id = auth_adapter.handle_callback(
code=code,
state=returned_state,
response=resp,
request=req,
extra_params={"username": "guest@example.com"},
)
# Assert fixation barrier
assert post_auth_session_id != pre_auth_session_id
assert identity.subject == "guest-001"
# Attacker's pre-auth session resolves to nothing
assert auth_adapter.current_identity(req) is None
# Authenticated user's new cookie resolves to identity
req_valid = create_request(cookies={auth_adapter.session_cookie_name: post_auth_session_id})
assert auth_adapter.current_identity(req_valid) == identity
# ============================================================================
# 3. Session Lifecycle & Invalidation Tests
# ============================================================================
def test_valid_session_cookie_resolves_to_identity(auth_adapter: OIDCAuthAdapter):
"""Returning requests presenting a valid session cookie must resolve to Identity."""
identity = Identity(
subject="guest-001",
email="guest@example.com",
name="Guest User",
groups=["guests"],
)
session_id = auth_adapter.establish_session(identity)
req = create_request(cookies={auth_adapter.session_cookie_name: session_id})
resolved = auth_adapter.current_identity(req)
assert resolved == identity
def test_anonymous_request_resolves_to_none(auth_adapter: OIDCAuthAdapter):
"""Anonymous requests (no cookie or unknown session) resolve to None."""
# 1. No cookies
req_empty = create_request(cookies={})
assert auth_adapter.current_identity(req_empty) is None
# 2. Unknown session ID
req_unknown = create_request(cookies={auth_adapter.session_cookie_name: "unknown_random_session_token"})
assert auth_adapter.current_identity(req_unknown) is None
def test_expired_session_is_rejected_and_evicted(auth_adapter: OIDCAuthAdapter):
"""Expired sessions are rejected, treated as unauthenticated, and evicted."""
identity = Identity(subject="usr_exp", email="exp@local")
# Establish session with very short TTL
session_id = auth_adapter.establish_session(identity, ttl=0.05)
req = create_request(cookies={auth_adapter.session_cookie_name: session_id})
# Initially valid
assert auth_adapter.current_identity(req) == identity
# Wait for expiration
time.sleep(0.06)
# Now expired: resolves to None and is evicted from memory
assert auth_adapter.current_identity(req) is None
assert session_id not in auth_adapter.sessions
def test_tampered_and_malformed_cookies_safely_rejected(auth_adapter: OIDCAuthAdapter):
"""Requests presenting tampered, malformed, or forged cookies must be safely rejected (not crash)."""
malicious_inputs = [
"tampered!@#$%^&*()",
"valid_part\x00malicious_bytes",
"a" * 1000,
"session\r\nSet-Cookie: evil=1",
"' OR '1'='1",
" \t\n ",
"../../etc/passwd",
"{'session': 'eval'}",
]
for bad_input in malicious_inputs:
req = create_request(cookies={auth_adapter.session_cookie_name: bad_input})
try:
resolved = auth_adapter.current_identity(req)
assert resolved is None, f"Expected None for malicious cookie: {bad_input!r}"
except Exception as exc:
pytest.fail(f"Application crashed on tampered cookie {bad_input!r}: {exc}")
def test_logout_invalidates_session_and_clears_cookie(auth_adapter: OIDCAuthAdapter):
"""Logout invalidates the session on the server and clears the browser cookie (Max-Age=0)."""
identity = Identity(subject="admin-001", email="admin@example.com")
session_id = auth_adapter.establish_session(identity)
req = create_request(cookies={auth_adapter.session_cookie_name: session_id})
assert auth_adapter.current_identity(req) == identity
# Perform logout
logout_resp = auth_adapter.logout(req)
# 1. Server-side session revoked
assert session_id not in auth_adapter.sessions
assert auth_adapter.current_identity(req) is None
# 2. Browser cookie cleared with Max-Age=0
set_cookie = logout_resp.headers.get("set-cookie", "")
assert auth_adapter.session_cookie_name in set_cookie
assert "Max-Age=0" in set_cookie or "max-age=0" in set_cookie
assert "HttpOnly" in set_cookie
# ============================================================================
# 4. FastAPI HTTP Integration Tests (Endpoints & TestClient)
# ============================================================================
def test_http_auth_session_and_logout_endpoints(
client: TestClient,
auth_adapter: OIDCAuthAdapter,
):
"""Integration test: /birthday/api/auth/session, /logout endpoints via HTTP TestClient."""
# 1. Anonymous session check
res_anon = client.get("/birthday/api/auth/session")
assert res_anon.status_code == 200
assert res_anon.json() == {"authenticated": False, "identity": None}
# 2. Establish valid session for fixture admin user
identity = Identity(
subject="admin-001",
email="admin@example.com",
name="Admin User",
groups=["bdinvite_admins"],
)
session_id = auth_adapter.establish_session(identity)
# 3. Present session cookie to /session
client.cookies.set(auth_adapter.session_cookie_name, session_id)
res_auth = client.get("/birthday/api/auth/session")
assert res_auth.status_code == 200
auth_data = res_auth.json()
assert auth_data["authenticated"] is True
assert auth_data["identity"]["subject"] == "admin-001"
assert auth_data["identity"]["email"] == "admin@example.com"
assert auth_data["identity"]["groups"] == ["bdinvite_admins"]
# 4. Admin endpoint accessed via session cookie
res_admin = client.get("/birthday/api/admin/rsvps")
assert res_admin.status_code == 200
# 5. Logout via API POST
res_logout = client.post("/birthday/api/auth/logout")
assert res_logout.status_code == 200
assert res_logout.json()["result"] == "SUCCESS"
assert session_id not in auth_adapter.sessions
# 6. Session cookie cleared on client
set_cookie_header = res_logout.headers.get("set-cookie", "")
assert "Max-Age=0" in set_cookie_header or "max-age=0" in set_cookie_header
# 7. Subsequent request is unauthenticated
res_after = client.get("/birthday/api/auth/session")
assert res_after.json()["authenticated"] is False
def test_fixture_live_users_password_grant_session_flow(auth_adapter: OIDCAuthAdapter):
"""Test full login session lifecycle against pre-seeded fixture users."""
# 1. Admin user authentication and session establishment
admin_id, admin_session_id = auth_adapter.authenticate_and_establish_session(
username="admin@example.com",
password="password123",
)
assert admin_id.subject == "admin-001"
assert "bdinvite_admins" in admin_id.groups
req_admin = create_request(cookies={auth_adapter.session_cookie_name: admin_session_id})
assert auth_adapter.current_identity(req_admin) == admin_id
# 2. Guest user authentication and session establishment
guest_id, guest_session_id = auth_adapter.authenticate_and_establish_session(
username="guest@example.com",
password="password123",
)
assert guest_id.subject == "guest-001"
assert "guests" in guest_id.groups
req_guest = create_request(cookies={auth_adapter.session_cookie_name: guest_session_id})
assert auth_adapter.current_identity(req_guest) == guest_id
# Distinct sessions for distinct users
assert admin_session_id != guest_session_id
+192
View File
@@ -57,6 +57,7 @@ dependencies = [
{ name = "pillow" }, { name = "pillow" },
{ name = "pydantic" }, { name = "pydantic" },
{ name = "pydantic-settings" }, { name = "pydantic-settings" },
{ name = "pyjwt", extra = ["crypto"] },
{ name = "sqlalchemy" }, { name = "sqlalchemy" },
{ name = "uvicorn" }, { name = "uvicorn" },
] ]
@@ -76,6 +77,7 @@ requires-dist = [
{ name = "pillow", specifier = ">=10.0.0" }, { name = "pillow", specifier = ">=10.0.0" },
{ name = "pydantic", specifier = ">=2.0.0" }, { name = "pydantic", specifier = ">=2.0.0" },
{ name = "pydantic-settings", specifier = ">=2.0.0" }, { name = "pydantic-settings", specifier = ">=2.0.0" },
{ name = "pyjwt", extras = ["crypto"], specifier = ">=2.8.0" },
{ name = "sqlalchemy", specifier = ">=2.0.0" }, { name = "sqlalchemy", specifier = ">=2.0.0" },
{ name = "uvicorn", specifier = ">=0.30.0" }, { name = "uvicorn", specifier = ">=0.30.0" },
] ]
@@ -97,6 +99,104 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" },
] ]
[[package]]
name = "cffi"
version = "2.1.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "pycparser", marker = "implementation_name != 'PyPy'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/70/d2/16d99a0c4948febc0ebd133a13b2f688ff7f8cb04da971e1128872ce0c03/cffi-2.1.1-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12", size = 183838, upload-time = "2026-08-03T21:19:29.637Z" },
{ url = "https://files.pythonhosted.org/packages/cd/95/31b535a9f0220ae9f357de4a08d57ce89cb417653c2fd9f075f50822a388/cffi-2.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1", size = 184168, upload-time = "2026-08-03T21:19:30.764Z" },
{ url = "https://files.pythonhosted.org/packages/ad/5a/4707a0dc1f203f5dde5a907b0d4e3c25d71120241048bd5bc6f1bb9d4e71/cffi-2.1.1-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0", size = 211805, upload-time = "2026-08-03T21:19:31.867Z" },
{ url = "https://files.pythonhosted.org/packages/ad/66/c19feabb28485b6e0bbaaafa90837a1ef5d302e90f2178bd33f17a49879b/cffi-2.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813", size = 218716, upload-time = "2026-08-03T21:19:32.896Z" },
{ url = "https://files.pythonhosted.org/packages/a7/92/500760486c8baab49a7a8a58ba7fc3355ec3974b454b8a09e528efde9e1d/cffi-2.1.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990", size = 205569, upload-time = "2026-08-03T21:19:34.142Z" },
{ url = "https://files.pythonhosted.org/packages/a5/a7/a67c733254d6e7373f7822f8082d8d6beade791e0cf12a7611f376fa61c7/cffi-2.1.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af", size = 204907, upload-time = "2026-08-03T21:19:35.174Z" },
{ url = "https://files.pythonhosted.org/packages/f7/a4/4399daaf8f7dfee9d7c3327fdb0426ee041cc63edc358b93911ceb2bfc7a/cffi-2.1.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632", size = 217807, upload-time = "2026-08-03T21:19:36.286Z" },
{ url = "https://files.pythonhosted.org/packages/28/f7/dabe6da2466ecbd82dc62e7342dc6b1065dad990c06f00f0ede9ebf2a0ed/cffi-2.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd", size = 221252, upload-time = "2026-08-03T21:19:37.416Z" },
{ url = "https://files.pythonhosted.org/packages/ce/87/616202d8e51342c07d2534c510111c4cc37201775ce8f60802c9335d1edd/cffi-2.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a", size = 214214, upload-time = "2026-08-03T21:19:38.507Z" },
{ url = "https://files.pythonhosted.org/packages/b4/c6/ab025d75d2c26c19b087c0124e75ee31cb65032f4fe345d356d8c507ab97/cffi-2.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa", size = 219408, upload-time = "2026-08-03T21:19:39.809Z" },
{ url = "https://files.pythonhosted.org/packages/db/e2/7e8109f65445bdc673a7b54f02c677de462db75674220fd1335efc8eb598/cffi-2.1.1-cp311-cp311-win32.whl", hash = "sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3", size = 174470, upload-time = "2026-08-03T21:19:41.246Z" },
{ url = "https://files.pythonhosted.org/packages/73/c0/77ba02423c2f7d7091143c45cd49e0e6575c4c1967394bb542bd923a9b74/cffi-2.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0", size = 185096, upload-time = "2026-08-03T21:19:42.615Z" },
{ url = "https://files.pythonhosted.org/packages/7c/47/9f1f85f9672ceda4984dc6c4f8824e8558992a2972c3d3c81fb8eb28d4ba/cffi-2.1.1-cp311-cp311-win_arm64.whl", hash = "sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455", size = 179941, upload-time = "2026-08-03T21:19:43.747Z" },
{ url = "https://files.pythonhosted.org/packages/10/69/43965eccfdead3b9220015fd1320e117be8c6ed01a62ffab76eeb752f5d5/cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0", size = 184821, upload-time = "2026-08-03T21:19:44.887Z" },
{ url = "https://files.pythonhosted.org/packages/54/7d/16e5a096677b5e313ca80cd5e5170efa3ea44624a82bb111925522da64b1/cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf", size = 184719, upload-time = "2026-08-03T21:19:46.129Z" },
{ url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" },
{ url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" },
{ url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" },
{ url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" },
{ url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" },
{ url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" },
{ url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" },
{ url = "https://files.pythonhosted.org/packages/80/fb/0bb75b7039588c074b37ae99f40d9bfddf990ecb2fbc346ebccd2e56b9be/cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e", size = 175292, upload-time = "2026-08-03T21:19:55.566Z" },
{ url = "https://files.pythonhosted.org/packages/d9/79/615cc094e2fb508cade7de88d3b4f6c4ec2bab695c97bce9153dc65aadf5/cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a", size = 185919, upload-time = "2026-08-03T21:19:56.89Z" },
{ url = "https://files.pythonhosted.org/packages/70/c6/d0ea84713fe46b243a436a18fcd47d639732747e21635c8a27191b06dc30/cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80", size = 180093, upload-time = "2026-08-03T21:19:58.155Z" },
{ url = "https://files.pythonhosted.org/packages/9d/f4/035513d4117049066b4779dc3b7c0c0fdad175fa13731c9f4003f1cd1478/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e", size = 194248, upload-time = "2026-08-03T21:19:59.399Z" },
{ url = "https://files.pythonhosted.org/packages/76/af/2aeb4dbb5fc41a04161ae9ff1518de7cec08e164f44a8ce6a4cf7fd2cd1d/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c", size = 196908, upload-time = "2026-08-03T21:20:00.746Z" },
{ url = "https://files.pythonhosted.org/packages/a7/46/2e5fdde8555706dd98139a910ca11be02809f3f605ce956f655d0214e100/cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6", size = 184805, upload-time = "2026-08-03T21:20:02.02Z" },
{ url = "https://files.pythonhosted.org/packages/55/41/4c7042f317b9217502988f0873af87e16ad606dc20f84e546e3e6ce9764c/cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971", size = 184764, upload-time = "2026-08-03T21:20:03.141Z" },
{ url = "https://files.pythonhosted.org/packages/43/1f/1c3d90d91811c8f86ced9ed637956c54bfe5b79ca98fe976d7f8c8979f6b/cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c", size = 214722, upload-time = "2026-08-03T21:20:04.377Z" },
{ url = "https://files.pythonhosted.org/packages/37/6f/3b5ce4c3b2192d250f04908f2bfd91ef34552ec8f7716a5d4abdb8d67bb2/cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125", size = 222369, upload-time = "2026-08-03T21:20:05.544Z" },
{ url = "https://files.pythonhosted.org/packages/02/10/4b3c75dde3d9663c9e02ba05c2668b954f671d4bbe346413ca8c696b295a/cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264", size = 210175, upload-time = "2026-08-03T21:20:06.75Z" },
{ url = "https://files.pythonhosted.org/packages/df/62/14f74b9543e605d17701dc797b815958b8bb70b7624ce1b832ddad48ed6c/cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3", size = 208670, upload-time = "2026-08-03T21:20:08.04Z" },
{ url = "https://files.pythonhosted.org/packages/95/95/86342356ff5953b3fb06f7ef7c5bee212d45e770abc7218d451b9148313c/cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2", size = 221824, upload-time = "2026-08-03T21:20:09.274Z" },
{ url = "https://files.pythonhosted.org/packages/eb/ff/7b3429ff53aafe931ed8a5fc69f481bbef7ba6de87ddcbb63d08f483f613/cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b", size = 225148, upload-time = "2026-08-03T21:20:10.7Z" },
{ url = "https://files.pythonhosted.org/packages/34/34/a95870b9221e09cf4f2ce3178b1a210abdfe63a1bd357da940418d7b8d15/cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7", size = 223564, upload-time = "2026-08-03T21:20:12.165Z" },
{ url = "https://files.pythonhosted.org/packages/70/ea/839b50531021a647fb5e929f72cf97bc1ff702b5472166164b5b6e76b851/cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac", size = 175263, upload-time = "2026-08-03T21:20:13.559Z" },
{ url = "https://files.pythonhosted.org/packages/60/a6/8b149b2c3f2e11aaa1618ef64500b45f50f22c57a977a4dff1aff1f91042/cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d", size = 185688, upload-time = "2026-08-03T21:20:14.69Z" },
{ url = "https://files.pythonhosted.org/packages/01/9a/11f687cb39d6a3504060d5242f04f48c735afb4d3d533958a20594890cb2/cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973", size = 180078, upload-time = "2026-08-03T21:20:15.917Z" },
{ url = "https://files.pythonhosted.org/packages/d3/7b/d6bbf82b8b96e7391438898c42f5bd96dd02030fd5b64937d248220003e2/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c", size = 194064, upload-time = "2026-08-03T21:20:17.148Z" },
{ url = "https://files.pythonhosted.org/packages/94/e6/bcc91b283be94735e268487a054004f0aa19947b6348fa367db53230abc8/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb", size = 196720, upload-time = "2026-08-03T21:20:18.268Z" },
{ url = "https://files.pythonhosted.org/packages/d9/99/c4b0c17cacdc9c3b8f280026286a9826d6a208c0f047591a3c3ce99b91fd/cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54", size = 184964, upload-time = "2026-08-03T21:20:19.708Z" },
{ url = "https://files.pythonhosted.org/packages/b3/a9/9db617d05d7367c1ad0ab00b3aa6e6f9281edd689b4ee9ea0e5a84e89c97/cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72", size = 184962, upload-time = "2026-08-03T21:20:20.833Z" },
{ url = "https://files.pythonhosted.org/packages/67/b8/b42132ca113dc567d37684437b46ca1dafc885902b02a110a02d5b511857/cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1", size = 222328, upload-time = "2026-08-03T21:20:22.118Z" },
{ url = "https://files.pythonhosted.org/packages/80/10/c5c0cbf0a657aecf59ef511409734230bf556f05a0d6c9eed7aa5c0a0166/cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062", size = 209985, upload-time = "2026-08-03T21:20:23.401Z" },
{ url = "https://files.pythonhosted.org/packages/d5/6c/bfa0b87b03b9238148beca990292843c9396ba069b54496596594173de7b/cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03", size = 208530, upload-time = "2026-08-03T21:20:24.628Z" },
{ url = "https://files.pythonhosted.org/packages/e9/02/4e7d553a7ac4b4238b38b3c1b80d486e9d4436f8d2acbf87a0997fe3f402/cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96", size = 221525, upload-time = "2026-08-03T21:20:25.758Z" },
{ url = "https://files.pythonhosted.org/packages/82/1d/a4aaf9babd75acb4d5f223bff71533bee748dd770a382619a798960ee9ba/cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527", size = 225053, upload-time = "2026-08-03T21:20:26.985Z" },
{ url = "https://files.pythonhosted.org/packages/81/10/5dc0e7bdd18e22107054288283380fc97a06ae3f1656a106908d666a3c88/cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13", size = 223213, upload-time = "2026-08-03T21:20:28.277Z" },
{ url = "https://files.pythonhosted.org/packages/0b/e9/d0061c364cde06ee43168a0d076ac1da512cbc380d44767b844ba34fe2b6/cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c", size = 177682, upload-time = "2026-08-03T21:20:44.288Z" },
{ url = "https://files.pythonhosted.org/packages/a7/06/1c3e01e3ba14c39f6d10bfbac52753b7e22259e38088e5cfe1d704918690/cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48", size = 187949, upload-time = "2026-08-03T21:20:45.623Z" },
{ url = "https://files.pythonhosted.org/packages/87/5b/da4e39efe18eeb89cf580ea9cfc66b6a7c3eadb808fc0cc1d3a295cb5a5d/cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836", size = 182947, upload-time = "2026-08-03T21:20:46.955Z" },
{ url = "https://files.pythonhosted.org/packages/23/59/40338bf421c5accea1d45158170c87006ef1cd371b05c077e76476949728/cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3", size = 188504, upload-time = "2026-08-03T21:20:29.495Z" },
{ url = "https://files.pythonhosted.org/packages/7d/47/5ecf1023850036e674c77ec4de86182d309ae344e39e7cba984b7df5d647/cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2", size = 188259, upload-time = "2026-08-03T21:20:31.291Z" },
{ url = "https://files.pythonhosted.org/packages/2a/9c/92934c3bea9f785b23eba304538c0b4d37a2a96d2431eb3a1bc87a11aa19/cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94", size = 223864, upload-time = "2026-08-03T21:20:32.571Z" },
{ url = "https://files.pythonhosted.org/packages/4d/45/ba4c93527bc38616a8bd36488acb69a2212d60486794f0c1f318949bbb76/cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc", size = 211538, upload-time = "2026-08-03T21:20:33.808Z" },
{ url = "https://files.pythonhosted.org/packages/80/e9/b6ef565e452acb932fb0cb5443f44a78efbd1233e566f02b5a83855e9115/cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29", size = 210688, upload-time = "2026-08-03T21:20:34.974Z" },
{ url = "https://files.pythonhosted.org/packages/9a/95/eff5f0cee78d2eabc7eebffec40d3fc1876b5f3c95582e018bb4b99601f2/cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676", size = 223803, upload-time = "2026-08-03T21:20:36.564Z" },
{ url = "https://files.pythonhosted.org/packages/fa/01/579d39fb8bef00a335a23d83757b44feb24cd6345a2c451b64cb67b9c362/cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e", size = 226763, upload-time = "2026-08-03T21:20:37.816Z" },
{ url = "https://files.pythonhosted.org/packages/8d/b0/0b44f47c60b01b57b6e2bbd92343f13a85a1d93bc46ccf6e47e244acd99c/cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f", size = 225688, upload-time = "2026-08-03T21:20:38.959Z" },
{ url = "https://files.pythonhosted.org/packages/eb/d2/3b7176cb570a1d3e27faf67b72f591af508036e0d8b2be2ef9af9e8c84bb/cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4", size = 182868, upload-time = "2026-08-03T21:20:40.388Z" },
{ url = "https://files.pythonhosted.org/packages/56/78/31f00c1bcd97c9bbf55f1bfdf5bc809a5de8887473e90bb9960dca825e80/cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e", size = 194104, upload-time = "2026-08-03T21:20:41.725Z" },
{ url = "https://files.pythonhosted.org/packages/7b/1b/58496f2ed0a35de575250c02a43ab3cc2c04d494a88fed31c1cabc0fd176/cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5", size = 186402, upload-time = "2026-08-03T21:20:43.042Z" },
{ url = "https://files.pythonhosted.org/packages/c1/8f/9ebe220eab48a093d1a5a5e339ab0dc7316eef3bb04d63c42f0251b61f50/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d", size = 194043, upload-time = "2026-08-03T21:20:48.179Z" },
{ url = "https://files.pythonhosted.org/packages/ff/69/844bad3ece306c4782c2ecb93597035b6690d48704b803914c199da1e8b3/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b", size = 196737, upload-time = "2026-08-03T21:20:49.457Z" },
{ url = "https://files.pythonhosted.org/packages/1b/8a/af668013284634733f02d683458a0728739c7d6ddb5e14cb0c20832266fe/cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4", size = 184933, upload-time = "2026-08-03T21:20:50.639Z" },
{ url = "https://files.pythonhosted.org/packages/0c/75/2f5207ff6d1a613133b23a5203cc0c2a628313b5eb3974d7956ae3c57950/cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8", size = 185002, upload-time = "2026-08-03T21:20:52.173Z" },
{ url = "https://files.pythonhosted.org/packages/e2/31/9e1313b0a6e30e91b3b3d3fff51ae99c857c07738e3afcce1f7334e1b7ab/cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6", size = 222271, upload-time = "2026-08-03T21:20:53.462Z" },
{ url = "https://files.pythonhosted.org/packages/50/e3/f6234a833e6e08c7007003074723c406559eecf9b48dfc97471e5a8eb7a0/cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80", size = 209919, upload-time = "2026-08-03T21:20:54.783Z" },
{ url = "https://files.pythonhosted.org/packages/0d/fc/5f74e293fced6edb51af3a46c4ccf6c23c9943774ecb375ddbd522c76add/cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779", size = 208529, upload-time = "2026-08-03T21:20:56.066Z" },
{ url = "https://files.pythonhosted.org/packages/44/16/29e6d01b388bef055ecd6ca8244b3f4d336bd09e92d5d892187b9601084e/cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399", size = 221630, upload-time = "2026-08-03T21:20:57.336Z" },
{ url = "https://files.pythonhosted.org/packages/a4/18/fa7f1f6857d5eb88a4ca99ffcbfb7c387a287ccc154c64a73e86314745d7/cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688", size = 225134, upload-time = "2026-08-03T21:20:58.675Z" },
{ url = "https://files.pythonhosted.org/packages/e0/9f/e8e3dfa04a1b4c241f8c91faacad872b4d4efd051d49764ad4e2fd4b9fea/cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7", size = 223197, upload-time = "2026-08-03T21:20:59.968Z" },
{ url = "https://files.pythonhosted.org/packages/f8/7e/8debeb04f1ab9fe2a6963964cd6f1aaf7192627b83926586a6a4e089c9fa/cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac", size = 177683, upload-time = "2026-08-03T21:21:14.901Z" },
{ url = "https://files.pythonhosted.org/packages/e0/31/5158704cc474ab65c1647932e88be78dc0873f47130e253be38bcaf13d01/cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960", size = 187897, upload-time = "2026-08-03T21:21:16.108Z" },
{ url = "https://files.pythonhosted.org/packages/cc/4b/b3a2da8570c704ffc0f9762cdc3ec0f02c8573798e0b5cf7f11c82bbb70f/cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1", size = 182935, upload-time = "2026-08-03T21:21:17.271Z" },
{ url = "https://files.pythonhosted.org/packages/d0/ef/5443574510a1207e6f6bc38ba6e1f1de36cb48fef07b2728bb896a21f430/cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc", size = 188464, upload-time = "2026-08-03T21:21:01.163Z" },
{ url = "https://files.pythonhosted.org/packages/7e/ae/a56fa8c4686ad50e148fcbc8d3ae0d03915ff5c30d795058988c24118cef/cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab", size = 188262, upload-time = "2026-08-03T21:21:02.382Z" },
{ url = "https://files.pythonhosted.org/packages/53/b2/6187f46f2912276a3ae284076109cc5c8680482f11f766ccf26db4a86427/cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e", size = 223779, upload-time = "2026-08-03T21:21:03.553Z" },
{ url = "https://files.pythonhosted.org/packages/8a/f6/c3ad28bd19f77047a03084424fbd4cbe997303267c14423737324be0385d/cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358", size = 211520, upload-time = "2026-08-03T21:21:04.863Z" },
{ url = "https://files.pythonhosted.org/packages/a0/cd/ccac9013a5bd9fd764de118674ab9c805b5ca10c19270d90ee273f8b2240/cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231", size = 210673, upload-time = "2026-08-03T21:21:06.223Z" },
{ url = "https://files.pythonhosted.org/packages/52/86/2976131c639aead931c5bee5aba67e4b09fbeb8018b6f282f70803f923a7/cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6", size = 223835, upload-time = "2026-08-03T21:21:07.539Z" },
{ url = "https://files.pythonhosted.org/packages/ac/0c/33a7aeab2f9c76918c52e084beb39c570db3588133412929e8ec06fab90b/cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94", size = 226705, upload-time = "2026-08-03T21:21:08.774Z" },
{ url = "https://files.pythonhosted.org/packages/e3/26/2cde30fdde421130bfc18f70395731a6e6b2053c6a1978a5258ff04e72fa/cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5", size = 225539, upload-time = "2026-08-03T21:21:09.911Z" },
{ url = "https://files.pythonhosted.org/packages/6d/cd/a361394c94b2129d604bb846f624a8e88255a3ee33129c434a00d715e64f/cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66", size = 182707, upload-time = "2026-08-03T21:21:11.226Z" },
{ url = "https://files.pythonhosted.org/packages/9b/b5/ba2b299993c26577d529b6ae29841f9e15b9fcf004d65f423f4fcf94ade9/cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3", size = 193772, upload-time = "2026-08-03T21:21:12.39Z" },
{ url = "https://files.pythonhosted.org/packages/aa/29/35e016098c814cd93de9cd320c66b5bfba14dc6ecedd3cb518fa7c408c69/cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692", size = 186360, upload-time = "2026-08-03T21:21:13.636Z" },
]
[[package]] [[package]]
name = "click" name = "click"
version = "8.5.0" version = "8.5.0"
@@ -115,6 +215,75 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
] ]
[[package]]
name = "cryptography"
version = "50.0.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cffi", marker = "platform_python_implementation != 'PyPy'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/9d/af/182eb91b0df3fe75c4d9f26fe70684569566745f6ba7e5c9c73a862c5252/cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5", size = 880623, upload-time = "2026-09-30T15:30:04.884Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/e5/56/d194340cc4a57535e82e1bee9e89667ac4b7c13b5d3f59686deae3094dd5/cryptography-50.0.2-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb", size = 3914904, upload-time = "2026-09-30T14:43:44.339Z" },
{ url = "https://files.pythonhosted.org/packages/d9/69/c9bd862c3bf43d6399c433caf002df16e2dffd4be49bdf515cda38038711/cryptography-50.0.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0", size = 4731146, upload-time = "2026-09-30T14:43:47.113Z" },
{ url = "https://files.pythonhosted.org/packages/21/69/64cef1f702bf6657e0cc186ed1a2891d50d29fb41586b254e1c07adea261/cryptography-50.0.2-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2", size = 4719841, upload-time = "2026-09-30T14:43:49.01Z" },
{ url = "https://files.pythonhosted.org/packages/38/6b/61a3f8d8c5e1e49a6cddccafc4015cc1c0021360ab0acb4080e7a423644a/cryptography-50.0.2-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480", size = 4738340, upload-time = "2026-09-30T14:43:50.932Z" },
{ url = "https://files.pythonhosted.org/packages/7b/2e/7212ca32fd43dc91f2f41db20160b268098874b4c9a0e7be94d6835f5b2e/cryptography-50.0.2-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134", size = 5367029, upload-time = "2026-09-30T14:43:52.911Z" },
{ url = "https://files.pythonhosted.org/packages/1a/f1/b474e930c4d910328780e3940da76f5aa5cbc48ce1fc14e44d239d9ea9db/cryptography-50.0.2-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856", size = 4753050, upload-time = "2026-09-30T14:43:55.272Z" },
{ url = "https://files.pythonhosted.org/packages/7c/52/9af10e80ac16b0fcc2123f9cbd5e7afbd0fd5075bb7a607c592258a39cda/cryptography-50.0.2-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e", size = 4376724, upload-time = "2026-09-30T14:43:57.24Z" },
{ url = "https://files.pythonhosted.org/packages/71/37/6202e488cc1eb625ea110c292c6bda92823176e023f427d8d5660ce8d632/cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04", size = 4737859, upload-time = "2026-09-30T14:43:59.541Z" },
{ url = "https://files.pythonhosted.org/packages/8f/30/e86d7d518489b0ae2497091a35287abcb1a2ce4037837a34afbe9b1d6964/cryptography-50.0.2-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc", size = 5324103, upload-time = "2026-09-30T14:44:01.901Z" },
{ url = "https://files.pythonhosted.org/packages/d3/69/2c833a049475e0a3444e94c7d0aca0aa51d166374a449b09e92ac98138de/cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079", size = 4752576, upload-time = "2026-09-30T14:44:04.545Z" },
{ url = "https://files.pythonhosted.org/packages/6c/5d/906970b83bbfc1f5bbfb677a143c181f2801f23b6a7204a3b47c42c97e65/cryptography-50.0.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51", size = 4870819, upload-time = "2026-09-30T14:44:06.884Z" },
{ url = "https://files.pythonhosted.org/packages/68/e3/f2298d3bb55e0c4a91841ec4d01b3f020ba8c5fbf15ccdcc6dcf03f97025/cryptography-50.0.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93", size = 5030152, upload-time = "2026-09-30T14:44:09.443Z" },
{ url = "https://files.pythonhosted.org/packages/9a/4f/adfc442765721292fff86d314ce385d3249d22db42295c0dd057727b60f3/cryptography-50.0.2-cp311-abi3-win_amd64.whl", hash = "sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c", size = 3824692, upload-time = "2026-09-30T14:44:11.671Z" },
{ url = "https://files.pythonhosted.org/packages/ce/cb/52eb3770c0d0be2702a98c6e96065ddc0a2877cf0845aa9c23397c142cd4/cryptography-50.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8", size = 3892731, upload-time = "2026-09-30T14:44:13.485Z" },
{ url = "https://files.pythonhosted.org/packages/19/8e/aa1fc533d4546b127b45de8aa024eb5933d23eff9debfe25931e56861095/cryptography-50.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047", size = 4710431, upload-time = "2026-09-30T14:44:15.427Z" },
{ url = "https://files.pythonhosted.org/packages/6a/64/72bc3f75176e7e406b748a3e3830432b8c51297b38368713df04dc04898a/cryptography-50.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539", size = 4694824, upload-time = "2026-09-30T14:44:17.69Z" },
{ url = "https://files.pythonhosted.org/packages/4e/c6/62c77550edfa5ca3f14bf44a1e6739b9fa09d6e998a11d97ed8213bccc98/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1", size = 4716967, upload-time = "2026-09-30T14:44:19.661Z" },
{ url = "https://files.pythonhosted.org/packages/f4/37/cce70f150c432914460157a6ecc161752e053aa5ec0ef3b3f7dc6e31039a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7", size = 5328676, upload-time = "2026-09-30T14:44:21.744Z" },
{ url = "https://files.pythonhosted.org/packages/aa/9a/6f2f0304d634ceafdeaf23e84537336664ac419b5d07611675c2ad3f6b7a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18", size = 4727698, upload-time = "2026-09-30T14:44:24.178Z" },
{ url = "https://files.pythonhosted.org/packages/1d/de/66bcf9244d118663b2e1aaded8990f4640e3d7b7411870a5765f252074d2/cryptography-50.0.2-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37", size = 4354821, upload-time = "2026-09-30T14:44:26.263Z" },
{ url = "https://files.pythonhosted.org/packages/bd/e6/db28a28c7b6c676addce89136de3d8db49ea825a8c863472e36e42ead4ad/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2", size = 4716748, upload-time = "2026-09-30T14:44:28.447Z" },
{ url = "https://files.pythonhosted.org/packages/30/96/01546c7f69ea0e2ab790a2e4f0934a4052fb9b388147fbf83c2fd72f1e57/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1", size = 5285085, upload-time = "2026-09-30T14:44:30.704Z" },
{ url = "https://files.pythonhosted.org/packages/6c/01/03263395f74d50b071e9e66daace3f8bef80493e5d410726f2ba8554736b/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05", size = 4727268, upload-time = "2026-09-30T14:44:32.92Z" },
{ url = "https://files.pythonhosted.org/packages/eb/94/2bfe8f29ec0cc9c0d99359c4161adf32858e4934b72c6d100d2ac0bbe962/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e", size = 4849503, upload-time = "2026-09-30T14:44:34.969Z" },
{ url = "https://files.pythonhosted.org/packages/54/44/e80651ecbf0e42b62e2bb5f5768916e07eea72e1297338956a61df361f88/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e", size = 5004057, upload-time = "2026-09-30T14:44:37.064Z" },
{ url = "https://files.pythonhosted.org/packages/f8/cc/1d33befb3cd7ea7e77d2d73f43f2066471da1b21f24a6156efcaabf6d2e8/cryptography-50.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45", size = 3795868, upload-time = "2026-09-30T14:44:39.71Z" },
{ url = "https://files.pythonhosted.org/packages/2d/49/93f6a6e7a87c9aa68d44d3e1cdb5fe8f60c90d5d2f46acae9a56892816b8/cryptography-50.0.2-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37", size = 4133708, upload-time = "2026-09-30T14:44:41.807Z" },
{ url = "https://files.pythonhosted.org/packages/8c/75/32ac2a56243d778805c16ca6a32b8f74fb757df7e28d7ecb560afafb59cf/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a", size = 4956267, upload-time = "2026-09-30T14:44:43.693Z" },
{ url = "https://files.pythonhosted.org/packages/aa/a4/2c8d734e43d97f0842ee9f1b7b4bfb3d0cf5e19edebf43c2afe6675c2320/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67", size = 4966465, upload-time = "2026-09-30T14:44:45.769Z" },
{ url = "https://files.pythonhosted.org/packages/c2/58/ee288c829a6f41f6235ae9dd33d82fd19b45442b65b4c8a3da36963d9f7a/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_aarch64.whl", hash = "sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc", size = 4959356, upload-time = "2026-09-30T14:44:48.211Z" },
{ url = "https://files.pythonhosted.org/packages/92/20/9ded6d51ddd9897f6b6e81fb9ebea7951d7cc5d6c890b0ed8abf77a51a80/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_ppc64le.whl", hash = "sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d", size = 5548822, upload-time = "2026-09-30T14:44:50.86Z" },
{ url = "https://files.pythonhosted.org/packages/02/a8/8df951850d6b31d2a00218f19e2b3f999523437ed7a819df7fa427942fca/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl", hash = "sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7", size = 5001199, upload-time = "2026-09-30T14:44:53.379Z" },
{ url = "https://files.pythonhosted.org/packages/8b/f9/36b3022218ce75b7cdf068fb95f809f9bd0d820e4955ef43b90c255cc7ac/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_31_armv7l.whl", hash = "sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408", size = 4629333, upload-time = "2026-09-30T14:44:55.635Z" },
{ url = "https://files.pythonhosted.org/packages/8c/72/20f99a219f6af47cdd1cbd978c243b92d71496e168a746138af44ded4f29/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_aarch64.whl", hash = "sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b", size = 4958822, upload-time = "2026-09-30T14:44:59.639Z" },
{ url = "https://files.pythonhosted.org/packages/f2/20/196f112617fb08eb4d608a2a6c422373d46f9cc2857f38fc0667033c0899/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_ppc64le.whl", hash = "sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd", size = 5506351, upload-time = "2026-09-30T14:45:02.267Z" },
{ url = "https://files.pythonhosted.org/packages/24/95/83378121ef3eaaaf71d4b781577ff794acb39b9e1b87a3f156898c8497ed/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_x86_64.whl", hash = "sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c", size = 5000859, upload-time = "2026-09-30T14:45:05.009Z" },
{ url = "https://files.pythonhosted.org/packages/22/f7/70fd7ae4d1dbfa7ba29b02e1b9068771519a86027756510b700ce81086a8/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be", size = 5092151, upload-time = "2026-09-30T15:29:15.932Z" },
{ url = "https://files.pythonhosted.org/packages/d4/be/688367b74de86984bd58d8efacfc7c9e68b89a6a22ced0fb4f38db50254a/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020", size = 5286120, upload-time = "2026-09-30T15:29:18.309Z" },
{ url = "https://files.pythonhosted.org/packages/39/d1/55f8a3f2ef5d1529e16835ef10cf0fe3d559ce237b46dddc440c0bba3649/cryptography-50.0.2-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c", size = 4111557, upload-time = "2026-09-30T15:29:20.155Z" },
{ url = "https://files.pythonhosted.org/packages/23/ad/ac987755d00e1e64273760228d2635ae38dae2be83e3c6e0d3289d91dec3/cryptography-50.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2", size = 3943588, upload-time = "2026-09-30T15:29:22.265Z" },
{ url = "https://files.pythonhosted.org/packages/d5/8d/6d585339bedf85d45044c85d8412dac53f2bb6f918e8b7777efba1787844/cryptography-50.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd", size = 4756166, upload-time = "2026-09-30T15:29:24.58Z" },
{ url = "https://files.pythonhosted.org/packages/bf/f1/1c1f6874e8550cfddd4b688ceb38cefb6ed15ceed224d56f133f3d88c214/cryptography-50.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767", size = 4749145, upload-time = "2026-09-30T15:29:26.807Z" },
{ url = "https://files.pythonhosted.org/packages/c1/63/61b15dc1a8de03fe0adbe3fd7608b3ad5c73bf50993bbcb1faaa930afe33/cryptography-50.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454", size = 4763638, upload-time = "2026-09-30T15:29:28.588Z" },
{ url = "https://files.pythonhosted.org/packages/fc/35/b345bdfa40c9126df1a9d33236aa98418367931b8725f84fc3ae2b98dc59/cryptography-50.0.2-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd", size = 5382217, upload-time = "2026-09-30T15:29:30.589Z" },
{ url = "https://files.pythonhosted.org/packages/4f/87/ef344a9e616871f2519c22d6afcda79ddd5d35e9592d95eb6e677608d055/cryptography-50.0.2-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5", size = 4781387, upload-time = "2026-09-30T15:29:32.605Z" },
{ url = "https://files.pythonhosted.org/packages/90/5b/f2fdb13cd0b96f6f932c8627bb292a45f11c64d21620a8e120aee9a3b848/cryptography-50.0.2-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107", size = 4403790, upload-time = "2026-09-30T15:29:34.374Z" },
{ url = "https://files.pythonhosted.org/packages/bc/ce/7e4f662b1e3c393513569e402cfc85ac7da0bd3d5435e122a3140219eb2d/cryptography-50.0.2-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602", size = 4764319, upload-time = "2026-09-30T15:29:36.149Z" },
{ url = "https://files.pythonhosted.org/packages/3c/3f/86ff33ce34cc0de6847fb96e035a1a760d81652e38643f617c02ad32ef7a/cryptography-50.0.2-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227", size = 5338560, upload-time = "2026-09-30T15:29:39.053Z" },
{ url = "https://files.pythonhosted.org/packages/40/cf/6b5c8e2fd9202d98988ab7cb5cc5c991704c4ad55f492ff408e4969f83f1/cryptography-50.0.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c", size = 4780973, upload-time = "2026-09-30T15:29:41.251Z" },
{ url = "https://files.pythonhosted.org/packages/10/bf/8d6ebc7dded797bd0f0160d52188021211f011a2b164ef0ae1dac4587465/cryptography-50.0.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e", size = 4897738, upload-time = "2026-09-30T15:29:43.106Z" },
{ url = "https://files.pythonhosted.org/packages/d4/aa/f3f6e0de7e6253b8baa8b2d8fb9d50924fa75cee3d4624bd4bc1208ee923/cryptography-50.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94", size = 5058280, upload-time = "2026-09-30T15:29:44.827Z" },
{ url = "https://files.pythonhosted.org/packages/f6/b6/a1faf3a27ae9405fb34b1713cc73b2d8a26b04d5c561578fa2e6ef3e5bb9/cryptography-50.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de", size = 3854095, upload-time = "2026-09-30T15:29:46.782Z" },
{ url = "https://files.pythonhosted.org/packages/1d/7a/f08d34ce09d60f89ebd391e2ebc6ba2b995e6dd7552f41820f8085f94e53/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67", size = 4716035, upload-time = "2026-09-30T15:29:48.681Z" },
{ url = "https://files.pythonhosted.org/packages/45/67/e18fb65592451a2acb76e9f2fbe14e0f47a8318b4c5430f1633851d03daa/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a", size = 4726917, upload-time = "2026-09-30T15:29:50.608Z" },
{ url = "https://files.pythonhosted.org/packages/83/28/38fdce17e60f6b825e69fc3b7f75e70a6612759980704697e1de4cbfaf6e/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48", size = 4715341, upload-time = "2026-09-30T15:29:52.522Z" },
{ url = "https://files.pythonhosted.org/packages/b6/b1/d9121a717e0f893c64bd6ca7702614778d7df2a5c309128a002421788516/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42", size = 4726322, upload-time = "2026-09-30T15:29:54.263Z" },
{ url = "https://files.pythonhosted.org/packages/36/8b/e6d153808bf353e152abd2fd4d8f09670d956ac78379ac46e60d7efbf04c/cryptography-50.0.2-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81", size = 3873097, upload-time = "2026-09-30T15:29:56.097Z" },
{ url = "https://files.pythonhosted.org/packages/ca/1d/1271f287ff7170ddafc2aad36260c4eec20ccd2fea70f38455e9d56d427b/cryptography-50.0.2-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452", size = 3805376, upload-time = "2026-09-30T15:29:58.729Z" },
]
[[package]] [[package]]
name = "detect-installer" name = "detect-installer"
version = "0.2.1" version = "0.2.1"
@@ -807,6 +976,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e4/04/d52c7016b04b6c5108f26691f9d33ec82a9b65d041f1a9c771137693d618/protobuf-7.36.2-py3-none-any.whl", hash = "sha256:bdb3a345d48db958e6ce1f18e508beb0cc981d64f24088427549c866cd039f1e", size = 179806, upload-time = "2026-09-17T20:07:58.211Z" }, { url = "https://files.pythonhosted.org/packages/e4/04/d52c7016b04b6c5108f26691f9d33ec82a9b65d041f1a9c771137693d618/protobuf-7.36.2-py3-none-any.whl", hash = "sha256:bdb3a345d48db958e6ce1f18e508beb0cc981d64f24088427549c866cd039f1e", size = 179806, upload-time = "2026-09-17T20:07:58.211Z" },
] ]
[[package]]
name = "pycparser"
version = "3.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" },
]
[[package]] [[package]]
name = "pydantic" name = "pydantic"
version = "2.13.5" version = "2.13.5"
@@ -965,6 +1143,20 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" },
] ]
[[package]]
name = "pyjwt"
version = "2.15.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/43/ea/5194e52748b0da83d71e082d75496eaec6e58f419f5e184786ded517e6a9/pyjwt-2.15.1.tar.gz", hash = "sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8", size = 121252, upload-time = "2026-09-28T18:40:42.598Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/50/ca/44de4e75f8aadc457f0634be3b542815078ded46dca30efb960edeecad6e/pyjwt-2.15.1-py3-none-any.whl", hash = "sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193", size = 33860, upload-time = "2026-09-28T18:40:41.429Z" },
]
[package.optional-dependencies]
crypto = [
{ name = "cryptography" },
]
[[package]] [[package]]
name = "pyright" name = "pyright"
version = "1.1.414" version = "1.1.414"
+1 -1
View File
@@ -5,7 +5,7 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "tsc -b && vite build", "build": "tsc -b && vite build && mkdir -p ../backend/static && cp -r dist/* ../backend/static/",
"preview": "vite preview", "preview": "vite preview",
"lint": "biome check .", "lint": "biome check .",
"lint:fix": "biome check --write .", "lint:fix": "biome check --write .",
+205 -1
View File
@@ -1,6 +1,161 @@
import { useCallback, useEffect, useState } from "react";
import { Link, NavLink, Outlet } from "react-router-dom"; import { Link, NavLink, Outlet } from "react-router-dom";
import { type AuthUser, fetchSession, logoutUser } from "../api/client";
export function AdminLayout() { export function AdminLayout() {
const [loading, setLoading] = useState<boolean>(true);
const [identity, setIdentity] = useState<AuthUser | null>(null);
const [loggedOut, setLoggedOut] = useState<boolean>(false);
useEffect(() => {
const params = new URLSearchParams(window.location.search);
if (params.get("logged_out") === "1") {
setLoading(false);
setLoggedOut(true);
return;
}
let isMounted = true;
fetchSession()
.then((session) => {
if (!isMounted) return;
if (session.authenticated && session.identity) {
setIdentity(session.identity);
setLoading(false);
} else {
// Unauthenticated user navigating to /birthday/admin initiates login flow
window.location.href = "/birthday/api/auth/login";
}
})
.catch(() => {
if (!isMounted) return;
window.location.href = "/birthday/api/auth/login";
});
return () => {
isMounted = false;
};
}, []);
const handleLogout = useCallback(async () => {
try {
await logoutUser();
} catch (err) {
console.error("Logout error:", err);
}
setIdentity(null);
setLoggedOut(true);
window.history.replaceState(null, "", "/birthday/admin?logged_out=1");
}, []);
if (loading) {
return (
<div
style={{
minHeight: "100vh",
backgroundColor: "#0f0f10",
color: "#f0f0f0",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontFamily: "var(--font-body)",
}}
>
<span style={{ fontSize: "1.1rem", color: "rgba(255, 255, 255, 0.7)" }}>
Cargando panel de control...
</span>
</div>
);
}
if (loggedOut || !identity) {
return (
<div
style={{
minHeight: "100vh",
backgroundColor: "#0f0f10",
color: "#f0f0f0",
fontFamily: "var(--font-body)",
}}
>
<header
style={{
borderBottom: "1px solid rgba(255, 255, 255, 0.1)",
backgroundColor: "#161618",
padding: "1rem 1.8rem",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
<div style={{ display: "flex", alignItems: "center", gap: "0.8rem" }}>
<span style={{ fontSize: "1.4rem" }}>🎂</span>
<h1
style={{
fontSize: "1.1rem",
fontWeight: 600,
letterSpacing: "0.08em",
color: "#ffffff",
textTransform: "uppercase",
}}
>
Panel de Control · Invitación
</h1>
</div>
<a
href="/birthday/api/auth/login"
data-testid="login-link"
style={{
color: "var(--color-gold-light)",
textDecoration: "none",
fontSize: "0.88rem",
fontWeight: 500,
}}
>
Iniciar Sesión
</a>
</header>
<div
data-testid="unauthenticated-state"
style={{
maxWidth: "480px",
margin: "4rem auto",
textAlign: "center",
padding: "2.5rem 1.5rem",
backgroundColor: "#161618",
borderRadius: "8px",
border: "1px solid rgba(255, 255, 255, 0.1)",
}}
>
<div style={{ fontSize: "2.5rem", marginBottom: "1rem" }}>🔒</div>
<h2 style={{ fontSize: "1.3rem", fontWeight: 600, color: "#fff", marginBottom: "0.6rem" }}>
Sesión Finalizada
</h2>
<p style={{ color: "rgba(255, 255, 255, 0.65)", fontSize: "0.9rem", marginBottom: "1.8rem" }}>
Has cerrado sesión correctamente. No hay sesión autenticada activa.
</p>
<a
href="/birthday/api/auth/login"
data-testid="login-btn"
style={{
display: "inline-block",
padding: "0.65rem 1.5rem",
backgroundColor: "var(--color-gold)",
color: "#0a0a0a",
fontWeight: 600,
borderRadius: "4px",
textDecoration: "none",
fontSize: "0.9rem",
}}
>
Iniciar Sesión
</a>
</div>
</div>
);
}
return ( return (
<div <div
style={{ style={{
@@ -38,7 +193,7 @@ export function AdminLayout() {
</h1> </h1>
</div> </div>
<nav style={{ display: "flex", alignItems: "center", gap: "1.4rem" }}> <nav style={{ display: "flex", alignItems: "center", gap: "1.4rem", flexWrap: "wrap" }}>
<NavLink <NavLink
to="/admin" to="/admin"
end end
@@ -88,6 +243,55 @@ export function AdminLayout() {
<span>Ver Pública</span> <span>Ver Pública</span>
<span>↗</span> <span>↗</span>
</Link> </Link>
{/* Authenticated User Info & Logout Button */}
<div
style={{
display: "flex",
alignItems: "center",
gap: "0.9rem",
borderLeft: "1px solid rgba(255, 255, 255, 0.15)",
paddingLeft: "1.2rem",
marginLeft: "0.5rem",
}}
>
<span
data-testid="user-info"
style={{
fontSize: "0.84rem",
color: "rgba(255, 255, 255, 0.85)",
fontWeight: 500,
}}
>
👤 {identity.name ? `${identity.name} (${identity.email})` : identity.email}
</span>
<button
type="button"
data-testid="logout-btn"
aria-label="Logout"
onClick={handleLogout}
style={{
backgroundColor: "transparent",
color: "rgba(255, 255, 255, 0.8)",
border: "1px solid rgba(255, 255, 255, 0.25)",
borderRadius: "4px",
padding: "0.3rem 0.75rem",
fontSize: "0.8rem",
cursor: "pointer",
transition: "all 0.2s ease",
}}
onMouseEnter={(e) => {
e.currentTarget.style.borderColor = "var(--color-gold)";
e.currentTarget.style.color = "var(--color-gold-light)";
}}
onMouseLeave={(e) => {
e.currentTarget.style.borderColor = "rgba(255, 255, 255, 0.25)";
e.currentTarget.style.color = "rgba(255, 255, 255, 0.8)";
}}
>
Logout
</button>
</div>
</nav> </nav>
</header> </header>
+43
View File
@@ -158,3 +158,46 @@ export async function updateAdminRsvp(
return res.json(); return res.json();
} }
export interface AuthUser {
subject: string;
email: string;
name: string | null;
groups: string[];
}
export interface SessionResponse {
authenticated: boolean;
identity: AuthUser | null;
}
export async function fetchSession(): Promise<SessionResponse> {
try {
const res = await fetch(`${BASE_API}/auth/me`, {
headers: { Accept: "application/json" },
});
if (!res.ok) {
return { authenticated: false, identity: null };
}
const data = await res.json();
if ("authenticated" in data) {
return data as SessionResponse;
}
if (data && (data.subject || data.email)) {
return {
authenticated: true,
identity: data as AuthUser,
};
}
return { authenticated: false, identity: null };
} catch {
return { authenticated: false, identity: null };
}
}
export async function logoutUser(): Promise<void> {
await fetch(`${BASE_API}/auth/logout`, {
method: "POST",
headers: { Accept: "application/json" },
});
}