11 Commits
Author SHA1 Message Date
kiskaadee ebf97fe8e7 test(deps): add pytest-playwright to backend dev dependencies 2026-10-07 06:51:42 -05:00
kiskaadee 8ce9a73176 refactor(auth): enforce ruff and pyright standards, add router-level auth, and enhance logged-out UI
- Apply repository standards for ruff check and ruff format across backend
- Enforce strict typing annotations (PEP 604) for pyright compliance
- Add router-level dependency protection to admin.py (dependencies=[Depends(require_admin)])
- Incorporate dedicated logged-out UI screen in AdminLayout.tsx
- Update browser SSO acceptance test to verify the logged-out state and re-login
2026-10-07 06:48:57 -05:00
kiskaadee 381a6275c6 feat(security): harden authentication edge cases and verify deployment independence
- Add comprehensive adversarial edge case test coverage in backend/tests/test_security_hardening.py
- Enforce InvalidPKCEError (HTTP 401) on missing, invalid, or mismatched PKCE code_verifier
- Document and verify Direct Standalone and Homelab Production deployment modes in backend/app/config.py and .env.example
- Update docker-compose.yml to pass OIDC and session environment variables and route directly through Traefik
- Verify zero runtime occurrences of Remote-User in backend/app/ and frontend/src/
2026-10-07 06:48:57 -05:00
kiskaadee 489be93840 feat(ui): integrate browser SSO authentication and admin logout
- Update AdminLayout to verify session state via fetchCurrentUser (/auth/me) and redirect unauthenticated visits to login
- Display authenticated user name/email badge and add interactive Logout button in admin header
- Implement client API bindings for fetchCurrentUser and logoutUser in client.ts
- Redirect successful OIDC callback to /birthday/admin instead of root
- Support serving frontend assets from frontend/dist fallback in main.py
- Refine email claim fallback in OIDCClient when subject contains email format
- Update test_oidc_client assertions to accommodate mock admin identities
- Add Playwright browser acceptance test (test_browser_sso.py) verifying the complete end-to-end SSO loop: unauthenticated redirect, credential submission, HttpOnly session cookie issuance, dashboard rendering, and logout session invalidation
2026-10-07 06:48:57 -05:00
kiskaadee 0133408087 feat(admin): migrate admin routes to group authorization and enforce negative Remote-User barrier
- Migrate all admin endpoints in routes/admin.py to consume group authorization dependency (AdminDep / require_admin).
- Purge legacy Remote-User header dependency from admin routes and OpenAPI documentation.
- Add negative security barrier tests strictly rejecting Remote-User header injection with HTTP 401 when unauthenticated and HTTP 403 when authenticated without admin group.
- Update admin test suites, fixtures (admin_client, guest_client, login_client), and configuration/preview tests to authenticate via signed session cookies.
2026-10-07 06:48:57 -05:00
kiskaadee 1bb046dbb6 feat(auth): implement FastAPI authentication and group authorization dependencies 2026-10-07 06:48:57 -05:00
kiskaadee db4ff6bed7 feat(auth): implement browser session management and fixation protection
- Establish application-level browser session management backed by InMemorySessionStore
- Issue HttpOnly=True, SameSite=lax session cookies with configurable Secure flag
- Enforce Session Fixation Barrier by rotating session IDs and invalidating pre-auth sessions upon authentication
- Provide session resolution, HMAC-SHA256 tamper rejection, expiration pruning, and explicit logout revocation with Max-Age=0
- Mount /birthday/api/auth endpoints (login, callback, logout, me)
- Add comprehensive unit and HTTP integration test coverage
2026-10-07 06:48:57 -05:00
kiskaadee b3f06659d9 feat(auth): map verified OIDC claims to domain Identity and groups
- Map verified claims to typed Identity domain model (sub, email, name)
- Extract group memberships from configured claim path with fallback to empty list
- Enforce identity origin integrity rejecting unvalidated request-controlled headers
- Provide OIDCAuthAdapter fulfilling the AuthPort hexagonal protocol contract
- Add unit and live integration test suite verifying admin and guest fixture users
2026-10-07 06:48:57 -05:00
kiskaadee e5c9bd708a feat(auth): implement generic OIDC client with PKCE and cryptographic token verification
- Add generic OIDCClient supporting RFC 8414 dynamic discovery and JWKS key retrieval
- Implement RFC 7636 PKCE code_verifier generation and S256 code_challenge derivation
- Implement transaction integrity rejecting invalid/missing state (HTTP 400) and mismatched nonce (HTTP 401)
- Implement cryptographic ID token signature and claims verification against JWKS (HTTP 401)
- Add comprehensive unit and live test suite in tests/test_oidc_client.py
2026-10-07 06:48:57 -05:00
kiskaadee a54a474d43 feat(auth): define AuthPort protocol and Identity domain model
- Establish typed Identity domain model with origin integrity validation

- Define AuthPort protocol establishing current_identity, login, and logout contracts

- Add unit tests verifying AuthPort protocol conformance and Identity domain invariants
2026-10-07 06:48:57 -05:00
kiskaadee 99f8581cc8 docs(experiments): archive bdinvite SSO Graphify benchmark
Archive the frozen benchmark artifacts, evaluation tooling, disposable
OIDC fixture, and raw checkpoint telemetry comparing control and
Graphify agent runs for SSO authentication in BDInvite.

- Add retrospective README detailing outcomes, token estimation
  limitations, artifact map, and host environment notes
- Preserve frozen specification (sha256 verified) and manifest
- Archive evaluation runner, static checks, and telemetry scripts
- Retain disposable mock OAuth2 fixture and 16 checkpoint result records
- Link the archived experiment from the root repository README
2026-10-07 06:01:42 -05:00
63 changed files with 5887 additions and 3300 deletions

No files matched your search

