Author SHA1 Message Date
kiskaadee d2aab52947 docs: refresh README, synchronize living specs, and align roadmap
- Expand root README with architecture overview, API summary, and local development guide
- Synchronize backend specification with PATCH/DELETE RSVP endpoints, map generator service, and updated dependencies
- Synchronize frontend specification with inline RSVP management, confirmation modal, and event timezone rendering
- Align roadmap with completed milestones and document staged Phase 6 OIDC SSO
2026-10-07 07:25:02 -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
57 changed files with 2411 additions and 4584 deletions

No files matched your search

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