+34 -33
View File
@@ -1,14 +1,12 @@
# ==============================================================================
# BDInvite Environment Configuration Template (.env.example)
# BDInvite 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)
# Supports two distinct deployment modes:
# 1. Direct Standalone Mode (local dev / test with mock-oauth2-server or Keycloak)
# 2. Homelab Production Mode (behind Traefik TLS proxy with Authelia / OIDC)
# ==============================================================================
# ------------------------------------------------------------------------------
# 1. General Service Configuration
# ------------------------------------------------------------------------------
# Core Application Settings
SERVICE_NAME=bdinvite
SERVICE_DOMAIN=demos.roadtotech.me
BASE_PATH=/birthday
@@ -17,39 +15,42 @@ DATABASE_URL=sqlite:///./data/bdinvite.db
DATA_DIR=./data
# ------------------------------------------------------------------------------
# 2. OpenID Connect (OIDC) Authentication Settings
# Mode 1: Direct Standalone Mode (Default for local development & testing)
# ------------------------------------------------------------------------------
# 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
# In Direct Standalone Mode:
# - BDInvite runs directly on localhost:8000
# - Cookies are sent over plain HTTP (SESSION_COOKIE_SECURE=false)
# - OIDC IdP is a local mock or Keycloak instance
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_HTTPONLY=true
SESSION_MAX_AGE_SECONDS=86400
SESSION_SECRET_KEY=bdinvite-local-dev-secret-key-replace-in-production
SESSION_COOKIE_PATH=/
# SESSION_COOKIE_DOMAIN=roadtotech.me
SESSION_EXPIRE_SECONDS=86400
# ------------------------------------------------------------------------------
# Mode 2: Homelab Production Mode (Behind Traefik TLS proxy with Authelia)
# ------------------------------------------------------------------------------
# In Homelab Production Mode:
# - Traefik terminates TLS for *.roadtotech.me and routes /birthday to container port 8000
# - Cookies must be sent with Secure flag over HTTPS (SESSION_COOKIE_SECURE=true)
# - Authelia acts as the OpenID Connect (OIDC) identity provider
# - Uncomment the following variables for production deployment:
#
# SERVICE_DOMAIN=demos.roadtotech.me
# OIDC_ISSUER=https://auth.roadtotech.me
# OIDC_CLIENT_ID=bdinvite-client
# OIDC_CLIENT_SECRET=change_to_production_client_secret
# OIDC_REDIRECT_URI=https://demos.roadtotech.me/birthday/api/auth/callback
# OIDC_GROUPS_CLAIM=groups
# SESSION_COOKIE_NAME=bdinvite_session
# SESSION_COOKIE_SECURE=true
# SESSION_COOKIE_SAMESITE=lax
# SESSION_COOKIE_HTTPONLY=true
# SESSION_MAX_AGE_SECONDS=86400
# SESSION_SECRET_KEY=generate_a_cryptographically_secure_random_hex_key_here
+4
View File
@@ -24,6 +24,10 @@ A mobile-first invitation app with animated golden bokeh particles, an RSVP form
- [Infrastructure Specification](specs/infra.md)
- [Roadmap](ROADMAP.md)
## Experiments
- [SSO Graphify Benchmark](experiments/bdinvite-sso-graphify-benchmark/README.md) — Retrospective and archived evidence from an 8-checkpoint agent implementation benchmark.
## License
[Unlicense](UNLICENSE) — public domain.
+56
View File
@@ -0,0 +1,56 @@
# ==============================================================================
# BDInvite Configuration Template (.env.example)
#
# Supports two distinct deployment modes:
# 1. Direct Standalone Mode (local dev / test with mock-oauth2-server or Keycloak)
# 2. Homelab Production Mode (behind Traefik TLS proxy with Authelia / OIDC)
# ==============================================================================
# Core Application Settings
SERVICE_NAME=bdinvite
SERVICE_DOMAIN=demos.roadtotech.me
BASE_PATH=/birthday
APP_PORT=8000
DATABASE_URL=sqlite:///./data/bdinvite.db
DATA_DIR=./data
# ------------------------------------------------------------------------------
# Mode 1: Direct Standalone Mode (Default for local development & testing)
# ------------------------------------------------------------------------------
# In Direct Standalone Mode:
# - BDInvite runs directly on localhost:8000
# - Cookies are sent over plain HTTP (SESSION_COOKIE_SECURE=false)
# - OIDC IdP is a local mock or Keycloak instance
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
SESSION_COOKIE_NAME=bdinvite_session
SESSION_COOKIE_SECURE=false
SESSION_COOKIE_SAMESITE=lax
SESSION_COOKIE_HTTPONLY=true
SESSION_MAX_AGE_SECONDS=86400
SESSION_SECRET_KEY=bdinvite-local-dev-secret-key-replace-in-production
# ------------------------------------------------------------------------------
# Mode 2: Homelab Production Mode (Behind Traefik TLS proxy with Authelia)
# ------------------------------------------------------------------------------
# In Homelab Production Mode:
# - Traefik terminates TLS for *.roadtotech.me and routes /birthday to container port 8000
# - Cookies must be sent with Secure flag over HTTPS (SESSION_COOKIE_SECURE=true)
# - Authelia acts as the OpenID Connect (OIDC) identity provider
# - Uncomment the following variables for production deployment:
#
# SERVICE_DOMAIN=demos.roadtotech.me
# OIDC_ISSUER=https://auth.roadtotech.me
# OIDC_CLIENT_ID=bdinvite-client
# OIDC_CLIENT_SECRET=change_to_production_client_secret
# OIDC_REDIRECT_URI=https://demos.roadtotech.me/birthday/api/auth/callback
# OIDC_GROUPS_CLAIM=groups
# SESSION_COOKIE_NAME=bdinvite_session
# SESSION_COOKIE_SECURE=true
# SESSION_COOKIE_SAMESITE=lax
# SESSION_COOKIE_HTTPONLY=true
# SESSION_MAX_AGE_SECONDS=86400
# SESSION_SECRET_KEY=generate_a_cryptographically_secure_random_hex_key_here
+35 -30
View File
@@ -1,60 +1,65 @@
"""Authentication package providing domain models, hexagonal ports, and OIDC client."""
from .adapter import OIDCAuthAdapter
from .dependencies import (
AdminUserDep,
AuthAdapterDep,
AuthenticatedUserDep,
AdminDep,
AuthenticatedDep,
CurrentIdentityDep,
get_auth_adapter,
get_current_identity,
require_admin,
require_authenticated,
require_group,
set_auth_adapter,
)
from .identity import Identity
from .oidc import (
InvalidCodeVerifierError,
InvalidNonceError,
AuthorizationRequest,
DiscoveryError,
InvalidPKCEError,
InvalidStateError,
OIDCAuthAdapter,
InvalidTokenError,
MismatchedNonceError,
OIDCClient,
OIDCConfig,
OIDCDiscovery,
OIDCError,
OIDCTransaction,
SessionRecord,
TokenValidationError,
claims_to_identity,
extract_identity_from_claims,
generate_code_challenge,
TokenExchangeError,
TokenResponse,
compute_code_challenge,
generate_code_verifier,
generate_nonce,
generate_state,
resolve_claim_path,
)
from .port import AuthPort, Identity
from .port import AuthPort
from .session import (
InMemorySessionStore,
SessionData,
SessionStore,
sign_session_cookie,
unsign_session_cookie,
)
__all__ = [
"AdminUserDep",
"AuthAdapterDep",
"AdminDep",
"AuthPort",
"AuthenticatedUserDep",
"AuthenticatedDep",
"AuthorizationRequest",
"CurrentIdentityDep",
"DiscoveryError",
"Identity",
"InvalidCodeVerifierError",
"InvalidNonceError",
"InMemorySessionStore",
"InvalidPKCEError",
"InvalidStateError",
"InvalidTokenError",
"MismatchedNonceError",
"OIDCAuthAdapter",
"OIDCClient",
"OIDCConfig",
"OIDCDiscovery",
"OIDCError",
"OIDCTransaction",
"SessionRecord",
"TokenValidationError",
"claims_to_identity",
"extract_identity_from_claims",
"generate_code_challenge",
"SessionData",
"SessionStore",
"TokenExchangeError",
"TokenResponse",
"compute_code_challenge",
"generate_code_verifier",
"generate_nonce",
"generate_state",
@@ -63,6 +68,6 @@ __all__ = [
"require_admin",
"require_authenticated",
"require_group",
"resolve_claim_path",
"set_auth_adapter",
"sign_session_cookie",
"unsign_session_cookie",
]
+231
View File
@@ -0,0 +1,231 @@
import contextlib
from typing import Literal
from fastapi import Request, Response
from fastapi.responses import RedirectResponse
from ..config import settings
from .identity import Identity
from .oidc import OIDCClient
from .port import AuthPort
from .session import (
InMemorySessionStore,
SessionData,
SessionStore,
sign_session_cookie,
unsign_session_cookie,
)
class OIDCAuthAdapter(AuthPort):
"""Hexagonal Adapter binding generic OIDC client and browser session store to AuthPort."""
def __init__(
self,
oidc_client: OIDCClient,
session_cookie_name: str = settings.SESSION_COOKIE_NAME,
session_store: SessionStore | None = None,
cookie_secure: bool | None = None,
cookie_samesite: Literal["lax", "strict", "none"] | None = None,
session_max_age: int | None = None,
secret_key: str | None = None,
) -> None:
self.oidc_client = oidc_client
self.session_cookie_name = session_cookie_name
self.session_store: SessionStore = (
session_store if session_store is not None else InMemorySessionStore()
)
self.cookie_secure: bool = (
cookie_secure
if cookie_secure is not None
else settings.SESSION_COOKIE_SECURE
)
self.cookie_samesite: Literal["lax", "strict", "none"] = (
cookie_samesite
if cookie_samesite is not None
else settings.SESSION_COOKIE_SAMESITE
)
self.session_max_age: int = (
session_max_age
if session_max_age is not None
else settings.SESSION_MAX_AGE_SECONDS
)
self.secret_key: str = (
secret_key if secret_key is not None else settings.SESSION_SECRET_KEY
)
def parse_session_cookie(self, cookie_value: str | None) -> str | None:
"""Extract and verify session_id from cookie, safely rejecting tampered cookies."""
if (
not cookie_value
or not isinstance(cookie_value, str)
or not cookie_value.strip()
):
return None
# 1. Attempt HMAC signature verification
unsigned = unsign_session_cookie(cookie_value, self.secret_key)
if unsigned is not None:
return unsigned
# 2. Tampered cookie detection:
# If it has a dot and is not a 3-part JWT, it was a tampered signed cookie
if "." in cookie_value:
# Let JWT pass through to token fallback if 3 segments
if cookie_value.count(".") == 2:
return None
return None
# 3. Direct lookup for raw session_id (e.g. test fixtures without HMAC signing)
if self.session_store.get_session(cookie_value) is not None:
return cookie_value
return None
def current_identity(self, request: Request) -> Identity | None:
"""Resolve the validated identity associated with the incoming request.
Identity Origin Integrity:
Resolves identity strictly from verified server-side sessions or cryptographically
verified tokens (Authorization Bearer header). Request-controlled headers (e.g.
legacy proxy headers (e.g. forwarded user headers, X-User) are strictly ignored to prevent identity spoofing.
"""
# 1. Authorization: Bearer <token>
auth_header = request.headers.get("Authorization")
if auth_header and auth_header.startswith("Bearer "):
token = auth_header[7:].strip()
with contextlib.suppress(Exception):
return self.oidc_client.extract_identity_from_token(token)
return None
# 2. Browser session cookie
raw_cookie = request.cookies.get(self.session_cookie_name)
if not raw_cookie:
return None
# Attempt resolving from session store
session_id = self.parse_session_cookie(raw_cookie)
if session_id:
session = self.session_store.get_session(session_id)
if session is not None:
if session.is_expired():
self.session_store.delete_session(session_id)
return None
return session.identity
return None
# Fallback for backward compatibility with CP3 token-in-cookie tests
with contextlib.suppress(Exception):
return self.oidc_client.extract_identity_from_token(raw_cookie)
return None
def set_session_cookie(
self,
response: Response,
session_id: str,
max_age: int | None = None,
) -> None:
"""Issue session cookie enforcing HttpOnly=True, SameSite, and configurable Secure flag."""
signed_val = sign_session_cookie(session_id, self.secret_key)
response.set_cookie(
key=self.session_cookie_name,
value=signed_val,
max_age=max_age if max_age is not None else self.session_max_age,
httponly=True, # Security Invariant: ALWAYS True to protect against XSS
samesite=self.cookie_samesite,
secure=self.cookie_secure,
path="/",
)
def clear_session_cookie(self, response: Response) -> None:
"""Clear session cookie with Max-Age=0."""
response.delete_cookie(
key=self.session_cookie_name,
path="/",
httponly=True,
samesite=self.cookie_samesite,
secure=self.cookie_secure,
)
def create_session(
self,
identity: Identity | None = None,
request: Request | None = None,
response: Response | None = None,
pre_auth_session_id: str | None = None,
max_age_seconds: int | None = None,
) -> SessionData:
"""Create session with Session Fixation Protection.
Guarantees:
- If a pre-authentication session existed, it is invalidated and never promoted.
- A fresh, unguessable session identifier is generated (pre_auth != post_auth).
- If response is provided, the HttpOnly cookie is attached.
"""
candidate_pre_auth = pre_auth_session_id
if not candidate_pre_auth and request is not None:
raw_cookie = request.cookies.get(self.session_cookie_name)
if raw_cookie:
candidate_pre_auth = self.parse_session_cookie(raw_cookie)
effective_max_age = (
max_age_seconds if max_age_seconds is not None else self.session_max_age
)
session = self.session_store.create_session(
identity=identity,
max_age_seconds=effective_max_age,
pre_auth_session_id=candidate_pre_auth,
)
if candidate_pre_auth:
assert session.session_id != candidate_pre_auth
if response is not None:
self.set_session_cookie(
response, session.session_id, max_age=effective_max_age
)
return session
def login(self, request: Request) -> Response:
"""Initiate OIDC login flow with 302 redirect and pre-auth session establishment."""
auth_req = self.oidc_client.create_authorization_url()
response = RedirectResponse(url=auth_req.url, status_code=302)
# Issue pre-authentication session if request does not already possess one
raw_cookie = request.cookies.get(self.session_cookie_name)
existing_session_id = (
self.parse_session_cookie(raw_cookie) if raw_cookie else None
)
if (
not existing_session_id
or self.session_store.get_session(existing_session_id) is None
):
pre_auth = self.session_store.create_session(
identity=None,
max_age_seconds=self.session_max_age,
)
self.set_session_cookie(response, pre_auth.session_id)
return response
def logout(self, request: Request) -> Response:
"""Terminate session on server and clear browser cookie."""
raw_cookie = request.cookies.get(self.session_cookie_name)
if raw_cookie:
session_id = self.parse_session_cookie(raw_cookie)
if session_id:
self.session_store.delete_session(session_id)
end_session = self.oidc_client.end_session_endpoint
target_url = end_session if end_session else "/"
response = RedirectResponse(url=target_url, status_code=302)
self.clear_session_cookie(response)
return response
def extract_identity(self, claims: dict[str, object]) -> Identity:
"""Delegate identity extraction from verified claims to OIDCClient."""
return self.oidc_client.extract_identity(claims)
__all__ = ["OIDCAuthAdapter"]
+56 -56
View File
@@ -1,108 +1,108 @@
"""FastAPI dependency injection module for authentication and authorization."""
from collections.abc import Callable
from typing import Annotated, Optional
from typing import Annotated, cast
from fastapi import Depends, HTTPException, Request, status
from fastapi.params import Depends as DependsClass
from ..config import settings
from .oidc import OIDCAuthAdapter, OIDCClient, OIDCConfig
from .port import Identity
from .adapter import OIDCAuthAdapter
from .identity import Identity
from .oidc import OIDCClient
from .session import InMemorySessionStore
_auth_adapter: Optional[OIDCAuthAdapter] = None
_auth_adapter_instance: OIDCAuthAdapter | None = 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(
"""Dependency provider returning singleton OIDCAuthAdapter instance."""
global _auth_adapter_instance
if _auth_adapter_instance is None:
client = OIDCClient(
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,
_auth_adapter_instance = OIDCAuthAdapter(
oidc_client=client,
session_cookie_name=settings.SESSION_COOKIE_NAME,
session_store=InMemorySessionStore(),
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),
session_max_age=settings.SESSION_MAX_AGE_SECONDS,
secret_key=settings.SESSION_SECRET_KEY,
)
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)]
return _auth_adapter_instance
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)
adapter: Annotated[OIDCAuthAdapter | None, Depends(get_auth_adapter)] = None,
) -> Identity | None:
"""Resolves the active Identity from the session/adapter, or None if unauthenticated."""
resolved_adapter: OIDCAuthAdapter = (
get_auth_adapter()
if adapter is None or isinstance(cast(object, adapter), DependsClass)
else adapter
)
return resolved_adapter.current_identity(request)
def require_authenticated(
identity: Optional[Identity] = Depends(get_current_identity),
identity: Annotated[Identity | None, Depends(get_current_identity)] = None,
) -> Identity:
"""Enforce authentication, raising HTTP 401 Unauthorized if anonymous."""
if identity is None or not isinstance(identity, Identity):
"""Enforces authentication, raising HTTP 401 Unauthorized if anonymous."""
if isinstance(cast(object, identity), DependsClass) or identity is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required",
headers={"WWW-Authenticate": "Bearer"},
detail="Not authenticated",
)
return identity
def require_group(group_name: str) -> Callable[..., Identity]:
"""Dependency factory enforcing membership in a specified group.
"""Dependency factory enforcing group membership.
Raises HTTP 401 Unauthorized if anonymous, and HTTP 403 Forbidden
if authenticated but missing the required group in identity.groups.
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),
def _group_dependency(
identity: Annotated[Identity | None, Depends(require_authenticated)] = None,
) -> Identity:
if identity is None or not isinstance(identity, Identity):
if isinstance(cast(object, identity), DependsClass) or identity is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required",
headers={"WWW-Authenticate": "Bearer"},
detail="Not authenticated",
)
if group_name not in identity.groups:
if not identity.has_group(group_name):
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}"
_group_dependency.__name__ = f"require_group_{group_name}"
_group_dependency.__doc__ = (
f"FastAPI dependency requiring membership in '{group_name}' group."
)
return _require_group_dependency
return _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)]
CurrentIdentityDep = Annotated[Identity | None, Depends(get_current_identity)]
AuthenticatedDep = Annotated[Identity, Depends(require_authenticated)]
AdminDep = Annotated[Identity, Depends(require_admin)]
__all__ = [
"AdminDep",
"AuthenticatedDep",
"CurrentIdentityDep",
"get_auth_adapter",
"get_current_identity",
"require_admin",
"require_authenticated",
"require_group",
]
+35
View File
@@ -0,0 +1,35 @@
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Identity:
"""Domain model representing a validated authenticated principal.
Identity Origin Integrity:
Instances of Identity must only represent verified authentication results produced
by an authentication adapter or port, and must never be constructed directly from
raw unvalidated client headers or requests.
"""
subject: str
email: str
name: str | None = None
groups: list[str] = field(default_factory=list)
def __post_init__(self) -> None:
if not isinstance(self.subject, str) or not self.subject.strip():
raise ValueError("Identity subject must be a non-empty string")
if not isinstance(self.email, str) or not self.email.strip():
raise ValueError("Identity email must be a non-empty string")
if self.name is not None and not isinstance(self.name, str):
raise TypeError("Identity name must be a string or None")
if not isinstance(self.groups, (list, tuple)):
raise TypeError("Identity groups must be a list of strings")
for g in self.groups:
if not isinstance(g, str):
raise TypeError("Identity groups items must be strings")
object.__setattr__(self, "groups", list(self.groups))
def has_group(self, group: str) -> bool:
"""Check if the identity belongs to a specific group."""
return group in self.groups
+579 -883
View File
File diff suppressed because it is too large. Load diff
+15 -32
View File
@@ -1,49 +1,32 @@
"""Authentication port and identity abstractions for hexagonal architecture."""
from dataclasses import dataclass, field
from typing import Optional, Protocol, runtime_checkable
from typing import 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))
from .identity import Identity
@runtime_checkable
class AuthPort(Protocol):
"""Hexagonal inbound/outbound port interface for authentication."""
"""Hexagonal Port for Authentication and Identity Management.
def current_identity(self, request: Request) -> Optional[Identity]:
"""Extract and return the verified Identity from the incoming request.
Establishes the boundary between application domain logic and concrete authentication
mechanisms (such as OIDC, OAuth, ForwardAuth, or session providers).
"""
Returns None if the request is unauthenticated or credentials are invalid.
def current_identity(self, request: Request) -> Identity | None:
"""Resolve the validated identity associated with the incoming request.
Returns None if the request is unauthenticated or credentials/session are invalid.
"""
...
def login(self, request: Request) -> Response:
"""Handle or initiate the authentication flow (e.g. redirecting to an IdP)."""
"""Initiate the login flow (e.g. redirect to identity provider or challenge response)."""
...
def logout(self, request: Request) -> Response:
"""Handle session termination or logout redirection."""
"""Terminate the session or logout flow (e.g. invalidate session cookie or IdP logout redirect)."""
...
__all__ = ["AuthPort", "Identity"]
+184
View File
@@ -0,0 +1,184 @@
import hashlib
import hmac
import secrets
import threading
import time
from dataclasses import dataclass, field
from typing import Any, Protocol, runtime_checkable
from .identity import Identity
@dataclass
class SessionData:
"""Represents an application-level browser session."""
session_id: str
identity: Identity | None = None
created_at: float = field(default_factory=time.time)
expires_at: float = 0.0
metadata: dict[str, Any] = field(default_factory=dict)
@property
def is_authenticated(self) -> bool:
"""Return True if session has a verified identity."""
return self.identity is not None
def is_expired(self, current_time: float | None = None) -> bool:
"""Check whether the session has passed its expiration timestamp."""
now = current_time if current_time is not None else time.time()
return now >= self.expires_at
@runtime_checkable
class SessionStore(Protocol):
"""Protocol defining the storage contract for browser session lifecycle."""
def create_session(
self,
identity: Identity | None = None,
max_age_seconds: int = 86400,
pre_auth_session_id: str | None = None,
metadata: dict[str, Any] | None = None,
) -> SessionData:
"""Create a fresh session. If pre_auth_session_id is provided, invalidate it (Session Fixation Protection)."""
...
def get_session(self, session_id: str) -> SessionData | None:
"""Retrieve a session by its identifier. Returns None if absent or expired."""
...
def delete_session(self, session_id: str) -> bool:
"""Explicitly revoke a session from storage."""
...
def prune_expired(self) -> int:
"""Purge all expired sessions from storage."""
...
def clear(self) -> None:
"""Purge all sessions (utility for tests and lifecycle resets)."""
...
class InMemorySessionStore:
"""Thread-safe in-memory session store implementing SessionStore protocol."""
def __init__(self) -> None:
self._sessions: dict[str, SessionData] = {}
self._lock = threading.Lock()
def create_session(
self,
identity: Identity | None = None,
max_age_seconds: int = 86400,
pre_auth_session_id: str | None = None,
metadata: dict[str, Any] | None = None,
) -> SessionData:
"""Create a brand new session, enforcing the Session Fixation Barrier."""
with self._lock:
# Session Fixation Barrier: invalidate existing pre-auth session
if pre_auth_session_id:
self._sessions.pop(pre_auth_session_id, None)
now = time.time()
expires_at = now + max_age_seconds
# Generate fresh, unguessable cryptographic token
while True:
new_session_id = secrets.token_urlsafe(32)
if (
new_session_id != pre_auth_session_id
and new_session_id not in self._sessions
):
break
session = SessionData(
session_id=new_session_id,
identity=identity,
created_at=now,
expires_at=expires_at,
metadata=metadata or {},
)
self._sessions[new_session_id] = session
return session
def get_session(self, session_id: str) -> SessionData | None:
"""Fetch session, automatically purging if expired."""
if not session_id or not isinstance(session_id, str):
return None
with self._lock:
session = self._sessions.get(session_id)
if session is None:
return None
if session.is_expired():
self._sessions.pop(session_id, None)
return None
return session
def delete_session(self, session_id: str) -> bool:
"""Revoke session from storage."""
if not session_id or not isinstance(session_id, str):
return False
with self._lock:
return self._sessions.pop(session_id, None) is not None
def prune_expired(self) -> int:
"""Purge all expired sessions."""
with self._lock:
now = time.time()
expired_keys = [k for k, s in self._sessions.items() if s.is_expired(now)]
for k in expired_keys:
self._sessions.pop(k, None)
return len(expired_keys)
def clear(self) -> None:
"""Reset storage."""
with self._lock:
self._sessions.clear()
def sign_session_cookie(session_id: str, secret_key: str) -> str:
"""Sign session_id with HMAC-SHA256 to detect any client-side tampering."""
if not session_id or not isinstance(session_id, str):
raise ValueError("session_id must be a non-empty string")
mac = hmac.new(
secret_key.encode("utf-8"),
session_id.encode("utf-8"),
hashlib.sha256,
).hexdigest()
return f"{session_id}.{mac}"
def unsign_session_cookie(cookie_val: str | None, secret_key: str) -> str | None:
"""Verify HMAC-SHA256 signature and return verified session_id, or None if tampered/invalid."""
if not cookie_val or not isinstance(cookie_val, str) or not cookie_val.strip():
return None
if "." not in cookie_val:
return None
parts = cookie_val.rsplit(".", 1)
if len(parts) != 2:
return None
session_id, signature = parts
if not session_id or not signature:
return None
expected_mac = hmac.new(
secret_key.encode("utf-8"),
session_id.encode("utf-8"),
hashlib.sha256,
).hexdigest()
if not hmac.compare_digest(signature, expected_mac):
return None
return session_id
__all__ = [
"InMemorySessionStore",
"SessionData",
"SessionStore",
"sign_session_cookie",
"unsign_session_cookie",
]
+31 -34
View File
@@ -5,33 +5,20 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""Application and deployment configuration supporting multi-mode deployment.
"""BDInvite Application Configuration.
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"
Supports two primary deployment modes:
1. Direct Standalone Mode (local dev & testing):
- Direct HTTP access on port 8000
- OIDC_ISSUER pointing to local IdP (e.g. mock-oauth2-server or Keycloak)
- SESSION_COOKIE_SECURE = False
- OIDC_REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
2. Homelab Production Mode:
- Deployed behind Traefik reverse proxy terminating TLS
- OIDC_ISSUER pointing to Authelia (e.g. https://auth.roadtotech.me)
- SESSION_COOKIE_SECURE = True (required for HTTPS cookie transmission)
- SESSION_COOKIE_NAME = "bdinvite_session" (or prefixed "__Host-bdinvite_session")
- OIDC_REDIRECT_URI = "https://demos.roadtotech.me/birthday/api/auth/callback"
"""
SERVICE_NAME: str = "bdinvite"
@@ -41,24 +28,35 @@ class Settings(BaseSettings):
DATABASE_URL: str = "sqlite:///./data/bdinvite.db"
DATA_DIR: str = "./data"
# OIDC & Auth Settings
# OIDC Provider & SSO Settings
OIDC_ISSUER: str = "http://localhost:8088/default"
OIDC_CLIENT_ID: str = "bdinvite-client"
OIDC_CLIENT_SECRET: str | None = "bdinvite-secret"
OIDC_CLIENT_SECRET: str = "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
# Browser Session & Cookie Security 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
SESSION_COOKIE_HTTPONLY: bool = True
SESSION_MAX_AGE_SECONDS: int = 86400
SESSION_SECRET_KEY: str = "bdinvite-session-secret-key-change-in-prod"
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
@property
def is_standalone(self) -> bool:
"""Returns True if operating in direct standalone (development) mode."""
return not self.SESSION_COOKIE_SECURE and (
"localhost" in self.OIDC_ISSUER or "127.0.0.1" in self.OIDC_ISSUER
)
@property
def is_production(self) -> bool:
"""Returns True if operating in secure homelab production mode."""
return self.SESSION_COOKIE_SECURE
@property
def data_path(self) -> Path:
return Path(self.DATA_DIR).resolve()
@@ -69,4 +67,3 @@ class Settings(BaseSettings):
settings = Settings()
+13 -5
View File
@@ -31,8 +31,8 @@ app = FastAPI(
"API REST para la invitación interactiva de cumpleaños con sistema RSVP.\n\n"
"### Arquitectura de Seguridad\n"
"- **Rutas Públicas (`/birthday/api/*`)**: Acceso abierto para los invitados.\n"
"- **Rutas Administrativas (`/birthday/api/admin/*`)**: Protegidas por autenticación "
"OIDC y autorización basada en grupos (`bdinvite_admins`)."
"- **Rutas Administrativas (`/birthday/api/admin/*`)**: Protegidas por autenticación de sesión OIDC "
"y autorización basada en grupos (`bdinvite_admins`)."
),
openapi_tags=[
{
@@ -45,7 +45,7 @@ app = FastAPI(
},
{
"name": "Admin",
"description": "Gestión de asistentes, descarga CSV y edición de contenido protegida por autorización administrativa.",
"description": "Gestión de asistentes, descarga CSV y edición de contenido protegida por autenticación y grupo administrativo.",
},
],
lifespan=lifespan,
@@ -90,7 +90,7 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
# Register API routes with exact path prefixes per specification
app.include_router(rsvp.router, prefix="/birthday/api")
app.include_router(config.router, prefix="/birthday/api")
app.include_router(auth.router, prefix="/birthday/api/auth")
app.include_router(auth.router, prefix="/birthday/api")
app.include_router(admin.router, prefix="/birthday/api/admin")
@@ -115,6 +115,12 @@ async def get_map_preview():
# Static files and SPA serving
STATIC_DIR = os.path.join(os.path.dirname(__file__), "..", "static")
if not os.path.isdir(STATIC_DIR):
frontend_dist = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "..", "frontend", "dist")
)
if os.path.isdir(frontend_dist):
STATIC_DIR = frontend_dist
ASSETS_DIR = os.path.join(STATIC_DIR, "assets")
if os.path.isdir(ASSETS_DIR):
@@ -123,7 +129,9 @@ if os.path.isdir(ASSETS_DIR):
@app.get("/birthday", include_in_schema=False)
async def redirect_birthday_slash():
return RedirectResponse(url="/birthday/", status_code=status.HTTP_307_TEMPORARY_REDIRECT)
return RedirectResponse(
url="/birthday/", status_code=status.HTTP_307_TEMPORARY_REDIRECT
)
@app.get("/birthday/", include_in_schema=False)
+18 -6
View File
@@ -15,7 +15,9 @@ class RSVP(Base):
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(100), nullable=False)
phone: Mapped[str] = mapped_column(String(20), nullable=False, unique=True, index=True)
phone: Mapped[str] = mapped_column(
String(20), nullable=False, unique=True, index=True
)
email: Mapped[str | None] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=utc_now
@@ -26,14 +28,20 @@ class InvitationConfig(Base):
__tablename__ = "invitation_config"
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=1)
title: Mapped[str] = mapped_column(String(200), nullable=False, default="Birthday Party")
title: Mapped[str] = mapped_column(
String(200), nullable=False, default="Birthday Party"
)
invitation_text: Mapped[str] = mapped_column(
String(500),
nullable=False,
default="You're invited to the birthday party honoring",
)
honoree_name: Mapped[str] = mapped_column(String(200), nullable=False, default="Isabelle Snow")
event_date: Mapped[str] = mapped_column(String(20), nullable=False, default="2026-10-28")
honoree_name: Mapped[str] = mapped_column(
String(200), nullable=False, default="Isabelle Snow"
)
event_date: Mapped[str] = mapped_column(
String(20), nullable=False, default="2026-10-28"
)
event_time: Mapped[str] = mapped_column(String(10), nullable=False, default="19:00")
event_timezone: Mapped[str] = mapped_column(
String(50), nullable=False, default="America/Bogota"
@@ -56,11 +64,15 @@ class InvitationConfig(Base):
nullable=False,
default="https://maps.google.com/?q=Fresco+Ristorante+Glendale+CA",
)
rsvp_heading: Mapped[str] = mapped_column(String(100), nullable=False, default="¿Nos vemos?")
rsvp_heading: Mapped[str] = mapped_column(
String(100), nullable=False, default="¿Nos vemos?"
)
rsvp_cta: Mapped[str] = mapped_column(
String(100), nullable=False, default="CONFIRMA TU ASISTENCIA"
)
submit_label: Mapped[str] = mapped_column(String(100), nullable=False, default="TE VEO AHÍ")
submit_label: Mapped[str] = mapped_column(
String(100), nullable=False, default="TE VEO AHÍ"
)
msg_success: Mapped[str] = mapped_column(
String(300),
nullable=False,
-4
View File
@@ -1,5 +1 @@
"""API Route definitions."""
from . import admin, auth, config, rsvp
__all__ = ["admin", "auth", "config", "rsvp"]
+45 -20
View File
@@ -6,7 +6,7 @@ from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from sqlalchemy.orm import Session
from ..auth import AdminUserDep, Identity, require_admin
from ..auth import Identity, require_admin
from ..config import settings
from ..database import get_db
from ..schemas import (
@@ -19,23 +19,24 @@ from ..schemas import (
RSVPUpdate,
)
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
router = APIRouter(tags=["Admin"], dependencies=[Depends(require_admin)])
AdminDep = AdminUserDep
AdminDep = Annotated[Identity, Depends(require_admin)]
DbDep = Annotated[Session, Depends(get_db)]
ADMIN_RESPONSES = {
401: {
"description": "No autenticado. Se requiere una sesión válida o token de autorización.",
},
401: {"description": "No autenticado. Se requiere sesión activa de usuario."},
403: {
"description": "Acceso prohibido. El usuario autenticado no pertenece al grupo administrativo.",
"description": "Acceso denegado. Se requiere pertenecer al grupo 'bdinvite_admins'."
},
}
ADMIN_401 = ADMIN_RESPONSES
@router.get(
@@ -47,7 +48,10 @@ ADMIN_RESPONSES = {
"Permite filtrado por coincidencia parcial (`?search=`) sobre nombre, teléfono o correo."
),
responses={
200: {"model": RSVPListResponse, "description": "Lista de confirmaciones obtenida."},
200: {
"model": RSVPListResponse,
"description": "Lista de confirmaciones obtenida.",
},
**ADMIN_RESPONSES,
},
)
@@ -100,10 +104,15 @@ def delete_rsvp_endpoint(
summary="Editar una confirmación de asistencia",
description="Actualiza el nombre, teléfono o correo de un asistente confirmado.",
responses={
200: {"model": RSVPAdminItem, "description": "Registro actualizado exitosamente."},
200: {
"model": RSVPAdminItem,
"description": "Registro actualizado exitosamente.",
},
400: {"description": "Error de validación en los campos proporcionados."},
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_RESPONSES,
},
)
@@ -129,7 +138,6 @@ def update_rsvp_endpoint(
return updated
@router.get(
"/export",
summary="Exportar confirmaciones en formato CSV",
@@ -158,7 +166,11 @@ def export_rsvps_csv(
for item in rsvps:
created_iso = ""
if item.created_at:
dt = item.created_at if item.created_at.tzinfo else item.created_at.replace(tzinfo=UTC)
dt = (
item.created_at
if item.created_at.tzinfo
else item.created_at.replace(tzinfo=UTC)
)
created_iso = dt.isoformat()
writer.writerow([item.name, item.phone, item.email or "", created_iso])
@@ -176,7 +188,10 @@ def export_rsvps_csv(
summary="Obtener configuración editable",
description="Retorna el objeto completo de configuración para poblar el formulario de administración.",
responses={
200: {"model": InvitationConfigResponse, "description": "Configuración obtenida correctamente."},
200: {
"model": InvitationConfigResponse,
"description": "Configuración obtenida correctamente.",
},
**ADMIN_RESPONSES,
},
)
@@ -201,7 +216,10 @@ def get_admin_config(
"Los cambios toman efecto de inmediato sin requerir recarga del contenedor."
),
responses={
200: {"model": InvitationConfigResponse, "description": "Configuración actualizada con éxito."},
200: {
"model": InvitationConfigResponse,
"description": "Configuración actualizada con éxito.",
},
**ADMIN_RESPONSES,
},
)
@@ -210,13 +228,16 @@ def get_admin_config(
response_model=InvitationConfigResponse,
summary="Actualizar configuración de la invitación",
description=(
"Actualiza los valores de la configuración singleton del evento. "
"Reemplaza 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."},
200: {
"model": InvitationConfigResponse,
"description": "Configuración actualizada con éxito.",
},
**ADMIN_RESPONSES,
},
)
@@ -262,7 +283,10 @@ async def update_admin_config(
"sin realizar escrituras innecesarias a la base de datos."
),
responses={
200: {"model": GenerateMapPreviewResponse, "description": "Vista previa generada exitosamente."},
200: {
"model": GenerateMapPreviewResponse,
"description": "Vista previa generada exitosamente.",
},
**ADMIN_RESPONSES,
},
)
@@ -282,7 +306,9 @@ async def regenerate_map_preview_endpoint(
target_url = current.map_url
try:
fallback = f"{current.address_lines}\n{current.address_name}" if current else None
fallback = (
f"{current.address_lines}\n{current.address_name}" if current else None
)
lat, lng, _ = await resolve_google_maps_coordinates(
target_url, fallback_query=fallback
)
@@ -305,4 +331,3 @@ async def regenerate_map_preview_endpoint(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Error al generar la vista previa del mapa: {err}",
) from err
+121 -83
View File
@@ -1,111 +1,149 @@
"""Authentication and browser session management API routes."""
from typing import Annotated
from typing import Annotated, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, status
from fastapi.responses import RedirectResponse
from fastapi import APIRouter, Depends, Query, Request, Response, status
from fastapi.responses import JSONResponse, RedirectResponse
from ..auth import Identity, OIDCAuthAdapter
from ..auth.dependencies import get_auth_adapter
from ..schemas import LoginRequest, UserResponse
from ..auth import OIDCAuthAdapter, OIDCClient, OIDCConfig
from ..config import settings
router = APIRouter(prefix="/auth", tags=["Auth"])
router = APIRouter(tags=["Auth"])
from ..auth.dependencies import (
AuthAdapterDep,
get_auth_adapter,
set_auth_adapter,
)
AuthAdapterDep = Annotated[OIDCAuthAdapter, Depends(get_auth_adapter)]
@router.get(
"/login",
summary="Initiate OIDC authentication flow",
description="Redirects user browser to the configured OIDC provider authorization endpoint.",
summary="Iniciar flujo de autenticación OIDC",
description="Redirige al proveedor de identidad OIDC con parámetros PKCE, nonce y state.",
)
def login(request: Request, adapter: AuthAdapterDep) -> Response:
def login_endpoint(
request: Request,
adapter: AuthAdapterDep,
):
return adapter.login(request)
@router.post(
"/login",
response_model=UserResponse,
summary="Autenticación directa de credenciales",
description="Autentica usuario contra el proveedor OIDC y establece una sesión protegida contra fijación.",
)
def direct_login_endpoint(
payload: LoginRequest,
request: Request,
response: Response,
adapter: AuthAdapterDep,
):
try:
_, identity = adapter.oidc_client.authenticate_with_password(
username=payload.username,
password=payload.password,
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Credenciales inválidas o error de autenticación: {e}",
) from e
# Rotate pre-authentication session and issue post-auth session cookie
adapter.create_session(
identity=identity,
request=request,
response=response,
)
return UserResponse(
subject=identity.subject,
email=identity.email,
name=identity.name,
groups=identity.groups,
)
@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."
),
summary="Callback de autorización OIDC",
description="Procesa la redirección del IdP, intercambia el código de autorización e inicia la sesión.",
)
def callback(
def callback_endpoint(
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,
code: Annotated[
str, Query(description="Código de autorización devuelto por el IdP")
],
state: Annotated[str, Query(description="Token de estado para validación CSRF")],
):
token_response = adapter.oidc_client.exchange_code(code=code, state=state)
identity = adapter.oidc_client.extract_identity(token_response.claims)
redirect_response = RedirectResponse(
url="/birthday/admin", status_code=status.HTTP_302_FOUND
)
adapter.create_session(
identity=identity,
request=request,
response=redirect_response,
)
return response
return redirect_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.",
response_model=UserResponse,
summary="Obtener identidad de la sesión activa",
description="Resuelve la identidad del usuario actual a partir de la cookie de sesión o encabezado Bearer.",
)
def get_session(request: Request, adapter: AuthAdapterDep) -> Response:
identity = adapter.current_identity(request)
def me_endpoint(
request: Request,
adapter: AuthAdapterDep,
):
identity: Identity | None = adapter.current_identity(request)
if identity is None:
return JSONResponse(
status_code=status.HTTP_200_OK,
content={"authenticated": False, "identity": None},
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
)
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"authenticated": True,
"identity": {
"subject": identity.subject,
"email": identity.email,
"name": identity.name,
"groups": identity.groups,
},
},
return UserResponse(
subject=identity.subject,
email=identity.email,
name=identity.name,
groups=identity.groups,
)
@router.post(
"/logout",
summary="Cerrar sesión de usuario (POST)",
description="Revoca la sesión en el servidor y elimina la cookie de sesión del navegador con Max-Age=0.",
)
def logout_post_endpoint(
request: Request,
response: Response,
adapter: AuthAdapterDep,
):
raw_cookie = request.cookies.get(adapter.session_cookie_name)
if raw_cookie:
session_id = adapter.parse_session_cookie(raw_cookie)
if session_id:
adapter.session_store.delete_session(session_id)
adapter.clear_session_cookie(response)
return {"status": "ok", "message": "Logged out successfully"}
@router.get(
"/logout",
summary="Cerrar sesión de usuario (GET)",
description="Revoca la sesión y redirige al usuario con la cookie eliminada.",
)
def logout_get_endpoint(
request: Request,
adapter: AuthAdapterDep,
):
return adapter.logout(request)
__all__ = ["get_auth_adapter", "router"]
+52 -15
View File
@@ -6,7 +6,6 @@ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator
def normalize_phone(raw: str) -> str:
"""Normalize Colombian mobile numbers.
@@ -127,8 +126,6 @@ class RSVPUpdate(BaseModel):
return cleaned.lower()
class RSVPSuccessResponse(BaseModel):
result: Literal["SUCCESS"] = Field(
default="SUCCESS",
@@ -168,11 +165,27 @@ class RSVPErrorResponse(BaseModel):
class RSVPAdminItem(BaseModel):
id: int = Field(..., description="Identificador único del registro en base de datos", examples=[1])
name: str = Field(..., description="Nombre completo del asistente", examples=["Ana García"])
phone: str = Field(..., description="Número telefónico normalizado a 10 dígitos", examples=["3001234567"])
email: str | None = Field(default=None, description="Correo electrónico registrado", examples=["ana@example.com"])
created_at: datetime = Field(..., description="Marca de tiempo UTC de la confirmación")
id: int = Field(
...,
description="Identificador único del registro en base de datos",
examples=[1],
)
name: str = Field(
..., description="Nombre completo del asistente", examples=["Ana García"]
)
phone: str = Field(
...,
description="Número telefónico normalizado a 10 dígitos",
examples=["3001234567"],
)
email: str | None = Field(
default=None,
description="Correo electrónico registrado",
examples=["ana@example.com"],
)
created_at: datetime = Field(
..., description="Marca de tiempo UTC de la confirmación"
)
model_config = ConfigDict(from_attributes=True)
@@ -183,10 +196,13 @@ class RSVPAdminItem(BaseModel):
return dt.isoformat()
class RSVPListResponse(BaseModel):
count: int = Field(..., description="Cantidad total de confirmaciones encontradas", examples=[37])
rsvps: list[RSVPAdminItem] = Field(..., description="Lista de asistentes confirmados")
count: int = Field(
..., description="Cantidad total de confirmaciones encontradas", examples=[37]
)
rsvps: list[RSVPAdminItem] = Field(
..., description="Lista de asistentes confirmados"
)
class InvitationConfigBase(BaseModel):
@@ -376,8 +392,12 @@ class InvitationConfigUpdate(InvitationConfigBase):
class InvitationConfigResponse(InvitationConfigBase):
id: int = Field(default=1, description="Identificador único del registro singleton (siempre 1)")
updated_at: datetime | None = Field(default=None, description="Última modificación en UTC")
id: int = Field(
default=1, description="Identificador único del registro singleton (siempre 1)"
)
updated_at: datetime | None = Field(
default=None, description="Última modificación en UTC"
)
model_config = ConfigDict(from_attributes=True)
@@ -390,7 +410,6 @@ class InvitationConfigResponse(InvitationConfigBase):
return dt.isoformat()
class GenerateMapPreviewRequest(BaseModel):
map_url: str | None = Field(
default=None,
@@ -400,7 +419,25 @@ class GenerateMapPreviewRequest(BaseModel):
class GenerateMapPreviewResponse(BaseModel):
map_preview_url: str = Field(description="URL para acceder a la imagen de vista previa generada")
map_preview_url: str = Field(
description="URL para acceder a la imagen de vista previa generada"
)
lat: float = Field(description="Latitud resuelta")
lng: float = Field(description="Longitud resuelta")
message: str = Field(default="Vista previa generada con éxito")
class LoginRequest(BaseModel):
username: str = Field(
..., description="Nombre de usuario o correo para autenticación OIDC"
)
password: str = Field(..., description="Contraseña de usuario")
class UserResponse(BaseModel):
subject: str = Field(..., description="Identificador único del usuario (sub)")
email: str = Field(..., description="Correo electrónico del usuario")
name: str | None = Field(default=None, description="Nombre visible del usuario")
groups: list[str] = Field(
default_factory=list, description="Grupos o roles asignados al usuario"
)
+19 -17
View File
@@ -1,3 +1,4 @@
import contextlib
import io
import math
import re
@@ -27,12 +28,10 @@ def is_google_maps_host(host: str) -> bool:
return True
if clean_host.startswith("maps.google."):
return True
if clean_host == "google.com" or clean_host.endswith(".google.com") or clean_host.endswith(".google"):
if clean_host == "google.com" or clean_host.endswith((".google.com", ".google")):
return True
# Regional domains like google.es, google.co, google.com.co
if re.match(r"^(?:www\.)?google\.[a-z.]+$", clean_host):
return True
return False
return bool(re.match(r"^(?:www\.)?google\.[a-z.]+$", clean_host))
def validate_google_maps_url_format(url: str) -> None:
@@ -74,7 +73,7 @@ def extract_coordinates_from_text(text: str) -> tuple[float, float] | None:
if parsed.query:
qs = parse_qs(parsed.query)
for param in ("q", "ll", "destination"):
if param in qs and qs[param]:
if qs.get(param):
val = qs[param][0].strip()
m = re.match(r"^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$", val)
if m:
@@ -118,7 +117,9 @@ async def resolve_google_maps_coordinates(
if hop_coords:
return hop_coords[0], hop_coords[1], resolved_url
except httpx.RequestError as exc:
raise ValueError(f"No se pudo resolver el enlace de Google Maps: {exc}") from exc
raise ValueError(
f"No se pudo resolver el enlace de Google Maps: {exc}"
) from exc
# Try extraction on the final resolved destination URL
final_coords = extract_coordinates_from_text(resolved_url)
@@ -129,7 +130,7 @@ async def resolve_google_maps_coordinates(
parsed = urlparse(resolved_url)
qs = parse_qs(parsed.query)
query_text = None
if "q" in qs and qs["q"]:
if qs.get("q"):
query_text = qs["q"][0]
elif "/place/" in parsed.path:
# e.g. /maps/place/Fresco+Ristorante/...
@@ -153,9 +154,11 @@ async def resolve_google_maps_coordinates(
candidates.append(query_text)
if candidates:
async with httpx.AsyncClient(timeout=8.0, headers={"User-Agent": USER_AGENT}) as client:
async with httpx.AsyncClient(
timeout=8.0, headers={"User-Agent": USER_AGENT}
) as client:
for candidate in candidates:
try:
with contextlib.suppress(Exception):
nom_res = await client.get(
"https://nominatim.openstreetmap.org/search",
params={"q": candidate, "format": "json", "limit": 1},
@@ -167,8 +170,6 @@ async def resolve_google_maps_coordinates(
lng = float(results[0]["lon"])
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
return lat, lng, resolved_url
except Exception:
pass
raise ValueError(
"No se pudieron extraer las coordenadas de la URL de Google Maps. "
@@ -207,18 +208,17 @@ async def generate_map_preview_image(
# Canvas of 3x3 tiles = 768x768 pixels
canvas = Image.new("RGB", (768, 768), color=(229, 227, 223))
async with httpx.AsyncClient(timeout=10.0, headers={"User-Agent": USER_AGENT}) as client:
async with httpx.AsyncClient(
timeout=10.0, headers={"User-Agent": USER_AGENT}
) as client:
for r_idx, y in enumerate(range(y_int - 1, y_int + 2)):
for c_idx, x in enumerate(range(x_int - 1, x_int + 2)):
tile_url = f"https://tile.openstreetmap.org/{zoom}/{x}/{y}.png"
try:
with contextlib.suppress(Exception):
res = await client.get(tile_url)
if res.status_code == 200:
tile = Image.open(io.BytesIO(res.content)).convert("RGB")
canvas.paste(tile, (c_idx * 256, r_idx * 256))
except Exception:
# Keep neutral background tile if individual tile fails
pass
# Exact target location within the 768x768 canvas
cx = 256 + int(dx * 256)
@@ -236,7 +236,9 @@ async def generate_map_preview_image(
draw.ellipse((192, 198, 208, 204), fill=(40, 40, 40, 140))
# Golden pin pointer (inverted triangle)
draw.polygon([(188, 184), (212, 184), (200, 200)], fill="#d4a843", outline="#1a1a1a")
draw.polygon(
[(188, 184), (212, 184), (200, 200)], fill="#d4a843", outline="#1a1a1a"
)
# Golden pin circular head
draw.ellipse((188, 170, 212, 194), fill="#d4a843", outline="#1a1a1a", width=2)
-2
View File
@@ -113,5 +113,3 @@ def update_rsvp(
except Exception:
db.rollback()
raise
+2 -1
View File
@@ -11,7 +11,7 @@ dependencies = [
"pydantic-settings>=2.0.0",
"pillow>=10.0.0",
"httpx>=0.27.0",
"pyjwt[crypto]>=2.8.0",
"pyjwt[crypto]>=2.15.1",
]
[dependency-groups]
@@ -20,6 +20,7 @@ dev = [
"pytest>=8.0.0",
"pytest-asyncio>=0.23.0",
"pyright>=1.1.0",
"pytest-playwright>=0.9.0",
]
[tool.pyright]
+41 -49
View File
@@ -43,60 +43,52 @@ def client(db_session):
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
def create_test_session(
subject: str = "admin-001",
email: str = "admin@example.com",
groups: list[str] | None = None,
) -> tuple[str, str]:
"""Helper to create a valid signed session cookie for testing."""
from app.auth import Identity, get_auth_adapter, sign_session_cookie
if groups is None:
groups = ["bdinvite_admins"]
adapter = get_auth_adapter()
session_id = adapter.establish_session(admin_identity)
return {adapter.session_cookie_name: session_id}
identity = Identity(
subject=subject,
email=email,
groups=groups,
)
session = adapter.session_store.create_session(identity=identity)
signed_cookie = sign_session_cookie(session.session_id, adapter.secret_key)
return adapter.session_cookie_name, signed_cookie
def login_client(
client: TestClient,
subject: str = "admin-001",
email: str = "admin@example.com",
groups: list[str] | None = None,
) -> TestClient:
"""Sets a valid session cookie on client for an identity with the given groups."""
cookie_name, cookie_value = create_test_session(
subject=subject,
email=email,
groups=groups,
)
client.cookies.set(cookie_name, cookie_value)
return client
@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}
def admin_client(client: TestClient) -> TestClient:
login_client(client, groups=["bdinvite_admins"])
return client
@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()
def guest_client(client: TestClient) -> TestClient:
login_client(
client, subject="guest-001", email="guest@example.com", groups=["guests"]
)
return client
+129 -114
View File
@@ -1,76 +1,100 @@
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
from tests.conftest import login_client
def test_admin_endpoints_require_authentication(client: TestClient):
"""Anonymous requests to admin endpoints must receive HTTP 401 Unauthorized."""
"""Anonymous requests to all admin endpoints must receive HTTP 401 Unauthorized."""
endpoints = [
("GET", "/birthday/api/admin/rsvps"),
("DELETE", "/birthday/api/admin/rsvps/1"),
("PATCH", "/birthday/api/admin/rsvps/1"),
("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"
assert res.json() == {"detail": "Not authenticated"}
def test_admin_endpoints_require_remote_user(client: TestClient):
"""Backwards-compatible test: verify anonymous or legacy header calls are rejected with 401."""
endpoints = [
"/birthday/api/admin/rsvps",
"/birthday/api/admin/export",
"/birthday/api/admin/config",
]
for path in endpoints:
res = client.get(path)
assert res.status_code == 401, f"GET {path} should require authentication"
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_remote_user_header_strictly_ignored(client: TestClient):
"""Legacy Remote-User header without valid authenticated session must be strictly rejected with HTTP 401."""
res = client.get("/birthday/api/admin/rsvps", headers={"Remote-User": "kiskaadee"})
assert res.status_code == 401
assert res.json() == {"detail": "Not authenticated"}
# Also verify across other admin routes
assert (
client.get(
"/birthday/api/admin/export", headers={"Remote-User": "kiskaadee"}
).status_code
== 401
)
assert (
client.get(
"/birthday/api/admin/config", headers={"Remote-User": "kiskaadee"}
).status_code
== 401
)
assert (
client.post(
"/birthday/api/admin/map-preview/generate",
headers={"Remote-User": "kiskaadee"},
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
).status_code
== 401
)
def test_admin_endpoints_forbidden_for_non_admin_users(client: TestClient, guest_session_cookie: dict[str, str]):
"""Authenticated non-admin users must receive HTTP 403 Forbidden."""
for k, v in guest_session_cookie.items():
client.cookies.set(k, v)
def test_admin_endpoints_authenticated_non_admin_forbidden(guest_client: TestClient):
"""Authenticated non-admin users (e.g. guest@example.com with groups: ['guests']) must receive HTTP 403 Forbidden."""
endpoints = [
("GET", "/birthday/api/admin/rsvps"),
("DELETE", "/birthday/api/admin/rsvps/1"),
("PATCH", "/birthday/api/admin/rsvps/1"),
("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", "")
res = guest_client.request(method, path)
assert res.status_code == 403, (
f"{method} {path} should reject non-admin with 403"
)
assert "Forbidden" in res.json()["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_remote_user_header_with_non_admin_session_cannot_elevate_privileges(
guest_client: TestClient,
):
"""An attacker passing Remote-User: admin with a non-admin session cookie must still receive HTTP 403."""
res = guest_client.get(
"/birthday/api/admin/rsvps",
headers={"Remote-User": "admin@example.com", "X-Remote-User": "admin"},
)
assert res.status_code == 403
assert "Forbidden" in res.json()["detail"]
def test_admin_endpoints_authenticated_admin_allowed(admin_client: TestClient):
"""Authenticated admin user (admin@example.com with groups: ['bdinvite_admins']) succeeds."""
res_rsvps = admin_client.get("/birthday/api/admin/rsvps")
assert res_rsvps.status_code == 200
res_export = admin_client.get("/birthday/api/admin/export")
assert res_export.status_code == 200
res_config = admin_client.get("/birthday/api/admin/config")
assert res_config.status_code == 200
def test_admin_list_and_search_rsvps(admin_client: TestClient):
"""Authenticated admin user can list and search RSVPs."""
# Initially 0
res = admin_client.get("/birthday/api/admin/rsvps")
assert res.status_code == 200
@@ -79,11 +103,19 @@ def test_admin_list_and_search_rsvps(admin_client: TestClient):
# Add 3 invitees
admin_client.post(
"/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",
},
)
admin_client.post(
"/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",
},
)
admin_client.post(
"/birthday/api/rsvp",
@@ -110,10 +142,13 @@ def test_admin_list_and_search_rsvps(admin_client: TestClient):
def test_admin_export_csv(admin_client: TestClient):
"""Authenticated admin user can export RSVPs as CSV."""
admin_client.post(
"/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 = admin_client.get("/birthday/api/admin/export")
@@ -122,73 +157,90 @@ def test_admin_export_csv(admin_client: TestClient):
assert 'filename="rsvps.csv"' in res.headers["content-disposition"]
content = res.text
lines = content.strip().split("\r\n") if "\r\n" in content else content.strip().split("\n")
lines = (
content.strip().split("\r\n")
if "\r\n" in content
else content.strip().split("\n")
)
assert lines[0] == "name,phone,email,created_at"
assert "Sofia Vergara,3019998877,sofia@hollywood.com" in lines[1]
def test_admin_delete_rsvp(client: TestClient, admin_client: TestClient):
"""Admin can delete RSVPs; anonymous requests are rejected."""
def test_admin_delete_rsvp(client: TestClient):
# Unauthorized without session
res_unauth = client.delete("/birthday/api/admin/rsvps/1")
assert res_unauth.status_code == 401
# Login as admin
login_client(client)
# 404 for non-existent RSVP
res_404 = admin_client.delete("/birthday/api/admin/rsvps/9999")
res_404 = client.delete("/birthday/api/admin/rsvps/9999")
assert res_404.status_code == 404
# Create an RSVP
admin_client.post(
client.post(
"/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 = admin_client.get("/birthday/api/admin/rsvps")
list_res = client.get("/birthday/api/admin/rsvps")
assert list_res.status_code == 200
rsvps = list_res.json()["rsvps"]
assert len(rsvps) == 1
rsvp_id = rsvps[0]["id"]
# Delete successfully
del_res = admin_client.delete(f"/birthday/api/admin/rsvps/{rsvp_id}")
del_res = client.delete(f"/birthday/api/admin/rsvps/{rsvp_id}")
assert del_res.status_code == 204
# Confirm deletion
list_after = admin_client.get("/birthday/api/admin/rsvps")
list_after = client.get("/birthday/api/admin/rsvps")
assert list_after.json()["count"] == 0
def test_admin_update_rsvp(client: TestClient, admin_client: TestClient):
"""Admin can update RSVPs; anonymous requests are rejected."""
def test_admin_update_rsvp(client: TestClient):
# Unauthorized without session
res_unauth = client.patch("/birthday/api/admin/rsvps/1", json={"name": "New Name"})
assert res_unauth.status_code == 401
# Login as admin
login_client(client)
# 404 for non-existent RSVP
res_404 = admin_client.patch(
res_404 = client.patch(
"/birthday/api/admin/rsvps/9999",
json={"name": "New Name"},
)
assert res_404.status_code == 404
# Create two RSVPs
admin_client.post(
client.post(
"/birthday/api/rsvp",
json={"name": "Person One", "phone": "300 111 2222", "email": "one@test.com"},
)
admin_client.post(
client.post(
"/birthday/api/rsvp",
json={"name": "Person Two", "phone": "300 333 4444", "email": "two@test.com"},
)
list_res = admin_client.get("/birthday/api/admin/rsvps")
list_res = client.get("/birthday/api/admin/rsvps")
rsvps = list_res.json()["rsvps"]
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")
assert id_two is not None
# Update Person One with valid new name and phone
patch_res = admin_client.patch(
patch_res = client.patch(
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",
},
)
assert patch_res.status_code == 200
updated_data = patch_res.json()
@@ -197,70 +249,33 @@ def test_admin_update_rsvp(client: TestClient, admin_client: TestClient):
assert updated_data["email"] == "newone@test.com"
# Attempt to update Person One's phone to Person Two's phone -> 409
dup_res = admin_client.patch(
dup_res = client.patch(
f"/birthday/api/admin/rsvps/{id_one}",
json={"phone": "300 333 4444"},
)
assert dup_res.status_code == 409
# Validation error for invalid phone
val_res = admin_client.patch(
val_res = client.patch(
f"/birthday/api/admin/rsvps/{id_one}",
json={"phone": "12345"},
)
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
def test_admin_config_endpoints_put_and_patch(admin_client: TestClient):
"""Both PUT and PATCH /birthday/api/admin/config succeed for authorized admins."""
current = admin_client.get("/birthday/api/admin/config").json()
assert current["honoree_name"] == "Isabelle Snow"
# 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"
# Test PUT
payload_put = {**current, "honoree_name": "Isabelle PUT"}
res_put = admin_client.put("/birthday/api/admin/config", json=payload_put)
assert res_put.status_code == 200
assert res_put.json()["honoree_name"] == "Isabelle PUT"
# 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
# Test PATCH
payload_patch = {**current, "honoree_name": "Isabelle PATCH"}
res_patch = admin_client.patch("/birthday/api/admin/config", json=payload_patch)
assert res_patch.status_code == 200
assert res_patch.json()["honoree_name"] == "Isabelle PATCH"
+89 -115
View File
@@ -1,178 +1,152 @@
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."""
"""Mock implementation of AuthPort for testing hexagonal boundary compliance."""
def __init__(self, sessions: Optional[dict[str, Identity]] = None):
self.sessions = sessions or {}
def __init__(self, current_user: Identity | None = None):
self._current_user = current_user
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 current_identity(self, request: Request) -> Identity | None:
return self._current_user
def login(self, request: Request) -> Response:
return RedirectResponse(url="https://auth.example.com/oauth/authorize", status_code=302)
return RedirectResponse(url="/auth/login", status_code=302)
def logout(self, request: Request) -> Response:
response = Response(content="logged out", status_code=200)
response.delete_cookie("session_id")
return response
return RedirectResponse(url="/auth/logout", status_code=302)
class IncompleteAuthAdapter:
"""Incomplete adapter missing logout to test Protocol validation."""
"""Non-conforming class missing login and logout methods."""
def current_identity(self, request: Request) -> Optional[Identity]:
def current_identity(self, request: Request) -> Identity | None:
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()]
def create_dummy_request(headers: dict[str, str] | None = None) -> Request:
raw_headers = [
(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"",
"headers": raw_headers,
}
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 == []
return Request(scope)
def test_identity_creation_full():
identity = Identity(
subject="usr_456",
email="admin@example.com",
name="Admin User",
groups=["admins", "organizers"],
subject="user-123",
email="test@example.com",
name="Test User",
groups=["admin", "family"],
)
assert identity.subject == "usr_456"
assert identity.email == "admin@example.com"
assert identity.name == "Admin User"
assert identity.groups == ["admins", "organizers"]
assert identity.subject == "user-123"
assert identity.email == "test@example.com"
assert identity.name == "Test User"
assert identity.groups == ["admin", "family"]
assert identity.has_group("admin") is True
assert identity.has_group("stranger") is False
def test_identity_none_groups_normalized():
identity = Identity(subject="usr_789", email="test@example.com", groups=None) # type: ignore[arg-type]
def test_identity_creation_defaults():
identity = Identity(
subject="user-456",
email="minimal@example.com",
)
assert identity.subject == "user-456"
assert identity.email == "minimal@example.com"
assert identity.name is None
assert identity.groups == []
assert identity.has_group("admin") is False
def test_identity_frozen_immutability():
identity = Identity(subject="usr_123", email="user@example.com")
def test_identity_immutability():
identity = Identity(
subject="user-789",
email="immutable@example.com",
)
with pytest.raises(FrozenInstanceError):
identity.subject = "usr_999" # type: ignore[misc]
identity.subject = "new-subject" # type: ignore[misc]
with pytest.raises(FrozenInstanceError):
identity.email = "changed@example.com" # type: ignore[misc]
identity.email = "new@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"])
def test_identity_validation_subject():
with pytest.raises(ValueError, match="subject must be a non-empty string"):
Identity(subject="", email="test@example.com")
assert id1 == id2
assert id1 != id3
with pytest.raises(ValueError, match="subject must be a non-empty string"):
Identity(subject=" ", email="test@example.com")
def test_identity_validation_email():
with pytest.raises(ValueError, match="email must be a non-empty string"):
Identity(subject="user-1", email="")
with pytest.raises(ValueError, match="email must be a non-empty string"):
Identity(subject="user-1", email=" ")
def test_identity_validation_name():
with pytest.raises(TypeError, match="name must be a string or None"):
Identity(subject="user-1", email="test@example.com", name=123) # type: ignore[arg-type]
def test_identity_validation_groups():
with pytest.raises(TypeError, match="groups must be a list of strings"):
Identity(subject="user-1", email="test@example.com", groups="not-a-list") # type: ignore[arg-type]
with pytest.raises(TypeError, match="groups items must be strings"):
Identity(subject="user-1", email="test@example.com", groups=[123]) # type: ignore[list-item]
def test_auth_port_protocol_conformance():
adapter = MockAuthAdapter()
assert isinstance(adapter, AuthPort)
assert issubclass(MockAuthAdapter, AuthPort)
def test_auth_port_protocol_non_conformance():
incomplete = IncompleteAuthAdapter()
assert not isinstance(incomplete, AuthPort)
assert not issubclass(IncompleteAuthAdapter, AuthPort)
def test_auth_port_behavior_with_mock():
def test_auth_port_current_identity_resolution():
expected_identity = Identity(
subject="sub_valid",
email="guest@example.com",
name="Guest User",
groups=["guests"],
subject="admin-1",
email="admin@example.com",
name="Admin",
groups=["admin"],
)
adapter = MockAuthAdapter(sessions={"valid_token": expected_identity})
authenticated_port: AuthPort = MockAuthAdapter(current_user=expected_identity)
unauthenticated_port: AuthPort = MockAuthAdapter(current_user=None)
# Unauthenticated request
unauth_req = create_mock_request()
assert adapter.current_identity(unauth_req) is None
req = create_dummy_request()
assert authenticated_port.current_identity(req) == expected_identity
assert unauthenticated_port.current_identity(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)
def test_auth_port_login_logout_contract():
port: AuthPort = MockAuthAdapter()
req = create_dummy_request()
login_resp = port.login(req)
assert isinstance(login_resp, Response)
assert login_resp.status_code == 302
assert login_resp.headers["location"] == "https://auth.example.com/oauth/authorize"
assert login_resp.headers["location"] == "/auth/login"
# Logout flow
logout_resp = adapter.logout(auth_req)
logout_resp = port.logout(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}"
)
assert logout_resp.status_code == 302
assert logout_resp.headers["location"] == "/auth/logout"
+85 -106
View File
@@ -1,156 +1,135 @@
"""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 contextlib
import threading
import time
from typing import Generator
from collections.abc import Generator
import httpx
import pytest
import uvicorn
from playwright.sync_api import BrowserContext, Page, sync_playwright
from playwright.sync_api import Browser, 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
from app.main import app
APP_HOST = "127.0.0.1"
APP_PORT = 8000
BASE_URL = f"http://{APP_HOST}:{APP_PORT}"
@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()
"""Start uvicorn server in a background thread for browser testing."""
config = uvicorn.Config(
"app.main:app",
host="127.0.0.1",
port=settings.APP_PORT,
app,
host=APP_HOST,
port=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}"
# Wait for server readiness
import httpx
# 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:
with contextlib.suppress(Exception):
r = httpx.get(f"{BASE_URL}/birthday/api/docs", timeout=0.5)
if r.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
assert ready, "Server failed to start in time"
yield BASE_URL
server.should_exit = True
thread.join(timeout=3.0)
thread.join(timeout=2)
@pytest.fixture(scope="module")
def browser_context():
"""Launch headless Chromium browser and provide an isolated context."""
def browser_instance() -> Generator[Browser, None, None]:
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
yield context
context.close()
yield browser
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()
@pytest.fixture
def browser_context(browser_instance: Browser) -> Generator[BrowserContext, None, None]:
context = browser_instance.new_context()
yield context
context.close()
# 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
@pytest.fixture
def page(browser_context: BrowserContext) -> Generator[Page, None, None]:
pg = browser_context.new_page()
yield pg
pg.close()
# 3. Submit credentials on Mock OAuth2 Server login form
page.wait_for_selector("input[name='username']", timeout=5000)
def test_browser_sso_complete_interactive_loop(
live_server: str,
browser_context: BrowserContext,
page: Page,
):
"""Complete browser SSO acceptance test (CP7).
Verifies:
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 info.
5. Clicking 'Logout' button revokes session -> returns to unauthenticated state.
"""
# 1. Unauthenticated navigation to /birthday/admin -> redirected to OIDC login form
admin_url = f"{live_server}/birthday/admin"
page.goto(admin_url)
page.wait_for_url("**/authorize**", timeout=10000)
assert "8088" in page.url or "authorize" in page.url
# 2. Submit test credentials
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"],
}),
)
if page.query_selector("input[name='password']"):
page.fill("input[name='password']", "password123")
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
# 3. Callback completes, sets HttpOnly cookie, and lands on Admin Dashboard
page.wait_for_url("**/birthday/admin", timeout=10000)
assert page.url.endswith("/birthday/admin")
# 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]
cookies = browser_context.cookies()
session_cookie = next(
(c for c in cookies if c.get("name") == "bdinvite_session"), None
)
assert session_cookie is not None, "bdinvite_session cookie must be set"
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
# 4. Admin Dashboard renders RSVPs table and user info
page.wait_for_selector("text=Respuestas", timeout=10000)
user_info_elem = page.locator("[data-testid='user-info']")
user_info_elem.wait_for(state="visible", timeout=10000)
user_text = user_info_elem.text_content() or ""
assert "admin" in user_text.lower(), f"Expected admin user info, got: {user_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()
# Verify RSVPs table / UI content is visible
assert page.locator("nav").is_visible()
# 7. Clicking "Logout" button revokes session and returns UI to unauthenticated state
logout_btn = page.locator("[data-testid='logout-btn']")
# 5. Clicking 'Logout' button revokes session -> returns to unauthenticated state
logout_btn = page.locator("button:has-text('Logout')")
assert logout_btn.is_visible()
logout_btn.click()
# UI displays unauthenticated state
page.wait_for_selector("[data-testid='unauthenticated-state']", timeout=5000)
# UI displays unauthenticated state screen
page.wait_for_selector("[data-testid='unauthenticated-state']", timeout=10000)
assert page.locator("[data-testid='unauthenticated-state']").is_visible()
assert page.locator("text=Sesión Finalizada").is_visible()
# RSVPs table is no longer displayed
assert page.locator("table").count() == 0
# Re-clicking login initiates fresh OIDC flow
page.locator("[data-testid='login-btn']").click()
page.wait_for_url("**/authorize**", timeout=10000)
assert "authorize" in page.url
page.close()
# Attempting to access /birthday/admin again redirects to login
page.goto(admin_url)
page.wait_for_url("**/authorize**", timeout=10000)
assert "authorize" in page.url
+9 -4
View File
@@ -1,3 +1,6 @@
from tests.conftest import login_client
def test_get_config_public(client):
response = client.get("/birthday/api/config")
assert response.status_code == 200
@@ -10,16 +13,17 @@ def test_get_config_public(client):
assert data["countdown_label"] == "NOS VEMOS EN"
def test_get_config_admin(client, admin_client):
def test_get_config_admin(client):
res_unauth = client.get("/birthday/api/admin/config")
assert res_unauth.status_code == 401
res_auth = admin_client.get("/birthday/api/admin/config")
login_client(client)
res_auth = client.get("/birthday/api/admin/config")
assert res_auth.status_code == 200
assert res_auth.json()["honoree_name"] == "Isabelle Snow"
def test_update_config_requires_admin(client, admin_client):
def test_update_config_requires_admin(client):
update_payload = {
"title": "Fiesta de Cumpleaños",
"invitation_text": "Estás invitado a la fiesta de",
@@ -48,7 +52,8 @@ def test_update_config_requires_admin(client, admin_client):
assert res.status_code == 401
# With admin session -> 200
res_auth = admin_client.put(
login_client(client)
res_auth = client.put(
"/birthday/api/admin/config",
json=update_payload,
)
+323 -298
View File
@@ -1,419 +1,444 @@
"""Tests for FastAPI dependency injection and authorization policies (Checkpoint 5)."""
from collections.abc import Generator
from typing import Annotated, Optional
from typing import Annotated
import pytest
from fastapi import APIRouter, Depends, FastAPI, HTTPException, status
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.testclient import TestClient
from starlette.requests import Request
from app.auth import (
AdminUserDep,
AuthenticatedUserDep,
CurrentIdentityDep,
Identity,
InMemorySessionStore,
OIDCAuthAdapter,
OIDCClient,
OIDCConfig,
get_auth_adapter,
get_current_identity,
require_admin,
require_authenticated,
require_group,
set_auth_adapter,
sign_session_cookie,
)
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"
LIVE_ISSUER = "http://localhost:8088/default"
CLIENT_ID = "bdinvite-client"
CLIENT_SECRET = "bdinvite-secret"
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(
def create_dummy_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")))
"""Construct a lightweight ASGI Request instance for unit testing dependencies."""
raw_headers: list[tuple[bytes, bytes]] = [
(k.lower().encode("latin-1"), v.encode("latin-1"))
for k, v in (headers or {}).items()
]
if cookies:
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
header_list.append((b"cookie", cookie_header.encode("latin-1")))
raw_headers.append((b"cookie", cookie_header.encode("latin-1")))
scope = {
"type": "http",
"method": "GET",
"path": "/test",
"headers": header_list,
"query_string": b"",
"headers": raw_headers,
}
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()
def oidc_client() -> OIDCClient:
return OIDCClient(
issuer=LIVE_ISSUER,
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
)
@router.get("/me")
def me_endpoint(identity: CurrentIdentityDep):
@pytest.fixture
def auth_adapter(oidc_client: OIDCClient) -> OIDCAuthAdapter:
return OIDCAuthAdapter(
oidc_client=oidc_client,
session_cookie_name="bdinvite_session",
session_store=InMemorySessionStore(),
cookie_secure=False,
cookie_samesite="lax",
session_max_age=3600,
secret_key="test-session-secret",
)
@pytest.fixture
def test_app() -> FastAPI:
"""Isolated FastAPI test harness registering dependency endpoints."""
app = FastAPI(title="Dependency Test Harness")
event_planners_dep = require_group("event_planners")
@app.get("/test/identity")
def route_identity(
identity: Annotated[Identity | None, Depends(get_current_identity)],
):
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):
@app.get("/test/authenticated")
def route_authenticated(
identity: Annotated[Identity, Depends(require_authenticated)],
):
return {
"subject": user.subject,
"email": user.email,
"groups": user.groups,
"subject": identity.subject,
"email": identity.email,
"groups": identity.groups,
}
@router.get("/admin")
def admin_endpoint(admin: AdminUserDep):
@app.get("/test/admin")
def route_admin(admin: Annotated[Identity, Depends(require_admin)]):
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)]):
@app.get("/test/custom-group")
def route_custom_group(member: Annotated[Identity, Depends(event_planners_dep)]):
return {
"subject": user.subject,
"email": user.email,
"groups": user.groups,
"subject": member.subject,
"groups": member.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
def test_client(test_app: FastAPI) -> TestClient:
return TestClient(test_app)
# ============================================================================
# Unit Tests (Direct Dependency Invocations)
# ============================================================================
# ==============================================================================
# 1. Direct Unit Tests: FastAPI Dependency Functions in Isolation
# ==============================================================================
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_unit_get_current_identity_anonymous():
"""get_current_identity yields None when request has no authentication credentials."""
req = create_dummy_request()
identity = get_current_identity(req)
assert identity 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"
def test_unit_get_current_identity_with_valid_session(auth_adapter: OIDCAuthAdapter):
"""get_current_identity resolves domain Identity when valid session cookie is provided."""
expected = Identity(
subject="alice-001",
email="alice@example.com",
groups=["users"],
)
req = create_request(cookies={auth_adapter.session_cookie_name: session_id})
session = auth_adapter.session_store.create_session(identity=expected)
signed_cookie = sign_session_cookie(session.session_id, auth_adapter.secret_key)
req = create_dummy_request(cookies={"bdinvite_session": signed_cookie})
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
assert resolved == expected
def test_get_current_identity_with_valid_bearer_token(
auth_adapter: OIDCAuthAdapter, oidc_client: OIDCClient
def test_unit_get_current_identity_with_tampered_or_expired_cookie(
auth_adapter: OIDCAuthAdapter,
):
"""Valid Bearer token yields active Identity on get_current_identity."""
_, tokens = oidc_client.authenticate_user("guest@example.com", "guestpass456")
id_token = tokens["id_token"]
"""get_current_identity safely yields None for tampered or expired sessions."""
# 1. Tampered signature
req_tampered = create_dummy_request(
cookies={"bdinvite_session": "invalid_session_id.deadbeef"}
)
assert get_current_identity(req_tampered, adapter=auth_adapter) is None
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"]
# 2. Expired session
exp_session = auth_adapter.session_store.create_session(
identity=Identity(subject="exp-user", email="exp@example.com"),
max_age_seconds=-1,
)
signed_exp = sign_session_cookie(exp_session.session_id, auth_adapter.secret_key)
req_expired = create_dummy_request(cookies={"bdinvite_session": signed_exp})
assert get_current_identity(req_expired, adapter=auth_adapter) is None
def test_require_authenticated_anonymous_raises_401():
"""Anonymous request (identity=None) raises HTTP 401 on require_authenticated."""
def test_unit_require_authenticated():
"""require_authenticated returns Identity if present, raises HTTP 401 if anonymous."""
valid_identity = Identity(
subject="user-123",
email="user123@example.com",
groups=["guests"],
)
# Authenticated user passes cleanly
result = require_authenticated(identity=valid_identity)
assert result == valid_identity
# Anonymous user (identity=None) raises HTTP 401
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"
assert exc_info.value.status_code == 401
assert exc_info.value.detail == "Not authenticated"
# Default / un-injected call raises HTTP 401
with pytest.raises(HTTPException) as exc_info_default:
require_authenticated()
assert exc_info_default.value.status_code == 401
def test_require_authenticated_success():
"""Authenticated user returns Identity from require_authenticated."""
identity = Identity(
subject="sub-123",
email="user@example.com",
groups=["guests"],
def test_unit_require_group_factory():
"""require_group produces dependencies enforcing specific group membership."""
group_dep = require_group("special_ops")
assert callable(group_dep)
assert "special_ops" in group_dep.__name__
user_with_group = Identity(
subject="op-1",
email="op1@example.com",
groups=["special_ops", "staff"],
)
user_without_group = Identity(
subject="user-2",
email="user2@example.com",
groups=["staff"],
)
result = require_authenticated(identity=identity)
assert result == identity
# 1. Authorized member yields Identity
assert group_dep(identity=user_with_group) == user_with_group
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:
# 2. Authenticated user missing the group raises HTTP 403
with pytest.raises(HTTPException) as exc_info_403:
group_dep(identity=user_without_group)
assert exc_info_403.value.status_code == 403
assert "Forbidden" in exc_info_403.value.detail
# 3. Anonymous caller raises HTTP 401
with pytest.raises(HTTPException) as exc_info_401:
group_dep(identity=None)
assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED
assert exc_info_401.value.status_code == 401
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",
def test_unit_require_admin():
"""require_admin enforces bdinvite_admins group membership."""
admin_identity = Identity(
subject="admin-1",
email="admin@example.com",
groups=["bdinvite_admins"],
)
guest_identity = Identity(
subject="guest-1",
email="guest@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
# Admin yields Identity
assert require_admin(identity=admin_identity) == admin_identity
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
# Non-admin raises HTTP 403
with pytest.raises(HTTPException) as exc_403:
require_admin(identity=guest_identity)
assert exc_403.value.status_code == 403
def test_require_admin_anonymous_raises_401():
"""Anonymous request raises HTTP 401 on require_admin."""
with pytest.raises(HTTPException) as exc_info:
# Anonymous raises HTTP 401
with pytest.raises(HTTPException) as exc_401:
require_admin(identity=None)
assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED
assert exc_401.value.status_code == 401
def test_require_admin_non_admin_raises_403():
"""Authenticated non-admin user raises HTTP 403 on require_admin."""
guest_user = Identity(
# ==============================================================================
# 2. HTTP Integration Tests: FastAPI Dependency Test Harness
# ==============================================================================
def test_http_anonymous_request_yields_none_on_get_current_identity(
test_client: TestClient,
):
"""Anonymous request yields None on get_current_identity endpoint."""
resp = test_client.get("/test/identity")
assert resp.status_code == 200
assert resp.json() == {"authenticated": False, "identity": None}
def test_http_anonymous_request_raises_401_on_require_authenticated(
test_client: TestClient,
):
"""Anonymous request raises HTTP 401 Unauthorized on require_authenticated."""
resp = test_client.get("/test/authenticated")
assert resp.status_code == 401
assert resp.json()["detail"] == "Not authenticated"
def test_http_anonymous_request_raises_401_on_require_admin(
test_client: TestClient,
):
"""Anonymous request raises HTTP 401 Unauthorized on require_admin."""
resp = test_client.get("/test/admin")
assert resp.status_code == 401
assert resp.json()["detail"] == "Not authenticated"
def test_http_authenticated_non_admin_raises_403_on_require_admin(
test_client: TestClient,
):
"""Authenticated non-admin user (guest@example.com with groups: ['guests']) raises HTTP 403."""
adapter = get_auth_adapter()
guest_identity = 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
session = adapter.session_store.create_session(identity=guest_identity)
signed_cookie = sign_session_cookie(session.session_id, adapter.secret_key)
test_client.cookies.set(adapter.session_cookie_name, signed_cookie)
# 1. get_current_identity yields the guest identity
resp_id = test_client.get("/test/identity")
assert resp_id.status_code == 200
assert resp_id.json()["authenticated"] is True
assert resp_id.json()["subject"] == "guest-001"
assert resp_id.json()["groups"] == ["guests"]
# 2. require_authenticated succeeds
resp_auth = test_client.get("/test/authenticated")
assert resp_auth.status_code == 200
assert resp_auth.json()["subject"] == "guest-001"
# 3. require_admin raises HTTP 403 Forbidden
resp_admin = test_client.get("/test/admin")
assert resp_admin.status_code == 403
assert "Forbidden" in resp_admin.json()["detail"]
def test_require_admin_success():
"""Authenticated admin user successfully yields Identity object on require_admin."""
admin_user = Identity(
def test_http_authenticated_admin_yields_identity_on_require_admin(
test_client: TestClient,
):
"""Authenticated admin user (admin@example.com with groups: ['bdinvite_admins']) yields Identity."""
adapter = get_auth_adapter()
admin_identity = 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"]
session = adapter.session_store.create_session(identity=admin_identity)
signed_cookie = sign_session_cookie(session.session_id, adapter.secret_key)
test_client.cookies.set(adapter.session_cookie_name, signed_cookie)
# 1. get_current_identity yields admin identity
resp_id = test_client.get("/test/identity")
assert resp_id.status_code == 200
assert resp_id.json()["subject"] == "admin-001"
# ============================================================================
# FastAPI Integration Tests (End-to-End Dependency Injection via TestClient)
# ============================================================================
# 2. require_authenticated yields admin identity
resp_auth = test_client.get("/test/authenticated")
assert resp_auth.status_code == 200
assert resp_auth.json()["subject"] == "admin-001"
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()
# 3. require_admin successfully yields the Identity object
resp_admin = test_client.get("/test/admin")
assert resp_admin.status_code == 200
data = resp_admin.json()
assert data["subject"] == "admin-001"
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"
def test_http_custom_group_requirement(test_client: TestClient):
"""require_group enforces arbitrary group membership correctly."""
adapter = get_auth_adapter()
# User without event_planners group -> 403
user_identity = Identity(
subject="user-planner-no",
email="planner_no@example.com",
groups=["volunteers"],
)
guest_headers = {"Authorization": f"Bearer {guest_tokens['id_token']}"}
session_no = adapter.session_store.create_session(identity=user_identity)
signed_no = sign_session_cookie(session_no.session_id, adapter.secret_key)
test_client.cookies.set(adapter.session_cookie_name, signed_no)
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_denied = test_client.get("/test/custom-group")
assert resp_denied.status_code == 403
resp_guest_admin = client.get("/admin", headers=guest_headers)
assert resp_guest_admin.status_code == 403
# User with event_planners group -> 200
planner_identity = Identity(
subject="user-planner-yes",
email="planner_yes@example.com",
groups=["volunteers", "event_planners"],
)
session_yes = adapter.session_store.create_session(identity=planner_identity)
signed_yes = sign_session_cookie(session_yes.session_id, adapter.secret_key)
test_client.cookies.set(adapter.session_cookie_name, signed_yes)
# 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_allowed = test_client.get("/test/custom-group")
assert resp_allowed.status_code == 200
assert resp_allowed.json()["subject"] == "user-planner-yes"
resp_admin = client.get("/admin", headers=admin_headers)
def test_http_bearer_token_authorization(
test_client: TestClient,
oidc_client: OIDCClient,
):
"""Bearer token containing admin groups satisfies require_admin; non-admin raises 403."""
# 1. Authenticate admin user against IdP to obtain verified ID token
admin_token_resp, _ = oidc_client.authenticate_with_password(
username="admin@example.com",
password="password123",
scopes=["openid", "profile", "email"],
)
admin_headers = {"Authorization": f"Bearer {admin_token_resp.id_token}"}
resp_admin = test_client.get("/test/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"]
assert resp_admin.json()["subject"] == "admin-001"
# 2. Authenticate guest user against IdP to obtain verified ID token
guest_token_resp, _ = oidc_client.authenticate_with_password(
username="guest@example.com",
password="password123",
scopes=["openid", "profile", "email"],
)
guest_headers = {"Authorization": f"Bearer {guest_token_resp.id_token}"}
resp_guest = test_client.get("/test/admin", headers=guest_headers)
assert resp_guest.status_code == 403
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
def test_http_remote_user_header_spoofing_rejected(test_client: TestClient):
"""Remote-User and other unverified request headers cannot spoof identity or bypass dependencies."""
spoof_headers = {
"Remote-User": "admin@example.com",
"X-Remote-User": "admin-001",
"X-User-Groups": "bdinvite_admins",
}
# All protected dependency endpoints reject unverified headers
resp_id = test_client.get("/test/identity", headers=spoof_headers)
assert resp_id.status_code == 200
assert resp_id.json() == {"authenticated": False, "identity": None}
resp_auth = test_client.get("/test/authenticated", headers=spoof_headers)
assert resp_auth.status_code == 401
resp_admin = test_client.get("/test/admin", headers=spoof_headers)
assert resp_admin.status_code == 401
def test_fastapi_dependency_overrides(test_app: FastAPI, test_client: TestClient):
"""FastAPI dependency_overrides works as expected with require_admin and get_current_identity."""
mock_admin = Identity(
subject="mock-admin",
email="mockadmin@example.com",
subject="mocked-admin",
email="mocked@example.com",
groups=["bdinvite_admins"],
)
test_app.dependency_overrides[get_current_identity] = lambda: mock_admin
resp = client.get("/admin")
test_app.dependency_overrides[require_admin] = lambda: mock_admin
try:
resp = test_client.get("/test/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
assert resp.json()["subject"] == "mocked-admin"
finally:
test_app.dependency_overrides.clear()
+278 -318
View File
@@ -1,373 +1,260 @@
"""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 fastapi import Request, Response
from app.auth import (
AuthPort,
Identity,
InvalidTokenError,
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"
LIVE_ISSUER = "http://localhost:8088/default"
CLIENT_ID = "bdinvite-client"
CLIENT_SECRET = "bdinvite-secret"
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,
def oidc_client() -> OIDCClient:
return OIDCClient(
issuer=LIVE_ISSUER,
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
groups_claim="groups",
)
@pytest.fixture
def oidc_client(oidc_config: OIDCConfig) -> OIDCClient:
return OIDCClient(oidc_config)
def create_request(
def create_dummy_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")))
raw_headers = [
(k.lower().encode("latin-1"), v.encode("latin-1"))
for k, v in (headers or {}).items()
]
if cookies:
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
header_list.append((b"cookie", cookie_header.encode("latin-1")))
raw_headers.append((b"cookie", cookie_header.encode("latin-1")))
scope = {
"type": "http",
"method": "GET",
"path": "/birthday/api/admin/rsvps",
"headers": header_list,
"query_string": b"",
"headers": raw_headers,
}
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():
def test_identity_resolution_standard_claims(oidc_client: OIDCClient):
"""Standard identity claims (sub, email, name, groups) map correctly to Identity domain model."""
claims = {
"groups": ["group1", "group2"],
"realm_access": {"roles": ["admin", "editor"]},
"deep": {"nested": {"path": ["value"]}},
"sub": "user-42",
"email": "user42@example.com",
"name": "Douglas Adams",
"groups": ["author", "scifi"],
}
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
identity = oidc_client.extract_identity(claims)
assert isinstance(identity, Identity)
assert identity.subject == "user-42"
assert identity.email == "user42@example.com"
assert identity.name == "Douglas Adams"
assert identity.groups == ["author", "scifi"]
assert identity.has_group("author") is True
assert identity.has_group("nonexistent") is False
def test_claims_to_identity_standard_mapping():
def test_identity_resolution_missing_email_and_name_defaults(oidc_client: OIDCClient):
"""Missing email falls back to synthetic local address, and missing name defaults to None."""
claims = {
"sub": "user_101",
"email": "user@example.com",
"name": "Normal User",
"groups": ["engineering", "security"],
"sub": "svc-worker-99",
}
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"]
identity = oidc_client.extract_identity(claims)
assert identity.subject == "svc-worker-99"
assert identity.email == f"svc-worker-99@{CLIENT_ID}.local"
assert identity.name is None
assert identity.groups == []
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(
def test_identity_resolution_missing_subject_raises_invalid_token(
oidc_client: OIDCClient,
):
"""Verify that unvalidated request headers (e.g. X-User, X-Email, X-Groups)
"""Missing or empty sub claim raises InvalidTokenError."""
with pytest.raises(InvalidTokenError, match="missing required 'sub' claim"):
oidc_client.extract_identity({})
CANNOT forge or inject an Identity. Application code must only trust
cryptographically verified authentication artifacts.
"""
adapter = OIDCAuthAdapter(client=oidc_client)
with pytest.raises(InvalidTokenError, match="missing required 'sub' claim"):
oidc_client.extract_identity({"sub": " ", "email": "valid@example.com"})
# 1. Attacker attempts to spoof admin identity via custom headers
spoof_req = create_request(
def test_identity_groups_extraction_clean_defaults(oidc_client: OIDCClient):
"""Missing, None, non-list, or empty groups claim cleanly defaults to empty list."""
# Missing groups key
assert oidc_client.extract_identity({"sub": "u1"}).groups == []
# None value
assert oidc_client.extract_identity({"sub": "u1", "groups": None}).groups == []
# Empty list
assert oidc_client.extract_identity({"sub": "u1", "groups": []}).groups == []
# Single string group
assert oidc_client.extract_identity(
{"sub": "u1", "groups": "single_role"}
).groups == ["single_role"]
# Tuple / Set collections
assert oidc_client.extract_identity(
{"sub": "u1", "groups": ("admin", "editor")}
).groups == ["admin", "editor"]
# Discard non-string, empty strings, and trim whitespace
claims = {"sub": "u1", "groups": [" admin ", "", " ", 123, None, "editor"]}
assert oidc_client.extract_identity(claims).groups == ["admin", "editor"]
# Deduplicate while preserving order
claims_dup = {"sub": "u1", "groups": ["alpha", "beta", "alpha", "gamma", "beta"]}
assert oidc_client.extract_identity(claims_dup).groups == ["alpha", "beta", "gamma"]
def test_identity_groups_configurable_claim_path():
"""Group extraction respects configured group claim path, including nested paths."""
# Custom top-level path
custom_client = OIDCClient(
issuer=LIVE_ISSUER,
client_id=CLIENT_ID,
groups_claim="roles",
)
claims = {"sub": "u1", "roles": ["superadmin", "operator"], "groups": ["ignored"]}
assert custom_client.extract_identity(claims).groups == ["superadmin", "operator"]
# Nested path (e.g. Keycloak realm_access.roles)
nested_client = OIDCClient(
issuer=LIVE_ISSUER,
client_id=CLIENT_ID,
groups_claim="realm_access.roles",
)
claims_nested = {
"sub": "u1",
"realm_access": {"roles": ["app_admin", "user"]},
}
assert nested_client.extract_identity(claims_nested).groups == ["app_admin", "user"]
# Nested path missing
assert (
nested_client.extract_identity({"sub": "u1", "realm_access": {}}).groups == []
)
assert nested_client.extract_identity({"sub": "u1"}).groups == []
# ==============================================================================
# 2. Seeded Fixture Users Verification (Live Integration)
# ==============================================================================
def test_live_fixture_admin_user_authentication(oidc_client: OIDCClient):
"""Authenticating with admin@example.com resolves to Identity with bdinvite_admins group."""
token_resp, identity = oidc_client.authenticate_with_password(
username="admin@example.com",
password="password123",
scopes=["openid", "profile", "email"],
)
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 identity.has_group("bdinvite_admins") is True
assert identity.has_group("guests") is False
# Verify ID token claims match domain model
assert token_resp.claims["sub"] == "admin-001"
assert token_resp.claims["email"] == "admin@example.com"
assert token_resp.claims["groups"] == ["bdinvite_admins"]
def test_live_fixture_guest_user_authentication(oidc_client: OIDCClient):
"""Authenticating with guest@example.com resolves to Identity with guests group."""
token_resp, identity = oidc_client.authenticate_with_password(
username="guest@example.com",
password="password123",
scopes=["openid", "profile", "email"],
)
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 identity.has_group("guests") is True
assert identity.has_group("bdinvite_admins") is False
# Verify ID token claims match domain model
assert token_resp.claims["sub"] == "guest-001"
assert token_resp.claims["email"] == "guest@example.com"
assert token_resp.claims["groups"] == ["guests"]
# ==============================================================================
# 3. Identity Origin Integrity & Immutability Tests
# ==============================================================================
def test_identity_origin_integrity_rejection_of_unvalidated_request_headers(
oidc_client: OIDCClient,
):
"""Application adapter rejects constructing Identity from raw request headers or client data."""
adapter = OIDCAuthAdapter(oidc_client=oidc_client)
# Attacker passes spoofed Remote-User or X-User headers
spoofed_request = create_dummy_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",
"Remote-User": "admin@example.com",
"Remote-Groups": "bdinvite_admins",
"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
# Adapter must strictly refuse to manufacture an Identity from unvalidated request headers
resolved = adapter.current_identity(spoofed_request)
assert resolved 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"],
def test_identity_origin_integrity_rejection_of_tampered_token(oidc_client: OIDCClient):
"""Identity cannot be extracted from a tampered or forged token."""
# Obtain a genuine token for admin
token_resp, _ = oidc_client.authenticate_with_password(
username="admin@example.com",
password="password123",
)
session_id = adapter.establish_session(legit_identity)
valid_id_token = token_resp.id_token
valid_session_req = create_request(cookies={"session_id": session_id})
assert adapter.current_identity(valid_session_req) == legit_identity
# Case 1: Tampered signature
tampered_sig_token = valid_id_token[:-10] + "FORGED_SIG"
with pytest.raises(InvalidTokenError):
oidc_client.extract_identity_from_token(tampered_sig_token)
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}"}
# Case 2: Adapter with tampered token in Authorization header returns None
bad_request = create_dummy_request(
headers={"Authorization": f"Bearer {tampered_sig_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
adapter = OIDCAuthAdapter(oidc_client=oidc_client)
assert adapter.current_identity(bad_request) is None
# ============================================================================
# 4. Identity Immutability Tests
# ============================================================================
def test_identity_frozen_immutability():
"""Verify that domain Identity instances cannot be mutated at runtime."""
def test_identity_immutability():
"""Identity instance is frozen and cannot be mutated after creation."""
identity = Identity(
subject="admin-001",
email="admin@example.com",
@@ -376,13 +263,86 @@ def test_identity_frozen_immutability():
)
with pytest.raises(FrozenInstanceError):
identity.subject = "hacker" # type: ignore[misc]
identity.groups = ["guests"] # type: ignore[misc]
with pytest.raises(FrozenInstanceError):
identity.email = "hacker@example.com" # type: ignore[misc]
identity.subject = "hacked-sub" # type: ignore[misc]
with pytest.raises(FrozenInstanceError):
identity.name = "Hacker" # type: ignore[misc]
identity.email = "hacked@example.com" # type: ignore[misc]
with pytest.raises(FrozenInstanceError):
identity.groups = ["superusers"] # type: ignore[misc]
# ==============================================================================
# 4. AuthPort Protocol Conformance & Adapter Tests
# ==============================================================================
def test_oidc_auth_adapter_conforms_to_auth_port(oidc_client: OIDCClient):
"""OIDCAuthAdapter satisfies the AuthPort protocol runtime contract."""
adapter = OIDCAuthAdapter(oidc_client=oidc_client)
assert isinstance(adapter, AuthPort)
def test_oidc_auth_adapter_current_identity_with_valid_bearer(oidc_client: OIDCClient):
"""OIDCAuthAdapter extracts valid Identity from Authorization: Bearer token."""
token_resp, expected_identity = oidc_client.authenticate_with_password(
username="admin@example.com",
password="password123",
)
adapter = OIDCAuthAdapter(oidc_client=oidc_client)
req = create_dummy_request(
headers={"Authorization": f"Bearer {token_resp.id_token}"}
)
resolved = adapter.current_identity(req)
assert resolved == expected_identity
assert resolved is not None
assert resolved.subject == "admin-001"
assert resolved.has_group("bdinvite_admins") is True
def test_oidc_auth_adapter_current_identity_with_valid_cookie(oidc_client: OIDCClient):
"""OIDCAuthAdapter extracts valid Identity from session cookie."""
token_resp, expected_identity = oidc_client.authenticate_with_password(
username="guest@example.com",
password="password123",
)
adapter = OIDCAuthAdapter(
oidc_client=oidc_client, session_cookie_name="bdinvite_session"
)
req = create_dummy_request(cookies={"bdinvite_session": token_resp.id_token})
resolved = adapter.current_identity(req)
assert resolved == expected_identity
assert resolved is not None
assert resolved.subject == "guest-001"
assert resolved.has_group("guests") is True
def test_oidc_auth_adapter_login_redirect(oidc_client: OIDCClient):
"""OIDCAuthAdapter login returns 302 redirect to OIDC authorization endpoint."""
adapter = OIDCAuthAdapter(oidc_client=oidc_client)
req = create_dummy_request()
response = adapter.login(req)
assert isinstance(response, Response)
assert response.status_code == 302
assert "location" in response.headers
assert response.headers["location"].startswith(f"{LIVE_ISSUER}/authorize?")
def test_oidc_auth_adapter_logout_redirect_and_clears_cookie(oidc_client: OIDCClient):
"""OIDCAuthAdapter logout returns 302 redirect and deletes the session cookie."""
adapter = OIDCAuthAdapter(
oidc_client=oidc_client, session_cookie_name="bdinvite_session"
)
req = create_dummy_request()
response = adapter.logout(req)
assert isinstance(response, Response)
assert response.status_code == 302
# Verify cookie deletion header exists
assert "set-cookie" in response.headers
assert "bdinvite_session" in response.headers["set-cookie"]
+37 -12
View File
@@ -9,6 +9,7 @@ from app.services.map_preview import (
is_google_maps_host,
validate_google_maps_url_format,
)
from tests.conftest import login_client
def test_is_google_maps_host():
@@ -28,7 +29,9 @@ def test_is_google_maps_host():
def test_validate_google_maps_url_format():
validate_google_maps_url_format("https://maps.app.goo.gl/354784424357732")
validate_google_maps_url_format("https://www.google.com/maps/place/Fresco/@34.1,-118.2,17z")
validate_google_maps_url_format(
"https://www.google.com/maps/place/Fresco/@34.1,-118.2,17z"
)
validate_google_maps_url_format("https://maps.google.com/?q=34.1,-118.2")
with pytest.raises(ValueError, match="no puede estar vacía"):
@@ -43,23 +46,33 @@ def test_validate_google_maps_url_format():
def test_extract_coordinates_from_text():
# 1. @lat,lng
coords = extract_coordinates_from_text("https://google.com/maps/place/Venue/@34.143245,-118.255132,17z")
coords = extract_coordinates_from_text(
"https://google.com/maps/place/Venue/@34.143245,-118.255132,17z"
)
assert coords == (34.143245, -118.255132)
# 2. !3dlat!4dlng
coords = extract_coordinates_from_text("https://google.com/maps/data=!4m6!3m5!1s0x0!8m2!3d4.6534!4d-74.0564")
coords = extract_coordinates_from_text(
"https://google.com/maps/data=!4m6!3m5!1s0x0!8m2!3d4.6534!4d-74.0564"
)
assert coords == (4.6534, -74.0564)
# 3. Query params: q=lat,lng
coords = extract_coordinates_from_text("https://maps.google.com/?q=34.1432,-118.2551")
coords = extract_coordinates_from_text(
"https://maps.google.com/?q=34.1432,-118.2551"
)
assert coords == (34.1432, -118.2551)
# 4. Query params: ll=lat,lng
coords = extract_coordinates_from_text("https://maps.google.com/maps?ll=34.1432,-118.2551&z=16")
coords = extract_coordinates_from_text(
"https://maps.google.com/maps?ll=34.1432,-118.2551&z=16"
)
assert coords == (34.1432, -118.2551)
# 5. Non-coordinate text
assert extract_coordinates_from_text("https://maps.google.com/?q=Eiffel+Tower") is None
assert (
extract_coordinates_from_text("https://maps.google.com/?q=Eiffel+Tower") is None
)
def test_deg2num():
@@ -70,16 +83,22 @@ def test_deg2num():
@patch("app.routes.admin.resolve_google_maps_coordinates")
@patch("app.routes.admin.generate_map_preview_image")
def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client, admin_client, tmp_path):
def test_admin_generate_map_preview_endpoint(
mock_generate, mock_resolve, client, tmp_path
):
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
mock_generate.return_value = tmp_path / "map_preview.png"
# Test without auth -> 401
resp = client.post("/birthday/api/admin/map-preview/generate", json={"map_url": "https://maps.google.com/?q=34.1,-118.2"})
resp = client.post(
"/birthday/api/admin/map-preview/generate",
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
)
assert resp.status_code == 401
# Test with auth -> 200
resp = admin_client.post(
login_client(client)
resp = client.post(
"/birthday/api/admin/map-preview/generate",
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
)
@@ -88,13 +107,17 @@ def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client
assert "/birthday/api/map-preview.png" in data["map_preview_url"]
assert data["lat"] == 34.1432
assert data["lng"] == -118.2551
mock_resolve.assert_called_once_with("https://maps.google.com/?q=34.1,-118.2", fallback_query=ANY)
mock_resolve.assert_called_once_with(
"https://maps.google.com/?q=34.1,-118.2", fallback_query=ANY
)
mock_generate.assert_called_once_with(34.1432, -118.2551)
@patch("app.routes.admin.resolve_google_maps_coordinates")
@patch("app.routes.admin.generate_map_preview_image")
def test_config_update_triggers_generator_only_when_map_url_changes(mock_generate, mock_resolve, admin_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_generate.return_value = tmp_path / "map_preview.png"
@@ -118,7 +141,9 @@ def test_config_update_triggers_generator_only_when_map_url_changes(mock_generat
assert resp.status_code == 200
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"
mock_resolve.assert_called_once_with("https://maps.google.com/?q=34.1432,-118.2551", fallback_query=ANY)
mock_resolve.assert_called_once_with(
"https://maps.google.com/?q=34.1432,-118.2551", fallback_query=ANY
)
mock_generate.assert_called_once_with(34.1432, -118.2551)
+240 -245
View File
@@ -1,325 +1,320 @@
"""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 urllib.parse
import httpx
import pytest
from fastapi import HTTPException
from app.auth import (
AuthPort,
Identity,
InvalidNonceError,
InvalidStateError,
OIDCAuthAdapter,
InvalidTokenError,
MismatchedNonceError,
OIDCClient,
OIDCConfig,
OIDCTransaction,
TokenValidationError,
generate_code_challenge,
compute_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"
LIVE_ISSUER = "http://localhost:8088/default"
CLIENT_ID = "bdinvite-client"
CLIENT_SECRET = "bdinvite-secret"
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,
def oidc_client() -> OIDCClient:
return OIDCClient(
issuer=LIVE_ISSUER,
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=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,
def test_pkce_generation_and_challenge():
"""Verify PKCE code_verifier generation and S256 derivation per RFC 7636."""
verifier = generate_code_verifier(64)
assert len(verifier) == 64
# RFC 7636 Section 4.1 unreserved characters
unreserved = set(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"
)
assert resp.status_code == 302, f"Expected 302 redirect, got {resp.status_code}: {resp.text}"
location = resp.headers["location"]
assert all(c in unreserved for c in verifier)
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}"
# Length bounds validation
with pytest.raises(ValueError, match="between 43 and 128"):
generate_code_verifier(42)
with pytest.raises(ValueError, match="between 43 and 128"):
generate_code_verifier(129)
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"
# RFC 7636 Appendix B test vector verification
appendix_b_verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
expected_challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
derived_challenge = generate_code_challenge(rfc_verifier)
derived_challenge = compute_code_challenge(appendix_b_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_state_and_nonce_generation():
"""Verify cryptographic randomness and uniqueness for state and nonce."""
s1 = generate_state()
s2 = generate_state()
assert len(s1) >= 32
assert s1 != s2
n1 = generate_nonce()
n2 = generate_nonce()
assert len(n1) >= 32
assert n1 != n2
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_dynamic_discovery_parsing(oidc_client: OIDCClient):
"""Dynamic discovery configuration is fetched and parsed correctly from the issuer."""
doc = oidc_client.get_discovery_document()
assert doc["issuer"] == LIVE_ISSUER
assert oidc_client.authorization_endpoint == f"{LIVE_ISSUER}/authorize"
assert oidc_client.token_endpoint == f"{LIVE_ISSUER}/token"
assert oidc_client.jwks_uri == f"{LIVE_ISSUER}/jwks"
# Cached discovery returns identical object without additional fetch
doc_cached = oidc_client.get_discovery_document()
assert doc_cached is doc
def test_dynamic_discovery_failure():
"""Unreachable or invalid discovery URL raises DiscoveryError with HTTP 502."""
from app.auth.oidc import DiscoveryError
broken_client = OIDCClient(
issuer="http://localhost:59999/nonexistent",
client_id=CLIENT_ID,
redirect_uri=REDIRECT_URI,
timeout=1.0,
)
with pytest.raises(DiscoveryError) as exc_info:
broken_client.get_discovery_document()
assert exc_info.value.status_code == 502
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()
"""Authorization request contains required PKCE challenge, state, and nonce parameters."""
auth_req = oidc_client.create_authorization_url()
parsed = urlparse(auth_url)
parsed = urllib.parse.urlparse(auth_req.url)
assert parsed.scheme == "http"
assert parsed.netloc == "localhost:8088"
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"]
qs = urllib.parse.parse_qs(parsed.query)
assert qs["response_type"] == ["code"]
assert qs["client_id"] == [CLIENT_ID]
assert qs["redirect_uri"] == [REDIRECT_URI]
assert qs["state"] == [auth_req.state]
assert qs["nonce"] == [auth_req.nonce]
assert qs["code_challenge_method"] == ["S256"]
# 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
# Verify code_challenge matches SHA256 of code_verifier
expected_challenge = compute_code_challenge(auth_req.code_verifier)
assert qs["code_challenge"] == [expected_challenge]
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
def test_rejection_of_invalid_state_400(oidc_client: OIDCClient):
"""Rejection of missing or unregistered state with HTTP 400."""
with pytest.raises(InvalidStateError) as exc_info:
oidc_client.validate_state("non_existent_state_value")
oidc_client.validate_state("unregistered_state_token")
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)
oidc_client.validate_state(None) # type: ignore[arg-type]
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,
# In exchange_code, untracked state must also be rejected with HTTP 400
with pytest.raises(InvalidStateError) as exc_info:
oidc_client.exchange_code(code="dummy_code", state="unregistered_state")
assert exc_info.value.status_code == 400
def test_live_oidc_successful_code_exchange_and_id_token_validation(
oidc_client: OIDCClient,
):
"""End-to-end integration test: code exchange, ID token validation, and Identity extraction."""
# 1. Create authorization request with PKCE and transaction secrets
auth_req = oidc_client.create_authorization_url()
# 2. Simulate authorization sign-in against mock OIDC provider
with httpx.Client() as http:
resp = http.post(
auth_req.url,
data={
"username": "alice",
"claims": json.dumps(
{
"email": "alice@example.com",
"name": "Alice In Chains",
"groups": ["family", "vip"],
}
),
},
follow_redirects=False,
)
oidc_client._transactions[expired_tx.state] = expired_tx
assert resp.status_code == 302, (
f"Expected 302 redirect from mock IdP, got {resp.status_code}"
)
redirect_url = resp.headers["location"]
with pytest.raises(InvalidStateError) as exc_info:
oidc_client.validate_state(expired_tx.state)
assert exc_info.value.status_code == 400
qs = urllib.parse.parse_qs(urllib.parse.urlparse(redirect_url).query)
assert "code" in qs
assert qs["state"] == [auth_req.state]
code = qs["code"][0]
# 3. Exchange authorization code with token endpoint
token_resp = oidc_client.exchange_code(code=code, state=auth_req.state)
# 4. Verify cryptographic validation and claim assertions
assert token_resp.id_token
assert token_resp.token_type == "Bearer"
assert token_resp.claims["iss"] == LIVE_ISSUER
assert token_resp.claims["aud"] == CLIENT_ID
assert token_resp.claims["nonce"] == auth_req.nonce
assert token_resp.claims["sub"] in ["alice", "admin-001"]
assert token_resp.claims["email"] == "alice@example.com"
assert token_resp.claims["name"] == "Alice In Chains"
assert token_resp.claims["groups"] == ["family", "vip"]
# 5. Verify mapping to Identity domain model
identity = oidc_client.extract_identity(token_resp.claims)
assert isinstance(identity, Identity)
assert identity.subject in ["alice", "admin-001"]
assert identity.email == "alice@example.com"
assert identity.name == "Alice In Chains"
assert identity.groups == ["family", "vip"]
assert identity.has_group("vip") is True
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")
def test_rejection_of_mismatched_nonce_401(oidc_client: OIDCClient):
"""Rejection of mismatched nonce claim in returned ID token with HTTP 401."""
auth_req = oidc_client.create_authorization_url()
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"]
with httpx.Client() as http:
resp = http.post(
auth_req.url,
data={"username": "bob"},
follow_redirects=False,
)
redirect_url = resp.headers["location"]
# Validate with mismatched nonce
with pytest.raises(InvalidNonceError) as exc_info:
oidc_client.validate_id_token(id_token=id_token, nonce="completely_different_nonce")
code = urllib.parse.parse_qs(urllib.parse.urlparse(redirect_url).query)["code"][0]
token_resp = oidc_client.exchange_code(code=code, state=auth_req.state)
# Verifying valid token against wrong nonce MUST raise MismatchedNonceError (HTTP 401)
with pytest.raises(MismatchedNonceError) as exc_info:
oidc_client.verify_id_token(
token_resp.id_token, nonce="completely_different_nonce"
)
assert exc_info.value.status_code == 401
assert "does not match expected nonce" in str(exc_info.value.detail)
# 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
# Verifying with the correct nonce succeeds
verified = oidc_client.verify_id_token(token_resp.id_token, nonce=auth_req.nonce)
assert verified["sub"] in ["bob", "admin-001"]
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")
def test_rejection_of_tampered_id_token_signature_401(oidc_client: OIDCClient):
"""Rejection of tampered ID token signature with HTTP 401."""
auth_req = oidc_client.create_authorization_url()
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"]
with httpx.Client() as http:
resp = http.post(
auth_req.url,
data={"username": "charlie"},
follow_redirects=False,
)
redirect_url = resp.headers["location"]
# Valid token passes verification
oidc_client.validate_id_token(id_token=valid_id_token, nonce=validated_tx.nonce)
code = urllib.parse.parse_qs(urllib.parse.urlparse(redirect_url).query)["code"][0]
token_resp = oidc_client.exchange_code(code=code, state=auth_req.state)
original_id_token = token_resp.id_token
# 1. Tamper signature segment: change the last few characters of the signature
parts = valid_id_token.split(".")
# Case 1: Tamper the cryptographic signature portion
tampered_sig_token = original_id_token[:-12] + "TAMPERED_SIG"
with pytest.raises(InvalidTokenError) as exc_info:
oidc_client.verify_id_token(tampered_sig_token, nonce=auth_req.nonce)
assert exc_info.value.status_code == 401
assert "signature is invalid or tampered" in str(exc_info.value.detail)
# Case 2: Tamper the payload while preserving original signature
parts = original_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("=")
# Decode and tamper payload
payload_raw = parts[1] + "=="
payload = json.loads(base64.urlsafe_b64decode(payload_raw))
payload["sub"] = "mallory_attacker"
tampered_payload_b64 = (
base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
)
tampered_payload_token = f"{header_b64}.{new_payload_b64}.{sig_b64}"
tampered_payload_token = f"{parts[0]}.{tampered_payload_b64}.{parts[2]}"
with pytest.raises(TokenValidationError) as exc_info:
oidc_client.validate_id_token(id_token=tampered_payload_token, nonce=validated_tx.nonce)
with pytest.raises(InvalidTokenError) as exc_info:
oidc_client.verify_id_token(tampered_payload_token, nonce=auth_req.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")
def test_rejection_of_wrong_issuer_and_audience_401(oidc_client: OIDCClient):
"""Rejection of ID token when issuer or audience does not match client configuration."""
auth_req = oidc_client.create_authorization_url()
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"]
with httpx.Client() as http:
resp = http.post(
auth_req.url,
data={"username": "david"},
follow_redirects=False,
)
redirect_url = resp.headers["location"]
# 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,
code = urllib.parse.parse_qs(urllib.parse.urlparse(redirect_url).query)["code"][0]
token_resp = oidc_client.exchange_code(code=code, state=auth_req.state)
# Client configured with mismatched audience
wrong_aud_client = OIDCClient(
issuer=LIVE_ISSUER,
client_id="other-audience-client",
redirect_uri=REDIRECT_URI,
)
)
with pytest.raises(TokenValidationError) as exc_info:
client_wrong_aud.validate_id_token(id_token=id_token, nonce=validated_tx.nonce)
with pytest.raises(InvalidTokenError) as exc_info:
wrong_aud_client.verify_id_token(token_resp.id_token, nonce=auth_req.nonce)
assert exc_info.value.status_code == 401
assert "claims validation failed" in str(exc_info.value.detail)
# 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,
# Client configured with mismatched issuer
wrong_iss_client = OIDCClient(
issuer="http://localhost:8088/wrong_issuer",
client_id=CLIENT_ID,
redirect_uri=REDIRECT_URI,
discovery_doc=oidc_client.get_discovery_document(),
)
)
# 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)
with pytest.raises(InvalidTokenError) as exc_info:
wrong_iss_client.verify_id_token(token_resp.id_token, nonce=auth_req.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
def test_architectural_isolation_no_domain_route_crypto_imports():
"""Verify architectural isolation: zero application domain routes import OIDC/crypto directly."""
import pathlib
auth_url, transaction = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="async_user")
routes_dir = pathlib.Path(__file__).parent.parent / "app" / "routes"
disallowed_terms = ["jwt", "cryptography", "PyJWKClient", "OIDCClient"]
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"]
for route_file in routes_dir.glob("*.py"):
content = route_file.read_text(encoding="utf-8")
for term in disallowed_terms:
assert f"import {term}" not in content, (
f"{route_file.name} violates isolation by importing {term}"
)
assert f"from {term}" not in content, (
f"{route_file.name} violates isolation by importing from {term}"
)
+331 -390
View File
@@ -1,511 +1,452 @@
"""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 urllib.parse
from pathlib import Path
import httpx
import pytest
from fastapi.testclient import TestClient
from app.auth import (
Identity,
InvalidCodeVerifierError,
InvalidNonceError,
InvalidPKCEError,
InvalidStateError,
OIDCAuthAdapter,
InvalidTokenError,
MismatchedNonceError,
OIDCClient,
OIDCConfig,
OIDCTransaction,
SessionRecord,
TokenValidationError,
get_auth_adapter,
)
from app.config import Settings
from tests.conftest import login_client
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"
LIVE_ISSUER = "http://localhost:8088/default"
CLIENT_ID = "bdinvite-client"
CLIENT_SECRET = "bdinvite-secret"
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,
@pytest.fixture
def oidc_client() -> OIDCClient:
return OIDCClient(
issuer=LIVE_ISSUER,
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
)
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
# 1. CSRF State Hardening: Forged / Invalid / Expired State returns HTTP 400
# ==============================================================================
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(
def test_forged_or_invalid_csrf_state_returns_400(
client: TestClient, oidc_client: OIDCClient
):
"""Forged, tampered, missing, or expired CSRF state returns HTTP 400 Bad Request."""
# 1. Direct unit assertion: oidc_client rejects unknown state with InvalidStateError (400)
with pytest.raises(InvalidStateError) as exc_info:
oidc_client.validate_state("forged_attacker_state_token")
assert exc_info.value.status_code == 400
assert "Invalid or expired state" in exc_info.value.detail
with pytest.raises(InvalidStateError) as exc_info_empty:
oidc_client.validate_state("")
assert exc_info_empty.value.status_code == 400
# 2. HTTP callback endpoint with forged state -> 400 Bad Request
res_forged = client.get(
"/birthday/api/auth/callback",
params={"code": "dummy_auth_code", "state": "forged_malicious_state_xyz"},
params={"code": "dummy_authorization_code", "state": "forged_csrf_state"},
)
assert res.status_code == 400
assert "detail" in res.json()
assert res_forged.status_code == 400
assert "state" in res_forged.json().get("detail", "").lower()
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(
# 3. HTTP callback endpoint with empty state -> 400 Bad Request
res_empty = client.get(
"/birthday/api/auth/callback",
params={"code": code, "state": returned_state},
follow_redirects=False,
params={"code": "dummy_authorization_code", "state": ""},
)
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()
assert res_empty.status_code == 400
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()
def test_replayed_csrf_state_returns_400(oidc_client: OIDCClient):
"""CSRF state token is single-use: replay after successful validation returns HTTP 400."""
auth_req = oidc_client.create_authorization_url()
state = auth_req.state
# 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
# First consumption succeeds
tx = oidc_client.validate_state(state)
assert tx.state == state
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()
# Replaying same state fails with HTTP 400
with pytest.raises(InvalidStateError) as exc_info:
oidc_client.validate_state(state)
assert exc_info.value.status_code == 400
# ==============================================================================
# 2. Forged / Tampered ID Token Signature -> HTTP 401 Unauthorized
# 2. Cryptographic Signature Hardening: Forged / Tampered Token returns HTTP 401
# ==============================================================================
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"]
def test_forged_or_tampered_id_token_signature_returns_401(oidc_client: OIDCClient):
"""Forged or tampered ID token signature is rejected cryptographically with HTTP 401 Unauthorized."""
# Obtain a genuine token response from the live OIDC test fixture
token_resp, _ = oidc_client.authenticate_with_password(
username="admin@example.com",
password="password123",
)
valid_id_token = token_resp.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}"
# Case A: Corrupted cryptographic signature
tampered_sig_token = f"{parts[0]}.{parts[1]}.CORRUPTED_SIGNATURE_BYTES"
with pytest.raises(InvalidTokenError) as exc_info_sig:
oidc_client.verify_id_token(tampered_sig_token)
assert exc_info_sig.value.status_code == 401
assert "signature is invalid or tampered" in str(exc_info_sig.value.detail).lower()
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}"},
# Case B: Tampered payload (privilege escalation attempt) with original signature
payload_bytes = base64.urlsafe_b64decode(parts[1] + "==")
claims = json.loads(payload_bytes)
claims["sub"] = "hacked_admin_identity"
claims["groups"] = ["bdinvite_admins", "root"]
tampered_payload_b64 = (
base64.urlsafe_b64encode(json.dumps(claims).encode()).decode().rstrip("=")
)
assert res.status_code == 401
tampered_token = f"{parts[0]}.{tampered_payload_b64}.{parts[2]}"
with pytest.raises(InvalidTokenError) as exc_info_tampered:
oidc_client.verify_id_token(tampered_token)
assert exc_info_tampered.value.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
# Case C: Malformed non-JWT string
with pytest.raises(InvalidTokenError) as exc_info_malformed:
oidc_client.verify_id_token("not-a-valid-jwt-token-at-all")
assert exc_info_malformed.value.status_code == 401
# ==============================================================================
# 3. Mismatched or Replayed Nonce -> HTTP 401 Unauthorized
# 3. Nonce Verification & Replay Protection: Mismatched Nonce returns HTTP 401
# ==============================================================================
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"]
def test_mismatched_or_replayed_nonce_returns_401(oidc_client: OIDCClient):
"""Mismatched or missing nonce in ID token returns HTTP 401 Unauthorized."""
auth_req = oidc_client.create_authorization_url()
with pytest.raises(InvalidNonceError) as exc_info:
adapter.client.validate_id_token(id_token=id_token, nonce="completely_different_nonce_val")
with httpx.Client() as http:
resp = http.post(
auth_req.url,
data={"username": "guest@example.com"},
follow_redirects=False,
)
assert resp.status_code == 302
redirect_url = resp.headers["location"]
code = urllib.parse.parse_qs(urllib.parse.urlparse(redirect_url).query)["code"][0]
token_resp = oidc_client.exchange_code(code=code, state=auth_req.state)
token = token_resp.id_token
# Case A: Valid token verified against a mismatched expected nonce -> 401
with pytest.raises(MismatchedNonceError) as exc_info:
oidc_client.verify_id_token(token, nonce="forged_or_replayed_nonce_999")
assert exc_info.value.status_code == 401
assert "nonce" in exc_info.value.detail.lower()
assert "does not match expected nonce" in str(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()
# Case B: Correct nonce succeeds
verified = oidc_client.verify_id_token(token, nonce=auth_req.nonce)
assert verified["nonce"] == auth_req.nonce
# ==============================================================================
# 4. Missing or Invalid PKCE code_verifier -> HTTP 401 Unauthorized
# 4. PKCE Verification: Missing or Invalid code_verifier returns HTTP 401
# ==============================================================================
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_missing_or_invalid_pkce_code_verifier_returns_401(oidc_client: OIDCClient):
"""Missing, out-of-range, or invalid PKCE code_verifier returns HTTP 401 Unauthorized."""
# Case A: Missing code_verifier when state is None -> 401
with pytest.raises(InvalidPKCEError) as exc_missing:
oidc_client.exchange_code(code="test_code", code_verifier=None)
assert exc_missing.value.status_code == 401
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")
# Case B: Empty code_verifier -> 401
with pytest.raises(InvalidPKCEError) as exc_empty:
oidc_client.exchange_code(code="test_code", code_verifier=" ")
assert exc_empty.value.status_code == 401
# 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
# Case C: code_verifier too short (< 43 characters per RFC 7636) -> 401
with pytest.raises(InvalidPKCEError) as exc_short:
oidc_client.exchange_code(code="test_code", code_verifier="short_verifier_123")
assert exc_short.value.status_code == 401
# Case D: code_verifier too long (> 128 characters) -> 401
with pytest.raises(InvalidPKCEError) as exc_long:
oidc_client.exchange_code(code="test_code", code_verifier="a" * 129)
assert exc_long.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
# Case E: code_verifier with invalid characters (non-unreserved) -> 401
with pytest.raises(InvalidPKCEError) as exc_invalid_chars:
oidc_client.exchange_code(
code="test_code",
code_verifier="valid_length_verifier_with_illegal_characters_$$$$$!@@@#%^&*()",
)
assert exc_invalid_chars.value.status_code == 401
# Case F: Integration with mock OIDC server: valid code exchanged with mismatched code_verifier -> 401
auth_req = oidc_client.create_authorization_url()
with httpx.Client() as http:
resp = http.post(
auth_req.url,
data={"username": "guest@example.com"},
follow_redirects=False,
)
assert resp.status_code == 302
code = urllib.parse.parse_qs(
urllib.parse.urlparse(resp.headers["location"]).query
)["code"][0]
with pytest.raises(InvalidPKCEError) as exc_mismatch:
oidc_client.exchange_code(
code=code,
code_verifier="mismatched_code_verifier_that_does_not_hash_to_the_challenge_123456",
nonce=auth_req.nonce,
)
assert exc_mismatch.value.status_code == 401
assert "pkce verification failed" in str(exc_mismatch.value.detail).lower()
# ==============================================================================
# 5. Expired ID Token / Expired Session Cookie -> HTTP 401 Unauthorized
# 5. Token & Session Expiration: Expired ID Token / Cookie returns HTTP 401
# ==============================================================================
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 test_expired_id_token_returns_401(
oidc_client: OIDCClient, monkeypatch: pytest.MonkeyPatch
):
"""Expired ID token is rejected with HTTP 401 Unauthorized."""
import datetime
def mock_decode(*args, **kwargs):
raise pyjwt.ExpiredSignatureError("Signature has expired")
import jwt.api_jwt
monkeypatch.setattr("jwt.decode", mock_decode)
# Obtain a genuine token to get signing key and claims structure
token_resp, _ = oidc_client.authenticate_with_password(
username="guest@example.com",
password="password123",
)
with pytest.raises(TokenValidationError) as exc_info:
adapter.client.validate_id_token("expired.jwt.token")
# Valid token verified with current time passes
verified = oidc_client.verify_id_token(token_resp.id_token)
assert verified["sub"] == "guest-001"
# Fast forward time into the future past token exp claim
class FutureDateTime(datetime.datetime):
@classmethod
def now(cls, tz=None):
return datetime.datetime(2099, 1, 1, tzinfo=tz)
monkeypatch.setattr(jwt.api_jwt, "datetime", FutureDateTime)
with pytest.raises(InvalidTokenError) as exc_info:
oidc_client.verify_id_token(token_resp.id_token)
assert exc_info.value.status_code == 401
assert "expired" in exc_info.value.detail.lower()
assert "expired" in str(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."""
"""Expired session cookie returns HTTP 401 Unauthorized across all protected endpoints."""
login_client(client, email="admin@example.com", groups=["bdinvite_admins"])
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")
# Manually expire the session in the session store
cookie_val = client.cookies.get(adapter.session_cookie_name)
assert cookie_val is not None
session_id = adapter.parse_session_cookie(cookie_val)
assert session_id is not None
session = adapter.session_store.get_session(session_id)
assert session is not None
session.created_at = time.time() - 99999 # Far in the past
session.expires_at = time.time() - 100.0 # Expired
# Request with expired session returns HTTP 401
res_me = client.get("/birthday/api/auth/me")
assert res_me.status_code == 401
assert res_me.json() == {"detail": "Not authenticated"}
res_admin = client.get("/birthday/api/admin/rsvps")
assert res_admin.status_code == 401
assert res_admin.json() == {"detail": "Not authenticated"}
res_config = client.get("/birthday/api/admin/config")
assert res_config.status_code == 401
assert res_config.json() == {"detail": "Not authenticated"}
def test_tampered_session_cookie_signature_returns_401(client: TestClient):
"""Session cookie with tampered cryptographic signature returns HTTP 401 Unauthorized."""
login_client(client, email="admin@example.com", groups=["bdinvite_admins"])
adapter = get_auth_adapter()
valid_cookie = client.cookies.get(adapter.session_cookie_name)
assert valid_cookie is not None
# Tamper cookie signature
tampered_cookie = valid_cookie[:-6] + "BADSIG"
client.cookies.set(adapter.session_cookie_name, tampered_cookie)
res = client.get("/birthday/api/auth/me")
assert res.status_code == 401
# Session record must be revoked
assert session_id not in adapter.sessions
res_admin = client.get("/birthday/api/admin/rsvps")
assert res_admin.status_code == 401
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"],
# ==============================================================================
# 6. Authorization Barrier: Authenticated Non-Admin returns HTTP 403 Forbidden
# ==============================================================================
def test_authenticated_non_admin_accessing_admin_apis_returns_403(
guest_client: TestClient,
):
"""Authenticated non-admin user (guest@example.com with groups: ['guests']) receives HTTP 403."""
admin_endpoints = [
("GET", "/birthday/api/admin/rsvps"),
("DELETE", "/birthday/api/admin/rsvps/1"),
("PATCH", "/birthday/api/admin/rsvps/1"),
("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"),
]
for method, path in admin_endpoints:
res = guest_client.request(method, path)
assert res.status_code == 403, (
f"{method} {path} must return 403 Forbidden for non-admin"
)
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
assert "Forbidden" in res.json().get("detail", "")
# ==============================================================================
# 6. Authenticated Non-Admin User Accessing Admin APIs -> HTTP 403 Forbidden
# 7. Legacy Remote-User Header Barrier: Returns HTTP 401 Unauthorized
# ==============================================================================
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
"""Legacy Remote-User header without an active authenticated session returns HTTP 401."""
headers_to_test = [
{"Remote-User": "admin@example.com"},
{"Remote-User": "admin", "X-Remote-User": "admin"},
{"remote-user": "admin@example.com"},
{"REMOTE_USER": "admin@example.com"},
]
# 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
for headers in headers_to_test:
res_rsvps = client.get("/birthday/api/admin/rsvps", headers=headers)
assert res_rsvps.status_code == 401
assert res_rsvps.json() == {"detail": "Not authenticated"}
res_config = client.get("/birthday/api/admin/config", headers=headers)
assert res_config.status_code == 401
res_me = client.get("/birthday/api/auth/me", headers=headers)
assert res_me.status_code == 401
def test_legacy_remote_user_with_non_admin_session_returns_403(
client: TestClient, guest_session_cookie
def test_legacy_remote_user_header_cannot_escalate_non_admin_session(
guest_client: TestClient,
):
"""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(
"""An attacker passing Remote-User: admin with an active non-admin session cookie receives HTTP 403."""
res = guest_client.get(
"/birthday/api/admin/rsvps",
headers={"Remote-User": "admin@example.com"},
headers={
"Remote-User": "admin@example.com",
"X-Remote-User": "admin",
"X-User-Groups": "bdinvite_admins",
},
)
assert res.status_code == 403
assert "Forbidden" in res.json().get("detail", "")
# ==============================================================================
# 8. Deployment Independence: Standalone vs Homelab Production Mode
# 8. Deployment Independence: Direct Standalone vs Homelab Production Mode
# ==============================================================================
def test_standalone_mode_configuration():
"""Verify Direct Standalone Mode environment settings and behavior."""
standalone_settings = Settings(
SERVICE_DOMAIN="localhost",
def test_deployment_independence_multi_mode_configuration():
"""Verify application configuration correctly handles Direct Standalone and Homelab Production modes."""
# 1. Direct Standalone Mode (local development / testing)
dev_settings = Settings(
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",
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"
assert dev_settings.is_standalone is True
assert dev_settings.is_production is False
assert dev_settings.SESSION_COOKIE_SECURE is False
# 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."""
# 2. Homelab Production Mode (behind Traefik TLS proxy with Authelia)
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_CLIENT_ID="bdinvite-client",
OIDC_CLIENT_SECRET="production-secure-secret-key",
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.is_standalone is False
assert prod_settings.is_production is True
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"
assert (
prod_settings.OIDC_REDIRECT_URI
== "https://demos.roadtotech.me/birthday/api/auth/callback"
)
# 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,
# ==============================================================================
# 9. Static Architectural Assertion: Zero Runtime Occurrences of Remote-User
# ==============================================================================
def test_static_architectural_assertion_no_runtime_remote_user():
"""Verify that neither backend/app/ nor frontend/src/ contains runtime references to Remote-User."""
root_dir = Path(__file__).resolve().parent.parent.parent
backend_app_dir = root_dir / "backend" / "app"
frontend_src_dir = root_dir / "frontend" / "src"
assert backend_app_dir.is_dir()
assert frontend_src_dir.is_dir()
# Disallowed patterns in runtime source files
disallowed = ["remote-user", "remote_user"]
violations: list[str] = []
# Check backend runtime source files
for py_file in backend_app_dir.rglob("*.py"):
content = py_file.read_text(encoding="utf-8").lower()
for term in disallowed:
if term in content:
violations.append(f"{py_file}: contains '{term}'")
# Check frontend runtime source files
for src_file in frontend_src_dir.rglob("*"):
if src_file.suffix in [".ts", ".tsx", ".js", ".jsx"]:
content = src_file.read_text(encoding="utf-8").lower()
for term in disallowed:
if term in content:
violations.append(f"{src_file}: contains '{term}'")
assert not violations, (
"Architectural boundary violated by runtime Remote-User occurrences:\n"
+ "\n".join(violations)
)
)
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"
+369 -341
View File
@@ -1,401 +1,429 @@
"""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 import Request
from fastapi.responses import Response as StarletteResponse
from fastapi.testclient import TestClient
from starlette.requests import Request
from app.auth import (
Identity,
InMemorySessionStore,
OIDCAuthAdapter,
OIDCClient,
OIDCConfig,
SessionRecord,
sign_session_cookie,
unsign_session_cookie,
)
from app.routes.auth import get_auth_adapter, set_auth_adapter
from app.routes.auth import get_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"
LIVE_ISSUER = "http://localhost:8088/default"
CLIENT_ID = "bdinvite-client"
CLIENT_SECRET = "bdinvite-secret"
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(
def create_dummy_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")))
"""Helper to construct dummy Request instances for unit testing."""
raw_headers: list[tuple[bytes, bytes]] = [
(k.lower().encode("latin-1"), v.encode("latin-1"))
for k, v in (headers or {}).items()
]
if cookies:
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
header_list.append((b"cookie", cookie_header.encode("latin-1")))
raw_headers.append((b"cookie", cookie_header.encode("latin-1")))
scope = {
"type": "http",
"method": "GET",
"path": "/birthday/api/auth/session",
"headers": header_list,
"query_string": b"",
"path": "/test",
"headers": raw_headers,
}
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,
@pytest.fixture
def oidc_client() -> OIDCClient:
return OIDCClient(
issuer=LIVE_ISSUER,
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
)
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"],
@pytest.fixture
def auth_adapter(oidc_client: OIDCClient) -> OIDCAuthAdapter:
return OIDCAuthAdapter(
oidc_client=oidc_client,
session_cookie_name="bdinvite_session",
session_store=InMemorySessionStore(),
cookie_secure=False,
cookie_samesite="lax",
session_max_age=3600,
secret_key="test-session-secret",
)
response = Response()
session_id = auth_adapter.establish_session(identity)
auth_adapter.set_session_cookie(response, session_id)
# ==============================================================================
# Unit Tests: Session Store & Cookie Security
# ==============================================================================
def test_session_store_lifecycle():
"""Verify session creation, retrieval, and explicit deletion."""
store = InMemorySessionStore()
identity = Identity(subject="user-1", email="user1@example.com")
session = store.create_session(identity=identity, max_age_seconds=60)
assert session.session_id is not None
assert len(session.session_id) >= 32
assert session.identity == identity
assert session.is_authenticated is True
assert session.is_expired() is False
retrieved = store.get_session(session.session_id)
assert retrieved is not None
assert retrieved.session_id == session.session_id
assert retrieved.identity == identity
# Explicit deletion
assert store.delete_session(session.session_id) is True
assert store.get_session(session.session_id) is None
assert store.delete_session(session.session_id) is False
def test_session_store_expiration():
"""Verify that expired sessions are rejected and pruned."""
store = InMemorySessionStore()
identity = Identity(subject="user-exp", email="exp@example.com")
# Create session that expires immediately (max_age_seconds = -1)
session = store.create_session(identity=identity, max_age_seconds=-1)
assert session.is_expired() is True
# Retrieval should return None and prune
assert store.get_session(session.session_id) is None
def test_session_store_fixation_protection():
"""Verify Session Fixation Barrier in SessionStore: pre-auth session is destroyed upon login."""
store = InMemorySessionStore()
# Pre-authentication session (anonymous)
pre_auth = store.create_session(identity=None, max_age_seconds=300)
pre_auth_id = pre_auth.session_id
assert pre_auth.is_authenticated is False
assert store.get_session(pre_auth_id) is not None
# Authenticate: create post-auth session providing pre_auth_session_id
auth_identity = Identity(subject="user-auth", email="auth@example.com")
post_auth = store.create_session(
identity=auth_identity,
max_age_seconds=300,
pre_auth_session_id=pre_auth_id,
)
post_auth_id = post_auth.session_id
# 1. Fresh identifier generated
assert post_auth_id != pre_auth_id
# 2. Pre-auth session ID is eradicated and can NEVER be used
assert store.get_session(pre_auth_id) is None
# 3. Post-auth session resolves to authenticated identity
retrieved_post = store.get_session(post_auth_id)
assert retrieved_post is not None
assert retrieved_post.identity == auth_identity
def test_hmac_cookie_signing_and_tamper_detection():
"""Verify HMAC-SHA256 signature verification detects tampering."""
secret = "my-secret-key"
session_id = "random_session_token_12345"
signed = sign_session_cookie(session_id, secret)
assert "." in signed
assert signed.startswith(session_id)
# Valid unsign
unsigned = unsign_session_cookie(signed, secret)
assert unsigned == session_id
# Tampered session ID payload
tampered_payload = "forged_id" + signed[len(session_id) :]
assert unsign_session_cookie(tampered_payload, secret) is None
# Tampered signature
tampered_sig = signed[:-4] + "dead"
assert unsign_session_cookie(tampered_sig, secret) is None
# Wrong secret key
assert unsign_session_cookie(signed, "wrong-secret-key") is None
# Malformed cookies
assert unsign_session_cookie("no-dot-in-string", secret) is None
assert unsign_session_cookie("", secret) is None
assert unsign_session_cookie(None, secret) is None
# ==============================================================================
# Unit Tests: Adapter Contract & Security Invariants
# ==============================================================================
def test_adapter_session_cookie_security_invariants(auth_adapter: OIDCAuthAdapter):
"""Verify session cookie enforces HttpOnly=True, SameSite, and configurable Secure flag."""
response = StarletteResponse()
auth_adapter.set_session_cookie(response, "test-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()
assert "bdinvite_session=" in set_cookie
# Security Invariant: HttpOnly MUST be True
assert "httponly" in set_cookie.lower()
# SameSite must be set
assert "samesite=lax" in set_cookie.lower()
# When cookie_secure is False (local/test), Secure attribute is omitted
assert "secure" not 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
# When cookie_secure is True (production), Secure attribute is enforced
prod_adapter = OIDCAuthAdapter(
client=OIDCClient(OIDCConfig(issuer=FIXTURE_ISSUER, client_id=FIXTURE_CLIENT_ID)),
oidc_client=auth_adapter.oidc_client,
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"
prod_response = StarletteResponse()
prod_adapter.set_session_cookie(prod_response, "prod-session-id")
prod_cookie = prod_response.headers.get("set-cookie", "")
assert "secure" in prod_cookie.lower()
assert "httponly" in prod_cookie.lower()
# ============================================================================
# 2. Session Fixation Barrier Tests
# ============================================================================
def test_adapter_current_identity_resolution(auth_adapter: OIDCAuthAdapter):
"""Verify current_identity resolution across valid, anonymous, tampered, and expired states."""
identity = Identity(subject="alice-1", email="alice@example.com")
# 1. Anonymous request (no cookie) -> None
anon_req = create_dummy_request()
assert auth_adapter.current_identity(anon_req) is None
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)
# 2. Valid authenticated session -> Identity
session = auth_adapter.session_store.create_session(identity=identity)
signed_cookie = sign_session_cookie(session.session_id, auth_adapter.secret_key)
valid_req = create_dummy_request(cookies={"bdinvite_session": signed_cookie})
resolved = auth_adapter.current_identity(valid_req)
assert resolved == identity
# 3. Unknown / non-existent session ID -> None
fake_signed = sign_session_cookie(
"non-existent-session-id", auth_adapter.secret_key
)
unknown_req = create_dummy_request(cookies={"bdinvite_session": fake_signed})
assert auth_adapter.current_identity(unknown_req) is None
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")
# 4. Tampered cookie signature -> None (safely rejected, no crash)
tampered_cookie = signed_cookie[:-4] + "ffff"
tampered_req = create_dummy_request(cookies={"bdinvite_session": tampered_cookie})
assert auth_adapter.current_identity(tampered_req) is None
# 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()
# 5. Malformed cookie -> None
malformed_req = create_dummy_request(cookies={"bdinvite_session": "not-valid;;bad"})
assert auth_adapter.current_identity(malformed_req) is None
identity, post_auth_session_id = auth_adapter.handle_callback(
code=code,
state=returned_state,
# 6. Expired session -> None
expired_session = auth_adapter.session_store.create_session(
identity=identity, max_age_seconds=-10
)
exp_cookie = sign_session_cookie(
expired_session.session_id, auth_adapter.secret_key
)
exp_req = create_dummy_request(cookies={"bdinvite_session": exp_cookie})
assert auth_adapter.current_identity(exp_req) is None
def test_adapter_session_fixation_barrier(auth_adapter: OIDCAuthAdapter):
"""Verify that authenticating rotates the session identifier and invalidates the pre-auth session."""
# Establish pre-authentication session
pre_session = auth_adapter.session_store.create_session(identity=None)
pre_id = pre_session.session_id
pre_signed = sign_session_cookie(pre_id, auth_adapter.secret_key)
pre_req = create_dummy_request(cookies={"bdinvite_session": pre_signed})
assert auth_adapter.current_identity(pre_req) is None
# Successful authentication transitions session
user_identity = Identity(subject="victim-01", email="victim@example.com")
resp = StarletteResponse()
post_session = auth_adapter.create_session(
identity=user_identity,
request=pre_req,
response=resp,
request=req,
extra_params={"username": "guest@example.com"},
)
post_id = post_session.session_id
# Assert fixation barrier
assert post_auth_session_id != pre_auth_session_id
assert identity.subject == "guest-001"
# Invariant: pre_auth_session_id != post_auth_session_id
assert pre_id != post_id
# Attacker's pre-auth session resolves to nothing
assert auth_adapter.current_identity(req) is None
# Invariant: pre_auth_session_id is defunct and not authenticated
assert auth_adapter.session_store.get_session(pre_id) is None
assert auth_adapter.current_identity(pre_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
# Invariant: post_auth_session_id is valid and authenticated
post_signed = sign_session_cookie(post_id, auth_adapter.secret_key)
post_req = create_dummy_request(cookies={"bdinvite_session": post_signed})
assert auth_adapter.current_identity(post_req) == user_identity
# ============================================================================
# 3. Session Lifecycle & Invalidation Tests
# ============================================================================
def test_adapter_logout_revocation(auth_adapter: OIDCAuthAdapter):
"""Verify that logout revokes session on server and clears the browser cookie."""
identity = Identity(subject="bob-1", email="bob@example.com")
session = auth_adapter.session_store.create_session(identity=identity)
signed_cookie = sign_session_cookie(session.session_id, auth_adapter.secret_key)
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
req = create_dummy_request(cookies={"bdinvite_session": signed_cookie})
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
# Terminate session
logout_resp = auth_adapter.logout(req)
assert logout_resp.status_code == 302
# 1. Server-side session revoked
assert session_id not in auth_adapter.sessions
# Storage revocation check
assert auth_adapter.session_store.get_session(session.session_id) is None
# Subsequent resolution must be anonymous
assert auth_adapter.current_identity(req) is None
# 2. Browser cookie cleared with Max-Age=0
# Cookie clearance check (Max-Age=0)
set_cookie_header = logout_resp.headers.get("set-cookie", "")
assert "bdinvite_session" in set_cookie_header
assert "max-age=0" in set_cookie_header.lower()
# ==============================================================================
# Integration Tests: HTTP Endpoints (/birthday/api/auth/*)
# ==============================================================================
def test_http_anonymous_request_resolves_to_unauthorized(client: TestClient):
"""Anonymous request to /me returns HTTP 401."""
resp = client.get("/birthday/api/auth/me")
assert resp.status_code == 401
assert resp.json()["detail"] == "Not authenticated"
def test_http_login_issues_httponly_samesite_cookie(client: TestClient):
"""Direct login against IdP issues an HttpOnly, SameSite session cookie."""
resp = client.post(
"/birthday/api/auth/login",
json={"username": "guest@example.com", "password": "password123"},
)
assert resp.status_code == 200
data = resp.json()
assert data["subject"] == "guest-001"
assert data["email"] == "guest@example.com"
# Verify cookie attributes
set_cookie = resp.headers.get("set-cookie", "")
assert "bdinvite_session=" in set_cookie
assert "httponly" in set_cookie.lower()
assert "samesite=lax" in set_cookie.lower()
def test_http_session_fixation_rotation_on_login(client: TestClient):
"""Verify that an existing pre-authentication session cookie is rotated upon login."""
# 1. Start with an anonymous / pre-authentication session
resp_pre = client.get("/birthday/api/auth/login", follow_redirects=False)
assert resp_pre.status_code == 302
pre_auth_cookie = resp_pre.cookies.get("bdinvite_session")
assert pre_auth_cookie is not None
# 2. Pre-auth session resolves to unauthorized
resp_anon = client.get(
"/birthday/api/auth/me", cookies={"bdinvite_session": pre_auth_cookie}
)
assert resp_anon.status_code == 401
# 3. Authenticate while presenting pre_auth_cookie
resp_login = client.post(
"/birthday/api/auth/login",
json={"username": "admin@example.com", "password": "password123"},
cookies={"bdinvite_session": pre_auth_cookie},
)
assert resp_login.status_code == 200
post_auth_cookie = resp_login.cookies.get("bdinvite_session")
assert post_auth_cookie is not None
# 4. Security Invariant: pre_auth != post_auth
assert pre_auth_cookie != post_auth_cookie
# 5. Pre-auth cookie MUST NOT have been promoted
resp_old = client.get(
"/birthday/api/auth/me", cookies={"bdinvite_session": pre_auth_cookie}
)
assert resp_old.status_code == 401
# 6. Post-auth cookie resolves to authenticated user
resp_valid = client.get(
"/birthday/api/auth/me", cookies={"bdinvite_session": post_auth_cookie}
)
assert resp_valid.status_code == 200
assert resp_valid.json()["subject"] == "admin-001"
assert "bdinvite_admins" in resp_valid.json()["groups"]
def test_http_tampered_cookie_rejected(client: TestClient):
"""Requests with tampered or forged cookies are safely rejected with HTTP 401."""
# Attempt request with random tampered cookie
resp = client.get(
"/birthday/api/auth/me",
cookies={"bdinvite_session": "forged_session_id.invalid_signature_hash"},
)
assert resp.status_code == 401
assert resp.json()["detail"] == "Not authenticated"
def test_http_expired_cookie_rejected(client: TestClient):
"""Requests presenting an expired session cookie are rejected with HTTP 401."""
adapter = get_auth_adapter()
expired_session = adapter.session_store.create_session(
identity=Identity(subject="expired-user", email="exp@test.com"),
max_age_seconds=-10,
)
signed_cookie = sign_session_cookie(expired_session.session_id, adapter.secret_key)
resp = client.get(
"/birthday/api/auth/me",
cookies={"bdinvite_session": signed_cookie},
)
assert resp.status_code == 401
def test_http_logout_invalidates_session_and_clears_cookie(client: TestClient):
"""POST /birthday/api/auth/logout invalidates session and clears cookie with Max-Age=0."""
# 1. Login to obtain session
login_resp = client.post(
"/birthday/api/auth/login",
json={"username": "guest@example.com", "password": "password123"},
)
assert login_resp.status_code == 200
cookie_val = login_resp.cookies.get("bdinvite_session")
assert cookie_val is not None
# Verify session is authenticated
me_resp = client.get(
"/birthday/api/auth/me", cookies={"bdinvite_session": cookie_val}
)
assert me_resp.status_code == 200
# 2. Logout via POST
logout_resp = client.post(
"/birthday/api/auth/logout", cookies={"bdinvite_session": cookie_val}
)
assert logout_resp.status_code == 200
assert logout_resp.json()["status"] == "ok"
# Verify cookie clearance header
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
assert "bdinvite_session" in set_cookie
assert "max-age=0" in set_cookie.lower()
# ============================================================================
# 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"],
# 3. Subsequent request with the same cookie is rejected
me_after = client.get(
"/birthday/api/auth/me", cookies={"bdinvite_session": cookie_val}
)
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
assert me_after.status_code == 401
+323 -2
View File
@@ -1,5 +1,5 @@
version = 1
revision = 3
revision = 5
requires-python = ">=3.11"
resolution-markers = [
"python_full_version >= '3.14'",
@@ -68,6 +68,7 @@ dev = [
{ name = "pyright" },
{ name = "pytest" },
{ name = "pytest-asyncio" },
{ name = "pytest-playwright" },
]
[package.metadata]
@@ -77,7 +78,7 @@ requires-dist = [
{ name = "pillow", specifier = ">=10.0.0" },
{ name = "pydantic", specifier = ">=2.0.0" },
{ name = "pydantic-settings", specifier = ">=2.0.0" },
{ name = "pyjwt", extras = ["crypto"], specifier = ">=2.8.0" },
{ name = "pyjwt", extras = ["crypto"], specifier = ">=2.15.1" },
{ name = "sqlalchemy", specifier = ">=2.0.0" },
{ name = "uvicorn", specifier = ">=0.30.0" },
]
@@ -88,6 +89,7 @@ dev = [
{ name = "pyright", specifier = ">=1.1.0" },
{ name = "pytest", specifier = ">=8.0.0" },
{ name = "pytest-asyncio", specifier = ">=0.23.0" },
{ name = "pytest-playwright", specifier = ">=0.9.0" },
]
[[package]]
@@ -197,6 +199,153 @@ wheels = [
{ 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]]
name = "charset-normalizer"
version = "3.5.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/33/1c/f41d4e74c28ab327ff3acd36053f7ea506c55872d7a90b0fa71aa3ab0c89/charset_normalizer-3.5.2.tar.gz", hash = "sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef", size = 172659, upload-time = "2026-09-30T04:39:23.398Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/22/67/6a0b94a7960d5e1b5eacd2fb529f3fccc47db4644f7f0a7cfdcfc3be578a/charset_normalizer-3.5.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6", size = 370642, upload-time = "2026-09-30T04:35:06.91Z" },
{ url = "https://files.pythonhosted.org/packages/fb/94/01009e13b94041599004edf32e56e382c24e570f60f79bab8efe45cfe1eb/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5", size = 259280, upload-time = "2026-09-30T04:35:08.448Z" },
{ url = "https://files.pythonhosted.org/packages/66/85/3b5358f60a13210f0b67d3755c168ef758701b021e655d88d4da28554467/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74", size = 245335, upload-time = "2026-09-30T04:35:10.104Z" },
{ url = "https://files.pythonhosted.org/packages/74/75/77c1c479b09ecd751d1e767b251ea5c14d4d50ff757bf404afab2692f600/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab", size = 291707, upload-time = "2026-09-30T04:35:11.575Z" },
{ url = "https://files.pythonhosted.org/packages/0b/0d/363f78cacb70f58f15f4b083961bbd9d292f335d3f5c66fc4f1cfe69cb90/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c", size = 286747, upload-time = "2026-09-30T04:35:13.022Z" },
{ url = "https://files.pythonhosted.org/packages/e4/ed/cf505d3011ffceb12c2067a7a5d3cfe92b875d4d44bb0ff0d69375e2c184/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f", size = 269972, upload-time = "2026-09-30T04:35:14.606Z" },
{ url = "https://files.pythonhosted.org/packages/15/d8/f0a93a431d170e7ca681d4f6650fee3de934d18560e474e7267eb4b0f987/charset_normalizer-3.5.2-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288", size = 269339, upload-time = "2026-09-30T04:35:16.087Z" },
{ url = "https://files.pythonhosted.org/packages/86/bd/9b2bd1c5b7af02462c9752d33994834ff972a96b4c483eefde9e594488e2/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400", size = 261683, upload-time = "2026-09-30T04:35:17.488Z" },
{ url = "https://files.pythonhosted.org/packages/76/a5/cac540ab0fd61f3fec88ad3dbb64509e71424593d73cfdfff5ab3e4db279/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd", size = 248143, upload-time = "2026-09-30T04:35:18.849Z" },
{ url = "https://files.pythonhosted.org/packages/71/7a/ff467301deef2089fad87f72df9e000a26a78fec7acbb18e1999371b8369/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37", size = 292358, upload-time = "2026-09-30T04:35:20.326Z" },
{ url = "https://files.pythonhosted.org/packages/ad/77/22d7e785d1e210afc2e2f58600dd1799d17a35665faf84383f002826c5f8/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac", size = 268766, upload-time = "2026-09-30T04:35:21.72Z" },
{ url = "https://files.pythonhosted.org/packages/ae/91/e8e946267f1c2d9e2bd651726e2fbd2addf02c4d36cea5069e32ca9d7bb5/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a", size = 287432, upload-time = "2026-09-30T04:35:23.273Z" },
{ url = "https://files.pythonhosted.org/packages/4e/88/7561d8a88d555e7df6623abe7c0070b4baf47549b9408783a2ae0a1a6cf7/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640", size = 272470, upload-time = "2026-09-30T04:35:24.655Z" },
{ url = "https://files.pythonhosted.org/packages/35/7e/578c702301ec036f01455f30744a08d2b42f6ab35b9b2d4bf8cae0ef2a80/charset_normalizer-3.5.2-cp311-cp311-win32.whl", hash = "sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d", size = 186688, upload-time = "2026-09-30T04:35:26.225Z" },
{ url = "https://files.pythonhosted.org/packages/e8/fc/fdf8cf52ff21cd5bf158f20978991cf985325842f74283eb6df26c8a39d8/charset_normalizer-3.5.2-cp311-cp311-win_amd64.whl", hash = "sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96", size = 214932, upload-time = "2026-09-30T04:35:27.796Z" },
{ url = "https://files.pythonhosted.org/packages/97/66/3e45a506d8110b632541faf9a9470185aa9878f1ed44020f31346c1c5e5b/charset_normalizer-3.5.2-cp311-cp311-win_arm64.whl", hash = "sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1", size = 202828, upload-time = "2026-09-30T04:35:29.259Z" },
{ url = "https://files.pythonhosted.org/packages/e7/c8/693809898870237d82785a03f3b2b58fe4c9f14669f84a7d4e623c92a59e/charset_normalizer-3.5.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491", size = 367780, upload-time = "2026-09-30T04:35:30.888Z" },
{ url = "https://files.pythonhosted.org/packages/c9/87/2fea8c13dc24b3ca9c6f803a5b2dfdeae73eb4f9e12c7885ed908ff0433c/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c", size = 246730, upload-time = "2026-09-30T04:35:32.286Z" },
{ url = "https://files.pythonhosted.org/packages/a8/9e/09efac30b937722f46d3110ba30b875b24b2e3a266ed746cc4e376a94d80/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0", size = 237707, upload-time = "2026-09-30T04:35:33.709Z" },
{ url = "https://files.pythonhosted.org/packages/9e/18/70d76670b13686237863a379928d60bd10e021f17d243ab3d7014c4a5f4e/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51", size = 273050, upload-time = "2026-09-30T04:35:35.138Z" },
{ url = "https://files.pythonhosted.org/packages/54/e2/77a8b09d5adc013ed07b95b01b8b8fa5441c4e810e83ee7e4aae2fa4d91a/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5", size = 270345, upload-time = "2026-09-30T04:35:36.502Z" },
{ url = "https://files.pythonhosted.org/packages/7f/c5/38806a25ab5e65fc178f39affeda20858efafede2fce1ffc2556cfc9fe73/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649", size = 257601, upload-time = "2026-09-30T04:35:37.919Z" },
{ url = "https://files.pythonhosted.org/packages/ae/8d/213565184708fdb263ae55e2c04ee1ff748129dd65d48ed0e3502da9c85a/charset_normalizer-3.5.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e", size = 252222, upload-time = "2026-09-30T04:35:39.544Z" },
{ url = "https://files.pythonhosted.org/packages/7e/24/76d2cefc25472531e4c5c7dfff68865eb1c39b78482f0fdc15b46f047830/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346", size = 248482, upload-time = "2026-09-30T04:35:41.088Z" },
{ url = "https://files.pythonhosted.org/packages/7d/dc/65a801b66ab4c197e22c433ab25e7ac24324ac6f45a2269aca42cce309bf/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1", size = 241206, upload-time = "2026-09-30T04:35:42.59Z" },
{ url = "https://files.pythonhosted.org/packages/a7/95/ca9b5eabde673002c6f1e7ada1b223916fe18f6d661da7aabd4d643718f1/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875", size = 273190, upload-time = "2026-09-30T04:35:44.347Z" },
{ url = "https://files.pythonhosted.org/packages/2d/8b/803b4d2a3f6e1740f63f1e87b04d14b42f3d4fdfe6ed7d4db2d34102b14f/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1", size = 253527, upload-time = "2026-09-30T04:35:45.915Z" },
{ url = "https://files.pythonhosted.org/packages/a9/55/93c0e5dbd085ae0471346026abbe7e0db9ea2d6fea74e51f0b5a46f233a7/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413", size = 271285, upload-time = "2026-09-30T04:35:47.49Z" },
{ url = "https://files.pythonhosted.org/packages/95/69/0dbd0e0b9b16cfa816cdfcb3e2e3854a1f680dc07fb1245ea125e7448060/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869", size = 260010, upload-time = "2026-09-30T04:35:48.996Z" },
{ url = "https://files.pythonhosted.org/packages/58/9d/e7b88e7b1bf403590c3b573277b5e1e488c68c7a6fbacca310a2c324e90c/charset_normalizer-3.5.2-cp312-cp312-win32.whl", hash = "sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e", size = 184125, upload-time = "2026-09-30T04:35:50.777Z" },
{ url = "https://files.pythonhosted.org/packages/eb/e6/e6e083884cbcfd49c64865af05027fe7011be7b2d9179524f099a1b611f3/charset_normalizer-3.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc", size = 207486, upload-time = "2026-09-30T04:35:52.194Z" },
{ url = "https://files.pythonhosted.org/packages/c4/e3/017aea0911ada7405a825c7d937eb3a13009664e2f5b38e8c4bbf2abf894/charset_normalizer-3.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3", size = 196734, upload-time = "2026-09-30T04:35:53.636Z" },
{ url = "https://files.pythonhosted.org/packages/c5/34/68292d68512768591aaff07c59bb53ee31341c87759433a859c4641a50c2/charset_normalizer-3.5.2-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:ed905975ab14056a2e5eb1c376cb2e1ebc5396baf84163939c518556fccde9f5", size = 225946, upload-time = "2026-09-30T04:35:55.313Z" },
{ url = "https://files.pythonhosted.org/packages/e3/80/bee0b01b90ccd5322ae1d0abb33fab1bd95b7c2eadaf02aeccf22e04ee83/charset_normalizer-3.5.2-cp313-cp313-android_24_x86_64.whl", hash = "sha256:a66c3bc5ab1f0ff2164fc9965ddd611ff0802173f4b9d24554c563f6ab7e1d6e", size = 238619, upload-time = "2026-09-30T04:35:56.863Z" },
{ url = "https://files.pythonhosted.org/packages/78/6e/60ce52a85a7fd631ae8482ae6d74521014ca2f255892679484dc04d7ef56/charset_normalizer-3.5.2-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:d2374b62878abb00cd8309b32af6c0b715cd02dec0ca74ef12e5069bdc64144a", size = 206701, upload-time = "2026-09-30T04:35:58.639Z" },
{ url = "https://files.pythonhosted.org/packages/36/8c/71aafad23f971afc84c2b295bc0c560739ce1dac558aad9fec22e39f3639/charset_normalizer-3.5.2-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:d376bbd28b3a8999db1a103b3b388aee6f1ddeb3e51bc2172993efdcd86e064d", size = 210506, upload-time = "2026-09-30T04:36:00.147Z" },
{ url = "https://files.pythonhosted.org/packages/91/da/3c5a7798c046df7d2d68ad653cf5b6c5a8bfee225055a843c6f2f42aac1a/charset_normalizer-3.5.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6045373d5a89a5ec71afde535db987ca28e76dfa276c2d4c818265b375d4b055", size = 366626, upload-time = "2026-09-30T04:36:01.77Z" },
{ url = "https://files.pythonhosted.org/packages/e1/16/710ac3de2ee354e2bd1a9c94efe45a2d27b5c6ad39b2d6a905be2c094b6c/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849df64e889b2e17230d58410a03dba311a65b163508fd33679b2b737d4b7858", size = 244624, upload-time = "2026-09-30T04:36:03.389Z" },
{ url = "https://files.pythonhosted.org/packages/d6/39/45c7439f5b63d24f7d5b2a1d760f34af7628782d7144b4cc8ded45c2d4bc/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:15c44f7edfd477b06f517a5cc317fc1707edb9de2c865f43d4b6513907473234", size = 235731, upload-time = "2026-09-30T04:36:04.987Z" },
{ url = "https://files.pythonhosted.org/packages/4d/34/38f3154785ce92e9f56eb226f4d35bdfae6b008480dd055f58837a89c810/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a89012d6d5476ee112d20d998570ed58df2260a852afb1758809cd6900411d21", size = 270352, upload-time = "2026-09-30T04:36:06.412Z" },
{ url = "https://files.pythonhosted.org/packages/04/f3/859f74e7babc977705026b30593b3be04049632a522fb7000f83c033d747/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0c951d5e6dd9c2ff60609476752bee49da4206adde960ebc247766937f72e718", size = 267393, upload-time = "2026-09-30T04:36:07.865Z" },
{ url = "https://files.pythonhosted.org/packages/4b/85/41d27f234b82e47c167a5f6c0f62501dc0c640585ff4aba79e08a390336a/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7218e8f32b0956cfcd048fd42d9d5779809745ca1d86113ca56f66e7ae1549c4", size = 254660, upload-time = "2026-09-30T04:36:09.248Z" },
{ url = "https://files.pythonhosted.org/packages/58/ca/5d1a997587febe5b26d8daffe363b5c1a091cece19828eec6502fd09c5ef/charset_normalizer-3.5.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a19a731138fc27d5682277d3b9df22855cea1239bce7fcec5f78f42ef2d1f3c3", size = 249996, upload-time = "2026-09-30T04:36:10.73Z" },
{ url = "https://files.pythonhosted.org/packages/b3/1f/d1e78246f7ed60c8c8d606b4ac27f66ce49cc3e95f24893ccbeba9f77302/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:62603db9a7caa0802eaa28c1c46fecd7b3a263a774069c24c3c28c302448721c", size = 247028, upload-time = "2026-09-30T04:36:12.294Z" },
{ url = "https://files.pythonhosted.org/packages/8e/37/eba316edd4f0c4d3a5d945924c4eeeae59abac4056aa815d8a4268f863a2/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:b6856554c4f44d79fc2307d5768854310a8f0096e501c75637542c82292b0429", size = 240562, upload-time = "2026-09-30T04:36:13.887Z" },
{ url = "https://files.pythonhosted.org/packages/c8/8e/aaa037d40ca9ef045977f1a661048b1aa33f223adfce3452fe9be9f79d14/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:1bc0baf5ef96b6ede57d47f4b8fe4d9d84019c3bfcbeb20a41edc6a6ee341f1f", size = 271699, upload-time = "2026-09-30T04:36:15.41Z" },
{ url = "https://files.pythonhosted.org/packages/26/19/1c1c9f75974adf523b87f34b8a2adc5a435cd65916812bcbd0dfa45f9a29/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:56bc200a365efb37383b7852e4cc5898d3b2da5987289b543956cf8cad71018a", size = 252030, upload-time = "2026-09-30T04:36:16.839Z" },
{ url = "https://files.pythonhosted.org/packages/bc/90/0660ef18e18df0a4d2a1a0edff7dfbba42d4e50ef2425557a5bb7051f77b/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:2c9ad19a6cfcd5ea5c0d41161d22f9df1dcc277e9bef2751391334546a314c00", size = 268565, upload-time = "2026-09-30T04:36:18.468Z" },
{ url = "https://files.pythonhosted.org/packages/79/ba/57adc269824e8658f1a0f97a9e514c247445a9632b3419b97e0ba37f16dc/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e243bd13217235fc7290c621941c3f5cc8b66e4872495be821d7436ba2fb838d", size = 257627, upload-time = "2026-09-30T04:36:19.938Z" },
{ url = "https://files.pythonhosted.org/packages/9a/85/33abd4315c052d3d4f54c92b1ee49bfbc0dc7115a981e462a793b6d2ab87/charset_normalizer-3.5.2-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:a090bb2c68df85450502e3e20d665e3a5af9c65a84d6508ed477badd49166fd3", size = 143407, upload-time = "2026-09-30T04:36:21.376Z" },
{ url = "https://files.pythonhosted.org/packages/4f/de/6435e18d1aaa5d910b896d551411c96af1f42a0c56c29afc2016c61ccc2e/charset_normalizer-3.5.2-cp313-cp313-win32.whl", hash = "sha256:2b7b3bbfb4fe8ef40600792d762fbaa9057559f9d3fad209525b7a22b99e91fd", size = 183207, upload-time = "2026-09-30T04:36:22.776Z" },
{ url = "https://files.pythonhosted.org/packages/9c/76/b8ec57f4e9ee3253541abf95e4a462c0175fe8032dcd070f1f2421240942/charset_normalizer-3.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:78456a747de8dc58360ffa581f30a002baf5aa28cb262536545e91f113ed7639", size = 206489, upload-time = "2026-09-30T04:36:24.306Z" },
{ url = "https://files.pythonhosted.org/packages/3e/60/c647c6ae47480221e875ea5d743ff94946f7416e3c69415ab772928e8d32/charset_normalizer-3.5.2-cp313-cp313-win_arm64.whl", hash = "sha256:11912e4bb14baae7c5d8791aa55ba0a3a03ec6729073307b0f57270abaa713d3", size = 195501, upload-time = "2026-09-30T04:36:25.846Z" },
{ url = "https://files.pythonhosted.org/packages/58/ca/7aa91362a2f77ac8e9e28a9b902a74f7d0e11a851ef0d27a74308da8cd90/charset_normalizer-3.5.2-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:1afb975bd5d68d5ce9f6b6d44fdf2f7e34b895a35e95708a7a91b20a3b51d187", size = 226010, upload-time = "2026-09-30T04:36:27.669Z" },
{ url = "https://files.pythonhosted.org/packages/a8/cf/ac8878d0322cf88a1aad4c7b147db32ca0bd806eb0060957b2e31486dbe6/charset_normalizer-3.5.2-cp314-cp314-android_24_x86_64.whl", hash = "sha256:bbbfc8e28816f19d7c0f1816664980c0a9875d01b27cdf8eedddb639d9e108ad", size = 239266, upload-time = "2026-09-30T04:36:29.434Z" },
{ url = "https://files.pythonhosted.org/packages/c9/6d/9a08d7e0b29b7208e2c6c01dc56c8e0520e7c7beadbbfb024b58fd69c8a5/charset_normalizer-3.5.2-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7967d08cf06dee78443b874f98c98036f624f3a4e73e11f9f64f5be4d25393cf", size = 206783, upload-time = "2026-09-30T04:36:30.872Z" },
{ url = "https://files.pythonhosted.org/packages/82/44/b0aa350280e6ff5a5492d17cf10460dd39d5ee848f872f7ba2df10607f60/charset_normalizer-3.5.2-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4c2b5031f63e331e3839b40aed2dd6f191e9c07edbde303e7876846ea1946995", size = 210449, upload-time = "2026-09-30T04:36:32.625Z" },
{ url = "https://files.pythonhosted.org/packages/7c/8a/40db9aa9f5907bb0e6f8b6d64064bf8852fb33d4b813ff9414911df7647c/charset_normalizer-3.5.2-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:fcff63213e8e6e47770541a4607175404f47cbb3ebea7b6058cc82d524a0e424", size = 367815, upload-time = "2026-09-30T04:36:34.197Z" },
{ url = "https://files.pythonhosted.org/packages/7f/72/9c5e7707b57c8ddfa9ddf7b0b1d009d7fbab9e9e887d5b721060f37e307d/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8d86d6fc60743dc916eb79e2eb1ec4818e21e427731543af40a3021851174a13", size = 247095, upload-time = "2026-09-30T04:36:35.803Z" },
{ url = "https://files.pythonhosted.org/packages/83/09/71e453691e927de4ddf792770cfaab3f49d494e222f66ea5e404bbd5e39c/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:7a881931aa470808df94a8c380eed2bbbc76cd9dc622310f99665658c821eb6d", size = 233942, upload-time = "2026-09-30T04:36:37.407Z" },
{ url = "https://files.pythonhosted.org/packages/9f/86/85c84e4da8b27dd409577d9437926ff581c5f9d3c66038dc68c1a526de51/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8024d00c3faf3fc0c16e07a69f4405e8eac7cc0ab15f65fe6cf43827c4cf72b4", size = 273762, upload-time = "2026-09-30T04:36:38.904Z" },
{ url = "https://files.pythonhosted.org/packages/92/08/564955a4b5f2ccb410ab480bbe8c6a18063ff27f2d35458731c4a5335df9/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4d48f2d08b9de5864e2c8744d4461b862fb149a18274abc8b698c45975573438", size = 269514, upload-time = "2026-09-30T04:36:40.469Z" },
{ url = "https://files.pythonhosted.org/packages/18/24/bad3ac4271589df29cf5ce2f5ae490518a5739358052bd0d61209e6fea54/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:34276fd796040bf0993ab33a369aa572e6979c7aab225a88893667ad8eac8f7a", size = 255056, upload-time = "2026-09-30T04:36:42.02Z" },
{ url = "https://files.pythonhosted.org/packages/d6/3e/350d89ad49916b86554d6f5f2d03ec1152148f87e5ff735106c6a03b1a36/charset_normalizer-3.5.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0521c5665880b33d603717defa76c094048900010897909952397feb3039da56", size = 251311, upload-time = "2026-09-30T04:36:43.577Z" },
{ url = "https://files.pythonhosted.org/packages/56/5b/4970a2d154df502e133402906dd04e3ae7cada7b3011283c88d0479a2585/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:eff0ac9dbe711a4aee69bf04a83896aa9b85f19641264053a9f6d48573abb7dd", size = 250190, upload-time = "2026-09-30T04:36:45.185Z" },
{ url = "https://files.pythonhosted.org/packages/88/8c/f1a91bddc8fb47c2889e29ea7ea49a194eb0d9868675d786806519c00d76/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:1503bccbeb36d5527790c3930327704c39af22de3112f1b1666a9f3ce15ee204", size = 237098, upload-time = "2026-09-30T04:36:46.689Z" },
{ url = "https://files.pythonhosted.org/packages/24/0e/bb5dace3cc7e79068425386a6589c19b5a2ab5fefc2a46abea6919683332/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:52aa6992700996af31f375de0c6bacd402b0097fe40b53c426b9f51a90ebabc7", size = 274228, upload-time = "2026-09-30T04:36:48.31Z" },
{ url = "https://files.pythonhosted.org/packages/9d/79/b849ad523017ea9f5a45581bbebed91439e0cf42fd2860a6f64e358eb5a6/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:e09a3942ecbdee5cce73ea9d42da82b81b72ac1bf031ce069b93b5adf4eac8cd", size = 252401, upload-time = "2026-09-30T04:36:50.091Z" },
{ url = "https://files.pythonhosted.org/packages/89/8c/75469d690cf47200bce8f6cad7655724fc23148e147abfc5ce78b5f65863/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:c7c9ab723cde841fefb34efbad91e87f00a674b1fe1cd0784fde742bf2c154dc", size = 271846, upload-time = "2026-09-30T04:36:51.719Z" },
{ url = "https://files.pythonhosted.org/packages/26/cd/6d52d3c7437cdcf2e310ce9f28f282e733d4ef60ed19105d1819c356255f/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ddc7dacc8ece3a182e7f15cb862d1fd616b46d076cb1ae9dd232b2c38b655874", size = 258151, upload-time = "2026-09-30T04:36:53.234Z" },
{ url = "https://files.pythonhosted.org/packages/f7/4c/070b38bdb5f49a70199fce923ec0726a49536a63ab262abbfcaaf351110b/charset_normalizer-3.5.2-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:ee43c17b173d46a3212baa6ead3ae258eeabdae48c263a01ccf0218c366dd655", size = 143570, upload-time = "2026-09-30T04:36:54.816Z" },
{ url = "https://files.pythonhosted.org/packages/81/84/9ebfc8ed6c8c4fcd8e726ff6bf220cc8deb3966e31dce9be8dd8aa017e64/charset_normalizer-3.5.2-cp314-cp314-win32.whl", hash = "sha256:4f87960d57feabfb618e4e0af6e7371645fa26a277860739d6e5d6e0012c92f0", size = 186412, upload-time = "2026-09-30T04:36:56.643Z" },
{ url = "https://files.pythonhosted.org/packages/d1/78/5ed86f743d4bc350db307e7636419a0a5ee1d91806d30c7f667bd5c80dae/charset_normalizer-3.5.2-cp314-cp314-win_amd64.whl", hash = "sha256:e4e81e09c1578b8df602e3db08b0b3ea0a6947ad612f52bf8dc5ea8d47691f0c", size = 210965, upload-time = "2026-09-30T04:36:58.205Z" },
{ url = "https://files.pythonhosted.org/packages/53/94/a3a7698e9b1a395e1eb99ccd9a324be9347973bff4e72db2a06496d7cd27/charset_normalizer-3.5.2-cp314-cp314-win_arm64.whl", hash = "sha256:80d02b6f04e92601a081dd97b23d3128033098bff5d35d392ddcc0476ea11253", size = 200406, upload-time = "2026-09-30T04:36:59.764Z" },
{ url = "https://files.pythonhosted.org/packages/c1/48/c5dd00d5ef7791f02666de250a5bb6071e29b7e133cf4b835800b6d3bc27/charset_normalizer-3.5.2-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:dca9ab98072a5a54ebacebdc45f53e645336b320c667410b061be1ca588ae709", size = 396871, upload-time = "2026-09-30T04:37:01.543Z" },
{ url = "https://files.pythonhosted.org/packages/12/c8/8379554b42e8368161d898476686947a0fdbd3e8865170d7909dcabfdee8/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f0aa869112ef88429ae17820d99c3dd9504c9e9c671d3c246f3d7442cb051084", size = 249711, upload-time = "2026-09-30T04:37:03.111Z" },
{ url = "https://files.pythonhosted.org/packages/4a/eb/2ddb1035d17320caa9f41682935123a9a250277b261c3efc86b2d2a21343/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c0afc6800ba57ccc350374c5bd6150419915d95ce93cdbab2d783d75eaf30ecb", size = 231146, upload-time = "2026-09-30T04:37:04.721Z" },
{ url = "https://files.pythonhosted.org/packages/4a/24/2ecb4bde104322cd7859d6594fcfa74649f8d90b3221c9feecbef149875b/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7dcd882da75ef9adf94903b1e3b9419e8aa8fb4c7396822b834b9ef7fb96954f", size = 271552, upload-time = "2026-09-30T04:37:06.295Z" },
{ url = "https://files.pythonhosted.org/packages/3f/98/9d5f6ebc3aee9fef5d30b4aff11fb2ab7a1222b4064f8ef2c7c87cde217a/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2e06a3a98f916dd41d27f3105e02e7a40181c98c94b9158733d03a6f80506c09", size = 269810, upload-time = "2026-09-30T04:37:07.905Z" },
{ url = "https://files.pythonhosted.org/packages/09/e1/a3b06a10461b1b7628853c934c644e03bc28e42767116afb52f19a56519b/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6bd128f206a7752ae1f2ab6c61bf8a24ba28913a10df8b14c2637b973ff97a80", size = 259845, upload-time = "2026-09-30T04:37:09.554Z" },
{ url = "https://files.pythonhosted.org/packages/fd/d3/6f561f74a296cf27d61775a1dc665ad13f3bff6a798810ca05907f37a7c4/charset_normalizer-3.5.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c8f3d67aeaf55f017982b73683f0e7342ba2f6635a78f69ce89ebb26aa411e5c", size = 252825, upload-time = "2026-09-30T04:37:11.274Z" },
{ url = "https://files.pythonhosted.org/packages/26/9f/69e13ca3b18f43e0eafcd34c04a45b732ae22a43b54a5fc9e119103356eb/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:fe9753dfee015c570d73df76f899f18444d41388bffcde097deba51c4fadbb9f", size = 252659, upload-time = "2026-09-30T04:37:12.941Z" },
{ url = "https://files.pythonhosted.org/packages/73/a9/ace29806a0dae18939919c76ba526472d83214afa101105fabff2cf30625/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:92888bb3187c5ba50500b00b3b310c9f2c651709d28036077680cb5255450a03", size = 238819, upload-time = "2026-09-30T04:37:14.659Z" },
{ url = "https://files.pythonhosted.org/packages/f8/c1/6116d52a2e3311ec80f21f5fb5e17b27405f10b9608af8f6e69516841a1b/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:d008d90a7f2471519aef0c90dfbe73b3e6e4d5e66ac48e19154c17e89e98b604", size = 272973, upload-time = "2026-09-30T04:37:16.346Z" },
{ url = "https://files.pythonhosted.org/packages/19/aa/9955c7e93bba10a9c7e8f7a5031b7ced66f3a1883a55c00712b8d5850ff3/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:31f3930700408d211f13378ccbe1c40845d8da54bd0681fac3a9b5aae81c7aa8", size = 253692, upload-time = "2026-09-30T04:37:18.212Z" },
{ url = "https://files.pythonhosted.org/packages/bb/33/2a6ae7fdc1b10cb581cef91addd8cdfc5f40d50abb5702309369d5834579/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:2a925889534b3748302dae5dead07cc13480de1dac3aea80a941b729b471ef93", size = 268757, upload-time = "2026-09-30T04:37:19.877Z" },
{ url = "https://files.pythonhosted.org/packages/a2/22/80992720a0282cd39bba1db35868e6b9c22f41281160143a836544bc1d8a/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f5ec61164adcec446f8969a3358ec3f9b26bbda3b9213e5586d219afa8df2915", size = 262220, upload-time = "2026-09-30T04:37:21.583Z" },
{ url = "https://files.pythonhosted.org/packages/92/9f/181fd07e1bffea1d95cd80c84ac537354f50699c22cfc4d3c02b6fc16208/charset_normalizer-3.5.2-cp314-cp314t-win32.whl", hash = "sha256:598a11a2c7ebaa5334bf698bf29568c9c390abac6a154d8170fedecd1cea38c5", size = 197797, upload-time = "2026-09-30T04:37:23.235Z" },
{ url = "https://files.pythonhosted.org/packages/49/1c/25d8415ec1c4f2f41f1680435e4c87cfb378ff2f677d950946f2a45d0632/charset_normalizer-3.5.2-cp314-cp314t-win_amd64.whl", hash = "sha256:7fdde2c9fd9e3eca40631e024664cf2584272cc8f96308cbe5fdfc930f51d8bc", size = 222765, upload-time = "2026-09-30T04:37:24.891Z" },
{ url = "https://files.pythonhosted.org/packages/3e/b4/46b48f013dadfc0d0d33b375438e31bdf5a989dc68389c6bf627054d4df9/charset_normalizer-3.5.2-cp314-cp314t-win_arm64.whl", hash = "sha256:d1befeed746d247c81127bb14de9dc3d30edb6e5976d34f83f86ed262b1d9105", size = 210985, upload-time = "2026-09-30T04:37:26.634Z" },
{ url = "https://files.pythonhosted.org/packages/ca/e9/34e597dee616d0b8ee4b34d29399e85c2204ade174157a48505d42baa4ff/charset_normalizer-3.5.2-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:87475fabc8d9996fd9c27debb395e642e8c838d78a00b6e932227a0e06b81e26", size = 367676, upload-time = "2026-09-30T04:37:28.329Z" },
{ url = "https://files.pythonhosted.org/packages/60/9f/a5d1c91c0263745e2cd344c5a4415d787c575501ab1d449f1148ac6b495d/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9409a8bf35cf78353942504b24a57de3d75b708997a1e4bd8db71ac8633ce364", size = 248414, upload-time = "2026-09-30T04:37:30.167Z" },
{ url = "https://files.pythonhosted.org/packages/26/79/e697f77464748a3ee3cf490c83d592459400d4898380d66c38366b03080c/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:498dc3188ca05a68231ac3fdbfc7f57eb67e1343c30e0fea17f8218c1599b253", size = 244775, upload-time = "2026-09-30T04:37:31.964Z" },
{ url = "https://files.pythonhosted.org/packages/ca/87/3d42a42e18ea066e2513936fd678a00696e77878b5ae04528976abdbcb83/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e242bb1c5e76e97dfa9e7f209a71e93a01d7f19ffdd5cfbb2e2d55b4f08f8ab0", size = 273877, upload-time = "2026-09-30T04:37:33.661Z" },
{ url = "https://files.pythonhosted.org/packages/c3/76/8a28136f3938ba9836f84280ce0c4d61ed1cf15a036b2034900c62634162/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:def79fa35ef0cef8d2accec024f4fdc7ead3012ff02f5215c783f39f03ef8cfc", size = 269455, upload-time = "2026-09-30T04:37:35.573Z" },
{ url = "https://files.pythonhosted.org/packages/a0/a1/4fbf5d0f0f1b2a080474c1cf9a2f12c4c6531bb0e8ba591055e846d2b4e9/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3df041de8887954562c9b261cba85ca0e9ded74048daf125f45edcfaa4832229", size = 257336, upload-time = "2026-09-30T04:37:37.397Z" },
{ url = "https://files.pythonhosted.org/packages/ba/a2/8b50aa320adb880ad579518e6f718f24944804b42a88b83d267d5d444125/charset_normalizer-3.5.2-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:04851f73ae72b8413dddadb16a49dfee95263553741fd42d546f7d66907e6be5", size = 257584, upload-time = "2026-09-30T04:37:39.522Z" },
{ url = "https://files.pythonhosted.org/packages/a5/57/50e3fed84e175f40349bd0da7a4fce94c87f0378f52d74f511d89e0bdc20/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:183b88127acdb4fabe59d951ab424faf1af7b63cdbb5f776186c1ea2ffcaed98", size = 251854, upload-time = "2026-09-30T04:37:41.23Z" },
{ url = "https://files.pythonhosted.org/packages/d6/54/f7fbb3493c9f49091213b9c2d6dd65800696f1ce1a3f196a4205f50417b1/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:16fa0eccf81304b79c5cd87f9271c3b85dd9dd99245e4422ae9c0dd45e0f99d3", size = 248767, upload-time = "2026-09-30T04:37:42.883Z" },
{ url = "https://files.pythonhosted.org/packages/d9/37/b3a6385acc5a1e45b39ae9c90bfb9cf838a09b9dd37ef2740ab4c6b4a2eb/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:7441d755b7ab94f8d4eb3e43ec05482d760842fd263d003a99102d742cd835e2", size = 274479, upload-time = "2026-09-30T04:37:44.658Z" },
{ url = "https://files.pythonhosted.org/packages/89/44/809913e2cfd279e635a9294fdbbfb1b1dc62a8189d473d561f649fce98d8/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:ca403d7e4798f525fdfc78e258820419cbbd0f0ecbab9de7840e3c017cf6b8cf", size = 258310, upload-time = "2026-09-30T04:37:46.529Z" },
{ url = "https://files.pythonhosted.org/packages/af/a2/f28400ab13359d91bd39179df8e149376b9bf36588e739a3a4f9de2b84b2/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:df29a0a7107f7011e77f4eebdddec4c7331e24d787a0b21a46d63bdf7445da95", size = 271100, upload-time = "2026-09-30T04:37:48.399Z" },
{ url = "https://files.pythonhosted.org/packages/e9/89/9bab37955edf0adb3b66f8a3a6617d9f2f487e0d56f295a6a286cb640aa6/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:f3c96f633825733f735c5a9cf21d21a257d8e1edf0b1cee0a064b9c424ca0f7d", size = 259936, upload-time = "2026-09-30T04:37:50.023Z" },
{ url = "https://files.pythonhosted.org/packages/23/b5/4459e08d45a679f903d50fea08bc52cfa728cca4d7bd02c757b5e5abda2e/charset_normalizer-3.5.2-cp315-cp315-win32.whl", hash = "sha256:281cb91036248400f4cc957495cccd44c275c2e0c5854f7e45ac5cf7dc193847", size = 186301, upload-time = "2026-09-30T04:37:51.722Z" },
{ url = "https://files.pythonhosted.org/packages/98/e8/55d5fd3935b4bce6da4fe0df61898e8c82653e317e677bd58aceb9c60f13/charset_normalizer-3.5.2-cp315-cp315-win_amd64.whl", hash = "sha256:89b53f3cda69831909888e0494f4fa0bcd3537e3e138dabeb620bd6ad946bae8", size = 210858, upload-time = "2026-09-30T04:37:53.427Z" },
{ url = "https://files.pythonhosted.org/packages/a9/5b/974423c2fd8e524c7a7f64318c1e02240ef954912fa2b4d70344107b9c68/charset_normalizer-3.5.2-cp315-cp315-win_arm64.whl", hash = "sha256:6be488a102b8cf28d0391d8c4ba7748938ae28b78ad901f8585520fca33ead1a", size = 200309, upload-time = "2026-09-30T04:37:55.015Z" },
{ url = "https://files.pythonhosted.org/packages/ee/f9/00ee0195db1013d8f7c416fd770fbeb560bb46eb2e36b054d05cb56f6cfa/charset_normalizer-3.5.2-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:915563965d418f986e7e145accc592eae9e1a1be3566ff98a05d7a9ec42a76e1", size = 395343, upload-time = "2026-09-30T04:37:56.743Z" },
{ url = "https://files.pythonhosted.org/packages/04/3a/c00b50e94c964cf934c7899cd47c97952fc11dad71cc5884b3c61795b09b/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:65cd72beeeca9d3aaea1201e5923859f308f952f9c71de93f06063c79f0f7a3b", size = 250114, upload-time = "2026-09-30T04:37:58.607Z" },
{ url = "https://files.pythonhosted.org/packages/50/27/d102dc880bbcffd0479ab64dfc1fb96777a854355a55e2bda72a71efadcb/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b7fd005a73d9e657273b7a10dc71a9e03c8fb9ee6999798d6918ce095b81ac7f", size = 239997, upload-time = "2026-09-30T04:38:00.511Z" },
{ url = "https://files.pythonhosted.org/packages/a5/4a/bf7ef45794dd293fab5f98a9309817977fbb845b9998f171b8cc5d8437a3/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e54da4baf05720032d527874d40b65fa4d7e5c6c6a43d0c3adbeffcaf275a2b3", size = 272313, upload-time = "2026-09-30T04:38:02.509Z" },
{ url = "https://files.pythonhosted.org/packages/e8/ee/008a2837737991474c5754bb3191010007663860979701990982a502cbaf/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:124fbf1a8ff966d87ae05bb8bd45a71f966055ed8bba320d0c7cf450bc5f4d0e", size = 269986, upload-time = "2026-09-30T04:38:04.435Z" },
{ url = "https://files.pythonhosted.org/packages/93/ad/bd74a283940dc910c5b14f8e4f80a248082bc9c0fcbe1f54530cb6d9cc5e/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:28b4f0d66fb834ff90f28209ac7bce77868c45d8c93e26f906709d9b7c2e1af9", size = 260202, upload-time = "2026-09-30T04:38:06.549Z" },
{ url = "https://files.pythonhosted.org/packages/8a/7b/ed341c66f69f688723501fac752be3d63c7159ca0d0d4174fc611e5710bb/charset_normalizer-3.5.2-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:58ca3755ee7ff7f59b57789ec9833c9de9ea275405cdd240eda1f193112e398a", size = 259083, upload-time = "2026-09-30T04:38:08.311Z" },
{ url = "https://files.pythonhosted.org/packages/cc/9d/e41588b777965e5031a43128a1e96173ebb35ac75fc53ec3b517e7c21cd4/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:443eae2bf318abeaf6f15d785138f71fd6de770e99a92158b8b814265e079115", size = 253081, upload-time = "2026-09-30T04:38:10.402Z" },
{ url = "https://files.pythonhosted.org/packages/81/35/b761eb6d8c1eb218b9b42b9b4d5ac902afdc399fb6dac6f9a9aac7bda589/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:58f361dcbab699cf8f42db3f47c8e7fd1036f138c23a5d08de9fde5f425a730c", size = 248712, upload-time = "2026-09-30T04:38:12.317Z" },
{ url = "https://files.pythonhosted.org/packages/4d/2c/147169a041b747759f37405c0a97157e8e92de967968373101ff14915cba/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:1b4cbc7c3491ccb4aa17fcd8165649d01cf39f76de1696da8631b5f71b85401d", size = 274176, upload-time = "2026-09-30T04:38:14.138Z" },
{ url = "https://files.pythonhosted.org/packages/f0/2d/0ff8db0d373ba8538db686db11cd7e8912031490b9e4f383b41912e8d594/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:ba0b1d2620edf869789c3879223f52bf2afc5d31b3cb47cc57b3a12c05e2aa9d", size = 259413, upload-time = "2026-09-30T04:38:15.841Z" },
{ url = "https://files.pythonhosted.org/packages/8a/8e/b4a085fb47c9d3a7e43576a4784fdd8fe23f907514a972de8086edaf7a48/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:5e2b6b57e9733d39f0c9fd3185efa6b8e29652c4cd8fe94180272cf6ed9a78c4", size = 269434, upload-time = "2026-09-30T04:38:17.626Z" },
{ url = "https://files.pythonhosted.org/packages/83/1c/d8d8d7322a7c3eecdf3237a4a419cf41d2eaad8e006ce7dfdd9d4c8fa2eb/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:51cf45226a9b588d0d2b4880c62d686934b63ab0bd79ca23ab0e9762eb27441b", size = 262716, upload-time = "2026-09-30T04:38:19.214Z" },
{ url = "https://files.pythonhosted.org/packages/a0/16/0e4c6ba9b44e97a2da150e52d331e8f9c968b21b358fbffa6c856cebcd89/charset_normalizer-3.5.2-cp315-cp315t-win32.whl", hash = "sha256:5fb29fb8cd1a46c27a1bf9613ad5ec2599310d46b4025d9556404a6b6a292800", size = 197159, upload-time = "2026-09-30T04:38:21.037Z" },
{ url = "https://files.pythonhosted.org/packages/be/33/e90bc2b1374f7f36ef106f56620de5a783907e19ca857efe2277e31cac3e/charset_normalizer-3.5.2-cp315-cp315t-win_amd64.whl", hash = "sha256:a192e2c40070d92c3ccf777e3a5c4ff515573cd2bb7ed0c537fdadbbec5bbf21", size = 221322, upload-time = "2026-09-30T04:38:22.886Z" },
{ url = "https://files.pythonhosted.org/packages/66/89/dfa6dcb08c200b7830ab56439e8c1890f2971d51aafbb3937894a2e7fcfc/charset_normalizer-3.5.2-cp315-cp315t-win_arm64.whl", hash = "sha256:749e97e1b32313717a565abbe321bc2190bc8b35f1a67e4cdbc7c56c8d8ffe58", size = 209192, upload-time = "2026-09-30T04:38:24.648Z" },
{ url = "https://files.pythonhosted.org/packages/8c/ab/176fbfd5b64939c55d652366aa5b9ef1d767af207a3aa6ebeb0d226c484d/charset_normalizer-3.5.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd", size = 331815, upload-time = "2026-09-30T04:38:26.216Z" },
{ url = "https://files.pythonhosted.org/packages/7e/84/371eac6b30bdbcbf2d632a1a01809103459216fcaae61b8b8d922c1bfb8a/charset_normalizer-3.5.2-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7", size = 253276, upload-time = "2026-09-30T04:38:28.032Z" },
{ url = "https://files.pythonhosted.org/packages/43/6f/c4fbae58febff71709c51bc7e18fdfa55341dc382704740f9f0cbf03817b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f", size = 241239, upload-time = "2026-09-30T04:38:29.732Z" },
{ url = "https://files.pythonhosted.org/packages/61/71/458c3f42164a07d0c5210798e9e704b39e540a6793b05aba67f3a35243a9/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93", size = 231121, upload-time = "2026-09-30T04:38:31.462Z" },
{ url = "https://files.pythonhosted.org/packages/09/54/ab9e89367076f6331bb6c65c4bf14a5361fa5191cb6561bf534f18504e1b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade", size = 260350, upload-time = "2026-09-30T04:38:33.239Z" },
{ url = "https://files.pythonhosted.org/packages/7c/c1/061431ecc688d9d76602502cb57cc01e691e682c18f1beb45f9673b5bbd2/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0", size = 255430, upload-time = "2026-09-30T04:38:34.865Z" },
{ url = "https://files.pythonhosted.org/packages/8d/1f/20c8949f0676f7ab811abdeb7f4d7f1cbc6e61ff20bef08b44edeb092bc8/charset_normalizer-3.5.2-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26", size = 250612, upload-time = "2026-09-30T04:38:36.649Z" },
{ url = "https://files.pythonhosted.org/packages/2b/9e/46f2fa4c431fc98c4ae76a8cb5bdca54e0341e3cfc3fcfd8e82740250818/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011", size = 242083, upload-time = "2026-09-30T04:38:38.26Z" },
{ url = "https://files.pythonhosted.org/packages/bd/39/559be29a0c0f086e0bba6922babd38916cc5e0b58ced4de13ee01ea05508/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621", size = 232738, upload-time = "2026-09-30T04:38:39.81Z" },
{ url = "https://files.pythonhosted.org/packages/ff/6c/387b0e4f756a282831c1d9fc6aeb6c51ca4507ca202767c8de15ce9b12e2/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4", size = 260703, upload-time = "2026-09-30T04:38:41.346Z" },
{ url = "https://files.pythonhosted.org/packages/96/92/1fdf015f09ef449f50d3ac4b67c90887c9c318b727daa95cc4f866e6521d/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e", size = 247622, upload-time = "2026-09-30T04:38:42.937Z" },
{ url = "https://files.pythonhosted.org/packages/dc/3c/8e7b8a5671ad5d433669fb2a76f1a0164df2d9b1718b0206bc2a16d840cc/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c", size = 257500, upload-time = "2026-09-30T04:38:44.604Z" },
{ url = "https://files.pythonhosted.org/packages/b4/f0/45b579df5cabc1d5d53ea1cc35e8437d3ca768c0acccc7041517cb6fbb32/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0", size = 255100, upload-time = "2026-09-30T04:38:46.289Z" },
{ url = "https://files.pythonhosted.org/packages/31/68/fdec18a343f5fb3f310588dd478b09ac4799e0b187dbade3a8cd776f03ef/charset_normalizer-3.5.2-cp37-abi3-win32.whl", hash = "sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf", size = 174499, upload-time = "2026-09-30T04:38:47.999Z" },
{ url = "https://files.pythonhosted.org/packages/9d/8a/b618149cc5207943a0242068d7a27897f56a62947b5a039085f2a22029f8/charset_normalizer-3.5.2-cp37-abi3-win_amd64.whl", hash = "sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036", size = 200092, upload-time = "2026-09-30T04:38:49.707Z" },
{ url = "https://files.pythonhosted.org/packages/03/cf/4c66866fa9e2b1c78e3c911516d1de497a677b7ac60f1eceda74ce777ca3/charset_normalizer-3.5.2-cp37-abi3-win_arm64.whl", hash = "sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e", size = 294363, upload-time = "2026-09-30T04:38:51.312Z" },
{ url = "https://files.pythonhosted.org/packages/fc/ad/d07d7862a62ffa6d79d68074d14823243dd235a77c45262acbf6adeb28bf/charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685", size = 68872, upload-time = "2026-09-30T04:39:21.828Z" },
]
[[package]]
name = "click"
version = "8.5.0"
@@ -533,6 +682,83 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/65/b9/6b29500a1c581ff4d77fd83c6568d068bee06f1b139fb6eb0a4f2d4bce8a/googleapis_common_protos-1.75.5-py3-none-any.whl", hash = "sha256:d7285525c23039db98f2463e6d5a4f9b958b94d497f03a844ece3259c4e72d5d", size = 307737, upload-time = "2026-09-29T19:25:48.735Z" },
]
[[package]]
name = "greenlet"
version = "3.5.6"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/3e/6e/0091f175ccd02b02bc8811bbcbcc6ac2e980be116e3b2f7a736ca322bf84/greenlet-3.5.6.tar.gz", hash = "sha256:8e67c43bdfc88d5fee6db0d3e40175b362fc95fb85f0412d233b9b203c53a575", size = 207653, upload-time = "2026-09-14T15:42:51.806Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f1/d7/41511ee2696f14be4200b524d9553dc4295e2bdeb20aa8962c3cb25e71c6/greenlet-3.5.6-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:a6a4b98a9132e0f45c9fc245a63894cfd8c45fb7a0d6bffc5eab3ec327cf7324", size = 294075, upload-time = "2026-09-14T14:25:16.922Z" },
{ url = "https://files.pythonhosted.org/packages/f8/7b/b509624970909294cd064ff7346148ca9941c21bec9026d7873dd254e9fa/greenlet-3.5.6-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45bfd2b51e38aaa5f9849f114d9c7c1d75f69187c849b3549cd64c465283abfa", size = 613429, upload-time = "2026-09-14T15:12:00.454Z" },
{ url = "https://files.pythonhosted.org/packages/2b/5c/d2eb503067f9ba20875ef8c87681f29a64f53bbbbe4059a5d7c53179d442/greenlet-3.5.6-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3c6dede9133e1da41d561bc3fb14e92b47e2ce39ae60edefaad145658ea7c5e2", size = 625405, upload-time = "2026-09-14T15:20:41.053Z" },
{ url = "https://files.pythonhosted.org/packages/1b/24/9b071d11c8bb9f5f38cccacc38fcc234d91997a4c395cc2bf43ecae89642/greenlet-3.5.6-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4fb8e59f68845d56c23c031dcd79c329f345e4a9d2ffac91c3d1ab366bdc457b", size = 633270, upload-time = "2026-09-14T15:25:04.864Z" },
{ url = "https://files.pythonhosted.org/packages/ec/d3/63d4477ce31dff2fd802a9a20240f6606aac85977e0fb18443aae33de3f6/greenlet-3.5.6-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1c20ea32a73d17b9b60e3371240e17b0068120c98a5ec01a224a7dd8c89733ba", size = 624428, upload-time = "2026-09-14T14:35:56.895Z" },
{ url = "https://files.pythonhosted.org/packages/88/17/ac11883ecc9da19c681c8b763ee39e6f7dca2aa81874eb11a075d3cbeb00/greenlet-3.5.6-cp311-cp311-manylinux_2_39_riscv64.whl", hash = "sha256:d701eab36200c36224833d07dbdb709adb7fd4253429548ddb5e547b8ed40586", size = 428068, upload-time = "2026-09-14T15:28:35.872Z" },
{ url = "https://files.pythonhosted.org/packages/ad/aa/9cde4e00688eaa2a03b91d12e4681439a87e6aad860399e0847af6a014ca/greenlet-3.5.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:5a0b2791239c99992a86c1b635b787fe2a877d9eaaa26f8891ce943832b585ae", size = 1588385, upload-time = "2026-09-14T15:10:05.386Z" },
{ url = "https://files.pythonhosted.org/packages/5c/01/24632b5ec186b64e21e07a8f53ce5e15a7e9cb33eddee99a5fe16379afa5/greenlet-3.5.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:188bf333769b7145e2b0b4a7f09615ec550ed44d3a2a8395fb7b36f0e9901e13", size = 1653119, upload-time = "2026-09-14T14:35:48.275Z" },
{ url = "https://files.pythonhosted.org/packages/ce/6c/019d2ef898f4b9ac845167f1c6f73229e9a4e2439362a5e2ce50205a19b0/greenlet-3.5.6-cp311-cp311-win_amd64.whl", hash = "sha256:a6b4ff33f7e011bbaa148238d131c4fd4f8afbab3c104ddfbdb2b12b74ff7016", size = 323317, upload-time = "2026-09-14T14:22:38.836Z" },
{ url = "https://files.pythonhosted.org/packages/5a/7a/439df999455e3bdf02b1c68f3848d4020385ef0a01f89f706b07bf148a65/greenlet-3.5.6-cp311-cp311-win_arm64.whl", hash = "sha256:59deccd347735a7774223b05a93773fddbb298aba3cea21be4337fb4752dbe32", size = 307739, upload-time = "2026-09-14T14:23:40.469Z" },
{ url = "https://files.pythonhosted.org/packages/72/18/3fc6d951466ae9a2a688edcddde3b2e388da0a8244e0caf7117bbeb0eb95/greenlet-3.5.6-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:a5876d0a60355af98d535c47f6cd6eb0f8a432396dab26845d380b92f8412422", size = 295668, upload-time = "2026-09-14T14:22:33.241Z" },
{ url = "https://files.pythonhosted.org/packages/27/89/366d2af5061eeefa5012f510d95a99c8620dcc457609838db4d538820318/greenlet-3.5.6-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e85880b538e59a59f55117b81f208a6660ad5ac328aad9305f812d9b8bc67a0f", size = 611700, upload-time = "2026-09-14T15:12:01.962Z" },
{ url = "https://files.pythonhosted.org/packages/54/1c/07f133f865fd58ae593dd2bbec3144acaee9b04ffe2eb48c6e121747ceef/greenlet-3.5.6-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f0ba7c2a329d650628f4c8572fd1db29f0a59dd70a3e3e0710dcf18a35cce9d8", size = 624223, upload-time = "2026-09-14T15:20:42.459Z" },
{ url = "https://files.pythonhosted.org/packages/a7/f2/844dc823ff2752ad049caa6b59d57e4572f9c445934b02d3518f4c67197c/greenlet-3.5.6-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ee7d9da3bf493909cf811a3f038840cb34fab5ae2956b8a263919f6e289ab188", size = 629529, upload-time = "2026-09-14T15:25:06.354Z" },
{ url = "https://files.pythonhosted.org/packages/66/6a/1594f3869c57c149abdb380492529e04d4c0229b5e4d79572c5bd0aaa673/greenlet-3.5.6-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:975736b002ed080d124cf81a79cb7e05cb26d6b3f5c7a7b651c0fcce70353aa1", size = 621404, upload-time = "2026-09-14T14:35:59.027Z" },
{ url = "https://files.pythonhosted.org/packages/c0/42/b1f8dbc89a53b9e77859fc1ad1627d106fc361daa3ea4bdf43a91ebb4338/greenlet-3.5.6-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:71890d5247020c25c21a6b65202782bfc281d4e6e244842419d30e3492bb6dcc", size = 432385, upload-time = "2026-09-14T15:28:37.369Z" },
{ url = "https://files.pythonhosted.org/packages/a2/f5/33e5c9e48178b9259fd000f8f45caa4a65036f65d3d0c06a602f570f025d/greenlet-3.5.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:0616b8f878098c5681fd8f0dc92d887551717402342a70f0abcbfea5f5ad8a44", size = 1584998, upload-time = "2026-09-14T15:10:06.653Z" },
{ url = "https://files.pythonhosted.org/packages/ef/31/9b4e140bc24d0ad7927ebd651f5608b0acc2334d061748c3b6ad19085cfa/greenlet-3.5.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3dbb4596a6a4e5d47121a33ff20533a81e60f302d9e67b69909a8bc21a43f0a7", size = 1647568, upload-time = "2026-09-14T14:35:49.787Z" },
{ url = "https://files.pythonhosted.org/packages/c3/71/d79f1791f824f8ff15c2978746640467ae932a2365e0201069f7f272395f/greenlet-3.5.6-cp312-cp312-win_amd64.whl", hash = "sha256:7ac4abb3877c43af320392c664774eef6fa2cc063c79a55fc02d844a3cbe7395", size = 324203, upload-time = "2026-09-14T14:22:54.504Z" },
{ url = "https://files.pythonhosted.org/packages/63/af/42aca4d56e8cb321912203069d8d34734cb288222f10ad2ae102718cc577/greenlet-3.5.6-cp312-cp312-win_arm64.whl", hash = "sha256:301102a49120b095e72a7838792b41233975fc1c155daec6d98f81c00c9280e0", size = 308310, upload-time = "2026-09-14T14:24:03.008Z" },
{ url = "https://files.pythonhosted.org/packages/f1/a1/e720a38852366c589e1a46cf570b886507ad2cf591050c203365638baab0/greenlet-3.5.6-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:f96f0e30b5a95c7631b12bfe214cbc90ec8fe8cfa36920596c10514a65743519", size = 294627, upload-time = "2026-09-14T14:24:40.102Z" },
{ url = "https://files.pythonhosted.org/packages/eb/c3/58187858df41354a11e6a55b421e7af9059798abdab3a384cc51b8567c38/greenlet-3.5.6-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c75116c9de79949de23006e2d9b35ee82874c594fcf5c0311b439acaa14b8441", size = 614356, upload-time = "2026-09-14T15:12:03.399Z" },
{ url = "https://files.pythonhosted.org/packages/ce/b9/3a7e67d5f05c9760b1ad411fa52264bd69cc08e22a2ebfb4018b90628ced/greenlet-3.5.6-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cad5782f93f7f738b62c6527b6f32a60694d924029f299a8b524758cfa53d815", size = 626756, upload-time = "2026-09-14T15:20:44.269Z" },
{ url = "https://files.pythonhosted.org/packages/c6/7c/40400455f5b5a65bb83e94fde66d1be9e5ec518638113f8083ace746c309/greenlet-3.5.6-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a93ee7c6e8fd0f8a83525a51bd777be57ee17787e91d805bd8d6faf9dcada18e", size = 632632, upload-time = "2026-09-14T15:25:07.813Z" },
{ url = "https://files.pythonhosted.org/packages/85/cb/ab0c123c514ed4e94c0dc9ee2e86362633e6b998cfc05de7fc9ac2eb9690/greenlet-3.5.6-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f98e8215e172f567ce80eeaed9107fb4d32b6c44f26983d9b8334658136a205a", size = 623779, upload-time = "2026-09-14T14:36:01.104Z" },
{ url = "https://files.pythonhosted.org/packages/f9/67/1f35cff30a6c51c3f23b63d4afcc7313ab4f97490ba3676fa78178984b27/greenlet-3.5.6-cp313-cp313-manylinux_2_39_riscv64.whl", hash = "sha256:7f731ebac68ea06d628658295cb2d217b10186329fcf9a3b6a149045059bf92e", size = 434933, upload-time = "2026-09-14T15:28:38.858Z" },
{ url = "https://files.pythonhosted.org/packages/a5/26/fda8a5a06e7073333ccb038133c5893b9e0c4fe29d5992a17e83c241bc6e/greenlet-3.5.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:df19e2d0b1620039af5102563fbd96e8938c7f5c3f5828528d641d9fc585525e", size = 1584930, upload-time = "2026-09-14T15:10:08.234Z" },
{ url = "https://files.pythonhosted.org/packages/2f/37/50f8813163148d6234e08b23dcad6a9e37f01d148c8ec976e4c44ea2d918/greenlet-3.5.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:06c0e933290fba8ffe53ead4ae1b8044b0e9754b75cebf381aa2bc3e50d82fac", size = 1647590, upload-time = "2026-09-14T14:35:51.173Z" },
{ url = "https://files.pythonhosted.org/packages/86/da/b7669b09586365654083a62bd0724cf06cb74bd5085a15cdd161271f992f/greenlet-3.5.6-cp313-cp313-win_amd64.whl", hash = "sha256:5b602b4201b965a8354d74e232364a66ff243dd142e350d035f46169bb36e13d", size = 324086, upload-time = "2026-09-14T14:23:48.428Z" },
{ url = "https://files.pythonhosted.org/packages/e5/5d/c9663cfe84a2a9e0aa96f066f5b0594c227ea4c647511e087e2e11d4ac0a/greenlet-3.5.6-cp313-cp313-win_arm64.whl", hash = "sha256:876077e7ebb8c84ed068e2b23d4c62ebb010d60df84b9591af1be2f39010ffb2", size = 308211, upload-time = "2026-09-14T14:28:01.634Z" },
{ url = "https://files.pythonhosted.org/packages/66/c0/d254544ae2b8bdd311aef000fafc02828c2771b17d994b3075620ea7cc6e/greenlet-3.5.6-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:8cddea1b8339451c2fb3388e138347b6126744f33b611bdb55b7357361cfef46", size = 295221, upload-time = "2026-09-14T14:25:11.583Z" },
{ url = "https://files.pythonhosted.org/packages/18/18/eb54be16b9cc3971e09ca5b73334e1b8c804a4630d9addaaf218a4fe300f/greenlet-3.5.6-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c59acfa8eb73a1e0d484392dc002bdf001fd4ce73394e0132df3d1ab6093d7cb", size = 660992, upload-time = "2026-09-14T15:12:04.876Z" },
{ url = "https://files.pythonhosted.org/packages/8f/b4/e193efe65671dcf294bc51fcc59efb52d154adf8612c4ea016da0d2c486c/greenlet-3.5.6-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a3b4a01c6da07ef9f80d4fe8933b994bc99747bcea3eab0330a9c34d3c12655b", size = 673428, upload-time = "2026-09-14T15:20:45.756Z" },
{ url = "https://files.pythonhosted.org/packages/fd/21/631bb45fafde1dca782152377c0676d182ec924820064047f533a3627b28/greenlet-3.5.6-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:dd0b83bed3405b586a3133629f1d1a5bc7bfd64822a3b7ab342bdc68e6dbc61b", size = 677688, upload-time = "2026-09-14T15:25:09.279Z" },
{ url = "https://files.pythonhosted.org/packages/45/ac/28fa7a9e50f2859466214c4ac584d776db52c1604ad4dd158960a5af2a1f/greenlet-3.5.6-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9a09d59bef1db94f384b5bcc2d523694d338f3df6b757aeeaf7baca5d0c0be88", size = 670773, upload-time = "2026-09-14T14:36:02.577Z" },
{ url = "https://files.pythonhosted.org/packages/40/30/2b0a73e68e1e18e30b601d0d183cfdfc2beca4de5a6843c630f0fc9fb90c/greenlet-3.5.6-cp314-cp314-manylinux_2_39_riscv64.whl", hash = "sha256:fdacf26402389bdd89857ad3c045a26fe8f3314f9a8b28226f82f88463a65b77", size = 480475, upload-time = "2026-09-14T15:28:40.741Z" },
{ url = "https://files.pythonhosted.org/packages/c3/cd/fb7d6cdd86ff3427c1494854f0e35437eba05142be91f530f6da75e09e19/greenlet-3.5.6-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8b7c73d1cef3d9ae963e9ff03f6222df43efbb9054ffd2f1969c935b7fc84c02", size = 1631900, upload-time = "2026-09-14T15:10:09.745Z" },
{ url = "https://files.pythonhosted.org/packages/f6/40/143bdbb20a516628cb15074ae52ed17d850b450292609c7a6fccac6dbece/greenlet-3.5.6-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:8b27df301f56e3b3d2298095c8f7d6b68f2521f6b1693e901fa039bdbae34424", size = 1693740, upload-time = "2026-09-14T14:35:52.959Z" },
{ url = "https://files.pythonhosted.org/packages/c9/9e/019642432e6ae283301df1361227d47610709d2dc69a38f95edef266d713/greenlet-3.5.6-cp314-cp314-win_amd64.whl", hash = "sha256:f8f0bd690e1a41294ac87905e8121c81a3761ec2583c768f13467428606c8c7a", size = 327473, upload-time = "2026-09-14T14:28:12.948Z" },
{ url = "https://files.pythonhosted.org/packages/e9/7f/8aafc7bf70c948786dba7221d0dc0838e5329bebc6d434ef2208b4f0e760/greenlet-3.5.6-cp314-cp314-win_arm64.whl", hash = "sha256:8cda13494d86a4f12429641117cb6ac4bbbc9c30a33f711f7d3a2e5fbe4b0b7e", size = 311095, upload-time = "2026-09-14T14:28:00.7Z" },
{ url = "https://files.pythonhosted.org/packages/14/7e/7a205688a5b3074933b18a906608d46d106e9a79d776bdab5a4abf4b4feb/greenlet-3.5.6-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:97c5a53e8c1754df58e73f047a99e287d4da1bdfe64b0072fb25c87000897951", size = 305352, upload-time = "2026-09-14T14:21:31.962Z" },
{ url = "https://files.pythonhosted.org/packages/78/cb/9c4a57a9d9dd0256e20b8f7f4f06554c2c92badebf0ab73ce344321b78b9/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fea4427d1ffdb3b523d7daa6712038428a4c16c450b9777bdd1221cfee0eab49", size = 672671, upload-time = "2026-09-14T15:12:06.347Z" },
{ url = "https://files.pythonhosted.org/packages/97/52/c6729681ebbd298f4decd28746815acc8a0b0a0fde21d2df33776fd4d042/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:73a29b5ba642e35433166a03a3e02935e7238c4b3467fbd77523b99edea23e5b", size = 679489, upload-time = "2026-09-14T15:20:47.291Z" },
{ url = "https://files.pythonhosted.org/packages/71/76/3c11c21e0716b1f1dc7c1a4b3d690abb1d3b448c69a9d32049fecb64010a/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:61a61b4a95a4f97922c3a6f5606d3e360851584bd47e500a5161373c53810e3d", size = 681303, upload-time = "2026-09-14T15:25:11.088Z" },
{ url = "https://files.pythonhosted.org/packages/58/c5/2b6c721ba8b8963da42d5a0f57f25b8aaeb1fe9bdd156875e57f3be648a2/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:460e70b033aba8ed47e2ac9b5d0d2157b05a34fbfa30a241400aef4118902cdc", size = 676608, upload-time = "2026-09-14T14:36:03.959Z" },
{ url = "https://files.pythonhosted.org/packages/3f/26/3ae402202452cd5941bbbd483e5a74297e2397e7aa3182c2a5e3ab7d5666/greenlet-3.5.6-cp314-cp314t-manylinux_2_39_riscv64.whl", hash = "sha256:fe3170a69fe039b18ad18171e66faa9a75f6fe9d78f968fd9b54e09fbd714d81", size = 510112, upload-time = "2026-09-14T15:28:42.112Z" },
{ url = "https://files.pythonhosted.org/packages/b2/04/0d018e0d05bcdde19a0fcb907834155f1fc853a9bedd3f3f5e6acadcae19/greenlet-3.5.6-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ca80a49b53ed1d22f7282da7255f7bb2fd1935fd0f623d8613fda38745f18961", size = 1641479, upload-time = "2026-09-14T15:10:11.216Z" },
{ url = "https://files.pythonhosted.org/packages/59/bb/f02ef9073919158f6403fe3701d4ed4403d646720e7201dfc6e9d264bac3/greenlet-3.5.6-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:916f92f2a8db10508f739d0b5e00b83defe5d1115a997c54532a6d7cf8c95404", size = 1698758, upload-time = "2026-09-14T14:35:54.336Z" },
{ url = "https://files.pythonhosted.org/packages/08/a5/1f48fe647473a2dcccfd1839b2ff2c78eb57009be776b4da071e901c9bff/greenlet-3.5.6-cp314-cp314t-win_amd64.whl", hash = "sha256:886bcf1870af74c32bc310fd00a6b803445e17e51b7d5a107c7b35c0f362cc16", size = 331574, upload-time = "2026-09-14T14:27:18.451Z" },
{ url = "https://files.pythonhosted.org/packages/cd/72/3882855a75838faeb54a58aeef4fd77d20b2a86d4bad570c70d41b565dcf/greenlet-3.5.6-cp315-cp315-macosx_11_0_universal2.whl", hash = "sha256:3ac3494c381dab876cad7d0b22f3a722f3e0c8deb3a65b9e7f35ad7f58b8fcb3", size = 295926, upload-time = "2026-09-14T14:27:21.16Z" },
{ url = "https://files.pythonhosted.org/packages/10/1f/be4d957d8a9b90bcbe8db206548a42134d96222d43e5ed3fc4708fb6e24b/greenlet-3.5.6-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:602024dae6d77e161f4b89491b62ca1d4f19949d79d47b2db057e476d21179d6", size = 666910, upload-time = "2026-09-14T15:12:07.901Z" },
{ url = "https://files.pythonhosted.org/packages/a1/af/60d62571a7d6de961e4ce7625d6c2faf359345659fc782d2cdf517c34577/greenlet-3.5.6-cp315-cp315-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f8e63209c3e1e828ee6a457529b4a6d8b05d050fe0ae03a7ae49e967c5d312e0", size = 677415, upload-time = "2026-09-14T15:20:48.817Z" },
{ url = "https://files.pythonhosted.org/packages/f5/41/b3114c97c10e796010f00a30f51c81470072bca4b53e396ccca87484fcf7/greenlet-3.5.6-cp315-cp315-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:9133d68624b1f2e89ec2f554d56aea8a5b0d7168cd9320200ba58d4d794845a4", size = 681337, upload-time = "2026-09-14T15:25:12.812Z" },
{ url = "https://files.pythonhosted.org/packages/fb/16/ac9e547b611539aaed1870eb1d6ddc57abdd5924b3a99bb9b5f0b44176b8/greenlet-3.5.6-cp315-cp315-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccadce0130fd813ec86ebfe969a6c58b42acc1d0fe55a47525375b740e07b605", size = 675927, upload-time = "2026-09-14T14:36:05.34Z" },
{ url = "https://files.pythonhosted.org/packages/48/1b/d41861c2fa00968e39e467a495ca8db9ce9b6310a5d9b57561b3d0dc48fa/greenlet-3.5.6-cp315-cp315-manylinux_2_39_riscv64.whl", hash = "sha256:5adcbbfe78bdc242c71740a02e0991cc1b2f34d33c8bb15ca45eee8fd1140942", size = 487339, upload-time = "2026-09-14T15:28:43.497Z" },
{ url = "https://files.pythonhosted.org/packages/c4/b1/b7ba08d6431121741f1d30be0d5d292e76873325179a63586cd9217b62f6/greenlet-3.5.6-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:9297fb9c39b9a2c039dbcd306c410bd6906b95244dec3bba4318d36c718c164c", size = 1637236, upload-time = "2026-09-14T15:10:12.442Z" },
{ url = "https://files.pythonhosted.org/packages/af/c5/3b1cbc68f0c082022fc8717f7fe4b8b13b8d583c52352be37f4e9f55bcd2/greenlet-3.5.6-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:b374e79ffa7511afc11773aef40a4ccea6191fba1c856ea2f9c56738dca69d7a", size = 1698526, upload-time = "2026-09-14T14:35:56.039Z" },
{ url = "https://files.pythonhosted.org/packages/de/56/12941ed2711400451c89d544e10f831800a2770f19dd55eac8f0f7f2003b/greenlet-3.5.6-cp315-cp315-win_amd64.whl", hash = "sha256:7969bffa322c097bd46ae595ada6a931cefda613f18ba64587e9cff4cb320756", size = 327739, upload-time = "2026-09-14T14:23:55.768Z" },
{ url = "https://files.pythonhosted.org/packages/c5/3b/576b9ed5ac929252e340cf60b4bcb6a8515350dc20797064b1922dc4ea75/greenlet-3.5.6-cp315-cp315-win_arm64.whl", hash = "sha256:8dba0129b93e7091dfefaf4cf7000172741bff7f47bf6326fcf17f32fbb54d6b", size = 311715, upload-time = "2026-09-14T14:28:25.154Z" },
{ url = "https://files.pythonhosted.org/packages/16/c2/86cfc5555a98e12b86966ddbd24fd39af32f71f2f785c6595b7feb2db156/greenlet-3.5.6-cp315-cp315t-macosx_11_0_universal2.whl", hash = "sha256:de3de000d459402cda015068fd135aa50c0bf6f2477a80d4da1e646f123b4e78", size = 306244, upload-time = "2026-09-14T14:27:57.565Z" },
{ url = "https://files.pythonhosted.org/packages/14/6d/83ffc9d05a75a80ab3a7595dbb1d9604e5d4fc2996d73a8ae2dbd1284900/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45663c01a4de48b9a64a2ee1509d92d1dfd3afb02b2ccfc9333029d11aef996a", size = 676578, upload-time = "2026-09-14T15:12:09.468Z" },
{ url = "https://files.pythonhosted.org/packages/5d/d6/c2cf684810e5caded075970aaadea654ecb58b8382b9aecf1d231b936894/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3deccbb57a481e3a408fe61cdfd5c13e0678fc0a30fdd09597917ca87b4be877", size = 684203, upload-time = "2026-09-14T15:20:50.261Z" },
{ url = "https://files.pythonhosted.org/packages/f2/d1/039c353d5593a97a89699e989324c9bc86af499e6c6152fe0180f5742204/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:63aff70fe5aac59c72215f42ec39fcb59ff46774fa966e717f8ecb6ee2273577", size = 686023, upload-time = "2026-09-14T15:25:14.528Z" },
{ url = "https://files.pythonhosted.org/packages/62/19/00e1bee5d2af890dc8f400b54d0b0f9b489965f92bc12b407ff72cc6f469/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:311018b46472fb26ee85870847fb89eb64cc8aaddb617400789d87076f7cfeec", size = 681253, upload-time = "2026-09-14T14:36:06.742Z" },
{ url = "https://files.pythonhosted.org/packages/8a/62/97ceb8e0b2ea96046cdf8e95b042715020ebb12d83ea0690db80a8f03d23/greenlet-3.5.6-cp315-cp315t-manylinux_2_39_riscv64.whl", hash = "sha256:520648db8fb92eef7b3e6013f5a6f901cdf0d6685f639c2f7a245879f865bef7", size = 517058, upload-time = "2026-09-14T15:28:44.924Z" },
{ url = "https://files.pythonhosted.org/packages/89/58/c9275fd0ca195d1d3402931bcce8cfcc74726ff76efb1883d229e6e1a3d7/greenlet-3.5.6-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:7f924a5a9d5890649566f2f6682e0d8ad8ca23028bacffbbac36dbd7fd680176", size = 1645988, upload-time = "2026-09-14T15:10:13.758Z" },
{ url = "https://files.pythonhosted.org/packages/e0/36/b35747582fa4f1a5453f8f3002405dbac788e450cec7674dc2d204b6ccb5/greenlet-3.5.6-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:de9923832f2d8c1a5ecd8d7260465a6ca5a86888a0d129e3bd5cf0406d2fc5bf", size = 1702383, upload-time = "2026-09-14T14:35:58.143Z" },
{ url = "https://files.pythonhosted.org/packages/ed/69/6ec22ac9351e474d2a134d0ff9400dc80362d1c20f0721088ffffdfc205b/greenlet-3.5.6-cp315-cp315t-win_amd64.whl", hash = "sha256:2ab5f42ac6c238eb71770715e6e909ad9a1a92b6c681ccb64cd5a0f07edb953f", size = 331845, upload-time = "2026-09-14T14:27:41.723Z" },
{ url = "https://files.pythonhosted.org/packages/30/cf/697c051fd534e223461fb8b523890e21a24eeca229cd50624cff6f02fabd/greenlet-3.5.6-cp315-cp315t-win_arm64.whl", hash = "sha256:f9fe868463ec7e1363733af77e38a5fda3e9b63940337048c945d69e0c80ff24", size = 315070, upload-time = "2026-09-14T14:22:21.476Z" },
]
[[package]]
name = "h11"
version = "0.16.0"
@@ -952,6 +1178,25 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/36/54/0169bc772ec491108b62f644f8ecf1fe5d8ae5ebafde2ee2142210166903/pillow-12.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a", size = 7231786, upload-time = "2026-07-01T11:56:35.046Z" },
]
[[package]]
name = "playwright"
version = "1.63.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "greenlet" },
{ name = "pyee" },
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/19/dd/fbb3d34228ad753bc14464d5f2252585b73367539775a88d0a3949cf5a45/playwright-1.63.0-py3-none-macosx_10_13_x86_64.whl", hash = "sha256:84c540759e8e7f01e690e197e04060f48899d37cea322299f255843273d3385d", size = 44278407, upload-time = "2026-09-15T16:49:06.045Z" },
{ url = "https://files.pythonhosted.org/packages/f5/9a/948b930b1a8c4ee869e5a139a2b7747caa06aab56a3f09a2f0abdcbda221/playwright-1.63.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:fd1aa00631d44d55e56e0975bf3f3f285fac4a9fd2813183f0c12a488f1a1b24", size = 42944679, upload-time = "2026-09-15T16:49:10.039Z" },
{ url = "https://files.pythonhosted.org/packages/94/11/dc5c13fa1602371603acd461be47529c1b3513815d3a0dc98f642c291a10/playwright-1.63.0-py3-none-macosx_11_0_universal2.whl", hash = "sha256:c89fc4736502a1f0fac2c8ca5d10c0cbc1c669f1f4774a2d8507a43140e4d53f", size = 44278410, upload-time = "2026-09-15T16:49:13.861Z" },
{ url = "https://files.pythonhosted.org/packages/27/9c/103a5037789062bdab27c7dca53f3ca6b075b572ab2cd96eec825b3aec4e/playwright-1.63.0-py3-none-manylinux1_x86_64.whl", hash = "sha256:ad21bc07516b187965a7521c5cf0df0bd657b17482eaad74335272d35a2b07de", size = 48217159, upload-time = "2026-09-15T16:49:17.404Z" },
{ url = "https://files.pythonhosted.org/packages/f3/82/3d85505284c5a210f2da6c07b8f757524e79d1fba9cfdafe1eafb766ae59/playwright-1.63.0-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:354e15b29503565fc598b89f16fbe070459343bef9d7498a93e304864000c6a7", size = 47902708, upload-time = "2026-09-15T16:49:21.055Z" },
{ url = "https://files.pythonhosted.org/packages/69/8d/f74ff6b52751859f4b69caf66aa7d4a3c8d6c1f0c7dc9920da103612ee39/playwright-1.63.0-py3-none-win32.whl", hash = "sha256:660c00c62639e31b16700ba5456b351ddba55bb766b7ce8261223aa34928e482", size = 38606075, upload-time = "2026-09-15T16:49:29.546Z" },
{ url = "https://files.pythonhosted.org/packages/76/eb/d6b8d92658038e260dbc7dd69fb3fdbe245aac283953de8b50b02bfe5f61/playwright-1.63.0-py3-none-win_amd64.whl", hash = "sha256:2f9a707a6c6c91157ed77bff2b8caeb04b3c8d46e70d585fc134298cbe4b5cc6", size = 38606082, upload-time = "2026-09-15T16:49:32.838Z" },
{ url = "https://files.pythonhosted.org/packages/be/75/2432b3e3c7c62103b72d4c4cc8b16a56383ada372bbb0d1278591e988f71/playwright-1.63.0-py3-none-win_arm64.whl", hash = "sha256:1e4a3a838ce22fb68ad17193fcd142a19610d9d70fb9966d2239f5dddc0cc05b", size = 34523554, upload-time = "2026-09-15T16:49:36.455Z" },
]
[[package]]
name = "pluggy"
version = "1.6.0"
@@ -1134,6 +1379,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/30/a4/2bffa9f8e804325a09867f0e9d30795c80ea9f8d62560bd1b6ad6220eb2f/pydantic_settings-2.15.0-py3-none-any.whl", hash = "sha256:0ba092c291c94baceb5eff768aa0d56400a457585bc0175925a5a5510303da42", size = 69413, upload-time = "2026-08-07T09:24:55.839Z" },
]
[[package]]
name = "pyee"
version = "13.0.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/8b/04/e7c1fe4dc78a6fdbfd6c337b1c3732ff543b8a397683ab38378447baa331/pyee-13.0.1.tar.gz", hash = "sha256:0b931f7c14535667ed4c7e0d531716368715e860b988770fc7eb8578d1f67fc8", size = 31655, upload-time = "2026-02-14T21:12:28.044Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/a0/c4/b4d4827c93ef43c01f599ef31453ccc1c132b353284fc6c87d535c233129/pyee-13.0.1-py3-none-any.whl", hash = "sha256:af2f8fede4171ef667dfded53f96e2ed0d6e6bd7ee3bb46437f77e3b57689228", size = 15659, upload-time = "2026-02-14T21:12:26.263Z" },
]
[[package]]
name = "pygments"
version = "2.21.0"
@@ -1199,6 +1456,34 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930, upload-time = "2026-05-26T09:56:02.576Z" },
]
[[package]]
name = "pytest-base-url"
version = "2.1.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "pytest" },
{ name = "requests" },
]
sdist = { url = "https://files.pythonhosted.org/packages/ae/1a/b64ac368de6b993135cb70ca4e5d958a5c268094a3a2a4cac6f0021b6c4f/pytest_base_url-2.1.0.tar.gz", hash = "sha256:02748589a54f9e63fcbe62301d6b0496da0d10231b753e950c63e03aee745d45", size = 6702, upload-time = "2024-01-31T22:43:00.81Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/98/1c/b00940ab9eb8ede7897443b771987f2f4a76f06be02f1b3f01eb7567e24a/pytest_base_url-2.1.0-py3-none-any.whl", hash = "sha256:3ad15611778764d451927b2a53240c1a7a591b521ea44cebfe45849d2d2812e6", size = 5302, upload-time = "2024-01-31T22:42:58.897Z" },
]
[[package]]
name = "pytest-playwright"
version = "0.9.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "playwright" },
{ name = "pytest" },
{ name = "pytest-base-url" },
{ name = "python-slugify" },
]
sdist = { url = "https://files.pythonhosted.org/packages/26/c4/31cab1a9edfa35546950bb30c033dbfe4d4f3a216f4bafb0537a1469a70c/pytest_playwright-0.9.0.tar.gz", hash = "sha256:bd44daa852b0fb8b0e55a2f88b727507dedda0e350bea5d09420647252f2454b", size = 17899, upload-time = "2026-08-10T10:20:16.407Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ab/70/72ff5c3833f0faa9b5fb23f24c0a606f070ad33bb61b802ba38dfe125e7d/pytest_playwright-0.9.0-py3-none-any.whl", hash = "sha256:9d9dc74e335c647944cecfffa706cc9e6e4bf4c25e84592c128b584d494d4471", size = 17915, upload-time = "2026-08-10T10:20:18.253Z" },
]
[[package]]
name = "python-dotenv"
version = "1.2.3"
@@ -1217,6 +1502,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e1/04/e8135ebd1ad02c56ec633277529b2602ff99ff634be76cdba5744cf554fd/python_multipart-0.0.32-py3-none-any.whl", hash = "sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23", size = 30042, upload-time = "2026-06-04T16:18:57.319Z" },
]
[[package]]
name = "python-slugify"
version = "8.0.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "text-unidecode" },
]
sdist = { url = "https://files.pythonhosted.org/packages/87/c7/5e1547c44e31da50a460df93af11a535ace568ef89d7a811069ead340c4a/python-slugify-8.0.4.tar.gz", hash = "sha256:59202371d1d05b54a9e7720c5e038f928f45daaffe41dd10822f3907b937c856", size = 10921, upload-time = "2024-02-08T18:32:45.488Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/a4/62/02da182e544a51a5c3ccf4b03ab79df279f9c60c5e82d5e8bec7ca26ac11/python_slugify-8.0.4-py2.py3-none-any.whl", hash = "sha256:276540b79961052b66b7d116620b36518847f52d5fd9e3a70164fc8c50faa6b8", size = 10051, upload-time = "2024-02-08T18:32:43.911Z" },
]
[[package]]
name = "pyyaml"
version = "6.0.3"
@@ -1272,6 +1569,21 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" },
]
[[package]]
name = "requests"
version = "2.34.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "certifi" },
{ name = "charset-normalizer" },
{ name = "idna" },
{ name = "urllib3" },
]
sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" },
]
[[package]]
name = "rich"
version = "15.0.0"
@@ -1549,6 +1861,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/4e/d6/1ec1b290f9e0fb067899b61e1d37a30c923068bad260b216dbe37a7d2967/starlette-1.7.0-py3-none-any.whl", hash = "sha256:67f8e99895493dd2911a03f11314af6ceebeae4e704bb9f43dfc6a9db151c93e", size = 78980, upload-time = "2026-09-23T07:30:24.567Z" },
]
[[package]]
name = "text-unidecode"
version = "1.3"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/ab/e2/e9a00f0ccb71718418230718b3d900e71a5d16e701a3dae079a21e9cd8f8/text-unidecode-1.3.tar.gz", hash = "sha256:bad6603bb14d279193107714b288be206cac565dfa49aa5b105294dd5c4aab93", size = 76885, upload-time = "2019-08-30T21:36:45.405Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/a6/a5/c0b6468d3824fe3fde30dbb5e1f687b291608f9473681bbf7dabbf5a87d7/text_unidecode-1.3-py2.py3-none-any.whl", hash = "sha256:1311f10e8b895935241623731c2ba64f4c455287888b18189350b67134a822e8", size = 78154, upload-time = "2019-08-30T21:37:03.543Z" },
]
[[package]]
name = "typer"
version = "0.27.2"
+16 -14
View File
@@ -7,26 +7,28 @@ services:
- ./data:/app/data
environment:
- BASE_PATH=/birthday
- SERVICE_DOMAIN=${SERVICE_DOMAIN:-demos.roadtotech.me}
- OIDC_ISSUER=${OIDC_ISSUER:-https://auth.roadtotech.me}
- OIDC_CLIENT_ID=${OIDC_CLIENT_ID:-bdinvite-client}
- OIDC_CLIENT_SECRET=${OIDC_CLIENT_SECRET}
- OIDC_REDIRECT_URI=${OIDC_REDIRECT_URI:-https://demos.roadtotech.me/birthday/api/auth/callback}
- OIDC_GROUPS_CLAIM=${OIDC_GROUPS_CLAIM:-groups}
- SESSION_COOKIE_NAME=${SESSION_COOKIE_NAME:-bdinvite_session}
- SESSION_COOKIE_SECURE=${SESSION_COOKIE_SECURE:-true}
- SESSION_COOKIE_SAMESITE=${SESSION_COOKIE_SAMESITE:-lax}
- SESSION_SECRET_KEY=${SESSION_SECRET_KEY}
networks:
- proxy-net
labels:
- "diun.enable=false"
- "traefik.enable=true"
# Public router (invitation + public API)
- "traefik.http.routers.bdinvite-public.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
- "traefik.http.routers.bdinvite-public.entrypoints=websecure"
- "traefik.http.routers.bdinvite-public.tls=true"
- "traefik.http.routers.bdinvite-public.priority=10"
- "traefik.http.routers.bdinvite-public.service=bdinvite-svc"
# Admin router (Authelia-protected)
- "traefik.http.routers.bdinvite-admin.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && (PathPrefix(`/birthday/admin`) || PathPrefix(`/birthday/api/admin`))"
- "traefik.http.routers.bdinvite-admin.entrypoints=websecure"
- "traefik.http.routers.bdinvite-admin.tls=true"
- "traefik.http.routers.bdinvite-admin.priority=20"
- "traefik.http.routers.bdinvite-admin.middlewares=authelia-auth@docker"
- "traefik.http.routers.bdinvite-admin.service=bdinvite-svc"
# Workload router (invitation, admin, and APIs)
- "traefik.http.routers.bdinvite.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
- "traefik.http.routers.bdinvite.entrypoints=websecure"
- "traefik.http.routers.bdinvite.tls=true"
- "traefik.http.routers.bdinvite.priority=10"
- "traefik.http.routers.bdinvite.service=bdinvite-svc"
# HTTP to HTTPS redirect
- "traefik.http.routers.bdinvite-red.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
@@ -0,0 +1,51 @@
# BDInvite Graphify-assisted SSO benchmark: retrospective
## Purpose
This experiment compared two agents implementing application-level OpenID Connect single sign-on in BDInvite. The control arm used the standard repository toolchain; the Graphify arm had Graphify available for repository exploration. The plan also specified eight implementation checkpoints, a disposable OIDC fixture, external verification, and collection of token estimates and tool-use telemetry.
## Outcome
The saved telemetry contains records for CP1 through CP8 for both arms. Every record is marked `PASS`. At CP8, both records report 25 baseline tests passing, zero failed verifications, the `Remote-User` static check passing, and a successful Docker build. The stored data therefore does not support describing the implementation experiment as a failure.
The token estimates do not show lower usage in the Graphify arm. Summing the per-checkpoint `total_tokens_est` values gives:
| Arm | Estimated tokens | Checkpoint records |
| --- | ---: | ---: |
| Control | 19,907,364 | 8 |
| Graphify | 22,923,088 | 8 |
The Graphify sum is approximately 15.1% higher. This is a descriptive comparison of the stored estimates, not a reliable measurement of actual model token usage or proof that Graphify caused the difference.
## Measurement limitations
The records identify the estimation method as `character_density_approximation`, with a ratio of 3.8. These are not direct token counts from the model provider. The experiment did not capture enough authoritative usage data to make a strong claim about Graphify's effect on token consumption. Treat the percentages as exploratory only.
The frozen plan describes a broader agent-assisted SSO implementation benchmark, even though token efficiency is one of the interests. The result set is also a single paired run with one control worktree and one Graphify worktree. It cannot separate the effect of Graphify from run-to-run variation, prompt/context differences, or other agent behavior.
## What is still useful
- The frozen plan records the intended checkpoints, security requirements, and evaluation protocol.
- The fixture and evaluator source show how the work was set up and verified.
- The checkpoint JSON files preserve implementation outcomes, tool-call telemetry, commits, and estimated usage.
- The outcome suggests a useful follow-up: rerun with provider-reported token counts, repeated trials, and a clearly specified primary metric before drawing conclusions about efficiency.
## Preserved artifacts
The accompanying directories retain the frozen specification, manifest, evaluator, disposable OIDC fixture, and raw control/Graphify result records. The `control/` and `graphify/` worktrees are intentionally not part of this archive; they remain separate implementation branches (`control/feat/sso-auth` and `graphify/feat/sso-auth`).
| Artifact | Path in archive | Description & handling |
| --- | --- | --- |
| Benchmark specification | `specification/bdinvite_sso_benchmark_plan.md` | Frozen experimental protocol and checkpoint criteria (hash verified against manifest). |
| Experiment manifest | `manifest.json` | Recorded hashes, baseline commit, fixture config, and worktree metadata. |
| Gatekeeper & Evaluator | `evaluator/` (`gatekeeper.py`, `static_checks.py`, `telemetry.py`) | Evaluator support code and gatekeeper script used during the experiment. |
| Disposable OIDC Fixture | `fixture/` (`config.json`, `docker-compose.yml`, `start.sh`, `stop.sh`, `README.md`) | Disposable mock OAuth2 test fixture configuration and run scripts. |
| Raw checkpoint telemetry | `results/control/*.json`, `results/graphify/*.json` | Raw evidence records for checkpoints CP1 through CP8 for both arms. |
## Machine-specific paths and archival integrity
Certain preserved files contain absolute paths tied to the host environment where the benchmark ran:
- `manifest.json` references local filesystem paths for `canonical_brain_plan` and `source_repository`.
- `evaluator/gatekeeper.py` hardcodes an absolute path to a local commit ledger (`/home/kiskaadee/Brain/00-inbox/commit-log.csv`).
These files are preserved without modification to maintain the historical integrity of the experimental record. Any portability improvements or harness generalization should be handled as an explicit separate follow-up rather than altering frozen experiment artifacts.
@@ -0,0 +1,499 @@
#!/usr/bin/env python3
"""Unified External Evaluator & Benchmark Gatekeeper.
Usage:
python evaluator/gatekeeper.py freeze-check
python evaluator/gatekeeper.py baseline --worktree <path>
python evaluator/gatekeeper.py verify --checkpoint CP1 --worktree <path> --agent control
"""
import argparse
import hashlib
import json
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Tuple
import httpx
from rich.console import Console
from rich.table import Table
# Add parent directory to sys.path
sys.path.insert(0, str(Path(__file__).parent.parent))
from evaluator.static_checks import (
check_application_domain_imports,
check_auth_port_abstraction,
check_remote_user_purged,
)
from evaluator.telemetry import log_checkpoint_telemetry
console = Console()
BENCHMARK_ROOT = Path(__file__).resolve().parent.parent
RESULTS_DIR = BENCHMARK_ROOT / "results"
MANIFEST_PATH = BENCHMARK_ROOT / "manifest.json"
SPECIFICATION_PATH = BENCHMARK_ROOT / "specification" / "bdinvite_sso_benchmark_plan.md"
FIXTURE_DIR = BENCHMARK_ROOT / "fixture"
EVALUATOR_DIR = BENCHMARK_ROOT / "evaluator"
COMMIT_LEDGER_PATH = Path("/home/kiskaadee/Brain/00-inbox/commit-log.csv")
def run_command(cmd: List[str], cwd: Path) -> subprocess.CompletedProcess:
"""Run a shell command and return CompletedProcess."""
return subprocess.run(
cmd,
cwd=cwd,
capture_output=True,
text=True,
)
def compute_sha256(file_path: Path) -> str:
"""Compute SHA-256 hash of a file."""
h = hashlib.sha256()
with open(file_path, "rb") as f:
while chunk := f.read(65536):
h.update(chunk)
return h.hexdigest()
def verify_baseline_tests(worktree: Path) -> Tuple[bool, int, int, str]:
"""Run the original 25 backend regression tests in the target worktree."""
backend_dir = worktree / "backend"
if not backend_dir.exists():
return False, 0, 0, f"Backend directory {backend_dir} does not exist."
baseline_files = [
"tests/test_admin.py",
"tests/test_config.py",
"tests/test_map_preview.py",
"tests/test_rsvp.py",
]
res = run_command(["uv", "run", "pytest"] + baseline_files, cwd=backend_dir)
import re
m = re.search(r"(\d+) passed", res.stdout)
passed_count = int(m.group(1)) if m else 0
passed = res.returncode == 0 and passed_count >= 25 and "failed" not in res.stdout
output = res.stdout + "\n" + res.stderr
return passed, passed_count if passed else 0, 25, output
def check_git_contamination(worktree: Path) -> Tuple[bool, List[str]]:
"""Verify that graphify-out or temporary artifacts are not tracked or committed."""
violations = []
# Check untracked / staged
res = run_command(["git", "status", "--porcelain"], cwd=worktree)
for line in res.stdout.splitlines():
if "graphify-out" in line:
violations.append(f"Untracked/Staged graphify-out in git status: {line}")
# Check commit log for graphify-out leaks
log_res = run_command(
["git", "log", "--name-only", "--pretty=format:%H", "42927b9..HEAD"],
cwd=worktree,
)
for line in log_res.stdout.splitlines():
if "graphify-out" in line:
violations.append(f"Committed graphify-out file found in git history: {line}")
return len(violations) == 0, violations
def check_commit_delegation(worktree: Path, baseline_sha: str = "42927b9") -> Tuple[bool, List[str], bool]:
"""Inspect commits created on top of baseline, verifying they are recorded in commit-log.csv."""
res = run_command(
["git", "rev-list", f"{baseline_sha}..HEAD"],
cwd=worktree,
)
commit_shas = [c.strip() for c in res.stdout.splitlines() if c.strip()]
if not commit_shas:
return True, [], False
# Check commit ledger if exists
ledger_content = COMMIT_LEDGER_PATH.read_text(encoding="utf-8") if COMMIT_LEDGER_PATH.exists() else ""
all_logged = True
for sha in commit_shas:
if sha not in ledger_content:
all_logged = False
break
return True, commit_shas, all_logged
def verify_freeze() -> bool:
"""Perform comprehensive Pre-Experiment Freeze Gate verification."""
console.print("\n[bold cyan]════════════════════════════════════════════════════════════[/bold cyan]")
console.print("[bold cyan] PRE-EXPERIMENT FREEZE GATE VERIFICATION (CP0) [/bold cyan]")
console.print("[bold cyan]════════════════════════════════════════════════════════════[/bold cyan]\n")
overall_pass = True
# 1. SPECIFICATION
if not SPECIFICATION_PATH.exists():
console.print(" [red]SPECIFICATION: FAIL (File not found)[/red]")
overall_pass = False
else:
spec_hash = compute_sha256(SPECIFICATION_PATH)
manifest_data = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
expected_hash = manifest_data.get("specification", {}).get("sha256")
if spec_hash == expected_hash:
console.print(f" [green]SPECIFICATION: PASS[/green] (SHA-256: [dim]{spec_hash[:12]}...[/dim])")
else:
console.print(f" [red]SPECIFICATION: FAIL (Hash mismatch: {spec_hash} != {expected_hash})[/red]")
overall_pass = False
# 2. MANIFEST
if MANIFEST_PATH.exists():
console.print(" [green]MANIFEST: PASS[/green]")
else:
console.print(" [red]MANIFEST: FAIL (manifest.json missing)[/red]")
overall_pass = False
# 3. FIXTURE (Test container lifecycle & discovery)
fixture_ok = True
start_script = FIXTURE_DIR / "start.sh"
stop_script = FIXTURE_DIR / "stop.sh"
if not (start_script.exists() and stop_script.exists()):
console.print(" [red]FIXTURE: FAIL (start.sh or stop.sh missing)[/red]")
fixture_ok = False
overall_pass = False
else:
# Test starting fixture
start_res = run_command([str(start_script)], cwd=FIXTURE_DIR)
if start_res.returncode != 0:
console.print(f" [red]FIXTURE: FAIL (Start failed: {start_res.stderr})[/red]")
fixture_ok = False
overall_pass = False
else:
# Query discovery
try:
r = httpx.get("http://localhost:8088/default/.well-known/openid-configuration", timeout=5.0)
disc = r.json()
assert disc.get("issuer") == "http://localhost:8088/default"
assert "authorization_endpoint" in disc
assert "token_endpoint" in disc
assert "jwks_uri" in disc
except Exception as e:
console.print(f" [red]FIXTURE: FAIL (Discovery validation error: {e})[/red]")
fixture_ok = False
overall_pass = False
# Stop fixture
stop_res = run_command([str(stop_script)], cwd=FIXTURE_DIR)
if stop_res.returncode != 0:
console.print(f" [red]FIXTURE: FAIL (Stop failed: {stop_res.stderr})[/red]")
fixture_ok = False
overall_pass = False
if fixture_ok:
console.print(" [green]FIXTURE: PASS[/green] (OIDC container discovery & lifecycle verified)")
# 4. EVALUATOR (Environment & Browser)
eval_ok = True
venv_py = EVALUATOR_DIR / ".venv" / "bin" / "python"
if not venv_py.exists():
console.print(" [red]EVALUATOR: FAIL (Virtualenv missing at evaluator/.venv)[/red]")
eval_ok = False
overall_pass = False
else:
# Check required imports
check_code = "import pytest, httpx, cryptography, jwt, playwright; print('OK')"
res = run_command([str(venv_py), "-c", check_code], cwd=EVALUATOR_DIR)
if res.returncode != 0 or "OK" not in res.stdout:
console.print(f" [red]EVALUATOR: FAIL (Required dependencies missing: {res.stderr})[/red]")
eval_ok = False
overall_pass = False
if eval_ok:
console.print(" [green]EVALUATOR: PASS[/green] (Python 3.13 venv, test runners, Chromium ready)")
# 5. CONTROL BASELINE
control_path = BENCHMARK_ROOT / "control"
ctrl_ok, ctrl_passed, ctrl_total, ctrl_err = verify_baseline_tests(control_path)
if ctrl_ok:
console.print(f" [green]CONTROL BASELINE: PASS[/green] ({ctrl_passed}/{ctrl_total} tests passing, commit: [dim]42927b9[/dim])")
else:
console.print(f" [red]CONTROL BASELINE: FAIL ({ctrl_passed}/{ctrl_total} tests passing: {ctrl_err})[/red]")
overall_pass = False
# 6. GRAPHIFY BASELINE
graphify_path = BENCHMARK_ROOT / "graphify"
graph_ok, graph_passed, graph_total, graph_err = verify_baseline_tests(graphify_path)
graph_json = graphify_path / "graphify-out" / "graph.json"
if graph_ok and graph_json.exists():
console.print(f" [green]GRAPHIFY BASELINE: PASS[/green] ({graph_passed}/{graph_total} tests passing, graph.json seeded)")
else:
console.print(f" [red]GRAPHIFY BASELINE: FAIL (Tests: {graph_passed}/{graph_total}, graph.json exists: {graph_json.exists()})[/red]")
overall_pass = False
# 7. GIT CONTAMINATION BARRIER
ctrl_clean, ctrl_contam = check_git_contamination(control_path)
graph_clean, graph_contam = check_git_contamination(graphify_path)
if ctrl_clean and graph_clean:
console.print(" [green]GIT CONTAMINATION BARRIER: PASS[/green] (graphify-out excluded from commits & tree)")
else:
console.print(" [red]GIT CONTAMINATION BARRIER: FAIL[/red]")
for c in ctrl_contam + graph_contam:
console.print(f" - {c}")
overall_pass = False
console.print("\n[bold cyan]────────────────────────────────────────────────────────────[/bold cyan]")
if overall_pass:
console.print("[bold green] RESULT: EXPERIMENT: READY[/bold green]")
console.print("[bold cyan]────────────────────────────────────────────────────────────[/bold cyan]\n")
else:
console.print("[bold red] RESULT: EXPERIMENT: BLOCKED (Resolve failures before CP1)[/bold red]")
console.print("[bold cyan]────────────────────────────────────────────────────────────[/bold cyan]\n")
return overall_pass
def verify_checkpoint(checkpoint: str, worktree: Path, agent: str) -> bool:
"""Execute gatekeeper checks for the requested checkpoint."""
started_at = datetime.now(timezone.utc)
console.print(
f"[bold blue]Evaluating {checkpoint} on {agent} ({worktree.name})...[/bold blue]"
)
verification_data: Dict[str, Any] = {
"checkpoint_tests": {"passed": 0, "total": 0},
"cumulative_regression_tests": {"passed": 0, "total": 25},
"failed_verifications_count": 0,
"details": [],
}
# Step 1: Baseline tests must always pass
base_ok, base_passed, base_total, base_out = verify_baseline_tests(worktree)
verification_data["cumulative_regression_tests"]["passed"] = base_passed
if not base_ok:
console.print("[red]❌ Baseline regression tests failed![/red]")
console.print(base_out)
verification_data["failed_verifications_count"] += 1
ended_at = datetime.now(timezone.utc)
log_checkpoint_telemetry(
RESULTS_DIR,
agent,
checkpoint,
started_at,
ended_at,
status="FAIL",
outcome_reason="baseline_regression_failure",
verification_data=verification_data,
)
return False
console.print("[green]✔ Baseline regression tests passed (25/25).[/green]")
# Step 2: Git contamination check
clean_tree, contam_violations = check_git_contamination(worktree)
if not clean_tree:
console.print("[red]❌ Git contamination violation: graphify-out found in history or staged:[/red]")
for cv in contam_violations:
console.print(f" - {cv}")
ended_at = datetime.now(timezone.utc)
log_checkpoint_telemetry(
RESULTS_DIR,
agent,
checkpoint,
started_at,
ended_at,
status="FAIL",
outcome_reason="git_contamination_detected",
verification_data=verification_data,
)
return False
# Step 3: Git delegation observability check
has_commits, commit_shas, all_logged = check_commit_delegation(worktree)
passed = False
outcome_reason = "none"
if checkpoint == "CP1":
# CP1: AuthPort & Identity abstraction, application domain imports isolation
has_abstractions, notes = check_auth_port_abstraction(worktree)
import_violations = check_application_domain_imports(worktree)
for n in notes:
console.print(f" [cyan]ℹ {n}[/cyan]")
if not has_abstractions:
console.print(
"[red]❌ AuthPort interface or Identity model not found in backend/app/.[/red]"
)
verification_data["failed_verifications_count"] += 1
outcome_reason = "missing_abstractions"
elif import_violations:
console.print(
"[red]❌ Application domain directly imports auth/crypto libraries:[/red]"
)
for v in import_violations:
console.print(f" - {v}")
verification_data["failed_verifications_count"] += 1
outcome_reason = "domain_import_violations"
else:
# Run any tests added for CP1
res = run_command(["uv", "run", "pytest"], cwd=worktree / "backend")
if res.returncode == 0:
console.print(
"[green]✔ CP1 AuthPort contract & isolation verified successfully![/green]"
)
passed = True
verification_data["checkpoint_tests"]["passed"] = 1
verification_data["checkpoint_tests"]["total"] = 1
else:
console.print("[red]❌ Worktree pytest suite failed:[/red]")
console.print(res.stdout + res.stderr)
verification_data["failed_verifications_count"] += 1
outcome_reason = "test_suite_failure"
elif checkpoint == "CP6":
# CP6: Negative Barrier - Remote-User header MUST be rejected with 401
res = run_command(
[
"uv",
"run",
"python",
"-c",
"""
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
res = client.get('/birthday/api/admin/rsvps', headers={'Remote-User': 'kiskaadee'})
assert res.status_code == 401, f'Expected 401, got {res.status_code}'
print('CRITICAL NEGATIVE GATE PASSED: Remote-User without session rejected with 401')
""",
],
cwd=worktree / "backend",
)
if res.returncode == 0:
console.print(f"[green]✔ {res.stdout.strip()}[/green]")
passed = True
else:
console.print("[red]❌ Critical negative gate failed:[/red]")
console.print(res.stdout + res.stderr)
outcome_reason = "negative_barrier_failure"
elif checkpoint == "CP8":
# CP8: Purge verification: zero occurrences of Remote-User in runtime
ru_violations = check_remote_user_purged(worktree)
if ru_violations:
console.print(
f"[red]❌ Found {len(ru_violations)} runtime references to Remote-User:[/red]"
)
for v in ru_violations:
console.print(f" - {v}")
outcome_reason = "remote_user_leak_detected"
else:
console.print(
"[green]✔ Static check passed: Zero runtime occurrences of Remote-User.[/green]"
)
passed = True
else:
# Generic checkpoint test execution via worktree pytest
res = run_command(["uv", "run", "pytest"], cwd=worktree / "backend")
if res.returncode == 0:
console.print(
f"[green]✔ {checkpoint} test suite passed in worktree.[/green]"
)
passed = True
else:
console.print(f"[red]❌ {checkpoint} test suite failed in worktree:[/red]")
console.print(res.stdout + res.stderr)
outcome_reason = "test_suite_failure"
ended_at = datetime.now(timezone.utc)
status_str = "PASS" if passed else "FAIL"
# Git commit telemetry
git_telemetry = {
"commits_created": len(commit_shas),
"commit_shas": commit_shas,
"checkpoint_commit_sha": commit_shas[0] if commit_shas else "",
"commit_delegate_logged": all_logged,
}
log_checkpoint_telemetry(
RESULTS_DIR,
agent,
checkpoint,
started_at,
ended_at,
status=status_str,
outcome_reason=outcome_reason,
verification_data=verification_data,
git_data=git_telemetry,
)
if passed:
console.print(
f"[bold green]🚀 Checkpoint {checkpoint} PASSED for {agent}![/bold green]"
)
else:
console.print(
f"[bold red]⛔ Checkpoint {checkpoint} FAILED for {agent}. Agent must iterate within this checkpoint.[/bold red]"
)
return passed
def main():
parser = argparse.ArgumentParser(description="BDInvite SSO Benchmark Gatekeeper")
subparsers = parser.add_subparsers(dest="command")
# Freeze-check command
subparsers.add_parser("freeze-check")
# Baseline command
base_parser = subparsers.add_parser("baseline")
base_parser.add_argument(
"--worktree", type=Path, required=True, help="Path to worktree"
)
# Verify command
verify_parser = subparsers.add_parser("verify")
verify_parser.add_argument(
"--checkpoint",
type=str,
required=True,
choices=[f"CP{i}" for i in range(1, 9)],
)
verify_parser.add_argument(
"--worktree", type=Path, required=True, help="Path to worktree"
)
verify_parser.add_argument(
"--agent",
type=str,
required=True,
choices=["control", "graphify"],
help="Agent name",
)
args = parser.parse_args()
if args.command == "freeze-check":
ok = verify_freeze()
sys.exit(0 if ok else 1)
elif args.command == "baseline":
ok, passed, total, out = verify_baseline_tests(args.worktree)
if ok:
console.print(f"[green]✔ Baseline passed: {passed}/{total}[/green]")
sys.exit(0)
else:
console.print(f"[red]❌ Baseline failed:\n{out}[/red]")
sys.exit(1)
elif args.command == "verify":
ok = verify_checkpoint(args.checkpoint, args.worktree, args.agent)
sys.exit(0 if ok else 1)
else:
parser.print_help()
if __name__ == "__main__":
main()
@@ -0,0 +1,116 @@
"""Static architectural assertion checks for BDInvite SSO Benchmark."""
import ast
import re
from pathlib import Path
from typing import List, Tuple
def check_remote_user_purged(worktree_path: Path) -> List[str]:
"""Verify that runtime code contains zero occurrences of Remote-User header checks."""
violations = []
target_dirs = [
worktree_path / "backend" / "app",
worktree_path / "frontend" / "src",
]
pattern = re.compile(r"remote[-_]user", re.IGNORECASE)
for target_dir in target_dirs:
if not target_dir.exists():
continue
for file_path in target_dir.rglob("*"):
if not file_path.is_file() or file_path.suffix not in {
".py",
".ts",
".tsx",
".js",
".jsx",
}:
continue
try:
content = file_path.read_text(encoding="utf-8")
for line_no, line in enumerate(content.splitlines(), start=1):
if pattern.search(line):
violations.append(
f"{file_path.relative_to(worktree_path)}:{line_no}: {line.strip()}"
)
except Exception as e:
violations.append(
f"Error reading {file_path.relative_to(worktree_path)}: {e}"
)
return violations
def check_application_domain_imports(worktree_path: Path) -> List[str]:
"""Verify application domain code does not import OIDC/OAuth/JWT/cryptography libraries directly."""
violations = []
app_dir = worktree_path / "backend" / "app"
forbidden_modules = {
"authlib",
"jwt",
"jose",
"cryptography",
"oauth2",
"oauthlib",
}
# Directories to inspect (routes, models, schemas, utils) excluding any dedicated auth module
for target in app_dir.rglob("*.py"):
rel_path = target.relative_to(app_dir)
# Skip auth module itself and tests
parts = rel_path.parts
if "auth" in parts or "tests" in parts:
continue
# Also skip auth route if named auth.py under routes
if rel_path.name in {"auth.py", "oidc.py"}:
continue
try:
tree = ast.parse(target.read_text(encoding="utf-8"), filename=str(target))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
base = alias.name.split(".")[0]
if base in forbidden_modules:
violations.append(
f"{target.relative_to(worktree_path)}:{node.lineno}: import {alias.name}"
)
elif isinstance(node, ast.ImportFrom) and node.module:
base = node.module.split(".")[0]
if base in forbidden_modules:
violations.append(
f"{target.relative_to(worktree_path)}:{node.lineno}: from {node.module} import ..."
)
except Exception as e:
violations.append(
f"Error parsing AST in {target.relative_to(worktree_path)}: {e}"
)
return violations
def check_auth_port_abstraction(worktree_path: Path) -> Tuple[bool, List[str]]:
"""Verify that AuthPort and Identity abstractions are defined."""
app_dir = worktree_path / "backend" / "app"
notes = []
has_identity = False
has_auth_port = False
for py_file in app_dir.rglob("*.py"):
try:
content = py_file.read_text(encoding="utf-8")
if "class Identity" in content:
has_identity = True
notes.append(
f"Found Identity class in {py_file.relative_to(worktree_path)}"
)
if "class AuthPort" in content or "class AuthenticationPort" in content or "class IAuth" in content:
has_auth_port = True
notes.append(
f"Found AuthPort interface in {py_file.relative_to(worktree_path)}"
)
except Exception:
pass
return (has_identity and has_auth_port), notes
@@ -0,0 +1,46 @@
"""Telemetry logging utility for BDInvite SSO Benchmark."""
import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Optional
def log_checkpoint_telemetry(
results_dir: Path,
agent: str,
checkpoint: str,
started_at: datetime,
ended_at: datetime,
status: str,
outcome_reason: str = "none",
verification_data: Optional[Dict[str, Any]] = None,
git_data: Optional[Dict[str, Any]] = None,
tool_calls: Optional[Dict[str, Any]] = None,
tokens: Optional[Dict[str, Any]] = None,
rework_iterations: int = 0,
) -> Path:
"""Record structured telemetry for a completed checkpoint evaluation."""
agent_dir = results_dir / agent
agent_dir.mkdir(parents=True, exist_ok=True)
out_file = agent_dir / f"{checkpoint}.json"
duration_wall_clock = int((ended_at - started_at).total_seconds())
record = {
"agent": agent,
"checkpoint": checkpoint,
"started_at": started_at.isoformat(),
"ended_at": ended_at.isoformat(),
"duration_wall_clock_seconds": duration_wall_clock,
"rework_iterations": rework_iterations,
"status": status,
"outcome_reason": outcome_reason,
"verification": verification_data or {},
"git": git_data or {},
"tool_calls": tool_calls or {},
"tokens": tokens or {},
}
out_file.write_text(json.dumps(record, indent=2), encoding="utf-8")
return out_file
@@ -0,0 +1,37 @@
# OIDC Benchmark Fixture
This fixture provides a standards-compliant, disposable OpenID Connect (OIDC) identity provider using `ghcr.io/navikt/mock-oauth2-server:2.1.10`.
## Endpoints
* **Base Issuer**: `http://localhost:8088/default`
* **Discovery Endpoint**: `http://localhost:8088/default/.well-known/openid-configuration`
* **Authorization Endpoint**: `http://localhost:8088/default/authorize`
* **Token Endpoint**: `http://localhost:8088/default/token`
* **JWKS URI**: `http://localhost:8088/default/jwks`
* **Userinfo Endpoint**: `http://localhost:8088/default/userinfo`
## Pre-Seeded Test Users
| Username / Email | Password | Subject | Name | Groups Claim | Expected Role |
| :--- | :--- | :--- | :--- | :--- | :--- |
| `admin@example.com` | `password123` | `admin-001` | `Admin User` | `["bdinvite_admins"]` | Admin |
| `guest@example.com` | `password123` | `guest-001` | `Guest User` | `["guests"]` | Non-Admin |
## Client Configuration
* **Client ID**: `bdinvite-client` (or any string)
* **Client Secret**: `bdinvite-secret` (or any string)
* **Redirect URI**: `http://localhost:8000/birthday/api/auth/callback` (or configured callback)
* **Supported PKCE**: `S256` (RFC 7636)
* **Supported Signing Alg**: `RS256`
## Management
```bash
# Start container and await readiness
./start.sh
# Stop container
./stop.sh
```
@@ -0,0 +1,59 @@
{
"interactiveLogin": true,
"tokenCallbacks": [
{
"issuerId": "default",
"tokenExpiry": 3600,
"requestMappings": [
{
"requestParam": "username",
"match": "admin@example.com",
"claims": {
"sub": "admin-001",
"email": "admin@example.com",
"name": "Admin User",
"groups": [
"bdinvite_admins"
]
}
},
{
"requestParam": "subject",
"match": "admin@example.com",
"claims": {
"sub": "admin-001",
"email": "admin@example.com",
"name": "Admin User",
"groups": [
"bdinvite_admins"
]
}
},
{
"requestParam": "username",
"match": "guest@example.com",
"claims": {
"sub": "guest-001",
"email": "guest@example.com",
"name": "Guest User",
"groups": [
"guests"
]
}
},
{
"requestParam": "subject",
"match": "guest@example.com",
"claims": {
"sub": "guest-001",
"email": "guest@example.com",
"name": "Guest User",
"groups": [
"guests"
]
}
}
]
}
]
}
@@ -0,0 +1,12 @@
services:
oidc:
image: ghcr.io/navikt/mock-oauth2-server:2.1.10
container_name: bdinvite-benchmark-oidc
ports:
- "8088:8080"
volumes:
- ./config.json:/config.json:ro
environment:
- JSON_CONFIG_PATH=/config.json
- SERVER_PORT=8080
restart: unless-stopped
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
echo "Starting OIDC Test Container..."
docker compose up -d
echo "Waiting for OIDC Discovery Endpoint..."
RETRY=0
MAX_RETRIES=20
until curl -s -f http://localhost:8088/default/.well-known/openid-configuration > /dev/null 2>&1; do
RETRY=$((RETRY+1))
if [ "$RETRY" -ge "$MAX_RETRIES" ]; then
echo "ERROR: OIDC container failed to become ready in time."
docker compose logs
exit 1
fi
sleep 1
done
echo "✅ OIDC Test Container ready at http://localhost:8088/default"
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
echo "Stopping OIDC Test Container..."
docker compose down
echo "✅ OIDC Test Container stopped."
@@ -0,0 +1,51 @@
{
"benchmark_name": "bdinvite_sso_benchmark",
"frozen_at": "2026-10-02T22:35:40Z",
"specification": {
"path": "specification/bdinvite_sso_benchmark_plan.md",
"sha256": "4b520fb57f1c96a5d7ac492d16aaabd8accd50b5afe328a3b0066102b4f27453",
"canonical_brain_plan": "/home/kiskaadee/Brain/01-plans/bdinvite/sso-benchmark-roadmap.md"
},
"baseline": {
"source_repository": "/home/kiskaadee/Homelab/Sites/bdinvite",
"commit_sha": "42927b9858c1b091bb6e78d3abcf6f9500bd7547",
"tests_total": 25,
"tests_passed": 25,
"status": "VERIFIED_CLEAN"
},
"fixture": {
"image": "ghcr.io/navikt/mock-oauth2-server:2.1.10",
"issuer_url": "http://localhost:8088/default",
"discovery_url": "http://localhost:8088/default/.well-known/openid-configuration",
"client_id": "bdinvite-client",
"client_secret": "bdinvite-secret",
"pre_seeded_users": [
{
"username": "admin@example.com",
"groups": ["bdinvite_admins"]
},
{
"username": "guest@example.com",
"groups": ["guests"]
}
]
},
"evaluator": {
"runner": "evaluator/gatekeeper.py",
"python_env": "evaluator/.venv",
"playwright_browser": "chromium",
"checkpoints": ["CP1", "CP2", "CP3", "CP4", "CP5", "CP6", "CP7", "CP8"]
},
"worktrees": {
"control": {
"path": "control",
"branch": "control/feat/sso-auth",
"toolchain": ["grep", "find", "view_file", "git"]
},
"graphify": {
"path": "graphify",
"branch": "graphify/feat/sso-auth",
"toolchain": ["grep", "find", "view_file", "git", "graphify"]
}
}
}
@@ -0,0 +1,54 @@
{
"agent": "control",
"checkpoint": "CP1",
"started_at": "2026-10-03T03:49:18.283328+00:00",
"ended_at": "2026-10-03T03:49:35.113702+00:00",
"duration_wall_clock_seconds": 16,
"rework_iterations": 0,
"status": "PASS",
"outcome_reason": "none",
"verification": {
"checkpoint_tests": {
"passed": 1,
"total": 1
},
"cumulative_regression_tests": {
"passed": 25,
"total": 25
},
"failed_verifications_count": 0,
"details": []
},
"git": {
"commits_created": 1,
"commit_shas": [
"79c3e8252c0d2e5fc0c9694ffb876e59ec11bb1e"
],
"checkpoint_commit_sha": "79c3e8252c0d2e5fc0c9694ffb876e59ec11bb1e",
"commit_delegate_logged": false,
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 6,
"run_grep_or_find": 2
},
"implementation": {
"write_to_file": 4
},
"verification": {
"run_test_command": 5
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 480370,
"output_tokens_est": 8308,
"total_tokens_est": 488678
}
}
@@ -0,0 +1,43 @@
{
"agent": "control",
"checkpoint": "CP2",
"status": "PASS",
"outcome_reason": "none",
"turns": 61,
"verification": {
"cumulative_tests_passed": 47,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"b2cee2447286816b7ebeb35fd6b841ae6506d9ac"
],
"checkpoint_commit_sha": "b2cee2447286816b7ebeb35fd6b841ae6506d9ac",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 9
},
"implementation": {
"write_to_file": 3,
"replace_file_content": 3
},
"verification": {
"run_command": 42
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 1537210,
"output_tokens_est": 26807,
"total_tokens_est": 1564017
}
}
@@ -0,0 +1,44 @@
{
"agent": "control",
"checkpoint": "CP3",
"status": "PASS",
"outcome_reason": "none",
"turns": 62,
"verification": {
"cumulative_tests_passed": 62,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"670f4f836dc2829b313c068805b39d883651fad3"
],
"checkpoint_commit_sha": "670f4f836dc2829b313c068805b39d883651fad3",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 19,
"search_web": 3
},
"implementation": {
"write_to_file": 2,
"replace_file_content": 6
},
"verification": {
"run_command": 26
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 1954952,
"output_tokens_est": 21635,
"total_tokens_est": 1976587
}
}
@@ -0,0 +1,43 @@
{
"agent": "control",
"checkpoint": "CP4",
"status": "PASS",
"outcome_reason": "none",
"turns": 66,
"verification": {
"cumulative_tests_passed": 76,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"d7618d574ce334b6bd63fbe6967fdc30cdd13e32"
],
"checkpoint_commit_sha": "d7618d574ce334b6bd63fbe6967fdc30cdd13e32",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 28
},
"implementation": {
"write_to_file": 5,
"replace_file_content": 6
},
"verification": {
"run_command": 21
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 2592809,
"output_tokens_est": 27256,
"total_tokens_est": 2620065
}
}
@@ -0,0 +1,43 @@
{
"agent": "control",
"checkpoint": "CP5",
"status": "PASS",
"outcome_reason": "none",
"turns": 53,
"verification": {
"cumulative_tests_passed": 91,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"f20fb0fc980061a91ecdd419a975b10c754b07dc"
],
"checkpoint_commit_sha": "f20fb0fc980061a91ecdd419a975b10c754b07dc",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 27
},
"implementation": {
"write_to_file": 3,
"replace_file_content": 1
},
"verification": {
"run_command": 18
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 1431139,
"output_tokens_est": 18882,
"total_tokens_est": 1450022
}
}
@@ -0,0 +1,44 @@
{
"agent": "control",
"checkpoint": "CP6",
"status": "PASS",
"outcome_reason": "none",
"turns": 82,
"verification": {
"cumulative_tests_passed": 96,
"baseline_passed": 25,
"failed_verifications_count": 0,
"negative_barrier_passed": true
},
"git": {
"commits_created": 1,
"commit_shas": [
"b0dea63c3fdff5d1ebdb0637a0a9491091db7083"
],
"checkpoint_commit_sha": "b0dea63c3fdff5d1ebdb0637a0a9491091db7083",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 31
},
"implementation": {
"write_to_file": 1,
"replace_file_content": 16
},
"verification": {
"run_command": 28
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 3833921,
"output_tokens_est": 23609,
"total_tokens_est": 3857530
}
}
@@ -0,0 +1,45 @@
{
"agent": "control",
"checkpoint": "CP7",
"status": "PASS",
"outcome_reason": "none",
"turns": 112,
"verification": {
"cumulative_tests_passed": 97,
"baseline_passed": 25,
"failed_verifications_count": 0,
"playwright_passed": true
},
"git": {
"commits_created": 1,
"commit_shas": [
"d9b589ccdaf7a3089b4aa107c641d81ad1792d74"
],
"checkpoint_commit_sha": "d9b589ccdaf7a3089b4aa107c641d81ad1792d74",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 34
},
"implementation": {
"write_to_file": 1,
"replace_file_content": 10
},
"verification": {
"run_command": 57,
"manage_task": 6
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 4271564,
"output_tokens_est": 19886,
"total_tokens_est": 4291450
}
}
@@ -0,0 +1,45 @@
{
"agent": "control",
"checkpoint": "CP8",
"status": "PASS",
"outcome_reason": "none",
"turns": 96,
"verification": {
"cumulative_tests_passed": 110,
"baseline_passed": 25,
"failed_verifications_count": 0,
"static_remote_user_purged": true,
"docker_build_passed": true
},
"git": {
"commits_created": 1,
"commit_shas": [
"713a5827695539993ff0cb3d12e8b0c0ebccb9f1"
],
"checkpoint_commit_sha": "713a5827695539993ff0cb3d12e8b0c0ebccb9f1",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 35
},
"implementation": {
"write_to_file": 3,
"replace_file_content": 10
},
"verification": {
"run_command": 44
},
"subagent_delegation": {
"git_commit": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 3636852,
"output_tokens_est": 22163,
"total_tokens_est": 3659015
}
}
@@ -0,0 +1,60 @@
{
"agent": "graphify",
"checkpoint": "CP1",
"started_at": "2026-10-03T03:49:39.232144+00:00",
"ended_at": "2026-10-03T03:49:56.661509+00:00",
"duration_wall_clock_seconds": 17,
"rework_iterations": 0,
"status": "PASS",
"outcome_reason": "none",
"verification": {
"checkpoint_tests": {
"passed": 1,
"total": 1
},
"cumulative_regression_tests": {
"passed": 25,
"total": 25
},
"failed_verifications_count": 0,
"details": []
},
"git": {
"commits_created": 1,
"commit_shas": [
"df498979d97a6ac2d58deb4f3f33b12556853217"
],
"checkpoint_commit_sha": "df498979d97a6ac2d58deb4f3f33b12556853217",
"commit_delegate_logged": false,
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 6,
"run_grep_or_find": 4,
"graphify_queries": 2,
"graphify_updates": 1
},
"implementation": {
"write_to_file": 3
},
"verification": {
"run_test_command": 6
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_updates": 1,
"graph_queries": 2
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 402812,
"output_tokens_est": 8740,
"total_tokens_est": 411553
}
}
@@ -0,0 +1,47 @@
{
"agent": "graphify",
"checkpoint": "CP2",
"status": "PASS",
"outcome_reason": "none",
"turns": 52,
"verification": {
"cumulative_tests_passed": 44,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"0a4032a34489e46a4540c4d5f5d89ee8aad2ba20"
],
"checkpoint_commit_sha": "0a4032a34489e46a4540c4d5f5d89ee8aad2ba20",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 7,
"graphify_update": 1
},
"implementation": {
"write_to_file": 3,
"replace_file_content": 1
},
"verification": {
"run_command": 37
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_updates": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 1041206,
"output_tokens_est": 24935,
"total_tokens_est": 1066142
}
}
@@ -0,0 +1,47 @@
{
"agent": "graphify",
"checkpoint": "CP3",
"status": "PASS",
"outcome_reason": "none",
"turns": 67,
"verification": {
"cumulative_tests_passed": 59,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"35be202adc7a8b93cf834ae68e2b592969abcc53"
],
"checkpoint_commit_sha": "35be202adc7a8b93cf834ae68e2b592969abcc53",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 20,
"graphify_update": 1
},
"implementation": {
"write_to_file": 1,
"replace_file_content": 5
},
"verification": {
"run_command": 28
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_updates": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 2392589,
"output_tokens_est": 26065,
"total_tokens_est": 2418654
}
}
@@ -0,0 +1,47 @@
{
"agent": "graphify",
"checkpoint": "CP4",
"status": "PASS",
"outcome_reason": "none",
"turns": 101,
"verification": {
"cumulative_tests_passed": 70,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"815a5847c6b4b557a1e181af67af05ce9d933001"
],
"checkpoint_commit_sha": "815a5847c6b4b557a1e181af67af05ce9d933001",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 41,
"graphify_update": 1
},
"implementation": {
"write_to_file": 3,
"replace_file_content": 14
},
"verification": {
"run_command": 39
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_updates": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 4542036,
"output_tokens_est": 32881,
"total_tokens_est": 4574917
}
}
@@ -0,0 +1,47 @@
{
"agent": "graphify",
"checkpoint": "CP5",
"status": "PASS",
"outcome_reason": "none",
"turns": 53,
"verification": {
"cumulative_tests_passed": 90,
"baseline_passed": 25,
"failed_verifications_count": 0
},
"git": {
"commits_created": 1,
"commit_shas": [
"27015d0d72e248e779ce091b5aacd0d8f22475f3"
],
"checkpoint_commit_sha": "27015d0d72e248e779ce091b5aacd0d8f22475f3",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 15,
"graphify_update": 1
},
"implementation": {
"write_to_file": 2,
"replace_file_content": 4
},
"verification": {
"run_command": 25
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_updates": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 1191995,
"output_tokens_est": 16039,
"total_tokens_est": 1208035
}
}
@@ -0,0 +1,48 @@
{
"agent": "graphify",
"checkpoint": "CP6",
"status": "PASS",
"outcome_reason": "none",
"turns": 79,
"verification": {
"cumulative_tests_passed": 95,
"baseline_passed": 25,
"failed_verifications_count": 0,
"negative_barrier_passed": true
},
"git": {
"commits_created": 1,
"commit_shas": [
"39ac42cfcea3bd379f7089bdf882703850ab3535"
],
"checkpoint_commit_sha": "39ac42cfcea3bd379f7089bdf882703850ab3535",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 32,
"graphify_update": 1
},
"implementation": {
"write_to_file": 1,
"replace_file_content": 11
},
"verification": {
"run_command": 31
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_updates": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 3348307,
"output_tokens_est": 21892,
"total_tokens_est": 3370200
}
}
@@ -0,0 +1,53 @@
{
"agent": "graphify",
"checkpoint": "CP7",
"status": "PASS",
"outcome_reason": "none",
"turns": 147,
"verification": {
"cumulative_tests_passed": 96,
"baseline_passed": 25,
"failed_verifications_count": 0,
"playwright_passed": true
},
"git": {
"commits_created": 1,
"commit_shas": [
"e1f745608a9a00a27baaa014b2d631f91adcbecd"
],
"checkpoint_commit_sha": "e1f745608a9a00a27baaa014b2d631f91adcbecd",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 41,
"graphify_query": 1,
"graphify_update": 1,
"search_web": 1
},
"implementation": {
"write_to_file": 1,
"replace_file_content": 7
},
"verification": {
"run_command": 87,
"manage_task": 5,
"schedule": 1
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_queries": 1,
"graph_updates": 1
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 6747276,
"output_tokens_est": 26848,
"total_tokens_est": 6774124
}
}
@@ -0,0 +1,49 @@
{
"agent": "graphify",
"checkpoint": "CP8",
"status": "PASS",
"outcome_reason": "none",
"turns": 93,
"verification": {
"cumulative_tests_passed": 115,
"baseline_passed": 25,
"failed_verifications_count": 0,
"static_remote_user_purged": true,
"docker_build_passed": true
},
"git": {
"commits_created": 1,
"commit_shas": [
"30d9a889a351b53158c0da87491194fb3056943a"
],
"checkpoint_commit_sha": "30d9a889a351b53158c0da87491194fb3056943a",
"commit_delegate_invocations": 1,
"commit_delegate_verified": true
},
"tool_calls": {
"exploration": {
"view_file": 30,
"graphify_update": 2
},
"implementation": {
"write_to_file": 2,
"replace_file_content": 13
},
"verification": {
"run_command": 44
},
"subagent_delegation": {
"git_commit": 1
},
"graph_lifecycle": {
"graph_updates": 2
}
},
"token_estimate": {
"method": "character_density_approximation",
"char_density_ratio": 3.8,
"input_context_tokens_est": 3079082,
"output_tokens_est": 20381,
"total_tokens_est": 3099463
}
}
@@ -0,0 +1,376 @@
# Implementation Plan: BDInvite SSO Benchmark & Checkpoint Roadmap (Frozen Specification v6)
## Goal Description
Establish a controlled, reproducible A/B benchmark comparing two autonomous agents implementing application-level OpenID Connect (OIDC) Single Sign-On (SSO) in the `bdinvite` repository:
1. **Control Agent**: Standard repository exploration and toolchain (`grep`, `find`, `view_file`, `git`, etc.).
2. **Treatment Agent (Graphify)**: Standard toolchain **plus** Graphify-augmented exploration (`graphify query`, `graphify path`, `graphify explain`, and `graphify update .`).
### Core Architectural Invariant: Hexagonal Authentication Boundary
The benchmark moves authentication from an infrastructure property (Traefik reverse proxy + Authelia ForwardAuth + `Remote-User` header inspection) into a **decoupled application port (`AuthPort`)**:
* **Strict Separation of Authentication vs. Authorization**:
- **Authentication ("Who are you?")**: Handled by `AuthPort`, which resolves requests into typed `Identity` objects carrying standard attributes and group memberships (`groups: list[str]`).
- **Authorization ("What are you allowed to do?")**: Handled exclusively by the **Application Domain**, which evaluates application policies against `identity.groups` (e.g., `"bdinvite_admins" in identity.groups`). `AuthPort` does not own authorization decisions.
* **Identity Origin Integrity**: `Identity` contains only claims authenticated and validated by the authentication module. Application code must **never** construct an authenticated `Identity` directly from unvalidated request-controlled data (headers, query parameters, body).
* **OIDC Authentication Module**: Implements `AuthPort` and communicates with any standards-compliant OIDC Provider through a generic OIDC client (discovery, PKCE/state/nonce, token exchange, JWKS signature validation).
* **Deployment Independence**: The exact same codebase runs:
- Locally / standalone against a disposable standards-compliant OIDC test container.
- In homelab production against **Authelia configured as an OIDC Provider**, reducing Traefik strictly to TLS termination and reverse-proxy routing (zero ForwardAuth middleware).
---
## Epistemic Roles of Benchmark Artifacts
The experiment maintains a strict division of artifact roles across three distinct locations:
| Artifact | Location | Epistemic Role | Mutability |
| :--- | :--- | :--- | :--- |
| **Canonical Engineering Plan** | `Brain/01-plans/bdinvite/sso-benchmark-roadmap.md` | Vault knowledge graph, project topology, roadmap | Mutable across project lifecycle |
| **Immutable Benchmark Snapshot** | `benchmark/specification/bdinvite_sso_benchmark_plan.md` | Concrete experimental input; hashed (SHA-256) | **Immutable / Frozen** |
| **Machine Event Ledger** | `Brain/00-inbox/commit-log.csv` | Lossless event capture from `commit-logger` | Append-only raw data |
---
## Frozen Experimental Invariants & Decisions
1. **Authentication vs. Authorization Separation**:
- `AuthPort` defines only authentication mechanics: `current_identity(request)`, `login(request)`, and `logout(request)`.
- `Identity` carries `subject`, `email`, `name`, and `groups: list[str]`.
- Group authorization is an application-domain policy: `require_group("bdinvite_admins")` verifies `"bdinvite_admins" in identity.groups`.
2. **Identity Origin Integrity**:
- Identity fields must be derived exclusively from claims contained in the cryptographically validated ID token / validated OIDC authentication result. Unvalidated userinfo or request data must not be used to construct `Identity`.
3. **Session Contract & Session Fixation Protection**:
- Browser session uses `HttpOnly: true` and an explicit `SameSite` policy. No bearer tokens exposed to JavaScript.
- Successful authentication must establish a **new session identifier**; an existing pre-authentication session identifier must not be promoted into an authenticated session (`pre_auth_session_id != post_auth_session_id`).
- `Secure` flag contract: `Secure=True` in production; configurable (`Secure=False`) in the local HTTP test environment so browsers do not reject cookies over local test ports.
- Internal storage (client-side encrypted/signed vs server-side SQLite table) is left to the agent's architectural discretion.
4. **Provider Model & Group Claim**:
- The test fixture uses a standards-compliant disposable OIDC provider container pre-seeded with discovery, JWKS, and standard users.
- The fixture's group claim is frozen as `"groups": ["bdinvite_admins"]` (for admin) and `"groups": ["guests"]` (for guest). The auth module maps this configured claim to `Identity.groups`.
5. **Git Workflow Invariant (Subagent Delegation)**:
- At every meaningful implementation milestone required by the roadmap, the primary implementation agent **must recruit the `git-commit` skill via subagent delegation** (`invoke_subagent` with Role: "Git History Custodian").
- **Both Control and Treatment agents MUST use the identical `git-commit` workflow.**
- **Graphify is explicitly excluded from the `git-commit` subagent's toolset and prompt.** The experimental variable remains strictly confined to the primary agent's repository exploration.
- The benchmark harness records the resulting commit SHA, parent SHA, subject, checkpoint, and timing. The harness itself **never** creates implementation commits.
- Commits created solely to manipulate benchmark metrics without meaningful code/test changes are prohibited.
6. **Graphify Lifecycle Rules**:
- The Graphify agent may run `graphify update .` whenever repository changes make the existing graph stale.
- Every graph update, query, path, and explanation is recorded in telemetry under `graph_lifecycle`.
- The prompt does **not** force the agent to use Graphify; Graphify is simply available as an additional capability alongside standard tools.
7. **Evaluator Immutability Barrier**:
- Neither agent may alter the roadmap, checkpoint definitions, verification test suite, test credentials, or telemetry logger. All evaluation occurs via an external test runner outside the agents' worktrees.
---
## Pre-Experiment Preparation & Freeze Phase
Before either implementation agent touches a worktree, the experiment harness executes the **Pre-Experiment Freeze Gate**:
```mermaid
flowchart TD
Start["Pre-Experiment Freeze Gate"] --> FreezeSpec["1. Write & Hash Specification<br/>benchmark/specification/bdinvite_sso_benchmark_plan.md<br/>Compute SHA-256"]
FreezeSpec --> FreezeHarness["2. Freeze Evaluator & Test Suite<br/>(External pytest + Playwright tests)"]
FreezeHarness --> FreezeFixture["3. Freeze OIDC Fixture & Credentials<br/>(Docker Compose + JWKS + Users)"]
FreezeFixture --> BaselineManifest["4. Generate baseline.json<br/>(Observed Commit SHA, 25 Passing Tests, Builds)"]
BaselineManifest --> Worktrees["5. Stand Up Isolated Worktrees<br/>control/ & graphify/<br/>Verify Identical Starting Commit"]
Worktrees --> CP0Done["CP0 Readiness Verified<br/>Launch Benchmark Execution"]
```
1. **Specification Hashing**:
- Write immutable snapshot to `/home/kiskaadee/Projects/tests/bdinvite-benchmark/specification/bdinvite_sso_benchmark_plan.md`.
- Calculate and record its SHA-256 hash in `manifest.json`.
2. **Evaluator Freeze**:
- Scaffold external evaluation scripts and test suites under `benchmark/evaluator/`.
3. **Fixture Freeze**:
- Stand up the disposable OIDC provider container (pre-seeded with discovery, JWKS, client credentials, and users).
4. **Baseline Manifest Generation**:
- Record observed starting commit (`42927b9858c1b091bb6e78d3abcf6f9500bd7547`), verify 25 passing backend tests, frontend build, and Docker container build.
5. **Worktree Provisioning**:
- Create worktree: `/home/kiskaadee/Projects/tests/bdinvite-benchmark/control` (branch `control/feat/sso-auth`).
- Create worktree: `/home/kiskaadee/Projects/tests/bdinvite-benchmark/graphify` (branch `graphify/feat/sso-auth`).
- Run initial `graphify extract . --code-only` inside the `graphify` worktree.
---
## Sequential Checkpoint Roadmap (CP1 – CP8)
```mermaid
flowchart LR
CP1["CP1: AuthPort Contract"] --> CP2["CP2: OIDC Client & PKCE"]
CP2 --> CP3["CP3: Identity Resolution"]
CP3 --> CP4["CP4: HttpOnly Session & Fixation"]
CP4 --> CP5["CP5: DI Dependencies"]
CP5 --> CP6["CP6: Admin Route Migration"]
CP6 --> CP7["CP7: Browser SSO Flow"]
CP7 --> CP8["CP8: Hardening & Independence"]
```
---
### Checkpoint 1 (CP1): The Authentication Port (`AuthPort`)
* **Objective**: Define the application-facing authentication boundary and identity domain models, decoupling the application domain completely from upstream protocols and proxies.
* **Behavioral Requirements**:
- Define domain abstraction: `Identity` (holding `subject: str`, `email: str`, `name: Optional[str]`, `groups: list[str]`).
- Identity Origin Integrity: `Identity` must only be constructed from validated authentication results, never raw client headers.
- Define `AuthPort` protocol establishing:
* `current_identity(request: Request) -> Optional[Identity]`
* `login(request: Request) -> Response`
* `logout(request: Request) -> Response`
- Zero application routes or domain models may import or reference OIDC, OAuth, JWT, or proxy headers.
* **Verification & Invariant**:
- Unit tests verifying `AuthPort` contract with a test mock implementation.
- **Behavioral Invariant**: **No externally observable application behavior changes during CP1.** (Minimal dependency wiring and unit tests are allowed; existing endpoints behave identically).
- All 25 baseline tests continue to pass.
* **Exit Criteria**:
- `AuthPort` abstraction established and testable in isolation.
- Changes committed via `git-commit` subagent.
---
### Checkpoint 2 (CP2): Generic OIDC Client, PKCE & Cryptographic Verification
* **Objective**: Implement the generic OIDC protocol client capable of communicating with any OIDC provider with strict PKCE, CSRF state, and replay nonce validation.
* **Protocol Invariants & Behavioral Requirements**:
- Fetch and parse OIDC discovery document (`/.well-known/openid-configuration`).
- **PKCE (RFC 7636)**:
* Generate cryptographically random `code_verifier`.
* Derive `code_challenge` using SHA-256 (`code_challenge_method=S256`).
* Include `code_challenge` and `code_challenge_method` in the authorization request.
* Persist `code_verifier` across the transaction and supply it in the token exchange.
- **Transaction Correlation (`state`)**: Construct authorization URL with a cryptographic `state` parameter; validate `state` on callback to prevent CSRF attacks.
- **Replay Protection (`nonce`)**: Construct authorization URL with a cryptographic `nonce`; validate that the signed ID token's `nonce` claim matches the initiated request.
- Exchange authorization code for token response (`/token`).
- Cryptographically validate ID Token:
* Signature verification against provider's JWKS endpoint (`/jwks.json`).
* Issuer validation (`iss` == configured issuer).
* Audience validation (`aud` == configured client ID).
* Expiration validation (`exp` > current timestamp).
* **Verification**:
- Automated tests against the OIDC test container:
* Valid code exchange returns signed ID token.
* Authorization request verified to contain PKCE and `state`/`nonce` parameters.
* Invalid `state` rejected with 400.
* Mismatched `nonce`, missing PKCE verifier, or expired token rejected with 401.
* Tampered signature rejected with 401.
* **Exit Criteria**:
- OIDC exchange passes all cryptographic and protocol validation gates.
- Changes committed via `git-commit` subagent.
---
### Checkpoint 3 (CP3): OIDC Identity & Group Extraction
* **Objective**: Connect the generic OIDC client to the `AuthPort` identity resolution lifecycle, deriving identity strictly from authenticated claims.
* **Behavioral Requirements**:
- Extract standard claims (`sub`, `email`, `name`).
- Extract group membership claims from the frozen fixture claim path (`"groups"`).
- Authoritative Provenance: `Identity` fields must be derived exclusively from claims contained in the cryptographically validated ID token / validated OIDC authentication result; unvalidated userinfo or request data must not be used to construct `Identity`.
- Confirm `admin@example.com` produces `groups: ["bdinvite_admins"]` and `guest@example.com` produces `groups: ["guests"]`.
* **Verification**:
- Test verifying end-to-end extraction from OIDC callback to typed `Identity`.
* **Exit Criteria**:
- Clean mapping from provider claims to application `Identity`.
- Changes committed via `git-commit` subagent.
---
### Checkpoint 4 (CP4): Browser Session Management & Session Fixation Protection
* **Objective**: Establish and persist an application-level browser session following successful OIDC authentication with session fixation protection.
* **Behavioral Requirements**:
- Issue session identifier via `HttpOnly`, `SameSite` cookie upon successful authentication.
- **Session Fixation Barrier**: Successful authentication must establish a **new session identifier**; an existing pre-authentication session identifier must not be promoted into an authenticated session (`pre_auth_session_id != post_auth_session_id`).
- Cookie security configuration: `Secure=True` in production, configurable for local HTTP testing.
- Session resolution: identify returning requests from the session cookie.
- Expiration: reject expired sessions.
- Invalidation: `/birthday/api/auth/logout` revokes session and clears cookie.
- Security Invariant: Session token/cookie must not be readable by client-side JavaScript (`HttpOnly: true`).
* **Verification**:
- Tests verifying:
* Pre-authentication session ID is rotated upon login.
* Request with valid session cookie resolves to authenticated `Identity`.
* Request without cookie resolves to anonymous (`None`).
* Tampered cookie rejected (401).
* Logout clears session.
* **Exit Criteria**:
- Browser session contract fully functional and verified.
- Changes committed via `git-commit` subagent.
---
### Checkpoint 5 (CP5): FastAPI Dependency Injection (Isolated Verification)
* **Objective**: Expose authentication and group authorization to FastAPI endpoints via standard dependency injection (`Depends`), verified independently on isolated test harnesses before modifying production admin routes.
* **Behavioral Requirements**:
- Implement FastAPI dependencies:
* `get_current_identity -> Optional[Identity]`
* `require_authenticated -> Identity` (401 if anonymous)
* `require_group(group_name: str) -> Callable[..., Identity]` (401 if anonymous, 403 if missing group)
- Application authorization policy:
* `require_admin = require_group("bdinvite_admins")`
* **Verification**:
- Verified on dedicated test routes / unit dependency harnesses:
* Anonymous request $\to$ 401 Unauthorized.
* Authenticated user without `bdinvite_admins` $\to$ 403 Forbidden.
* Authenticated user with `bdinvite_admins` $\to$ yields `Identity` object.
* **Exit Criteria**:
- Dependency injection contract verified in isolation without yet altering production admin routes.
- Changes committed via `git-commit` subagent.
---
### Checkpoint 6 (CP6): Admin API Route Migration & Negative Barrier
* **Objective**: Migrate all endpoints in `backend/app/routes/admin.py` to use `Depends(require_group("bdinvite_admins"))`, purging `Remote-User` from runtime code.
* **Behavioral Requirements**:
- Update `/rsvps`, `/export`, `/config`, `/map-preview/generate` to consume the new group authorization dependency.
- Update `test_admin.py` test suite to use test session injection rather than mock headers.
- Anonymous requests receive 401 Unauthorized.
- Authenticated non-admin requests (`guest@example.com`) receive 403 Forbidden.
- Authenticated admin requests (`admin@example.com`) succeed.
- **CRITICAL NEGATIVE GATE**:
```python
def test_remote_user_header_strictly_ignored(client):
# A request containing Remote-User without a valid session MUST be rejected
res = client.get("/birthday/api/admin/rsvps", headers={"Remote-User": "kiskaadee"})
assert res.status_code == 401
```
* **Exit Criteria**:
- Negative gate passes.
- All existing admin functionality (RSVP listing, CSV export, config updates) passes cleanly.
- Changes committed via `git-commit` subagent.
---
### Checkpoint 7 (CP7): Complete Browser SSO Flow (Playwright Acceptance)
* **Objective**: Integrate the React SPA in `frontend/src/admin` with the OIDC authentication flow and verify the complete browser lifecycle using a real browser automation suite (Playwright).
* **Deterministic Contract & Behavioral Requirements**:
- An unauthenticated navigation to `/birthday/admin` must initiate authentication by navigating to `/birthday/api/auth/login`.
- The login endpoint redirects to the configured OIDC authorization endpoint.
- Callback completes, sets `HttpOnly` cookie, and redirects user into `/birthday/admin`.
- Admin header displays authenticated user info and a working Logout button.
- Clicking Logout calls `/birthday/api/auth/logout` and returns UI to unauthenticated state.
* **Verification (Playwright Acceptance Suite)**:
- Real browser automation validating the entire interactive loop:
1. Navigate to `/birthday/admin` $\to$ redirected to OIDC login.
2. Submit test credentials (`admin@example.com` / `password123`).
3. Browser follows redirect to callback $\to$ receives `HttpOnly` session cookie $\to$ lands on Admin Dashboard.
4. Confirm RSVPs table renders live data.
5. Click Logout button $\to$ cookie invalidated $\to$ unauthenticated state confirmed.
- Frontend TypeScript build compiles with zero errors (`npm run build`).
* **Exit Criteria**:
- Playwright browser acceptance test passes 100%.
- Changes committed via `git-commit` subagent.
---
### Checkpoint 8 (CP8): Security Hardening & Deployment Independence
* **Objective**: Subject the completed application to adversarial edge cases, verify cumulative test status, and verify dual-environment deployment.
* **Adversarial & Security Verification**:
1. Forged / invalid CSRF `state` $\to$ 400 Bad Request.
2. Forged / tampered ID token $\to$ 401 Unauthorized.
3. Mismatched / replayed `nonce` $\to$ 401 Unauthorized.
4. Missing or invalid PKCE `code_verifier` $\to$ 401 Unauthorized.
5. Expired ID token / expired session $\to$ 401 Unauthorized.
6. Non-admin user accessing admin APIs $\to$ 403 Forbidden.
7. Forged `Remote-User` header $\to$ 401 Unauthorized.
* **Deployment Independence Verification**:
1. **Direct Standalone Mode**: BDInvite + OIDC test container with NO Traefik and NO Authelia $\to$ **PASS**.
2. **Homelab Production Mode**: BDInvite deployed with Authelia acting as an OIDC provider, with Traefik providing pure TLS/ingress $\to$ **PASS**.
* **Cumulative Verification Definition**:
The cumulative suite requires 100% pass across:
- All checkpoint-specific suites (CP1–CP7).
- All baseline regression tests (25/25 original tests).
- Playwright end-to-end browser suite.
- CP8 adversarial security suite.
* **Exit Criteria**:
- All cumulative verification tests pass.
- Multi-stage Docker container builds successfully.
- Changes committed via `git-commit` subagent.
- Final checkpoint report generated.
---
## Enhanced Telemetry & Metric Capture Protocol
For each subagent across each checkpoint (CP1 to CP8), the experiment harness records granular telemetry into `results/<agent>/<checkpoint>.json`:
```json
{
"agent": "control | graphify",
"checkpoint": "CP4",
"started_at": "2026-10-02T22:30:00Z",
"ended_at": "2026-10-02T22:45:00Z",
"duration_wall_clock_seconds": 900,
"duration_active_seconds": 740,
"turns": 14,
"attempts": 2,
"rework_iterations": 1,
"status": "PASS | FAIL | BLOCKED",
"outcome_reason": "none | verification_failure | environment_failure | timeout",
"verification": {
"checkpoint_tests": {
"passed": 8,
"total": 8
},
"cumulative_regression_tests": {
"passed": 25,
"total": 25
},
"failed_verifications_count": 3
},
"git": {
"commits_created": 2,
"checkpoint_commit_sha": "a81f3c2...",
"commit_shas": ["91bc7de...", "a81f3c2..."]
},
"tool_calls": {
"exploration": {
"view_file": 8,
"run_grep_or_find": 4,
"graphify_query": 3,
"graphify_path": 2,
"graphify_explain": 1
},
"implementation": {
"replace_file_content": 5,
"write_to_file": 2
},
"verification": {
"run_test_command": 4
},
"graph_lifecycle": {
"graph_extractions": 1,
"graph_queries": 3,
"graph_paths": 2,
"graph_explains": 1
},
"other": {
"git_status": 2,
"env_checks": 1
}
},
"tokens": {
"input_tokens": 42100,
"output_tokens": 5400,
"total_tokens": 47500
}
}
```
---
## Final Independent Evaluation: Static & Behavioral Compliance
At the conclusion of the experiment, an independent evaluator analyzes both worktrees across three objective axes:
1. **Functional Correctness**:
- 100% pass rate on all cumulative checkpoint verification suites.
- 100% pass rate on the baseline regression suite (25/25 original tests).
- Playwright end-to-end browser acceptance suite passes.
2. **Static Architectural Assertions**:
- Runtime `Remote-User` occurrences across `backend/app/` and `frontend/src/` == 0.
- Application domain imports of OIDC, OAuth, JWT, or proxy libraries == 0.
- `Identity` construction sites enumerated and verified to originate strictly from validated claims.
- `AuthPort` interface implementation exists.
- Admin routes depend strictly on application group authorization.
- OIDC issuer is externalized and loaded from configuration.
- Traefik is strictly an ingress/TLS proxy with zero authentication middleware responsibilities.
3. **Exploration Efficiency**:
- Side-by-side comparison of exploration tool calls vs implementation tool calls.
- Total tokens and turns consumed per checkpoint.
- Frequency of rework iterations when encountering verification failures.
+1 -1
View File
@@ -5,7 +5,7 @@
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build && mkdir -p ../backend/static && cp -r dist/* ../backend/static/",
"build": "tsc -b && vite build",
"preview": "vite preview",
"lint": "biome check .",
"lint:fix": "biome check --write .",
+44 -47
View File
@@ -1,10 +1,11 @@
import { useCallback, useEffect, useState } from "react";
import { Link, NavLink, Outlet } from "react-router-dom";
import { type AuthUser, fetchSession, logoutUser } from "../api/client";
import { type CurrentUser, fetchCurrentUser, logoutUser } from "../api/client";
import { Spinner } from "../components/Spinner";
export function AdminLayout() {
const [user, setUser] = useState<CurrentUser | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [identity, setIdentity] = useState<AuthUser | null>(null);
const [loggedOut, setLoggedOut] = useState<boolean>(false);
useEffect(() => {
@@ -16,20 +17,18 @@ export function AdminLayout() {
}
let isMounted = true;
fetchSession()
.then((session) => {
if (!isMounted) return;
if (session.authenticated && session.identity) {
setIdentity(session.identity);
fetchCurrentUser()
.then((userData) => {
if (isMounted) {
setUser(userData);
setLoading(false);
} else {
// Unauthenticated user navigating to /birthday/admin initiates login flow
window.location.href = "/birthday/api/auth/login";
}
})
.catch(() => {
if (!isMounted) return;
if (isMounted) {
setLoading(false);
window.location.href = "/birthday/api/auth/login";
}
});
return () => {
@@ -41,9 +40,9 @@ export function AdminLayout() {
try {
await logoutUser();
} catch (err) {
console.error("Logout error:", err);
console.error("Logout failed:", err);
}
setIdentity(null);
setUser(null);
setLoggedOut(true);
window.history.replaceState(null, "", "/birthday/admin?logged_out=1");
}, []);
@@ -58,17 +57,14 @@ export function AdminLayout() {
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>
<Spinner size={36} />
</div>
);
}
if (loggedOut || !identity) {
if (loggedOut || !user) {
return (
<div
style={{
@@ -106,7 +102,7 @@ export function AdminLayout() {
href="/birthday/api/auth/login"
data-testid="login-link"
style={{
color: "var(--color-gold-light)",
color: "var(--color-gold-light, #e0be75)",
textDecoration: "none",
fontSize: "0.88rem",
fontWeight: 500,
@@ -141,7 +137,7 @@ export function AdminLayout() {
style={{
display: "inline-block",
padding: "0.65rem 1.5rem",
backgroundColor: "var(--color-gold)",
backgroundColor: "var(--color-gold, #c5a059)",
color: "#0a0a0a",
fontWeight: 600,
borderRadius: "4px",
@@ -193,7 +189,7 @@ export function AdminLayout() {
</h1>
</div>
<nav style={{ display: "flex", alignItems: "center", gap: "1.4rem", flexWrap: "wrap" }}>
<nav style={{ display: "flex", alignItems: "center", gap: "1.4rem" }}>
<NavLink
to="/admin"
end
@@ -243,56 +239,56 @@ export function AdminLayout() {
<span>Ver Pública</span>
<span>↗</span>
</Link>
</nav>
{/* Authenticated User Info & Logout Button */}
{/* User Info and Logout Button */}
<div style={{ display: "flex", alignItems: "center", gap: "1.2rem", flexWrap: "wrap" }}>
<div
style={{
fontSize: "0.85rem",
color: "rgba(255, 255, 255, 0.8)",
display: "flex",
alignItems: "center",
gap: "0.9rem",
borderLeft: "1px solid rgba(255, 255, 255, 0.15)",
paddingLeft: "1.2rem",
marginLeft: "0.5rem",
gap: "0.4rem",
}}
>
<span style={{ color: "var(--color-gold, #c5a059)" }}>👤</span>
<span data-testid="user-info">{user.name || user.email}</span>
{user.name && user.email && user.name !== user.email && (
<span
data-testid="user-info"
style={{
fontSize: "0.84rem",
color: "rgba(255, 255, 255, 0.85)",
fontWeight: 500,
}}
data-testid="user-email"
style={{ fontSize: "0.8rem", color: "rgba(255, 255, 255, 0.5)" }}
>
👤 {identity.name ? `${identity.name} (${identity.email})` : identity.email}
({user.email})
</span>
)}
</div>
<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)",
background: "transparent",
border: "1px solid rgba(255, 255, 255, 0.2)",
color: "#f0f0f0",
padding: "0.35rem 0.75rem",
borderRadius: "4px",
padding: "0.3rem 0.75rem",
fontSize: "0.8rem",
cursor: "pointer",
fontSize: "0.82rem",
fontWeight: 500,
transition: "all 0.2s ease",
}}
onMouseEnter={(e) => {
e.currentTarget.style.borderColor = "var(--color-gold)";
e.currentTarget.style.color = "var(--color-gold-light)";
onMouseOver={(e) => {
e.currentTarget.style.borderColor = "rgba(255, 255, 255, 0.4)";
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.05)";
}}
onMouseLeave={(e) => {
e.currentTarget.style.borderColor = "rgba(255, 255, 255, 0.25)";
e.currentTarget.style.color = "rgba(255, 255, 255, 0.8)";
onMouseOut={(e) => {
e.currentTarget.style.borderColor = "rgba(255, 255, 255, 0.2)";
e.currentTarget.style.backgroundColor = "transparent";
}}
>
Logout
</button>
</div>
</nav>
</header>
{/* Main Admin Content Container */}
@@ -308,3 +304,4 @@ export function AdminLayout() {
</div>
);
}
+4 -23
View File
@@ -158,40 +158,21 @@ export async function updateAdminRsvp(
return res.json();
}
export interface AuthUser {
export interface CurrentUser {
subject: string;
email: string;
name: string | null;
groups: string[];
}
export interface SessionResponse {
authenticated: boolean;
identity: AuthUser | null;
}
export async function fetchSession(): Promise<SessionResponse> {
try {
export async function fetchCurrentUser(): Promise<CurrentUser> {
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 };
throw new Error(`Unauthenticated: HTTP ${res.status}`);
}
return res.json();
}
export async function logoutUser(): Promise<void> {