Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ebf97fe8e7 | ||
|
|
8ce9a73176 | ||
|
|
381a6275c6 | ||
|
|
489be93840 | ||
|
|
0133408087 | ||
|
|
1bb046dbb6 | ||
|
|
db4ff6bed7 | ||
|
|
b3f06659d9 | ||
|
|
e5c9bd708a | ||
|
|
a54a474d43 | ||
|
|
99f8581cc8 | ||
|
|
42927b9858 | ||
|
|
338dc20126 | ||
|
|
6880b74b60 | ||
|
|
c44ecfc14b | ||
|
|
c8264b3d76 | ||
|
|
818413b4f4 | ||
|
|
f4a70ffe1d | ||
|
|
b1bb564957 | ||
|
|
d4ae37fef8 | ||
|
|
6f9026a5e6 | ||
|
|
77ead3b99a | ||
|
|
83dead536b | ||
|
|
856da792e0 | ||
|
|
a7567aa69b | ||
|
|
9dbcf72295 |
No files matched your search
@@ -0,0 +1,13 @@
|
||||
node_modules/
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
.venv/
|
||||
backend/.venv/
|
||||
.pytest_cache/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
data/
|
||||
backend/data/
|
||||
.git/
|
||||
.direnv/
|
||||
.env*
|
||||
@@ -0,0 +1,56 @@
|
||||
# ==============================================================================
|
||||
# BDInvite Configuration Template (.env.example)
|
||||
#
|
||||
# Supports two distinct deployment modes:
|
||||
# 1. Direct Standalone Mode (local dev / test with mock-oauth2-server or Keycloak)
|
||||
# 2. Homelab Production Mode (behind Traefik TLS proxy with Authelia / OIDC)
|
||||
# ==============================================================================
|
||||
|
||||
# Core Application Settings
|
||||
SERVICE_NAME=bdinvite
|
||||
SERVICE_DOMAIN=demos.roadtotech.me
|
||||
BASE_PATH=/birthday
|
||||
APP_PORT=8000
|
||||
DATABASE_URL=sqlite:///./data/bdinvite.db
|
||||
DATA_DIR=./data
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Mode 1: Direct Standalone Mode (Default for local development & testing)
|
||||
# ------------------------------------------------------------------------------
|
||||
# In Direct Standalone Mode:
|
||||
# - BDInvite runs directly on localhost:8000
|
||||
# - Cookies are sent over plain HTTP (SESSION_COOKIE_SECURE=false)
|
||||
# - OIDC IdP is a local mock or Keycloak instance
|
||||
OIDC_ISSUER=http://localhost:8088/default
|
||||
OIDC_CLIENT_ID=bdinvite-client
|
||||
OIDC_CLIENT_SECRET=bdinvite-secret
|
||||
OIDC_REDIRECT_URI=http://localhost:8000/birthday/api/auth/callback
|
||||
OIDC_GROUPS_CLAIM=groups
|
||||
SESSION_COOKIE_NAME=bdinvite_session
|
||||
SESSION_COOKIE_SECURE=false
|
||||
SESSION_COOKIE_SAMESITE=lax
|
||||
SESSION_COOKIE_HTTPONLY=true
|
||||
SESSION_MAX_AGE_SECONDS=86400
|
||||
SESSION_SECRET_KEY=bdinvite-local-dev-secret-key-replace-in-production
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Mode 2: Homelab Production Mode (Behind Traefik TLS proxy with Authelia)
|
||||
# ------------------------------------------------------------------------------
|
||||
# In Homelab Production Mode:
|
||||
# - Traefik terminates TLS for *.roadtotech.me and routes /birthday to container port 8000
|
||||
# - Cookies must be sent with Secure flag over HTTPS (SESSION_COOKIE_SECURE=true)
|
||||
# - Authelia acts as the OpenID Connect (OIDC) identity provider
|
||||
# - Uncomment the following variables for production deployment:
|
||||
#
|
||||
# SERVICE_DOMAIN=demos.roadtotech.me
|
||||
# OIDC_ISSUER=https://auth.roadtotech.me
|
||||
# OIDC_CLIENT_ID=bdinvite-client
|
||||
# OIDC_CLIENT_SECRET=change_to_production_client_secret
|
||||
# OIDC_REDIRECT_URI=https://demos.roadtotech.me/birthday/api/auth/callback
|
||||
# OIDC_GROUPS_CLAIM=groups
|
||||
# SESSION_COOKIE_NAME=bdinvite_session
|
||||
# SESSION_COOKIE_SECURE=true
|
||||
# SESSION_COOKIE_SAMESITE=lax
|
||||
# SESSION_COOKIE_HTTPONLY=true
|
||||
# SESSION_MAX_AGE_SECONDS=86400
|
||||
# SESSION_SECRET_KEY=generate_a_cryptographically_secure_random_hex_key_here
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
# Dependencies
|
||||
frontend/node_modules/
|
||||
|
||||
# Python
|
||||
backend/__pycache__/
|
||||
backend/**/__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
.venv/
|
||||
**/.venv/
|
||||
.pytest_cache/
|
||||
**/.pytest_cache/
|
||||
backend/data/
|
||||
|
||||
# Build output
|
||||
frontend/dist/
|
||||
backend/static/
|
||||
*.tsbuildinfo
|
||||
|
||||
# Data (volume-mounted, contains SQLite DB)
|
||||
data/
|
||||
|
||||
# Environment
|
||||
.env
|
||||
*.env.local
|
||||
.direnv/
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
# Stage 1: Build React frontend
|
||||
FROM node:20-alpine AS frontend-build
|
||||
WORKDIR /build
|
||||
COPY frontend/package.json frontend/package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY frontend/ ./
|
||||
RUN npm run build
|
||||
|
||||
# Stage 2: Python runtime
|
||||
FROM ghcr.io/astral-sh/uv:python3.11-bookworm-slim
|
||||
WORKDIR /app
|
||||
ENV UV_COMPILE_BYTECODE=1
|
||||
COPY backend/pyproject.toml backend/uv.lock* ./
|
||||
RUN uv sync --frozen --no-install-project --no-dev
|
||||
COPY backend/ .
|
||||
COPY --from=frontend-build /build/dist ./static
|
||||
CMD ["uv", "run", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -1 +1,33 @@
|
||||
# bdinvite
|
||||
|
||||
Interactive digital birthday invitation with RSVP.
|
||||
|
||||
## 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.
|
||||
|
||||
- **Guest**: `demos.roadtotech.me/birthday/`
|
||||
- **Admin**: `demos.roadtotech.me/birthday/admin` (Authelia-protected)
|
||||
|
||||
## Stack
|
||||
|
||||
| Layer | Technology |
|
||||
|---|---|
|
||||
| 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)
|
||||
- [Backend Specification](specs/backend.md)
|
||||
- [Infrastructure Specification](specs/infra.md)
|
||||
- [Roadmap](ROADMAP.md)
|
||||
|
||||
## Experiments
|
||||
|
||||
- [SSO Graphify Benchmark](experiments/bdinvite-sso-graphify-benchmark/README.md) — Retrospective and archived evidence from an 8-checkpoint agent implementation benchmark.
|
||||
|
||||
## License
|
||||
|
||||
[Unlicense](UNLICENSE) — public domain.
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
# Roadmap
|
||||
|
||||
## Phase 0 — Documentation Foundation
|
||||
|
||||
- [x] Frontend specification
|
||||
- [x] Backend specification
|
||||
- [x] Infrastructure specification
|
||||
- [x] Project README
|
||||
- [x] Roadmap
|
||||
- [x] License (Unlicense)
|
||||
|
||||
## Phase 1 — Backend
|
||||
|
||||
- [x] Project scaffolding (`pyproject.toml`, app directory)
|
||||
- [x] SQLite database with WAL mode
|
||||
- [x] SQLAlchemy models (`RSVP`, `InvitationConfig`)
|
||||
- [x] Pydantic request/response schemas
|
||||
- [x] Config seeding and CRUD
|
||||
- [x] `POST /birthday/api/rsvp` with phone normalization
|
||||
- [x] `GET /birthday/api/config`
|
||||
- [x] Admin endpoints with `Remote-User` guard
|
||||
- [x] CSV export endpoint
|
||||
- [x] SPA catch-all route
|
||||
- [x] Backend tests (15 unit/integration tests passing)
|
||||
|
||||
## Phase 2 — Frontend Scaffolding
|
||||
|
||||
- [x] Vite + React + TypeScript setup
|
||||
- [x] React Router with `basename=/birthday`
|
||||
- [x] API client (`/birthday/api/*`)
|
||||
- [x] Config loading state (`CONFIG_LOADING` → `INVITATION` | `CONFIG_ERROR`)
|
||||
- [x] Self-hosted font files (display script + Montserrat)
|
||||
- [x] CSS Modules setup and global styles
|
||||
- [x] TypeScript interfaces for config and API responses
|
||||
|
||||
## Phase 3 — Guest Experience
|
||||
|
||||
- [x] Invitation hero section (fixed aspect ratio)
|
||||
- [x] Canvas 2D particle background (golden bokeh)
|
||||
- [x] RSVP CTA with smooth scroll transition
|
||||
- [x] RSVP form with client-side validation (Colombian phone format)
|
||||
- [x] Submission state machine (`SUBMITTING` → `SUCCESS` | `DUPLICATE` | `ERROR`)
|
||||
- [x] Confirmation section: personalized message
|
||||
- [x] Countdown timer (timezone-aware, `NOS VEMOS EN DD:HH:MM:SS`)
|
||||
- [x] Map preview (circular static image, link to `mapUrl`)
|
||||
- [x] Venue info (compact name + address)
|
||||
- [x] `sessionStorage` post-RSVP state preservation
|
||||
- [x] Accessibility (semantic HTML, keyboard nav, aria-live, focus states)
|
||||
- [x] `prefers-reduced-motion` support (static particles)
|
||||
- [x] Responsive behavior (mobile-first, desktop stage)
|
||||
|
||||
## Phase 4 — Admin Dashboard
|
||||
|
||||
- [x] Admin layout shell (header, navigation)
|
||||
- [x] RSVP table with total count
|
||||
- [x] Search/filter RSVPs
|
||||
- [x] CSV export download button
|
||||
- [x] Config editor form (flat fields, Pydantic-validated)
|
||||
- [x] Text preview of invitation content
|
||||
|
||||
|
||||
## Phase 5 — Infrastructure & Deployment
|
||||
|
||||
- [x] Dockerfile (multi-stage build)
|
||||
- [x] `docker-compose.yml` with split Traefik routing
|
||||
- [x] `app.yaml` manifest for `appctl`
|
||||
- [x] `.gitignore` finalized
|
||||
- [x] Local Docker build verification
|
||||
- [ ] Deployment to `demos.roadtotech.me`
|
||||
- [ ] Post-deployment verification
|
||||
- [ ] Authelia admin route verification
|
||||
|
||||
## Future
|
||||
|
||||
- [ ] 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
|
||||
- [ ] Enhanced admin features (edit/delete RSVP, attendance status, guest count)
|
||||
- [ ] CSV import
|
||||
@@ -0,0 +1,24 @@
|
||||
This is free and unencumbered software released into the public domain.
|
||||
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or
|
||||
distribute this software, either in source code form or as a compiled
|
||||
binary, for any purpose, commercial or non-commercial, and by any
|
||||
means.
|
||||
|
||||
In jurisdictions that recognize copyright laws, the author or authors
|
||||
of this software dedicate any and all copyright interest in the
|
||||
software to the public domain. We make this dedication for the benefit
|
||||
of the public at large and to the detriment of our heirs and
|
||||
successors. We intend this dedication to be an overt act of
|
||||
relinquishment in perpetuity of all present and future rights to this
|
||||
software under copyright law.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
For more information, please refer to <https://unlicense.org>
|
||||
@@ -0,0 +1,18 @@
|
||||
name: "bdinvite"
|
||||
aliases:
|
||||
- "birthday"
|
||||
- "invite"
|
||||
domain: "demos.roadtotech.me"
|
||||
description: "Interactive Digital Birthday Invitation with RSVP"
|
||||
visible: true
|
||||
auth: false
|
||||
networks:
|
||||
- proxy-net
|
||||
env:
|
||||
BASE_PATH: "/birthday"
|
||||
homepage:
|
||||
title: "Birthday Invite"
|
||||
group: "Applications"
|
||||
icon: "party.png"
|
||||
container: "bdinvite"
|
||||
weight: 30
|
||||
@@ -0,0 +1,56 @@
|
||||
# ==============================================================================
|
||||
# BDInvite Configuration Template (.env.example)
|
||||
#
|
||||
# Supports two distinct deployment modes:
|
||||
# 1. Direct Standalone Mode (local dev / test with mock-oauth2-server or Keycloak)
|
||||
# 2. Homelab Production Mode (behind Traefik TLS proxy with Authelia / OIDC)
|
||||
# ==============================================================================
|
||||
|
||||
# Core Application Settings
|
||||
SERVICE_NAME=bdinvite
|
||||
SERVICE_DOMAIN=demos.roadtotech.me
|
||||
BASE_PATH=/birthday
|
||||
APP_PORT=8000
|
||||
DATABASE_URL=sqlite:///./data/bdinvite.db
|
||||
DATA_DIR=./data
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Mode 1: Direct Standalone Mode (Default for local development & testing)
|
||||
# ------------------------------------------------------------------------------
|
||||
# In Direct Standalone Mode:
|
||||
# - BDInvite runs directly on localhost:8000
|
||||
# - Cookies are sent over plain HTTP (SESSION_COOKIE_SECURE=false)
|
||||
# - OIDC IdP is a local mock or Keycloak instance
|
||||
OIDC_ISSUER=http://localhost:8088/default
|
||||
OIDC_CLIENT_ID=bdinvite-client
|
||||
OIDC_CLIENT_SECRET=bdinvite-secret
|
||||
OIDC_REDIRECT_URI=http://localhost:8000/birthday/api/auth/callback
|
||||
OIDC_GROUPS_CLAIM=groups
|
||||
SESSION_COOKIE_NAME=bdinvite_session
|
||||
SESSION_COOKIE_SECURE=false
|
||||
SESSION_COOKIE_SAMESITE=lax
|
||||
SESSION_COOKIE_HTTPONLY=true
|
||||
SESSION_MAX_AGE_SECONDS=86400
|
||||
SESSION_SECRET_KEY=bdinvite-local-dev-secret-key-replace-in-production
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Mode 2: Homelab Production Mode (Behind Traefik TLS proxy with Authelia)
|
||||
# ------------------------------------------------------------------------------
|
||||
# In Homelab Production Mode:
|
||||
# - Traefik terminates TLS for *.roadtotech.me and routes /birthday to container port 8000
|
||||
# - Cookies must be sent with Secure flag over HTTPS (SESSION_COOKIE_SECURE=true)
|
||||
# - Authelia acts as the OpenID Connect (OIDC) identity provider
|
||||
# - Uncomment the following variables for production deployment:
|
||||
#
|
||||
# SERVICE_DOMAIN=demos.roadtotech.me
|
||||
# OIDC_ISSUER=https://auth.roadtotech.me
|
||||
# OIDC_CLIENT_ID=bdinvite-client
|
||||
# OIDC_CLIENT_SECRET=change_to_production_client_secret
|
||||
# OIDC_REDIRECT_URI=https://demos.roadtotech.me/birthday/api/auth/callback
|
||||
# OIDC_GROUPS_CLAIM=groups
|
||||
# SESSION_COOKIE_NAME=bdinvite_session
|
||||
# SESSION_COOKIE_SECURE=true
|
||||
# SESSION_COOKIE_SAMESITE=lax
|
||||
# SESSION_COOKIE_HTTPONLY=true
|
||||
# SESSION_MAX_AGE_SECONDS=86400
|
||||
# SESSION_SECRET_KEY=generate_a_cryptographically_secure_random_hex_key_here
|
||||
@@ -0,0 +1 @@
|
||||
"""Birthday Invitation Application Package."""
|
||||
@@ -0,0 +1,73 @@
|
||||
from .adapter import OIDCAuthAdapter
|
||||
from .dependencies import (
|
||||
AdminDep,
|
||||
AuthenticatedDep,
|
||||
CurrentIdentityDep,
|
||||
get_auth_adapter,
|
||||
get_current_identity,
|
||||
require_admin,
|
||||
require_authenticated,
|
||||
require_group,
|
||||
)
|
||||
from .identity import Identity
|
||||
from .oidc import (
|
||||
AuthorizationRequest,
|
||||
DiscoveryError,
|
||||
InvalidPKCEError,
|
||||
InvalidStateError,
|
||||
InvalidTokenError,
|
||||
MismatchedNonceError,
|
||||
OIDCClient,
|
||||
OIDCConfig,
|
||||
OIDCError,
|
||||
OIDCTransaction,
|
||||
TokenExchangeError,
|
||||
TokenResponse,
|
||||
compute_code_challenge,
|
||||
generate_code_verifier,
|
||||
generate_nonce,
|
||||
generate_state,
|
||||
)
|
||||
from .port import AuthPort
|
||||
from .session import (
|
||||
InMemorySessionStore,
|
||||
SessionData,
|
||||
SessionStore,
|
||||
sign_session_cookie,
|
||||
unsign_session_cookie,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AdminDep",
|
||||
"AuthPort",
|
||||
"AuthenticatedDep",
|
||||
"AuthorizationRequest",
|
||||
"CurrentIdentityDep",
|
||||
"DiscoveryError",
|
||||
"Identity",
|
||||
"InMemorySessionStore",
|
||||
"InvalidPKCEError",
|
||||
"InvalidStateError",
|
||||
"InvalidTokenError",
|
||||
"MismatchedNonceError",
|
||||
"OIDCAuthAdapter",
|
||||
"OIDCClient",
|
||||
"OIDCConfig",
|
||||
"OIDCError",
|
||||
"OIDCTransaction",
|
||||
"SessionData",
|
||||
"SessionStore",
|
||||
"TokenExchangeError",
|
||||
"TokenResponse",
|
||||
"compute_code_challenge",
|
||||
"generate_code_verifier",
|
||||
"generate_nonce",
|
||||
"generate_state",
|
||||
"get_auth_adapter",
|
||||
"get_current_identity",
|
||||
"require_admin",
|
||||
"require_authenticated",
|
||||
"require_group",
|
||||
"sign_session_cookie",
|
||||
"unsign_session_cookie",
|
||||
]
|
||||
@@ -0,0 +1,231 @@
|
||||
import contextlib
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import Request, Response
|
||||
from fastapi.responses import RedirectResponse
|
||||
|
||||
from ..config import settings
|
||||
from .identity import Identity
|
||||
from .oidc import OIDCClient
|
||||
from .port import AuthPort
|
||||
from .session import (
|
||||
InMemorySessionStore,
|
||||
SessionData,
|
||||
SessionStore,
|
||||
sign_session_cookie,
|
||||
unsign_session_cookie,
|
||||
)
|
||||
|
||||
|
||||
class OIDCAuthAdapter(AuthPort):
|
||||
"""Hexagonal Adapter binding generic OIDC client and browser session store to AuthPort."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
oidc_client: OIDCClient,
|
||||
session_cookie_name: str = settings.SESSION_COOKIE_NAME,
|
||||
session_store: SessionStore | None = None,
|
||||
cookie_secure: bool | None = None,
|
||||
cookie_samesite: Literal["lax", "strict", "none"] | None = None,
|
||||
session_max_age: int | None = None,
|
||||
secret_key: str | None = None,
|
||||
) -> None:
|
||||
self.oidc_client = oidc_client
|
||||
self.session_cookie_name = session_cookie_name
|
||||
self.session_store: SessionStore = (
|
||||
session_store if session_store is not None else InMemorySessionStore()
|
||||
)
|
||||
self.cookie_secure: bool = (
|
||||
cookie_secure
|
||||
if cookie_secure is not None
|
||||
else settings.SESSION_COOKIE_SECURE
|
||||
)
|
||||
self.cookie_samesite: Literal["lax", "strict", "none"] = (
|
||||
cookie_samesite
|
||||
if cookie_samesite is not None
|
||||
else settings.SESSION_COOKIE_SAMESITE
|
||||
)
|
||||
self.session_max_age: int = (
|
||||
session_max_age
|
||||
if session_max_age is not None
|
||||
else settings.SESSION_MAX_AGE_SECONDS
|
||||
)
|
||||
self.secret_key: str = (
|
||||
secret_key if secret_key is not None else settings.SESSION_SECRET_KEY
|
||||
)
|
||||
|
||||
def parse_session_cookie(self, cookie_value: str | None) -> str | None:
|
||||
"""Extract and verify session_id from cookie, safely rejecting tampered cookies."""
|
||||
if (
|
||||
not cookie_value
|
||||
or not isinstance(cookie_value, str)
|
||||
or not cookie_value.strip()
|
||||
):
|
||||
return None
|
||||
|
||||
# 1. Attempt HMAC signature verification
|
||||
unsigned = unsign_session_cookie(cookie_value, self.secret_key)
|
||||
if unsigned is not None:
|
||||
return unsigned
|
||||
|
||||
# 2. Tampered cookie detection:
|
||||
# If it has a dot and is not a 3-part JWT, it was a tampered signed cookie
|
||||
if "." in cookie_value:
|
||||
# Let JWT pass through to token fallback if 3 segments
|
||||
if cookie_value.count(".") == 2:
|
||||
return None
|
||||
return None
|
||||
|
||||
# 3. Direct lookup for raw session_id (e.g. test fixtures without HMAC signing)
|
||||
if self.session_store.get_session(cookie_value) is not None:
|
||||
return cookie_value
|
||||
|
||||
return None
|
||||
|
||||
def current_identity(self, request: Request) -> Identity | None:
|
||||
"""Resolve the validated identity associated with the incoming request.
|
||||
|
||||
Identity Origin Integrity:
|
||||
Resolves identity strictly from verified server-side sessions or cryptographically
|
||||
verified tokens (Authorization Bearer header). Request-controlled headers (e.g.
|
||||
legacy proxy headers (e.g. forwarded user headers, X-User) are strictly ignored to prevent identity spoofing.
|
||||
"""
|
||||
# 1. Authorization: Bearer <token>
|
||||
auth_header = request.headers.get("Authorization")
|
||||
if auth_header and auth_header.startswith("Bearer "):
|
||||
token = auth_header[7:].strip()
|
||||
with contextlib.suppress(Exception):
|
||||
return self.oidc_client.extract_identity_from_token(token)
|
||||
return None
|
||||
|
||||
# 2. Browser session cookie
|
||||
raw_cookie = request.cookies.get(self.session_cookie_name)
|
||||
if not raw_cookie:
|
||||
return None
|
||||
|
||||
# Attempt resolving from session store
|
||||
session_id = self.parse_session_cookie(raw_cookie)
|
||||
if session_id:
|
||||
session = self.session_store.get_session(session_id)
|
||||
if session is not None:
|
||||
if session.is_expired():
|
||||
self.session_store.delete_session(session_id)
|
||||
return None
|
||||
return session.identity
|
||||
return None
|
||||
|
||||
# Fallback for backward compatibility with CP3 token-in-cookie tests
|
||||
with contextlib.suppress(Exception):
|
||||
return self.oidc_client.extract_identity_from_token(raw_cookie)
|
||||
return None
|
||||
|
||||
def set_session_cookie(
|
||||
self,
|
||||
response: Response,
|
||||
session_id: str,
|
||||
max_age: int | None = None,
|
||||
) -> None:
|
||||
"""Issue session cookie enforcing HttpOnly=True, SameSite, and configurable Secure flag."""
|
||||
signed_val = sign_session_cookie(session_id, self.secret_key)
|
||||
response.set_cookie(
|
||||
key=self.session_cookie_name,
|
||||
value=signed_val,
|
||||
max_age=max_age if max_age is not None else self.session_max_age,
|
||||
httponly=True, # Security Invariant: ALWAYS True to protect against XSS
|
||||
samesite=self.cookie_samesite,
|
||||
secure=self.cookie_secure,
|
||||
path="/",
|
||||
)
|
||||
|
||||
def clear_session_cookie(self, response: Response) -> None:
|
||||
"""Clear session cookie with Max-Age=0."""
|
||||
response.delete_cookie(
|
||||
key=self.session_cookie_name,
|
||||
path="/",
|
||||
httponly=True,
|
||||
samesite=self.cookie_samesite,
|
||||
secure=self.cookie_secure,
|
||||
)
|
||||
|
||||
def create_session(
|
||||
self,
|
||||
identity: Identity | None = None,
|
||||
request: Request | None = None,
|
||||
response: Response | None = None,
|
||||
pre_auth_session_id: str | None = None,
|
||||
max_age_seconds: int | None = None,
|
||||
) -> SessionData:
|
||||
"""Create session with Session Fixation Protection.
|
||||
|
||||
Guarantees:
|
||||
- If a pre-authentication session existed, it is invalidated and never promoted.
|
||||
- A fresh, unguessable session identifier is generated (pre_auth != post_auth).
|
||||
- If response is provided, the HttpOnly cookie is attached.
|
||||
"""
|
||||
candidate_pre_auth = pre_auth_session_id
|
||||
if not candidate_pre_auth and request is not None:
|
||||
raw_cookie = request.cookies.get(self.session_cookie_name)
|
||||
if raw_cookie:
|
||||
candidate_pre_auth = self.parse_session_cookie(raw_cookie)
|
||||
|
||||
effective_max_age = (
|
||||
max_age_seconds if max_age_seconds is not None else self.session_max_age
|
||||
)
|
||||
session = self.session_store.create_session(
|
||||
identity=identity,
|
||||
max_age_seconds=effective_max_age,
|
||||
pre_auth_session_id=candidate_pre_auth,
|
||||
)
|
||||
|
||||
if candidate_pre_auth:
|
||||
assert session.session_id != candidate_pre_auth
|
||||
|
||||
if response is not None:
|
||||
self.set_session_cookie(
|
||||
response, session.session_id, max_age=effective_max_age
|
||||
)
|
||||
|
||||
return session
|
||||
|
||||
def login(self, request: Request) -> Response:
|
||||
"""Initiate OIDC login flow with 302 redirect and pre-auth session establishment."""
|
||||
auth_req = self.oidc_client.create_authorization_url()
|
||||
response = RedirectResponse(url=auth_req.url, status_code=302)
|
||||
|
||||
# Issue pre-authentication session if request does not already possess one
|
||||
raw_cookie = request.cookies.get(self.session_cookie_name)
|
||||
existing_session_id = (
|
||||
self.parse_session_cookie(raw_cookie) if raw_cookie else None
|
||||
)
|
||||
if (
|
||||
not existing_session_id
|
||||
or self.session_store.get_session(existing_session_id) is None
|
||||
):
|
||||
pre_auth = self.session_store.create_session(
|
||||
identity=None,
|
||||
max_age_seconds=self.session_max_age,
|
||||
)
|
||||
self.set_session_cookie(response, pre_auth.session_id)
|
||||
|
||||
return response
|
||||
|
||||
def logout(self, request: Request) -> Response:
|
||||
"""Terminate session on server and clear browser cookie."""
|
||||
raw_cookie = request.cookies.get(self.session_cookie_name)
|
||||
if raw_cookie:
|
||||
session_id = self.parse_session_cookie(raw_cookie)
|
||||
if session_id:
|
||||
self.session_store.delete_session(session_id)
|
||||
|
||||
end_session = self.oidc_client.end_session_endpoint
|
||||
target_url = end_session if end_session else "/"
|
||||
response = RedirectResponse(url=target_url, status_code=302)
|
||||
self.clear_session_cookie(response)
|
||||
return response
|
||||
|
||||
def extract_identity(self, claims: dict[str, object]) -> Identity:
|
||||
"""Delegate identity extraction from verified claims to OIDCClient."""
|
||||
return self.oidc_client.extract_identity(claims)
|
||||
|
||||
|
||||
__all__ = ["OIDCAuthAdapter"]
|
||||
@@ -0,0 +1,108 @@
|
||||
from collections.abc import Callable
|
||||
from typing import Annotated, cast
|
||||
|
||||
from fastapi import Depends, HTTPException, Request, status
|
||||
from fastapi.params import Depends as DependsClass
|
||||
|
||||
from ..config import settings
|
||||
from .adapter import OIDCAuthAdapter
|
||||
from .identity import Identity
|
||||
from .oidc import OIDCClient
|
||||
from .session import InMemorySessionStore
|
||||
|
||||
_auth_adapter_instance: OIDCAuthAdapter | None = None
|
||||
|
||||
|
||||
def get_auth_adapter() -> OIDCAuthAdapter:
|
||||
"""Dependency provider returning singleton OIDCAuthAdapter instance."""
|
||||
global _auth_adapter_instance
|
||||
if _auth_adapter_instance is None:
|
||||
client = OIDCClient(
|
||||
issuer=settings.OIDC_ISSUER,
|
||||
client_id=settings.OIDC_CLIENT_ID,
|
||||
client_secret=settings.OIDC_CLIENT_SECRET,
|
||||
redirect_uri=settings.OIDC_REDIRECT_URI,
|
||||
groups_claim=settings.OIDC_GROUPS_CLAIM,
|
||||
)
|
||||
_auth_adapter_instance = OIDCAuthAdapter(
|
||||
oidc_client=client,
|
||||
session_cookie_name=settings.SESSION_COOKIE_NAME,
|
||||
session_store=InMemorySessionStore(),
|
||||
cookie_secure=settings.SESSION_COOKIE_SECURE,
|
||||
cookie_samesite=settings.SESSION_COOKIE_SAMESITE,
|
||||
session_max_age=settings.SESSION_MAX_AGE_SECONDS,
|
||||
secret_key=settings.SESSION_SECRET_KEY,
|
||||
)
|
||||
return _auth_adapter_instance
|
||||
|
||||
|
||||
def get_current_identity(
|
||||
request: Request,
|
||||
adapter: Annotated[OIDCAuthAdapter | None, Depends(get_auth_adapter)] = None,
|
||||
) -> Identity | None:
|
||||
"""Resolves the active Identity from the session/adapter, or None if unauthenticated."""
|
||||
resolved_adapter: OIDCAuthAdapter = (
|
||||
get_auth_adapter()
|
||||
if adapter is None or isinstance(cast(object, adapter), DependsClass)
|
||||
else adapter
|
||||
)
|
||||
return resolved_adapter.current_identity(request)
|
||||
|
||||
|
||||
def require_authenticated(
|
||||
identity: Annotated[Identity | None, Depends(get_current_identity)] = None,
|
||||
) -> Identity:
|
||||
"""Enforces authentication, raising HTTP 401 Unauthorized if anonymous."""
|
||||
if isinstance(cast(object, identity), DependsClass) or identity is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Not authenticated",
|
||||
)
|
||||
return identity
|
||||
|
||||
|
||||
def require_group(group_name: str) -> Callable[..., Identity]:
|
||||
"""Dependency factory enforcing group membership.
|
||||
|
||||
Raises HTTP 401 Unauthorized if anonymous, and HTTP 403 Forbidden if
|
||||
authenticated but missing the required group in identity.groups.
|
||||
"""
|
||||
|
||||
def _group_dependency(
|
||||
identity: Annotated[Identity | None, Depends(require_authenticated)] = None,
|
||||
) -> Identity:
|
||||
if isinstance(cast(object, identity), DependsClass) or identity is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Not authenticated",
|
||||
)
|
||||
if not identity.has_group(group_name):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Forbidden: user is not a member of group '{group_name}'",
|
||||
)
|
||||
return identity
|
||||
|
||||
_group_dependency.__name__ = f"require_group_{group_name}"
|
||||
_group_dependency.__doc__ = (
|
||||
f"FastAPI dependency requiring membership in '{group_name}' group."
|
||||
)
|
||||
return _group_dependency
|
||||
|
||||
|
||||
require_admin: Callable[..., Identity] = require_group("bdinvite_admins")
|
||||
|
||||
CurrentIdentityDep = Annotated[Identity | None, Depends(get_current_identity)]
|
||||
AuthenticatedDep = Annotated[Identity, Depends(require_authenticated)]
|
||||
AdminDep = Annotated[Identity, Depends(require_admin)]
|
||||
|
||||
__all__ = [
|
||||
"AdminDep",
|
||||
"AuthenticatedDep",
|
||||
"CurrentIdentityDep",
|
||||
"get_auth_adapter",
|
||||
"get_current_identity",
|
||||
"require_admin",
|
||||
"require_authenticated",
|
||||
"require_group",
|
||||
]
|
||||
@@ -0,0 +1,35 @@
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Identity:
|
||||
"""Domain model representing a validated authenticated principal.
|
||||
|
||||
Identity Origin Integrity:
|
||||
Instances of Identity must only represent verified authentication results produced
|
||||
by an authentication adapter or port, and must never be constructed directly from
|
||||
raw unvalidated client headers or requests.
|
||||
"""
|
||||
|
||||
subject: str
|
||||
email: str
|
||||
name: str | None = None
|
||||
groups: list[str] = field(default_factory=list)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.subject, str) or not self.subject.strip():
|
||||
raise ValueError("Identity subject must be a non-empty string")
|
||||
if not isinstance(self.email, str) or not self.email.strip():
|
||||
raise ValueError("Identity email must be a non-empty string")
|
||||
if self.name is not None and not isinstance(self.name, str):
|
||||
raise TypeError("Identity name must be a string or None")
|
||||
if not isinstance(self.groups, (list, tuple)):
|
||||
raise TypeError("Identity groups must be a list of strings")
|
||||
for g in self.groups:
|
||||
if not isinstance(g, str):
|
||||
raise TypeError("Identity groups items must be strings")
|
||||
object.__setattr__(self, "groups", list(self.groups))
|
||||
|
||||
def has_group(self, group: str) -> bool:
|
||||
"""Check if the identity belongs to a specific group."""
|
||||
return group in self.groups
|
||||
@@ -0,0 +1,723 @@
|
||||
import base64
|
||||
import contextlib
|
||||
import hashlib
|
||||
import secrets
|
||||
import string
|
||||
import time
|
||||
import urllib.parse
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import jwt
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from .identity import Identity
|
||||
|
||||
PKCE_CHARSET = string.ascii_letters + string.digits + "-._~"
|
||||
DEFAULT_SCOPES = ["openid", "profile", "email"]
|
||||
DEFAULT_SIGNING_ALGS = [
|
||||
"RS256",
|
||||
"RS384",
|
||||
"RS512",
|
||||
"ES256",
|
||||
"ES384",
|
||||
"ES512",
|
||||
"PS256",
|
||||
"PS384",
|
||||
"PS512",
|
||||
]
|
||||
|
||||
|
||||
class OIDCError(HTTPException):
|
||||
"""Base exception for all OIDC protocol and authentication errors."""
|
||||
|
||||
def __init__(self, status_code: int, detail: str) -> None:
|
||||
super().__init__(status_code=status_code, detail=detail)
|
||||
|
||||
|
||||
class InvalidStateError(OIDCError):
|
||||
"""Raised when the state parameter is missing, invalid, or expired (CSRF protection)."""
|
||||
|
||||
def __init__(
|
||||
self, detail: str = "Invalid, missing, or expired state parameter"
|
||||
) -> None:
|
||||
super().__init__(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)
|
||||
|
||||
|
||||
class MismatchedNonceError(OIDCError):
|
||||
"""Raised when the nonce in the ID token does not match the request nonce (Replay protection)."""
|
||||
|
||||
def __init__(
|
||||
self, detail: str = "Mismatched or missing nonce claim in ID token"
|
||||
) -> None:
|
||||
super().__init__(status_code=status.HTTP_401_UNAUTHORIZED, detail=detail)
|
||||
|
||||
|
||||
class InvalidTokenError(OIDCError):
|
||||
"""Raised when the ID token signature, issuer, audience, or expiration is invalid."""
|
||||
|
||||
def __init__(self, detail: str = "Invalid or expired ID token") -> None:
|
||||
super().__init__(status_code=status.HTTP_401_UNAUTHORIZED, detail=detail)
|
||||
|
||||
|
||||
class DiscoveryError(OIDCError):
|
||||
"""Raised when dynamic OIDC discovery configuration cannot be retrieved or parsed."""
|
||||
|
||||
def __init__(
|
||||
self, detail: str = "Failed to fetch or parse OIDC discovery document"
|
||||
) -> None:
|
||||
super().__init__(status_code=status.HTTP_502_BAD_GATEWAY, detail=detail)
|
||||
|
||||
|
||||
class TokenExchangeError(OIDCError):
|
||||
"""Raised when the token endpoint returns an error during authorization code exchange."""
|
||||
|
||||
def __init__(
|
||||
self, detail: str = "Failed to exchange authorization code for tokens"
|
||||
) -> None:
|
||||
super().__init__(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)
|
||||
|
||||
|
||||
class InvalidPKCEError(OIDCError):
|
||||
"""Raised when the PKCE code_verifier is missing, invalid, or fails verification."""
|
||||
|
||||
def __init__(self, detail: str = "Missing or invalid PKCE code_verifier") -> None:
|
||||
super().__init__(status_code=status.HTTP_401_UNAUTHORIZED, detail=detail)
|
||||
|
||||
|
||||
@dataclass
|
||||
class OIDCConfig:
|
||||
"""Configuration for generic OIDC client."""
|
||||
|
||||
issuer: str
|
||||
client_id: str
|
||||
client_secret: str | None = None
|
||||
redirect_uri: str = "http://localhost:8000/birthday/api/auth/callback"
|
||||
scopes: list[str] = field(default_factory=lambda: list(DEFAULT_SCOPES))
|
||||
groups_claim: str = "groups"
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.issuer, str) or not self.issuer.strip():
|
||||
raise ValueError("OIDC issuer must be a non-empty string")
|
||||
if not isinstance(self.client_id, str) or not self.client_id.strip():
|
||||
raise ValueError("OIDC client_id must be a non-empty string")
|
||||
if not isinstance(self.redirect_uri, str) or not self.redirect_uri.strip():
|
||||
raise ValueError("OIDC redirect_uri must be a non-empty string")
|
||||
if not isinstance(self.groups_claim, str) or not self.groups_claim.strip():
|
||||
raise ValueError("OIDC groups_claim must be a non-empty string")
|
||||
self.issuer = self.issuer.rstrip("/")
|
||||
|
||||
|
||||
def _extract_claim_path(claims: dict[str, Any], path: str) -> Any:
|
||||
"""Extract claim value from dictionary supporting dot-separated paths (e.g. 'realm_access.roles')."""
|
||||
current: Any = claims
|
||||
for part in path.split("."):
|
||||
if isinstance(current, dict):
|
||||
current = current.get(part)
|
||||
else:
|
||||
return None
|
||||
return current
|
||||
|
||||
|
||||
@dataclass
|
||||
class OIDCTransaction:
|
||||
"""In-flight authentication transaction state."""
|
||||
|
||||
state: str
|
||||
nonce: str
|
||||
code_verifier: str
|
||||
created_at: float = field(default_factory=time.time)
|
||||
|
||||
|
||||
@dataclass
|
||||
class AuthorizationRequest:
|
||||
"""Initiated authorization request containing URL and security secrets."""
|
||||
|
||||
url: str
|
||||
state: str
|
||||
nonce: str
|
||||
code_verifier: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class TokenResponse:
|
||||
"""Result of token endpoint exchange and cryptographic validation."""
|
||||
|
||||
id_token: str
|
||||
access_token: str | None = None
|
||||
refresh_token: str | None = None
|
||||
token_type: str | None = None
|
||||
expires_in: int | None = None
|
||||
raw: dict[str, Any] = field(default_factory=dict)
|
||||
claims: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
def generate_code_verifier(length: int = 64) -> str:
|
||||
"""Generate cryptographically secure PKCE code_verifier (RFC 7636 Section 4.1)."""
|
||||
if not (43 <= length <= 128):
|
||||
raise ValueError(
|
||||
"PKCE code_verifier length must be between 43 and 128 characters"
|
||||
)
|
||||
return "".join(secrets.choice(PKCE_CHARSET) for _ in range(length))
|
||||
|
||||
|
||||
def compute_code_challenge(code_verifier: str) -> str:
|
||||
"""Derive PKCE code_challenge using SHA-256 (RFC 7636 Section 4.2)."""
|
||||
if not (43 <= len(code_verifier) <= 128):
|
||||
raise ValueError(
|
||||
"PKCE code_verifier length must be between 43 and 128 characters"
|
||||
)
|
||||
digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
|
||||
return base64.urlsafe_b64encode(digest).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def generate_state(nbytes: int = 32) -> str:
|
||||
"""Generate cryptographic state token for CSRF protection."""
|
||||
return secrets.token_urlsafe(nbytes)
|
||||
|
||||
|
||||
def generate_nonce(nbytes: int = 32) -> str:
|
||||
"""Generate cryptographic nonce for replay protection."""
|
||||
return secrets.token_urlsafe(nbytes)
|
||||
|
||||
|
||||
class OIDCClient:
|
||||
"""Generic OpenID Connect (OIDC) client supporting Dynamic Discovery, PKCE, and JWT Verification."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: OIDCConfig | None = None,
|
||||
*,
|
||||
issuer: str | None = None,
|
||||
client_id: str | None = None,
|
||||
client_secret: str | None = None,
|
||||
redirect_uri: str | None = None,
|
||||
scopes: list[str] | None = None,
|
||||
groups_claim: str | None = None,
|
||||
discovery_doc: dict[str, Any] | None = None,
|
||||
timeout: float = 10.0,
|
||||
max_state_age_seconds: float = 600.0,
|
||||
) -> None:
|
||||
if config is not None:
|
||||
self.config = config
|
||||
else:
|
||||
if not issuer or not client_id:
|
||||
raise ValueError(
|
||||
"Both 'issuer' and 'client_id' are required if 'config' is not supplied"
|
||||
)
|
||||
self.config = OIDCConfig(
|
||||
issuer=issuer,
|
||||
client_id=client_id,
|
||||
client_secret=client_secret,
|
||||
redirect_uri=redirect_uri
|
||||
or "http://localhost:8000/birthday/api/auth/callback",
|
||||
scopes=scopes if scopes is not None else list(DEFAULT_SCOPES),
|
||||
groups_claim=groups_claim or "groups",
|
||||
)
|
||||
|
||||
self.timeout = timeout
|
||||
self.max_state_age_seconds = max_state_age_seconds
|
||||
self._discovery_doc: dict[str, Any] | None = discovery_doc
|
||||
self._jwks_client: jwt.PyJWKClient | None = None
|
||||
self._transactions: dict[str, OIDCTransaction] = {}
|
||||
|
||||
def get_discovery_document(self, refresh: bool = False) -> dict[str, Any]:
|
||||
"""Fetch and parse OIDC discovery configuration dynamically from the issuer."""
|
||||
if self._discovery_doc is not None and not refresh:
|
||||
return self._discovery_doc
|
||||
|
||||
discovery_url = f"{self.config.issuer}/.well-known/openid-configuration"
|
||||
try:
|
||||
with httpx.Client(timeout=self.timeout) as client:
|
||||
response = client.get(discovery_url)
|
||||
if response.status_code != 200:
|
||||
raise DiscoveryError(
|
||||
f"Discovery endpoint returned HTTP {response.status_code}: {response.text}"
|
||||
)
|
||||
data = response.json()
|
||||
if not isinstance(data, dict):
|
||||
raise DiscoveryError(
|
||||
"Discovery document root must be a JSON object"
|
||||
)
|
||||
self._discovery_doc = data
|
||||
return data
|
||||
except DiscoveryError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise DiscoveryError(
|
||||
f"Failed to fetch discovery document from {discovery_url}: {e}"
|
||||
) from e
|
||||
|
||||
def _get_discovery_field(self, field_name: str) -> str:
|
||||
doc = self.get_discovery_document()
|
||||
val = doc.get(field_name)
|
||||
if not val or not isinstance(val, str):
|
||||
raise DiscoveryError(
|
||||
f"Discovery document missing required field: {field_name}"
|
||||
)
|
||||
return val
|
||||
|
||||
@property
|
||||
def authorization_endpoint(self) -> str:
|
||||
return self._get_discovery_field("authorization_endpoint")
|
||||
|
||||
@property
|
||||
def token_endpoint(self) -> str:
|
||||
return self._get_discovery_field("token_endpoint")
|
||||
|
||||
@property
|
||||
def jwks_uri(self) -> str:
|
||||
return self._get_discovery_field("jwks_uri")
|
||||
|
||||
@property
|
||||
def userinfo_endpoint(self) -> str | None:
|
||||
doc = self.get_discovery_document()
|
||||
val = doc.get("userinfo_endpoint")
|
||||
return str(val) if val else None
|
||||
|
||||
@property
|
||||
def end_session_endpoint(self) -> str | None:
|
||||
doc = self.get_discovery_document()
|
||||
val = doc.get("end_session_endpoint")
|
||||
return str(val) if val else None
|
||||
|
||||
@property
|
||||
def supported_signing_algorithms(self) -> list[str]:
|
||||
doc = self.get_discovery_document()
|
||||
discovered = doc.get("id_token_signing_alg_values_supported")
|
||||
if isinstance(discovered, list) and discovered:
|
||||
# Union discovered with default algorithms while preserving order
|
||||
algs = [str(a) for a in discovered if isinstance(a, str)]
|
||||
for alg in DEFAULT_SIGNING_ALGS:
|
||||
if alg not in algs:
|
||||
algs.append(alg)
|
||||
return algs
|
||||
return list(DEFAULT_SIGNING_ALGS)
|
||||
|
||||
def get_jwks_client(self, refresh: bool = False) -> jwt.PyJWKClient:
|
||||
"""Obtain or cache PyJWKClient for signing key resolution."""
|
||||
if self._jwks_client is None or refresh:
|
||||
self._jwks_client = jwt.PyJWKClient(
|
||||
self.jwks_uri, cache_jwk_set=True, lifespan=3600
|
||||
)
|
||||
return self._jwks_client
|
||||
|
||||
def save_transaction(self, transaction: OIDCTransaction) -> None:
|
||||
"""Store an in-flight authentication transaction."""
|
||||
self._prune_expired_transactions()
|
||||
self._transactions[transaction.state] = transaction
|
||||
|
||||
def _prune_expired_transactions(self) -> None:
|
||||
now = time.time()
|
||||
expired = [
|
||||
s
|
||||
for s, tx in self._transactions.items()
|
||||
if now - tx.created_at > self.max_state_age_seconds
|
||||
]
|
||||
for s in expired:
|
||||
self._transactions.pop(s, None)
|
||||
|
||||
def validate_state(self, state: str | None) -> OIDCTransaction:
|
||||
"""Validate state parameter against pending transactions, rejecting CSRF attacks with HTTP 400."""
|
||||
self._prune_expired_transactions()
|
||||
if not state or not isinstance(state, str) or not state.strip():
|
||||
raise InvalidStateError("State parameter is missing or empty")
|
||||
|
||||
transaction = self._transactions.pop(state, None)
|
||||
if transaction is None:
|
||||
raise InvalidStateError("Invalid or expired state parameter")
|
||||
|
||||
return transaction
|
||||
|
||||
def create_authorization_url(
|
||||
self,
|
||||
state: str | None = None,
|
||||
nonce: str | None = None,
|
||||
code_verifier: str | None = None,
|
||||
scopes: list[str] | None = None,
|
||||
extra_params: dict[str, str] | None = None,
|
||||
) -> AuthorizationRequest:
|
||||
"""Generate authorization URL with PKCE (S256), cryptographic state, and nonce."""
|
||||
actual_state = state if state is not None else generate_state()
|
||||
actual_nonce = nonce if nonce is not None else generate_nonce()
|
||||
actual_verifier = (
|
||||
code_verifier if code_verifier is not None else generate_code_verifier()
|
||||
)
|
||||
|
||||
code_challenge = compute_code_challenge(actual_verifier)
|
||||
|
||||
# Persist transaction for authorization code exchange
|
||||
self.save_transaction(
|
||||
OIDCTransaction(
|
||||
state=actual_state,
|
||||
nonce=actual_nonce,
|
||||
code_verifier=actual_verifier,
|
||||
)
|
||||
)
|
||||
|
||||
query_scopes = scopes if scopes is not None else self.config.scopes
|
||||
params: dict[str, str] = {
|
||||
"response_type": "code",
|
||||
"client_id": self.config.client_id,
|
||||
"redirect_uri": self.config.redirect_uri,
|
||||
"scope": " ".join(query_scopes),
|
||||
"state": actual_state,
|
||||
"nonce": actual_nonce,
|
||||
"code_challenge": code_challenge,
|
||||
"code_challenge_method": "S256",
|
||||
}
|
||||
if extra_params:
|
||||
params.update(extra_params)
|
||||
|
||||
auth_url = f"{self.authorization_endpoint}?{urllib.parse.urlencode(params)}"
|
||||
return AuthorizationRequest(
|
||||
url=auth_url,
|
||||
state=actual_state,
|
||||
nonce=actual_nonce,
|
||||
code_verifier=actual_verifier,
|
||||
)
|
||||
|
||||
def get_signing_key(self, token: str) -> Any:
|
||||
"""Resolve cryptographic signing key from JWKS."""
|
||||
jwks_client = self.get_jwks_client()
|
||||
try:
|
||||
return jwks_client.get_signing_key_from_jwt(token)
|
||||
except jwt.PyJWKClientError as e:
|
||||
with contextlib.suppress(Exception):
|
||||
jwk_set = jwks_client.get_jwk_set()
|
||||
if jwk_set and len(jwk_set.keys) == 1:
|
||||
return jwk_set.keys[0]
|
||||
raise InvalidTokenError(f"Signing key not found in JWKS: {e}") from e
|
||||
except jwt.DecodeError as e:
|
||||
raise InvalidTokenError(
|
||||
f"ID token signature is invalid or tampered: {e}"
|
||||
) from e
|
||||
except Exception as e:
|
||||
raise InvalidTokenError(
|
||||
f"Error resolving signing key from JWKS: {e}"
|
||||
) from e
|
||||
|
||||
def verify_id_token(
|
||||
self,
|
||||
id_token: str,
|
||||
nonce: str | None = None,
|
||||
leeway: float = 60.0,
|
||||
) -> dict[str, Any]:
|
||||
"""Cryptographically validate returned ID token.
|
||||
|
||||
Validations:
|
||||
- Signature verification against keys from JWKS.
|
||||
- Issuer validation (iss == issuer).
|
||||
- Audience validation (aud == client_id).
|
||||
- Expiration validation (exp > current_time).
|
||||
- Nonce validation (nonce == expected_nonce).
|
||||
- Rejection of tampered signatures or claims (HTTP 401).
|
||||
"""
|
||||
if not id_token or not isinstance(id_token, str) or not id_token.strip():
|
||||
raise InvalidTokenError("ID token must be a non-empty string")
|
||||
|
||||
signing_key = self.get_signing_key(id_token)
|
||||
|
||||
try:
|
||||
claims = jwt.decode(
|
||||
id_token,
|
||||
signing_key.key,
|
||||
algorithms=self.supported_signing_algorithms,
|
||||
issuer=self.config.issuer,
|
||||
audience=self.config.client_id,
|
||||
leeway=leeway,
|
||||
options={
|
||||
"verify_signature": True,
|
||||
"verify_iss": True,
|
||||
"verify_aud": True,
|
||||
"verify_exp": True,
|
||||
},
|
||||
)
|
||||
except jwt.ExpiredSignatureError as e:
|
||||
raise InvalidTokenError(f"ID token has expired: {e}") from e
|
||||
except (jwt.InvalidSignatureError, jwt.DecodeError) as e:
|
||||
raise InvalidTokenError(
|
||||
f"ID token signature is invalid or tampered: {e}"
|
||||
) from e
|
||||
except (jwt.InvalidAudienceError, jwt.InvalidIssuerError) as e:
|
||||
raise InvalidTokenError(f"ID token claims validation failed: {e}") from e
|
||||
except jwt.PyJWTError as e:
|
||||
raise InvalidTokenError(f"ID token verification failed: {e}") from e
|
||||
|
||||
# Validate nonce claim for replay protection
|
||||
if nonce is not None:
|
||||
token_nonce = claims.get("nonce")
|
||||
if not token_nonce or token_nonce != nonce:
|
||||
raise MismatchedNonceError(
|
||||
f"ID token nonce '{token_nonce}' does not match expected nonce '{nonce}'"
|
||||
)
|
||||
|
||||
return claims
|
||||
|
||||
def exchange_code(
|
||||
self,
|
||||
code: str,
|
||||
state: str | None = None,
|
||||
code_verifier: str | None = None,
|
||||
nonce: str | None = None,
|
||||
extra_token_params: dict[str, str] | None = None,
|
||||
) -> TokenResponse:
|
||||
"""Exchange authorization code for tokens using PKCE code_verifier and cryptographically verify ID token."""
|
||||
if not code or not isinstance(code, str) or not code.strip():
|
||||
raise TokenExchangeError("Authorization code must be a non-empty string")
|
||||
|
||||
# Resolve state and secrets
|
||||
resolved_verifier = code_verifier
|
||||
resolved_nonce = nonce
|
||||
|
||||
if state is not None:
|
||||
if resolved_verifier is None or resolved_nonce is None:
|
||||
# State lookup is required to recover transaction secrets
|
||||
tx = self.validate_state(state)
|
||||
resolved_verifier = tx.code_verifier
|
||||
resolved_nonce = tx.nonce
|
||||
else:
|
||||
# State was provided alongside explicit secrets; validate if tracked
|
||||
if state in self._transactions:
|
||||
self._transactions.pop(state)
|
||||
elif not state.strip():
|
||||
raise InvalidStateError("State parameter cannot be empty")
|
||||
elif resolved_verifier is None:
|
||||
raise InvalidPKCEError("Missing PKCE code_verifier")
|
||||
|
||||
if (
|
||||
resolved_verifier is None
|
||||
or not isinstance(resolved_verifier, str)
|
||||
or not resolved_verifier.strip()
|
||||
):
|
||||
raise InvalidPKCEError("Missing or invalid PKCE code_verifier")
|
||||
|
||||
# Validate code_verifier length and character set per RFC 7636
|
||||
if not (43 <= len(resolved_verifier) <= 128) or not all(
|
||||
c in PKCE_CHARSET for c in resolved_verifier
|
||||
):
|
||||
raise InvalidPKCEError(
|
||||
"Invalid PKCE code_verifier: length must be between 43 and 128 unreserved characters"
|
||||
)
|
||||
|
||||
data: dict[str, str] = {
|
||||
"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
"redirect_uri": self.config.redirect_uri,
|
||||
"code_verifier": resolved_verifier,
|
||||
}
|
||||
if extra_token_params:
|
||||
data.update(extra_token_params)
|
||||
|
||||
auth: httpx.BasicAuth | None = None
|
||||
if self.config.client_secret:
|
||||
auth = httpx.BasicAuth(self.config.client_id, self.config.client_secret)
|
||||
data["client_id"] = self.config.client_id
|
||||
data["client_secret"] = self.config.client_secret
|
||||
else:
|
||||
data["client_id"] = self.config.client_id
|
||||
|
||||
try:
|
||||
with httpx.Client(timeout=self.timeout) as client:
|
||||
if auth is not None:
|
||||
response = client.post(
|
||||
self.token_endpoint,
|
||||
data=data,
|
||||
auth=auth,
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
else:
|
||||
response = client.post(
|
||||
self.token_endpoint,
|
||||
data=data,
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
except Exception as e:
|
||||
raise TokenExchangeError(
|
||||
f"Failed to communicate with token endpoint: {e}"
|
||||
) from e
|
||||
|
||||
if response.status_code != 200:
|
||||
error_data: dict[str, Any] = {}
|
||||
with contextlib.suppress(Exception):
|
||||
parsed = response.json()
|
||||
if isinstance(parsed, dict):
|
||||
error_data = parsed
|
||||
err_desc = str(error_data.get("error_description", "")).lower()
|
||||
err_code = str(error_data.get("error", "")).lower()
|
||||
if (
|
||||
"pkce" in err_desc
|
||||
or "code_verifier" in err_desc
|
||||
or "invalid_grant" in err_code
|
||||
):
|
||||
raise InvalidPKCEError(
|
||||
f"PKCE verification failed: {error_data.get('error_description') or error_data.get('error') or response.text}"
|
||||
)
|
||||
raise TokenExchangeError(
|
||||
f"Token endpoint returned HTTP {response.status_code}: {response.text}"
|
||||
)
|
||||
|
||||
try:
|
||||
token_data = response.json()
|
||||
except Exception as e:
|
||||
raise TokenExchangeError(f"Failed to parse token response JSON: {e}") from e
|
||||
|
||||
if not isinstance(token_data, dict):
|
||||
raise TokenExchangeError("Token response JSON root must be an object")
|
||||
|
||||
id_token = token_data.get("id_token")
|
||||
if not id_token or not isinstance(id_token, str):
|
||||
raise TokenExchangeError("Token response missing 'id_token'")
|
||||
|
||||
# Cryptographically verify returned ID token
|
||||
claims = self.verify_id_token(id_token, nonce=resolved_nonce)
|
||||
|
||||
return TokenResponse(
|
||||
id_token=id_token,
|
||||
access_token=token_data.get("access_token"),
|
||||
refresh_token=token_data.get("refresh_token"),
|
||||
token_type=token_data.get("token_type"),
|
||||
expires_in=token_data.get("expires_in"),
|
||||
raw=token_data,
|
||||
claims=claims,
|
||||
)
|
||||
|
||||
def extract_identity(self, claims: dict[str, Any]) -> Identity:
|
||||
"""Map validated ID token claims into typed Identity domain model.
|
||||
|
||||
Extracts:
|
||||
- sub -> Identity.subject (non-empty string required)
|
||||
- email -> Identity.email (falls back to {sub}@{client_id}.local if not present)
|
||||
- name -> Identity.name (optional string or None)
|
||||
- groups_claim path -> Identity.groups (list of unique strings, defaults to [])
|
||||
"""
|
||||
subject = str(claims.get("sub", "")).strip()
|
||||
if not subject:
|
||||
raise InvalidTokenError("ID token missing required 'sub' claim")
|
||||
|
||||
email_val = claims.get("email")
|
||||
if email_val and isinstance(email_val, str) and email_val.strip():
|
||||
email = email_val.strip()
|
||||
elif "@" in subject:
|
||||
email = subject
|
||||
else:
|
||||
email = f"{subject}@{self.config.client_id}.local"
|
||||
|
||||
name_val = claims.get("name")
|
||||
name = (
|
||||
str(name_val).strip()
|
||||
if name_val and isinstance(name_val, str) and name_val.strip()
|
||||
else None
|
||||
)
|
||||
|
||||
raw_groups = _extract_claim_path(claims, self.config.groups_claim)
|
||||
if isinstance(raw_groups, str):
|
||||
groups = [raw_groups.strip()] if raw_groups.strip() else []
|
||||
elif isinstance(raw_groups, (list, tuple, set)):
|
||||
groups = [
|
||||
str(g).strip()
|
||||
for g in raw_groups
|
||||
if isinstance(g, str) and str(g).strip()
|
||||
]
|
||||
else:
|
||||
groups = []
|
||||
|
||||
# Deduplicate while preserving order
|
||||
unique_groups = list(dict.fromkeys(groups))
|
||||
|
||||
return Identity(
|
||||
subject=subject,
|
||||
email=email,
|
||||
name=name,
|
||||
groups=unique_groups,
|
||||
)
|
||||
|
||||
def extract_identity_from_token(
|
||||
self,
|
||||
id_token: str,
|
||||
nonce: str | None = None,
|
||||
leeway: float = 60.0,
|
||||
) -> Identity:
|
||||
"""Cryptographically verify ID token and extract domain Identity with origin integrity."""
|
||||
claims = self.verify_id_token(id_token=id_token, nonce=nonce, leeway=leeway)
|
||||
return self.extract_identity(claims)
|
||||
|
||||
def authenticate_with_password(
|
||||
self,
|
||||
username: str,
|
||||
password: str,
|
||||
scopes: list[str] | None = None,
|
||||
) -> tuple[TokenResponse, Identity]:
|
||||
"""Authenticate using resource owner password credentials against IdP and extract Identity.
|
||||
|
||||
Validates returned ID token cryptographically and maps claims to domain Identity.
|
||||
"""
|
||||
if not username or not isinstance(username, str) or not username.strip():
|
||||
raise TokenExchangeError("Username must be a non-empty string")
|
||||
if not password or not isinstance(password, str):
|
||||
raise TokenExchangeError("Password must be a non-empty string")
|
||||
|
||||
query_scopes = scopes if scopes is not None else self.config.scopes
|
||||
data: dict[str, str] = {
|
||||
"grant_type": "password",
|
||||
"client_id": self.config.client_id,
|
||||
"username": username,
|
||||
"password": password,
|
||||
"scope": " ".join(query_scopes),
|
||||
}
|
||||
|
||||
auth: httpx.BasicAuth | None = None
|
||||
if self.config.client_secret:
|
||||
auth = httpx.BasicAuth(self.config.client_id, self.config.client_secret)
|
||||
data["client_secret"] = self.config.client_secret
|
||||
|
||||
try:
|
||||
with httpx.Client(timeout=self.timeout) as client:
|
||||
if auth is not None:
|
||||
response = client.post(
|
||||
self.token_endpoint,
|
||||
data=data,
|
||||
auth=auth,
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
else:
|
||||
response = client.post(
|
||||
self.token_endpoint,
|
||||
data=data,
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
except Exception as e:
|
||||
raise TokenExchangeError(
|
||||
f"Failed to communicate with token endpoint: {e}"
|
||||
) from e
|
||||
|
||||
if response.status_code != 200:
|
||||
raise TokenExchangeError(
|
||||
f"Token endpoint returned HTTP {response.status_code}: {response.text}"
|
||||
)
|
||||
|
||||
try:
|
||||
token_data = response.json()
|
||||
except Exception as e:
|
||||
raise TokenExchangeError(f"Failed to parse token response JSON: {e}") from e
|
||||
|
||||
if not isinstance(token_data, dict):
|
||||
raise TokenExchangeError("Token response JSON root must be an object")
|
||||
|
||||
id_token = token_data.get("id_token")
|
||||
if not id_token or not isinstance(id_token, str):
|
||||
raise TokenExchangeError("Token response missing 'id_token'")
|
||||
|
||||
claims = self.verify_id_token(id_token)
|
||||
token_response = TokenResponse(
|
||||
id_token=id_token,
|
||||
access_token=token_data.get("access_token"),
|
||||
refresh_token=token_data.get("refresh_token"),
|
||||
token_type=token_data.get("token_type"),
|
||||
expires_in=token_data.get("expires_in"),
|
||||
raw=token_data,
|
||||
claims=claims,
|
||||
)
|
||||
identity = self.extract_identity(claims)
|
||||
return token_response, identity
|
||||
@@ -0,0 +1,32 @@
|
||||
from typing import Protocol, runtime_checkable
|
||||
|
||||
from fastapi import Request, Response
|
||||
|
||||
from .identity import Identity
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class AuthPort(Protocol):
|
||||
"""Hexagonal Port for Authentication and Identity Management.
|
||||
|
||||
Establishes the boundary between application domain logic and concrete authentication
|
||||
mechanisms (such as OIDC, OAuth, ForwardAuth, or session providers).
|
||||
"""
|
||||
|
||||
def current_identity(self, request: Request) -> Identity | None:
|
||||
"""Resolve the validated identity associated with the incoming request.
|
||||
|
||||
Returns None if the request is unauthenticated or credentials/session are invalid.
|
||||
"""
|
||||
...
|
||||
|
||||
def login(self, request: Request) -> Response:
|
||||
"""Initiate the login flow (e.g. redirect to identity provider or challenge response)."""
|
||||
...
|
||||
|
||||
def logout(self, request: Request) -> Response:
|
||||
"""Terminate the session or logout flow (e.g. invalidate session cookie or IdP logout redirect)."""
|
||||
...
|
||||
|
||||
|
||||
__all__ = ["AuthPort", "Identity"]
|
||||
@@ -0,0 +1,184 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Protocol, runtime_checkable
|
||||
|
||||
from .identity import Identity
|
||||
|
||||
|
||||
@dataclass
|
||||
class SessionData:
|
||||
"""Represents an application-level browser session."""
|
||||
|
||||
session_id: str
|
||||
identity: Identity | None = None
|
||||
created_at: float = field(default_factory=time.time)
|
||||
expires_at: float = 0.0
|
||||
metadata: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def is_authenticated(self) -> bool:
|
||||
"""Return True if session has a verified identity."""
|
||||
return self.identity is not None
|
||||
|
||||
def is_expired(self, current_time: float | None = None) -> bool:
|
||||
"""Check whether the session has passed its expiration timestamp."""
|
||||
now = current_time if current_time is not None else time.time()
|
||||
return now >= self.expires_at
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class SessionStore(Protocol):
|
||||
"""Protocol defining the storage contract for browser session lifecycle."""
|
||||
|
||||
def create_session(
|
||||
self,
|
||||
identity: Identity | None = None,
|
||||
max_age_seconds: int = 86400,
|
||||
pre_auth_session_id: str | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> SessionData:
|
||||
"""Create a fresh session. If pre_auth_session_id is provided, invalidate it (Session Fixation Protection)."""
|
||||
...
|
||||
|
||||
def get_session(self, session_id: str) -> SessionData | None:
|
||||
"""Retrieve a session by its identifier. Returns None if absent or expired."""
|
||||
...
|
||||
|
||||
def delete_session(self, session_id: str) -> bool:
|
||||
"""Explicitly revoke a session from storage."""
|
||||
...
|
||||
|
||||
def prune_expired(self) -> int:
|
||||
"""Purge all expired sessions from storage."""
|
||||
...
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Purge all sessions (utility for tests and lifecycle resets)."""
|
||||
...
|
||||
|
||||
|
||||
class InMemorySessionStore:
|
||||
"""Thread-safe in-memory session store implementing SessionStore protocol."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._sessions: dict[str, SessionData] = {}
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def create_session(
|
||||
self,
|
||||
identity: Identity | None = None,
|
||||
max_age_seconds: int = 86400,
|
||||
pre_auth_session_id: str | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> SessionData:
|
||||
"""Create a brand new session, enforcing the Session Fixation Barrier."""
|
||||
with self._lock:
|
||||
# Session Fixation Barrier: invalidate existing pre-auth session
|
||||
if pre_auth_session_id:
|
||||
self._sessions.pop(pre_auth_session_id, None)
|
||||
|
||||
now = time.time()
|
||||
expires_at = now + max_age_seconds
|
||||
|
||||
# Generate fresh, unguessable cryptographic token
|
||||
while True:
|
||||
new_session_id = secrets.token_urlsafe(32)
|
||||
if (
|
||||
new_session_id != pre_auth_session_id
|
||||
and new_session_id not in self._sessions
|
||||
):
|
||||
break
|
||||
|
||||
session = SessionData(
|
||||
session_id=new_session_id,
|
||||
identity=identity,
|
||||
created_at=now,
|
||||
expires_at=expires_at,
|
||||
metadata=metadata or {},
|
||||
)
|
||||
self._sessions[new_session_id] = session
|
||||
return session
|
||||
|
||||
def get_session(self, session_id: str) -> SessionData | None:
|
||||
"""Fetch session, automatically purging if expired."""
|
||||
if not session_id or not isinstance(session_id, str):
|
||||
return None
|
||||
|
||||
with self._lock:
|
||||
session = self._sessions.get(session_id)
|
||||
if session is None:
|
||||
return None
|
||||
if session.is_expired():
|
||||
self._sessions.pop(session_id, None)
|
||||
return None
|
||||
return session
|
||||
|
||||
def delete_session(self, session_id: str) -> bool:
|
||||
"""Revoke session from storage."""
|
||||
if not session_id or not isinstance(session_id, str):
|
||||
return False
|
||||
|
||||
with self._lock:
|
||||
return self._sessions.pop(session_id, None) is not None
|
||||
|
||||
def prune_expired(self) -> int:
|
||||
"""Purge all expired sessions."""
|
||||
with self._lock:
|
||||
now = time.time()
|
||||
expired_keys = [k for k, s in self._sessions.items() if s.is_expired(now)]
|
||||
for k in expired_keys:
|
||||
self._sessions.pop(k, None)
|
||||
return len(expired_keys)
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Reset storage."""
|
||||
with self._lock:
|
||||
self._sessions.clear()
|
||||
|
||||
|
||||
def sign_session_cookie(session_id: str, secret_key: str) -> str:
|
||||
"""Sign session_id with HMAC-SHA256 to detect any client-side tampering."""
|
||||
if not session_id or not isinstance(session_id, str):
|
||||
raise ValueError("session_id must be a non-empty string")
|
||||
mac = hmac.new(
|
||||
secret_key.encode("utf-8"),
|
||||
session_id.encode("utf-8"),
|
||||
hashlib.sha256,
|
||||
).hexdigest()
|
||||
return f"{session_id}.{mac}"
|
||||
|
||||
|
||||
def unsign_session_cookie(cookie_val: str | None, secret_key: str) -> str | None:
|
||||
"""Verify HMAC-SHA256 signature and return verified session_id, or None if tampered/invalid."""
|
||||
if not cookie_val or not isinstance(cookie_val, str) or not cookie_val.strip():
|
||||
return None
|
||||
if "." not in cookie_val:
|
||||
return None
|
||||
parts = cookie_val.rsplit(".", 1)
|
||||
if len(parts) != 2:
|
||||
return None
|
||||
session_id, signature = parts
|
||||
if not session_id or not signature:
|
||||
return None
|
||||
|
||||
expected_mac = hmac.new(
|
||||
secret_key.encode("utf-8"),
|
||||
session_id.encode("utf-8"),
|
||||
hashlib.sha256,
|
||||
).hexdigest()
|
||||
if not hmac.compare_digest(signature, expected_mac):
|
||||
return None
|
||||
return session_id
|
||||
|
||||
|
||||
__all__ = [
|
||||
"InMemorySessionStore",
|
||||
"SessionData",
|
||||
"SessionStore",
|
||||
"sign_session_cookie",
|
||||
"unsign_session_cookie",
|
||||
]
|
||||
@@ -0,0 +1,69 @@
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""BDInvite Application Configuration.
|
||||
|
||||
Supports two primary deployment modes:
|
||||
1. Direct Standalone Mode (local dev & testing):
|
||||
- Direct HTTP access on port 8000
|
||||
- OIDC_ISSUER pointing to local IdP (e.g. mock-oauth2-server or Keycloak)
|
||||
- SESSION_COOKIE_SECURE = False
|
||||
- OIDC_REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
|
||||
2. Homelab Production Mode:
|
||||
- Deployed behind Traefik reverse proxy terminating TLS
|
||||
- OIDC_ISSUER pointing to Authelia (e.g. https://auth.roadtotech.me)
|
||||
- SESSION_COOKIE_SECURE = True (required for HTTPS cookie transmission)
|
||||
- SESSION_COOKIE_NAME = "bdinvite_session" (or prefixed "__Host-bdinvite_session")
|
||||
- OIDC_REDIRECT_URI = "https://demos.roadtotech.me/birthday/api/auth/callback"
|
||||
"""
|
||||
|
||||
SERVICE_NAME: str = "bdinvite"
|
||||
SERVICE_DOMAIN: str = "demos.roadtotech.me"
|
||||
BASE_PATH: str = "/birthday"
|
||||
APP_PORT: int = 8000
|
||||
DATABASE_URL: str = "sqlite:///./data/bdinvite.db"
|
||||
DATA_DIR: str = "./data"
|
||||
|
||||
# OIDC Provider & SSO Settings
|
||||
OIDC_ISSUER: str = "http://localhost:8088/default"
|
||||
OIDC_CLIENT_ID: str = "bdinvite-client"
|
||||
OIDC_CLIENT_SECRET: str = "bdinvite-secret"
|
||||
OIDC_REDIRECT_URI: str = "http://localhost:8000/birthday/api/auth/callback"
|
||||
OIDC_GROUPS_CLAIM: str = "groups"
|
||||
|
||||
# Browser Session & Cookie Security Settings
|
||||
SESSION_COOKIE_NAME: str = "bdinvite_session"
|
||||
SESSION_COOKIE_SECURE: bool = False
|
||||
SESSION_COOKIE_SAMESITE: Literal["lax", "strict", "none"] = "lax"
|
||||
SESSION_COOKIE_HTTPONLY: bool = True
|
||||
SESSION_MAX_AGE_SECONDS: int = 86400
|
||||
SESSION_SECRET_KEY: str = "bdinvite-session-secret-key-change-in-prod"
|
||||
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||
|
||||
@property
|
||||
def is_standalone(self) -> bool:
|
||||
"""Returns True if operating in direct standalone (development) mode."""
|
||||
return not self.SESSION_COOKIE_SECURE and (
|
||||
"localhost" in self.OIDC_ISSUER or "127.0.0.1" in self.OIDC_ISSUER
|
||||
)
|
||||
|
||||
@property
|
||||
def is_production(self) -> bool:
|
||||
"""Returns True if operating in secure homelab production mode."""
|
||||
return self.SESSION_COOKIE_SECURE
|
||||
|
||||
@property
|
||||
def data_path(self) -> Path:
|
||||
return Path(self.DATA_DIR).resolve()
|
||||
|
||||
@property
|
||||
def map_preview_file(self) -> Path:
|
||||
return self.data_path / "map_preview.png"
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,43 @@
|
||||
import os
|
||||
from collections.abc import Generator
|
||||
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
|
||||
|
||||
from .config import settings
|
||||
|
||||
# Ensure data directory exists if a local relative file path is used
|
||||
if settings.DATABASE_URL.startswith("sqlite:///./data/"):
|
||||
os.makedirs("./data", exist_ok=True)
|
||||
|
||||
connect_args = {}
|
||||
if settings.DATABASE_URL.startswith("sqlite"):
|
||||
connect_args["check_same_thread"] = False
|
||||
|
||||
engine = create_engine(
|
||||
settings.DATABASE_URL,
|
||||
connect_args=connect_args,
|
||||
)
|
||||
|
||||
|
||||
@event.listens_for(engine, "connect")
|
||||
def set_sqlite_pragma(dbapi_connection, connection_record):
|
||||
if settings.DATABASE_URL.startswith("sqlite"):
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL;")
|
||||
cursor.close()
|
||||
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,155 @@
|
||||
import os
|
||||
from collections.abc import AsyncGenerator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, Request, status
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from .config import settings
|
||||
from .database import Base, SessionLocal, engine
|
||||
from .routes import admin, auth, config, rsvp
|
||||
from .services.config import seed_default_config
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
# Ensure tables are created on startup
|
||||
Base.metadata.create_all(bind=engine)
|
||||
# Seed default configuration row
|
||||
with SessionLocal() as db:
|
||||
seed_default_config(db)
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="Birthday Invitation API",
|
||||
version="1.0.0",
|
||||
description=(
|
||||
"API REST para la invitación interactiva de cumpleaños con sistema RSVP.\n\n"
|
||||
"### Arquitectura de Seguridad\n"
|
||||
"- **Rutas Públicas (`/birthday/api/*`)**: Acceso abierto para los invitados.\n"
|
||||
"- **Rutas Administrativas (`/birthday/api/admin/*`)**: Protegidas por autenticación de sesión OIDC "
|
||||
"y autorización basada en grupos (`bdinvite_admins`)."
|
||||
),
|
||||
openapi_tags=[
|
||||
{
|
||||
"name": "RSVP",
|
||||
"description": "Registro y validación de confirmación de asistencia para invitados.",
|
||||
},
|
||||
{
|
||||
"name": "Config",
|
||||
"description": "Consulta pública de la configuración singleton del evento.",
|
||||
},
|
||||
{
|
||||
"name": "Admin",
|
||||
"description": "Gestión de asistentes, descarga CSV y edición de contenido protegida por autenticación y grupo administrativo.",
|
||||
},
|
||||
],
|
||||
lifespan=lifespan,
|
||||
docs_url="/birthday/api/docs",
|
||||
openapi_url="/birthday/api/openapi.json",
|
||||
)
|
||||
|
||||
|
||||
@app.get("/docs", include_in_schema=False)
|
||||
async def redirect_to_docs():
|
||||
return RedirectResponse(url="/birthday/api/docs")
|
||||
|
||||
|
||||
# CORS configuration
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
# Exception handler to normalize validation errors into our contract
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
errors: dict[str, str] = {}
|
||||
for err in exc.errors():
|
||||
loc = err.get("loc", [])
|
||||
field = str(loc[-1]) if loc else "general"
|
||||
msg = err.get("msg", "Entrada inválida")
|
||||
# Clean standard Pydantic error prefixes if present
|
||||
msg = msg.removeprefix("Value error, ")
|
||||
errors[field] = msg
|
||||
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
content={"result": "VALIDATION_ERROR", "errors": errors},
|
||||
)
|
||||
|
||||
|
||||
# Register API routes with exact path prefixes per specification
|
||||
app.include_router(rsvp.router, prefix="/birthday/api")
|
||||
app.include_router(config.router, prefix="/birthday/api")
|
||||
app.include_router(auth.router, prefix="/birthday/api")
|
||||
app.include_router(admin.router, prefix="/birthday/api/admin")
|
||||
|
||||
|
||||
@app.get(
|
||||
"/birthday/api/map-preview.png",
|
||||
tags=["Config"],
|
||||
summary="Obtener imagen de vista previa del mapa generada",
|
||||
description="Retorna el archivo PNG de vista previa del mapa generado centrado en la ubicación.",
|
||||
)
|
||||
async def get_map_preview():
|
||||
if settings.map_preview_file.exists():
|
||||
return FileResponse(
|
||||
settings.map_preview_file,
|
||||
media_type="image/png",
|
||||
headers={"Cache-Control": "public, max-age=300"},
|
||||
)
|
||||
return RedirectResponse(
|
||||
url="https://tile.openstreetmap.org/15/8802/13443.png",
|
||||
status_code=status.HTTP_307_TEMPORARY_REDIRECT,
|
||||
)
|
||||
|
||||
|
||||
# Static files and SPA serving
|
||||
STATIC_DIR = os.path.join(os.path.dirname(__file__), "..", "static")
|
||||
if not os.path.isdir(STATIC_DIR):
|
||||
frontend_dist = os.path.abspath(
|
||||
os.path.join(os.path.dirname(__file__), "..", "..", "frontend", "dist")
|
||||
)
|
||||
if os.path.isdir(frontend_dist):
|
||||
STATIC_DIR = frontend_dist
|
||||
ASSETS_DIR = os.path.join(STATIC_DIR, "assets")
|
||||
|
||||
if os.path.isdir(ASSETS_DIR):
|
||||
app.mount("/birthday/assets", StaticFiles(directory=ASSETS_DIR), name="assets")
|
||||
|
||||
|
||||
@app.get("/birthday", include_in_schema=False)
|
||||
async def redirect_birthday_slash():
|
||||
return RedirectResponse(
|
||||
url="/birthday/", status_code=status.HTTP_307_TEMPORARY_REDIRECT
|
||||
)
|
||||
|
||||
|
||||
@app.get("/birthday/", include_in_schema=False)
|
||||
@app.get("/birthday/{full_path:path}", include_in_schema=False)
|
||||
async def spa_catch_all(full_path: str = ""):
|
||||
if full_path:
|
||||
requested_file = os.path.join(STATIC_DIR, full_path)
|
||||
if os.path.isfile(requested_file):
|
||||
return FileResponse(requested_file)
|
||||
|
||||
index_file = os.path.join(STATIC_DIR, "index.html")
|
||||
if os.path.isfile(index_file):
|
||||
return FileResponse(index_file)
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_200_OK,
|
||||
content={
|
||||
"service": "bdinvite",
|
||||
"status": "ready",
|
||||
"message": "Frontend static assets not yet compiled in this environment.",
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,110 @@
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import DateTime, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .database import Base
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(UTC)
|
||||
|
||||
|
||||
class RSVP(Base):
|
||||
__tablename__ = "rsvps"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
phone: Mapped[str] = mapped_column(
|
||||
String(20), nullable=False, unique=True, index=True
|
||||
)
|
||||
email: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, default=utc_now
|
||||
)
|
||||
|
||||
|
||||
class InvitationConfig(Base):
|
||||
__tablename__ = "invitation_config"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=1)
|
||||
title: Mapped[str] = mapped_column(
|
||||
String(200), nullable=False, default="Birthday Party"
|
||||
)
|
||||
invitation_text: Mapped[str] = mapped_column(
|
||||
String(500),
|
||||
nullable=False,
|
||||
default="You're invited to the birthday party honoring",
|
||||
)
|
||||
honoree_name: Mapped[str] = mapped_column(
|
||||
String(200), nullable=False, default="Isabelle Snow"
|
||||
)
|
||||
event_date: Mapped[str] = mapped_column(
|
||||
String(20), nullable=False, default="2026-10-28"
|
||||
)
|
||||
event_time: Mapped[str] = mapped_column(String(10), nullable=False, default="19:00")
|
||||
event_timezone: Mapped[str] = mapped_column(
|
||||
String(50), nullable=False, default="America/Bogota"
|
||||
)
|
||||
address_name: Mapped[str] = mapped_column(
|
||||
String(200), nullable=False, default="Fresco Ristorante"
|
||||
)
|
||||
address_lines: Mapped[str] = mapped_column(
|
||||
Text,
|
||||
nullable=False,
|
||||
default="514 S Brand Blvd\nGlendale, CA 91204",
|
||||
)
|
||||
map_preview_url: Mapped[str] = mapped_column(
|
||||
String(500),
|
||||
nullable=False,
|
||||
default="https://tile.openstreetmap.org/15/8802/13443.png",
|
||||
)
|
||||
map_url: Mapped[str] = mapped_column(
|
||||
String(500),
|
||||
nullable=False,
|
||||
default="https://maps.google.com/?q=Fresco+Ristorante+Glendale+CA",
|
||||
)
|
||||
rsvp_heading: Mapped[str] = mapped_column(
|
||||
String(100), nullable=False, default="¿Nos vemos?"
|
||||
)
|
||||
rsvp_cta: Mapped[str] = mapped_column(
|
||||
String(100), nullable=False, default="CONFIRMA TU ASISTENCIA"
|
||||
)
|
||||
submit_label: Mapped[str] = mapped_column(
|
||||
String(100), nullable=False, default="TE VEO AHÍ"
|
||||
)
|
||||
msg_success: Mapped[str] = mapped_column(
|
||||
String(300),
|
||||
nullable=False,
|
||||
default="¡Perfecto! Tu asistencia ha sido confirmada.",
|
||||
)
|
||||
msg_success_greeting: Mapped[str] = mapped_column(
|
||||
String(100), nullable=False, default="Gracias, {name}."
|
||||
)
|
||||
msg_duplicate: Mapped[str] = mapped_column(
|
||||
String(300),
|
||||
nullable=False,
|
||||
default="Parece que ya tenemos tus datos registrados.",
|
||||
)
|
||||
msg_error: Mapped[str] = mapped_column(
|
||||
String(300),
|
||||
nullable=False,
|
||||
default="No pudimos registrar tu asistencia. Inténtalo nuevamente.",
|
||||
)
|
||||
msg_config_error: Mapped[str] = mapped_column(
|
||||
String(300),
|
||||
nullable=False,
|
||||
default="No pudimos cargar la invitación. Inténtalo nuevamente.",
|
||||
)
|
||||
countdown_label: Mapped[str] = mapped_column(
|
||||
String(100), nullable=False, default="NOS VEMOS EN"
|
||||
)
|
||||
countdown_in_progress: Mapped[str] = mapped_column(
|
||||
String(100), nullable=False, default="EVENTO EN CURSO"
|
||||
)
|
||||
countdown_finished: Mapped[str] = mapped_column(
|
||||
String(100), nullable=False, default="EVENTO FINALIZADO"
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, default=utc_now, onupdate=utc_now
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
"""API Route definitions."""
|
||||
@@ -0,0 +1,333 @@
|
||||
import csv
|
||||
import io
|
||||
from datetime import UTC, datetime
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..auth import Identity, require_admin
|
||||
from ..config import settings
|
||||
from ..database import get_db
|
||||
from ..schemas import (
|
||||
GenerateMapPreviewRequest,
|
||||
GenerateMapPreviewResponse,
|
||||
InvitationConfigResponse,
|
||||
InvitationConfigUpdate,
|
||||
RSVPAdminItem,
|
||||
RSVPListResponse,
|
||||
RSVPUpdate,
|
||||
)
|
||||
from ..services.config import get_config, seed_default_config, update_config
|
||||
from ..services.map_preview import (
|
||||
generate_map_preview_image,
|
||||
resolve_google_maps_coordinates,
|
||||
)
|
||||
from ..services.rsvp import delete_rsvp, get_rsvps, update_rsvp
|
||||
|
||||
router = APIRouter(tags=["Admin"], dependencies=[Depends(require_admin)])
|
||||
|
||||
AdminDep = Annotated[Identity, Depends(require_admin)]
|
||||
DbDep = Annotated[Session, Depends(get_db)]
|
||||
|
||||
ADMIN_RESPONSES = {
|
||||
401: {"description": "No autenticado. Se requiere sesión activa de usuario."},
|
||||
403: {
|
||||
"description": "Acceso denegado. Se requiere pertenecer al grupo 'bdinvite_admins'."
|
||||
},
|
||||
}
|
||||
ADMIN_401 = ADMIN_RESPONSES
|
||||
|
||||
|
||||
@router.get(
|
||||
"/rsvps",
|
||||
response_model=RSVPListResponse,
|
||||
summary="Listar asistentes confirmados",
|
||||
description=(
|
||||
"Obtiene el total y la lista de todos los invitados que han confirmado asistencia. "
|
||||
"Permite filtrado por coincidencia parcial (`?search=`) sobre nombre, teléfono o correo."
|
||||
),
|
||||
responses={
|
||||
200: {
|
||||
"model": RSVPListResponse,
|
||||
"description": "Lista de confirmaciones obtenida.",
|
||||
},
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
def list_rsvps(
|
||||
admin: AdminDep,
|
||||
db: DbDep,
|
||||
search: Annotated[
|
||||
str | None,
|
||||
Query(
|
||||
description="Término de búsqueda opcional (subcadena en nombre, teléfono o email)",
|
||||
examples=["Andrés"],
|
||||
),
|
||||
] = None,
|
||||
):
|
||||
rsvps = get_rsvps(db, search=search)
|
||||
return RSVPListResponse(
|
||||
count=len(rsvps),
|
||||
rsvps=rsvps, # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/rsvps/{rsvp_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="Eliminar confirmación de asistencia",
|
||||
description="Elimina permanentemente un registro de RSVP por su identificador.",
|
||||
responses={
|
||||
204: {"description": "Registro eliminado con éxito."},
|
||||
404: {"description": "Registro no encontrado."},
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
def delete_rsvp_endpoint(
|
||||
rsvp_id: int,
|
||||
admin: AdminDep,
|
||||
db: DbDep,
|
||||
):
|
||||
deleted = delete_rsvp(db, rsvp_id)
|
||||
if not deleted:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"No se encontró el registro con ID {rsvp_id}",
|
||||
)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/rsvps/{rsvp_id}",
|
||||
response_model=RSVPAdminItem,
|
||||
summary="Editar una confirmación de asistencia",
|
||||
description="Actualiza el nombre, teléfono o correo de un asistente confirmado.",
|
||||
responses={
|
||||
200: {
|
||||
"model": RSVPAdminItem,
|
||||
"description": "Registro actualizado exitosamente.",
|
||||
},
|
||||
400: {"description": "Error de validación en los campos proporcionados."},
|
||||
404: {"description": "Registro no encontrado."},
|
||||
409: {
|
||||
"description": "El número de teléfono ya está registrado por otro asistente."
|
||||
},
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
def update_rsvp_endpoint(
|
||||
rsvp_id: int,
|
||||
payload: RSVPUpdate,
|
||||
admin: AdminDep,
|
||||
db: DbDep,
|
||||
):
|
||||
status_res, updated = update_rsvp(db, rsvp_id, payload)
|
||||
|
||||
if status_res == "NOT_FOUND":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"No se encontró el registro con ID {rsvp_id}",
|
||||
)
|
||||
if status_res == "DUPLICATE":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="El número de teléfono ya está registrado para otro asistente.",
|
||||
)
|
||||
assert updated is not None
|
||||
return updated
|
||||
|
||||
|
||||
@router.get(
|
||||
"/export",
|
||||
summary="Exportar confirmaciones en formato CSV",
|
||||
description=(
|
||||
"Genera dinámicamente un archivo CSV con las columnas: `name`, `phone`, `email` y `created_at`. "
|
||||
"Descarga el archivo directamente con encabezados `Content-Disposition: attachment`."
|
||||
),
|
||||
responses={
|
||||
200: {
|
||||
"content": {"text/csv": {}},
|
||||
"description": "Descarga del archivo CSV `rsvps.csv`.",
|
||||
},
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
def export_rsvps_csv(
|
||||
admin: AdminDep,
|
||||
db: DbDep,
|
||||
):
|
||||
rsvps = get_rsvps(db)
|
||||
|
||||
output = io.StringIO()
|
||||
writer = csv.writer(output)
|
||||
writer.writerow(["name", "phone", "email", "created_at"])
|
||||
|
||||
for item in rsvps:
|
||||
created_iso = ""
|
||||
if item.created_at:
|
||||
dt = (
|
||||
item.created_at
|
||||
if item.created_at.tzinfo
|
||||
else item.created_at.replace(tzinfo=UTC)
|
||||
)
|
||||
created_iso = dt.isoformat()
|
||||
writer.writerow([item.name, item.phone, item.email or "", created_iso])
|
||||
|
||||
csv_content = output.getvalue()
|
||||
return Response(
|
||||
content=csv_content,
|
||||
media_type="text/csv",
|
||||
headers={"Content-Disposition": 'attachment; filename="rsvps.csv"'},
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/config",
|
||||
response_model=InvitationConfigResponse,
|
||||
summary="Obtener configuración editable",
|
||||
description="Retorna el objeto completo de configuración para poblar el formulario de administración.",
|
||||
responses={
|
||||
200: {
|
||||
"model": InvitationConfigResponse,
|
||||
"description": "Configuración obtenida correctamente.",
|
||||
},
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
def get_admin_config(
|
||||
admin: AdminDep,
|
||||
db: DbDep,
|
||||
):
|
||||
config = get_config(db)
|
||||
if not config:
|
||||
config = seed_default_config(db)
|
||||
return config
|
||||
|
||||
|
||||
@router.put(
|
||||
"/config",
|
||||
response_model=InvitationConfigResponse,
|
||||
summary="Actualizar configuración de la invitación",
|
||||
description=(
|
||||
"Reemplaza los valores de la configuración singleton del evento. "
|
||||
"Si la URL de Google Maps cambió, valida y regenera automáticamente la vista previa del mapa. "
|
||||
"Aplica validación de fecha ISO, hora en formato militar 24h y zona horaria válida IANA. "
|
||||
"Los cambios toman efecto de inmediato sin requerir recarga del contenedor."
|
||||
),
|
||||
responses={
|
||||
200: {
|
||||
"model": InvitationConfigResponse,
|
||||
"description": "Configuración actualizada con éxito.",
|
||||
},
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
@router.patch(
|
||||
"/config",
|
||||
response_model=InvitationConfigResponse,
|
||||
summary="Actualizar configuración de la invitación",
|
||||
description=(
|
||||
"Reemplaza los valores de la configuración singleton del evento. "
|
||||
"Si la URL de Google Maps cambió, valida y regenera automáticamente la vista previa del mapa. "
|
||||
"Aplica validación de fecha ISO, hora en formato militar 24h y zona horaria válida IANA. "
|
||||
"Los cambios toman efecto de inmediato sin requerir recarga del contenedor."
|
||||
),
|
||||
responses={
|
||||
200: {
|
||||
"model": InvitationConfigResponse,
|
||||
"description": "Configuración actualizada con éxito.",
|
||||
},
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
async def update_admin_config(
|
||||
update_in: InvitationConfigUpdate,
|
||||
admin: AdminDep,
|
||||
db: DbDep,
|
||||
):
|
||||
current = get_config(db)
|
||||
if not current:
|
||||
current = seed_default_config(db)
|
||||
|
||||
# Condition: Trigger generation ONLY if map_url was changed
|
||||
if current.map_url != update_in.map_url:
|
||||
try:
|
||||
fallback = f"{update_in.address_lines}\n{update_in.address_name}"
|
||||
lat, lng, _ = await resolve_google_maps_coordinates(
|
||||
update_in.map_url, fallback_query=fallback
|
||||
)
|
||||
await generate_map_preview_image(lat, lng)
|
||||
update_in.map_preview_url = f"{settings.BASE_PATH}/api/map-preview.png"
|
||||
except ValueError as err:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=str(err),
|
||||
) from err
|
||||
except Exception as err:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Error al generar la vista previa del mapa: {err}",
|
||||
) from err
|
||||
|
||||
updated = update_config(db, update_in)
|
||||
return updated
|
||||
|
||||
|
||||
@router.post(
|
||||
"/map-preview/generate",
|
||||
response_model=GenerateMapPreviewResponse,
|
||||
summary="Regenerar la vista previa del mapa",
|
||||
description=(
|
||||
"Genera o regenera la imagen del mapa en disco para la URL provista o la configurada actualmente, "
|
||||
"sin realizar escrituras innecesarias a la base de datos."
|
||||
),
|
||||
responses={
|
||||
200: {
|
||||
"model": GenerateMapPreviewResponse,
|
||||
"description": "Vista previa generada exitosamente.",
|
||||
},
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
async def regenerate_map_preview_endpoint(
|
||||
admin: AdminDep,
|
||||
db: DbDep,
|
||||
payload: GenerateMapPreviewRequest | None = None,
|
||||
):
|
||||
current = get_config(db)
|
||||
target_url = payload.map_url.strip() if (payload and payload.map_url) else None
|
||||
if not target_url:
|
||||
if not current or not current.map_url:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="No se proporcionó una URL de Google Maps ni existe una guardada en la configuración.",
|
||||
)
|
||||
target_url = current.map_url
|
||||
|
||||
try:
|
||||
fallback = (
|
||||
f"{current.address_lines}\n{current.address_name}" if current else None
|
||||
)
|
||||
lat, lng, _ = await resolve_google_maps_coordinates(
|
||||
target_url, fallback_query=fallback
|
||||
)
|
||||
await generate_map_preview_image(lat, lng)
|
||||
|
||||
timestamp = int(datetime.now(UTC).timestamp())
|
||||
return GenerateMapPreviewResponse(
|
||||
map_preview_url=f"{settings.BASE_PATH}/api/map-preview.png?t={timestamp}",
|
||||
lat=lat,
|
||||
lng=lng,
|
||||
message="Vista previa del mapa generada exitosamente.",
|
||||
)
|
||||
except ValueError as err:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=str(err),
|
||||
) from err
|
||||
except Exception as err:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Error al generar la vista previa del mapa: {err}",
|
||||
) from err
|
||||
@@ -0,0 +1,149 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, status
|
||||
from fastapi.responses import RedirectResponse
|
||||
|
||||
from ..auth import Identity, OIDCAuthAdapter
|
||||
from ..auth.dependencies import get_auth_adapter
|
||||
from ..schemas import LoginRequest, UserResponse
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["Auth"])
|
||||
|
||||
|
||||
AuthAdapterDep = Annotated[OIDCAuthAdapter, Depends(get_auth_adapter)]
|
||||
|
||||
|
||||
@router.get(
|
||||
"/login",
|
||||
summary="Iniciar flujo de autenticación OIDC",
|
||||
description="Redirige al proveedor de identidad OIDC con parámetros PKCE, nonce y state.",
|
||||
)
|
||||
def login_endpoint(
|
||||
request: Request,
|
||||
adapter: AuthAdapterDep,
|
||||
):
|
||||
return adapter.login(request)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/login",
|
||||
response_model=UserResponse,
|
||||
summary="Autenticación directa de credenciales",
|
||||
description="Autentica usuario contra el proveedor OIDC y establece una sesión protegida contra fijación.",
|
||||
)
|
||||
def direct_login_endpoint(
|
||||
payload: LoginRequest,
|
||||
request: Request,
|
||||
response: Response,
|
||||
adapter: AuthAdapterDep,
|
||||
):
|
||||
try:
|
||||
_, identity = adapter.oidc_client.authenticate_with_password(
|
||||
username=payload.username,
|
||||
password=payload.password,
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=f"Credenciales inválidas o error de autenticación: {e}",
|
||||
) from e
|
||||
|
||||
# Rotate pre-authentication session and issue post-auth session cookie
|
||||
adapter.create_session(
|
||||
identity=identity,
|
||||
request=request,
|
||||
response=response,
|
||||
)
|
||||
|
||||
return UserResponse(
|
||||
subject=identity.subject,
|
||||
email=identity.email,
|
||||
name=identity.name,
|
||||
groups=identity.groups,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/callback",
|
||||
summary="Callback de autorización OIDC",
|
||||
description="Procesa la redirección del IdP, intercambia el código de autorización e inicia la sesión.",
|
||||
)
|
||||
def callback_endpoint(
|
||||
request: Request,
|
||||
adapter: AuthAdapterDep,
|
||||
code: Annotated[
|
||||
str, Query(description="Código de autorización devuelto por el IdP")
|
||||
],
|
||||
state: Annotated[str, Query(description="Token de estado para validación CSRF")],
|
||||
):
|
||||
token_response = adapter.oidc_client.exchange_code(code=code, state=state)
|
||||
identity = adapter.oidc_client.extract_identity(token_response.claims)
|
||||
|
||||
redirect_response = RedirectResponse(
|
||||
url="/birthday/admin", status_code=status.HTTP_302_FOUND
|
||||
)
|
||||
adapter.create_session(
|
||||
identity=identity,
|
||||
request=request,
|
||||
response=redirect_response,
|
||||
)
|
||||
return redirect_response
|
||||
|
||||
|
||||
@router.get(
|
||||
"/me",
|
||||
response_model=UserResponse,
|
||||
summary="Obtener identidad de la sesión activa",
|
||||
description="Resuelve la identidad del usuario actual a partir de la cookie de sesión o encabezado Bearer.",
|
||||
)
|
||||
def me_endpoint(
|
||||
request: Request,
|
||||
adapter: AuthAdapterDep,
|
||||
):
|
||||
identity: Identity | None = adapter.current_identity(request)
|
||||
if identity is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Not authenticated",
|
||||
)
|
||||
return UserResponse(
|
||||
subject=identity.subject,
|
||||
email=identity.email,
|
||||
name=identity.name,
|
||||
groups=identity.groups,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/logout",
|
||||
summary="Cerrar sesión de usuario (POST)",
|
||||
description="Revoca la sesión en el servidor y elimina la cookie de sesión del navegador con Max-Age=0.",
|
||||
)
|
||||
def logout_post_endpoint(
|
||||
request: Request,
|
||||
response: Response,
|
||||
adapter: AuthAdapterDep,
|
||||
):
|
||||
raw_cookie = request.cookies.get(adapter.session_cookie_name)
|
||||
if raw_cookie:
|
||||
session_id = adapter.parse_session_cookie(raw_cookie)
|
||||
if session_id:
|
||||
adapter.session_store.delete_session(session_id)
|
||||
|
||||
adapter.clear_session_cookie(response)
|
||||
return {"status": "ok", "message": "Logged out successfully"}
|
||||
|
||||
|
||||
@router.get(
|
||||
"/logout",
|
||||
summary="Cerrar sesión de usuario (GET)",
|
||||
description="Revoca la sesión y redirige al usuario con la cookie eliminada.",
|
||||
)
|
||||
def logout_get_endpoint(
|
||||
request: Request,
|
||||
adapter: AuthAdapterDep,
|
||||
):
|
||||
return adapter.logout(request)
|
||||
|
||||
|
||||
__all__ = ["get_auth_adapter", "router"]
|
||||
@@ -0,0 +1,45 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..schemas import InvitationConfigResponse, RSVPErrorResponse
|
||||
from ..services.config import get_config, seed_default_config
|
||||
|
||||
router = APIRouter(tags=["Config"])
|
||||
|
||||
DbDep = Annotated[Session, Depends(get_db)]
|
||||
|
||||
|
||||
@router.get(
|
||||
"/config",
|
||||
response_model=InvitationConfigResponse,
|
||||
summary="Obtener configuración de la invitación",
|
||||
description=(
|
||||
"Retorna la configuración singleton actual del evento para ser renderizada en la "
|
||||
"experiencia web pública del invitado (textos, homenajeado, coordenadas de tiempo y lugar)."
|
||||
),
|
||||
responses={
|
||||
200: {
|
||||
"model": InvitationConfigResponse,
|
||||
"description": "Configuración del evento obtenida correctamente.",
|
||||
},
|
||||
500: {
|
||||
"model": RSVPErrorResponse,
|
||||
"description": "Fallo al inicializar o consultar el registro singleton.",
|
||||
},
|
||||
},
|
||||
)
|
||||
def read_config(db: DbDep):
|
||||
config = get_config(db)
|
||||
if not config:
|
||||
config = seed_default_config(db)
|
||||
|
||||
if not config:
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
content={"result": "ERROR"},
|
||||
)
|
||||
return config
|
||||
@@ -0,0 +1,74 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..schemas import (
|
||||
RSVPCreate,
|
||||
RSVPDuplicateResponse,
|
||||
RSVPErrorResponse,
|
||||
RSVPSuccessResponse,
|
||||
RSVPValidationErrorResponse,
|
||||
)
|
||||
from ..services.rsvp import create_rsvp
|
||||
|
||||
router = APIRouter(tags=["RSVP"])
|
||||
|
||||
DbDep = Annotated[Session, Depends(get_db)]
|
||||
|
||||
|
||||
@router.post(
|
||||
"/rsvp",
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Registrar confirmación de asistencia",
|
||||
description=(
|
||||
"Recibe y procesa la confirmación de asistencia de un invitado. "
|
||||
"El número telefónico es normalizado estrictamente al formato móvil colombiano de 10 dígitos "
|
||||
"(comenzando en 3). Si el teléfono ya existe en el sistema, retorna un discriminador semántico "
|
||||
"`DUPLICATE` con código HTTP 409."
|
||||
),
|
||||
responses={
|
||||
201: {
|
||||
"model": RSVPSuccessResponse,
|
||||
"description": "Confirmación registrada exitosamente.",
|
||||
},
|
||||
409: {
|
||||
"model": RSVPDuplicateResponse,
|
||||
"description": "El número de teléfono ya ha sido registrado previamente.",
|
||||
},
|
||||
422: {
|
||||
"model": RSVPValidationErrorResponse,
|
||||
"description": "Fallo de validación de formato en los datos ingresados.",
|
||||
},
|
||||
500: {
|
||||
"model": RSVPErrorResponse,
|
||||
"description": "Error no controlado al persistir en la base de datos.",
|
||||
},
|
||||
},
|
||||
)
|
||||
def submit_rsvp(rsvp_in: RSVPCreate, db: DbDep):
|
||||
try:
|
||||
result_status, new_rsvp = create_rsvp(db, rsvp_in)
|
||||
if result_status == "DUPLICATE":
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
content={"result": "DUPLICATE"},
|
||||
)
|
||||
assert new_rsvp is not None
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
content={"result": "SUCCESS", "name": new_rsvp.name},
|
||||
)
|
||||
except ValueError as e:
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
content={"result": "VALIDATION_ERROR", "errors": {"phone": str(e)}},
|
||||
)
|
||||
except SQLAlchemyError:
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
content={"result": "ERROR"},
|
||||
)
|
||||
@@ -0,0 +1,443 @@
|
||||
import re
|
||||
from datetime import UTC, date, datetime
|
||||
from typing import Literal
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator
|
||||
|
||||
|
||||
def normalize_phone(raw: str) -> str:
|
||||
"""Normalize Colombian mobile numbers.
|
||||
|
||||
Rules:
|
||||
1. Strip all non-digit characters.
|
||||
2. If starts with '57' and has 12 digits, strip '57'.
|
||||
3. Must be exactly 10 digits and start with '3'.
|
||||
"""
|
||||
digits = re.sub(r"\D", "", raw)
|
||||
if digits.startswith("57") and len(digits) == 12:
|
||||
digits = digits[2:]
|
||||
|
||||
if len(digits) != 10 or not digits.startswith("3"):
|
||||
raise ValueError("Formato de teléfono inválido")
|
||||
|
||||
return digits
|
||||
|
||||
|
||||
class RSVPCreate(BaseModel):
|
||||
name: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
description="Nombre completo del invitado",
|
||||
examples=["Andrés García"],
|
||||
)
|
||||
phone: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=50,
|
||||
description="Número móvil en formato colombiano (10 dígitos, con o sin prefijo +57)",
|
||||
examples=["+57 300 123 4567"],
|
||||
)
|
||||
email: str | None = Field(
|
||||
default=None,
|
||||
max_length=255,
|
||||
description="Correo electrónico opcional para confirmación y recordatorios",
|
||||
examples=["andres@example.com"],
|
||||
)
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def normalize_name(cls, v: str) -> str:
|
||||
cleaned = " ".join(v.strip().split())
|
||||
if not cleaned:
|
||||
raise ValueError("El nombre no puede estar vacío.")
|
||||
return cleaned
|
||||
|
||||
@field_validator("phone")
|
||||
@classmethod
|
||||
def validate_phone(cls, v: str) -> str:
|
||||
return normalize_phone(v)
|
||||
|
||||
@field_validator("email")
|
||||
@classmethod
|
||||
def validate_email(cls, v: str | None) -> str | None:
|
||||
if v is None:
|
||||
return None
|
||||
cleaned = v.strip()
|
||||
if not cleaned:
|
||||
return None
|
||||
email_regex = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
|
||||
if not re.match(email_regex, cleaned):
|
||||
raise ValueError("Formato de correo electrónico inválido")
|
||||
return cleaned.lower()
|
||||
|
||||
|
||||
class RSVPUpdate(BaseModel):
|
||||
name: str | None = Field(
|
||||
default=None,
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
description="Nombre completo del invitado",
|
||||
examples=["Andrés García"],
|
||||
)
|
||||
phone: str | None = Field(
|
||||
default=None,
|
||||
min_length=1,
|
||||
max_length=50,
|
||||
description="Número móvil en formato colombiano (10 dígitos, con o sin prefijo +57)",
|
||||
examples=["+57 300 123 4567"],
|
||||
)
|
||||
email: str | None = Field(
|
||||
default=None,
|
||||
max_length=255,
|
||||
description="Correo electrónico opcional para confirmación y recordatorios",
|
||||
examples=["andres@example.com"],
|
||||
)
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def normalize_name(cls, v: str | None) -> str | None:
|
||||
if v is None:
|
||||
return None
|
||||
cleaned = " ".join(v.strip().split())
|
||||
if not cleaned:
|
||||
raise ValueError("El nombre no puede estar vacío.")
|
||||
return cleaned
|
||||
|
||||
@field_validator("phone")
|
||||
@classmethod
|
||||
def validate_phone(cls, v: str | None) -> str | None:
|
||||
if v is None:
|
||||
return None
|
||||
return normalize_phone(v)
|
||||
|
||||
@field_validator("email")
|
||||
@classmethod
|
||||
def validate_email(cls, v: str | None) -> str | None:
|
||||
if v is None:
|
||||
return None
|
||||
cleaned = v.strip()
|
||||
if not cleaned:
|
||||
return None
|
||||
email_regex = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
|
||||
if not re.match(email_regex, cleaned):
|
||||
raise ValueError("Formato de correo electrónico inválido")
|
||||
return cleaned.lower()
|
||||
|
||||
|
||||
class RSVPSuccessResponse(BaseModel):
|
||||
result: Literal["SUCCESS"] = Field(
|
||||
default="SUCCESS",
|
||||
description="Discriminador semántico de confirmación exitosa",
|
||||
)
|
||||
name: str = Field(
|
||||
...,
|
||||
description="Nombre del invitado registrado",
|
||||
examples=["Andrés García"],
|
||||
)
|
||||
|
||||
|
||||
class RSVPDuplicateResponse(BaseModel):
|
||||
result: Literal["DUPLICATE"] = Field(
|
||||
default="DUPLICATE",
|
||||
description="Indica que el número de teléfono móvil ya tiene una confirmación registrada",
|
||||
)
|
||||
|
||||
|
||||
class RSVPValidationErrorResponse(BaseModel):
|
||||
result: Literal["VALIDATION_ERROR"] = Field(
|
||||
default="VALIDATION_ERROR",
|
||||
description="Indica error de validación en los datos enviados",
|
||||
)
|
||||
errors: dict[str, str] = Field(
|
||||
...,
|
||||
description="Mapa de nombres de campos con sus respectivos mensajes de error",
|
||||
examples=[{"phone": "Formato de teléfono inválido"}],
|
||||
)
|
||||
|
||||
|
||||
class RSVPErrorResponse(BaseModel):
|
||||
result: Literal["ERROR"] = Field(
|
||||
default="ERROR",
|
||||
description="Error interno no controlado durante el procesamiento",
|
||||
)
|
||||
|
||||
|
||||
class RSVPAdminItem(BaseModel):
|
||||
id: int = Field(
|
||||
...,
|
||||
description="Identificador único del registro en base de datos",
|
||||
examples=[1],
|
||||
)
|
||||
name: str = Field(
|
||||
..., description="Nombre completo del asistente", examples=["Ana García"]
|
||||
)
|
||||
phone: str = Field(
|
||||
...,
|
||||
description="Número telefónico normalizado a 10 dígitos",
|
||||
examples=["3001234567"],
|
||||
)
|
||||
email: str | None = Field(
|
||||
default=None,
|
||||
description="Correo electrónico registrado",
|
||||
examples=["ana@example.com"],
|
||||
)
|
||||
created_at: datetime = Field(
|
||||
..., description="Marca de tiempo UTC de la confirmación"
|
||||
)
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
@field_serializer("created_at")
|
||||
def serialize_created_at(self, dt: datetime) -> str:
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=UTC)
|
||||
return dt.isoformat()
|
||||
|
||||
|
||||
class RSVPListResponse(BaseModel):
|
||||
count: int = Field(
|
||||
..., description="Cantidad total de confirmaciones encontradas", examples=[37]
|
||||
)
|
||||
rsvps: list[RSVPAdminItem] = Field(
|
||||
..., description="Lista de asistentes confirmados"
|
||||
)
|
||||
|
||||
|
||||
class InvitationConfigBase(BaseModel):
|
||||
title: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=200,
|
||||
description="Título principal de la portada (tipografía script grande)",
|
||||
examples=["Birthday Party"],
|
||||
)
|
||||
invitation_text: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=500,
|
||||
description="Texto introductorio de la invitación",
|
||||
examples=["You're invited to the birthday party honoring"],
|
||||
)
|
||||
honoree_name: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=200,
|
||||
description="Nombre del homenajeado(a)",
|
||||
examples=["Isabelle Snow"],
|
||||
)
|
||||
event_date: str = Field(
|
||||
...,
|
||||
description="Fecha del evento en formato ISO 8601 (YYYY-MM-DD)",
|
||||
examples=["2026-10-28"],
|
||||
)
|
||||
event_time: str = Field(
|
||||
...,
|
||||
description="Hora de inicio del evento en formato 24 horas (HH:MM)",
|
||||
examples=["19:00"],
|
||||
)
|
||||
event_timezone: str = Field(
|
||||
...,
|
||||
description="Identificador de zona horaria IANA para el cálculo exacto de la cuenta regresiva",
|
||||
examples=["America/Bogota"],
|
||||
)
|
||||
address_name: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=200,
|
||||
description="Nombre del restaurante, salón o recinto",
|
||||
examples=["Fresco Ristorante"],
|
||||
)
|
||||
address_lines: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
description="Líneas de dirección del lugar (separadas por salto de línea)",
|
||||
examples=["514 S Brand Blvd\nGlendale, CA 91204"],
|
||||
)
|
||||
map_preview_url: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=500,
|
||||
description="URL de la imagen miniatura que se muestra en el widget circular",
|
||||
examples=["https://tile.openstreetmap.org/15/8802/13443.png"],
|
||||
)
|
||||
map_url: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=500,
|
||||
description="Enlace externo a Google Maps u otro servicio de navegación",
|
||||
examples=["https://maps.google.com/?q=Fresco+Ristorante+Glendale+CA"],
|
||||
)
|
||||
rsvp_heading: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
description="Encabezado del formulario de confirmación",
|
||||
examples=["¿Nos vemos?"],
|
||||
)
|
||||
rsvp_cta: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
description="Texto del botón CTA en la portada que desplaza al formulario",
|
||||
examples=["CONFIRMA TU ASISTENCIA"],
|
||||
)
|
||||
submit_label: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
description="Texto del botón de envío del formulario",
|
||||
examples=["TE VEO AHÍ"],
|
||||
)
|
||||
msg_success: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=300,
|
||||
description="Mensaje principal tras confirmar asistencia",
|
||||
examples=["¡Perfecto! Tu asistencia ha sido confirmada."],
|
||||
)
|
||||
msg_success_greeting: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
description="Saludo personalizado; {name} se reemplaza con el nombre del invitado",
|
||||
examples=["Gracias, {name}."],
|
||||
)
|
||||
msg_duplicate: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=300,
|
||||
description="Mensaje mostrado si el número ya está registrado",
|
||||
examples=["Parece que ya tenemos tus datos registrados."],
|
||||
)
|
||||
msg_error: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=300,
|
||||
description="Mensaje en caso de fallo general del servidor",
|
||||
examples=["No pudimos registrar tu asistencia. Inténtalo nuevamente."],
|
||||
)
|
||||
msg_config_error: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=300,
|
||||
description="Mensaje si la configuración no puede cargarse en el navegador",
|
||||
examples=["No pudimos cargar la invitación. Inténtalo nuevamente."],
|
||||
)
|
||||
countdown_label: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
description="Etiqueta superior del contador regresivo",
|
||||
examples=["NOS VEMOS EN"],
|
||||
)
|
||||
countdown_in_progress: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
description="Texto mostrado cuando el evento está ocurriendo en tiempo real",
|
||||
examples=["EVENTO EN CURSO"],
|
||||
)
|
||||
countdown_finished: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
description="Texto mostrado cuando el evento ha culminado",
|
||||
examples=["EVENTO FINALIZADO"],
|
||||
)
|
||||
|
||||
@field_validator("event_date")
|
||||
@classmethod
|
||||
def validate_event_date(cls, v: str) -> str:
|
||||
match = re.match(r"^\d{4}-\d{2}-\d{2}$", v.strip())
|
||||
if not match:
|
||||
raise ValueError("La fecha debe estar en formato YYYY-MM-DD")
|
||||
try:
|
||||
date.fromisoformat(v.strip())
|
||||
except ValueError as err:
|
||||
raise ValueError("Fecha de evento inválida") from err
|
||||
return v.strip()
|
||||
|
||||
@field_validator("event_time")
|
||||
@classmethod
|
||||
def validate_event_time(cls, v: str) -> str:
|
||||
match = re.match(r"^([01]\d|2[0-3]):([0-5]\d)$", v.strip())
|
||||
if not match:
|
||||
raise ValueError("La hora debe estar en formato HH:MM (24 horas)")
|
||||
return v.strip()
|
||||
|
||||
@field_validator("event_timezone")
|
||||
@classmethod
|
||||
def validate_event_timezone(cls, v: str) -> str:
|
||||
clean = v.strip()
|
||||
try:
|
||||
ZoneInfo(clean)
|
||||
except (ZoneInfoNotFoundError, ValueError):
|
||||
raise ValueError(f"Zona horaria IANA desconocida: {clean}")
|
||||
return clean
|
||||
|
||||
@field_validator("map_url")
|
||||
@classmethod
|
||||
def validate_map_url(cls, v: str) -> str:
|
||||
from .services.map_preview import validate_google_maps_url_format
|
||||
|
||||
clean = v.strip()
|
||||
validate_google_maps_url_format(clean)
|
||||
return clean
|
||||
|
||||
|
||||
class InvitationConfigUpdate(InvitationConfigBase):
|
||||
pass
|
||||
|
||||
|
||||
class InvitationConfigResponse(InvitationConfigBase):
|
||||
id: int = Field(
|
||||
default=1, description="Identificador único del registro singleton (siempre 1)"
|
||||
)
|
||||
updated_at: datetime | None = Field(
|
||||
default=None, description="Última modificación en UTC"
|
||||
)
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
@field_serializer("updated_at")
|
||||
def serialize_updated_at(self, dt: datetime | None) -> str | None:
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=UTC)
|
||||
return dt.isoformat()
|
||||
|
||||
|
||||
class GenerateMapPreviewRequest(BaseModel):
|
||||
map_url: str | None = Field(
|
||||
default=None,
|
||||
description="URL de Google Maps a procesar. Si se omite, se usa la configurada actualmente.",
|
||||
examples=["https://maps.app.goo.gl/abcd1234efgh5678"],
|
||||
)
|
||||
|
||||
|
||||
class GenerateMapPreviewResponse(BaseModel):
|
||||
map_preview_url: str = Field(
|
||||
description="URL para acceder a la imagen de vista previa generada"
|
||||
)
|
||||
lat: float = Field(description="Latitud resuelta")
|
||||
lng: float = Field(description="Longitud resuelta")
|
||||
message: str = Field(default="Vista previa generada con éxito")
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username: str = Field(
|
||||
..., description="Nombre de usuario o correo para autenticación OIDC"
|
||||
)
|
||||
password: str = Field(..., description="Contraseña de usuario")
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
subject: str = Field(..., description="Identificador único del usuario (sub)")
|
||||
email: str = Field(..., description="Correo electrónico del usuario")
|
||||
name: str | None = Field(default=None, description="Nombre visible del usuario")
|
||||
groups: list[str] = Field(
|
||||
default_factory=list, description="Grupos o roles asignados al usuario"
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
"""Service layer for RSVP and Config business logic."""
|
||||
@@ -0,0 +1,44 @@
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import InvitationConfig
|
||||
from ..schemas import InvitationConfigUpdate
|
||||
|
||||
|
||||
def seed_default_config(db: Session) -> InvitationConfig:
|
||||
"""Ensure the singleton config row (id=1) exists with default values."""
|
||||
config = db.execute(
|
||||
select(InvitationConfig).where(InvitationConfig.id == 1)
|
||||
).scalar_one_or_none()
|
||||
|
||||
if not config:
|
||||
config = InvitationConfig(id=1)
|
||||
db.add(config)
|
||||
db.commit()
|
||||
db.refresh(config)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def get_config(db: Session) -> InvitationConfig | None:
|
||||
"""Retrieve the current invitation config."""
|
||||
return db.execute(
|
||||
select(InvitationConfig).where(InvitationConfig.id == 1)
|
||||
).scalar_one_or_none()
|
||||
|
||||
|
||||
def update_config(db: Session, update_in: InvitationConfigUpdate) -> InvitationConfig:
|
||||
"""Update the invitation config singleton."""
|
||||
config = get_config(db)
|
||||
if not config:
|
||||
config = seed_default_config(db)
|
||||
|
||||
for field, value in update_in.model_dump().items():
|
||||
setattr(config, field, value)
|
||||
|
||||
config.updated_at = datetime.now(UTC)
|
||||
db.commit()
|
||||
db.refresh(config)
|
||||
return config
|
||||
@@ -0,0 +1,251 @@
|
||||
import contextlib
|
||||
import io
|
||||
import math
|
||||
import re
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, unquote, urlparse
|
||||
|
||||
import httpx
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from ..config import settings
|
||||
|
||||
USER_AGENT = "bdinvite-map-preview/1.0 (contact: admin@roadtotech.me)"
|
||||
|
||||
GOOGLE_MAPS_DOMAINS = (
|
||||
"maps.app.goo.gl",
|
||||
"goo.gl",
|
||||
"google.com",
|
||||
"www.google.com",
|
||||
"maps.google.com",
|
||||
)
|
||||
|
||||
|
||||
def is_google_maps_host(host: str) -> bool:
|
||||
"""Check if the hostname belongs to Google Maps, Google share links, or Goo.gl shortlinks."""
|
||||
clean_host = host.lower().strip()
|
||||
if clean_host in ("maps.app.goo.gl", "goo.gl", "share.google"):
|
||||
return True
|
||||
if clean_host.startswith("maps.google."):
|
||||
return True
|
||||
if clean_host == "google.com" or clean_host.endswith((".google.com", ".google")):
|
||||
return True
|
||||
# Regional domains like google.es, google.co, google.com.co
|
||||
return bool(re.match(r"^(?:www\.)?google\.[a-z.]+$", clean_host))
|
||||
|
||||
|
||||
def validate_google_maps_url_format(url: str) -> None:
|
||||
"""Validate that the given string is a structurally sound Google Maps URL."""
|
||||
clean = url.strip()
|
||||
if not clean:
|
||||
raise ValueError("La URL de Google Maps no puede estar vacía.")
|
||||
|
||||
parsed = urlparse(clean)
|
||||
if parsed.scheme not in ("http", "https"):
|
||||
raise ValueError("La URL debe comenzar con http:// o https://")
|
||||
|
||||
if not parsed.netloc or not is_google_maps_host(parsed.netloc):
|
||||
raise ValueError(
|
||||
"La URL debe ser un enlace de Google Maps válido (ej. maps.app.goo.gl/... o google.com/maps/...)"
|
||||
)
|
||||
|
||||
|
||||
def extract_coordinates_from_text(text: str) -> tuple[float, float] | None:
|
||||
"""Extract latitude and longitude from URL fragments, paths, or query strings."""
|
||||
# Pattern 1: @<lat>,<lng> (e.g. /@34.143245,-118.255132,17z)
|
||||
match_at = re.search(r"@(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)", text)
|
||||
if match_at:
|
||||
lat = float(match_at.group(1))
|
||||
lng = float(match_at.group(2))
|
||||
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
|
||||
return lat, lng
|
||||
|
||||
# Pattern 2: !3d<lat>!4d<lng> (Google Maps protobuf data parameter)
|
||||
match_data = re.search(r"!3d(-?\d+(?:\.\d+)?)(?:!4d|.*?!4d)(-?\d+(?:\.\d+)?)", text)
|
||||
if match_data:
|
||||
lat = float(match_data.group(1))
|
||||
lng = float(match_data.group(2))
|
||||
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
|
||||
return lat, lng
|
||||
|
||||
# Pattern 3: Query parameters (q=lat,lng, ll=lat,lng, destination=lat,lng)
|
||||
parsed = urlparse(text)
|
||||
if parsed.query:
|
||||
qs = parse_qs(parsed.query)
|
||||
for param in ("q", "ll", "destination"):
|
||||
if qs.get(param):
|
||||
val = qs[param][0].strip()
|
||||
m = re.match(r"^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$", val)
|
||||
if m:
|
||||
lat = float(m.group(1))
|
||||
lng = float(m.group(2))
|
||||
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
|
||||
return lat, lng
|
||||
|
||||
return None
|
||||
|
||||
|
||||
async def resolve_google_maps_coordinates(
|
||||
map_url: str,
|
||||
fallback_query: str | None = None,
|
||||
) -> tuple[float, float, str]:
|
||||
"""
|
||||
Validate and resolve a Google Maps URL, following redirects if necessary,
|
||||
and return (latitude, longitude, resolved_url).
|
||||
"""
|
||||
validate_google_maps_url_format(map_url)
|
||||
clean_url = map_url.strip()
|
||||
|
||||
# Try direct extraction before making any network requests
|
||||
direct_coords = extract_coordinates_from_text(clean_url)
|
||||
if direct_coords:
|
||||
return direct_coords[0], direct_coords[1], clean_url
|
||||
|
||||
# Follow HTTP redirects to resolve short links (maps.app.goo.gl, share.google, etc.)
|
||||
resolved_url = clean_url
|
||||
async with httpx.AsyncClient(
|
||||
follow_redirects=True,
|
||||
timeout=10.0,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
) as client:
|
||||
try:
|
||||
response = await client.get(clean_url)
|
||||
resolved_url = str(response.url)
|
||||
# Check redirect history URLs in case coordinates were in an intermediate hop
|
||||
for hop in response.history:
|
||||
hop_coords = extract_coordinates_from_text(str(hop.url))
|
||||
if hop_coords:
|
||||
return hop_coords[0], hop_coords[1], resolved_url
|
||||
except httpx.RequestError as exc:
|
||||
raise ValueError(
|
||||
f"No se pudo resolver el enlace de Google Maps: {exc}"
|
||||
) from exc
|
||||
|
||||
# Try extraction on the final resolved destination URL
|
||||
final_coords = extract_coordinates_from_text(resolved_url)
|
||||
if final_coords:
|
||||
return final_coords[0], final_coords[1], resolved_url
|
||||
|
||||
# Fallback: check if there is a place search query in the URL or query string
|
||||
parsed = urlparse(resolved_url)
|
||||
qs = parse_qs(parsed.query)
|
||||
query_text = None
|
||||
if qs.get("q"):
|
||||
query_text = qs["q"][0]
|
||||
elif "/place/" in parsed.path:
|
||||
# e.g. /maps/place/Fresco+Ristorante/...
|
||||
place_part = parsed.path.split("/place/")[1].split("/")[0]
|
||||
query_text = unquote(place_part.replace("+", " "))
|
||||
|
||||
# Build search candidates for geocoding
|
||||
candidates: list[str] = []
|
||||
clean_fallback = fallback_query.strip() if fallback_query else None
|
||||
|
||||
if query_text and clean_fallback:
|
||||
candidates.append(f"{query_text}, {clean_fallback}")
|
||||
if clean_fallback:
|
||||
for line in clean_fallback.splitlines():
|
||||
line_str = line.strip().strip(",")
|
||||
if line_str and line_str not in candidates:
|
||||
candidates.append(line_str)
|
||||
if clean_fallback not in candidates:
|
||||
candidates.append(clean_fallback)
|
||||
if query_text and query_text not in candidates:
|
||||
candidates.append(query_text)
|
||||
|
||||
if candidates:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=8.0, headers={"User-Agent": USER_AGENT}
|
||||
) as client:
|
||||
for candidate in candidates:
|
||||
with contextlib.suppress(Exception):
|
||||
nom_res = await client.get(
|
||||
"https://nominatim.openstreetmap.org/search",
|
||||
params={"q": candidate, "format": "json", "limit": 1},
|
||||
)
|
||||
if nom_res.status_code == 200:
|
||||
results = nom_res.json()
|
||||
if results and isinstance(results, list) and len(results) > 0:
|
||||
lat = float(results[0]["lat"])
|
||||
lng = float(results[0]["lon"])
|
||||
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
|
||||
return lat, lng, resolved_url
|
||||
|
||||
raise ValueError(
|
||||
"No se pudieron extraer las coordenadas de la URL de Google Maps. "
|
||||
"Asegúrate de que el enlace dirija a un lugar o coordenadas específicas."
|
||||
)
|
||||
|
||||
|
||||
def deg2num(lat_deg: float, lon_deg: float, zoom: int) -> tuple[float, float]:
|
||||
"""Convert latitude and longitude to floating-point Slippy tile coordinates."""
|
||||
lat_rad = math.radians(lat_deg)
|
||||
n = 2.0**zoom
|
||||
xtile = (lon_deg + 180.0) / 360.0 * n
|
||||
ytile = (1.0 - math.asinh(math.tan(lat_rad)) / math.pi) / 2.0 * n
|
||||
return xtile, ytile
|
||||
|
||||
|
||||
async def generate_map_preview_image(
|
||||
lat: float,
|
||||
lng: float,
|
||||
zoom: int = 16,
|
||||
output_path: Path | None = None,
|
||||
) -> Path:
|
||||
"""
|
||||
Download OpenStreetMap tiles surrounding (lat, lng), stitch them into a canvas,
|
||||
crop a 400x400 square centered on the location, render a golden marker pin,
|
||||
and save the resulting PNG to output_path (defaulting to settings.map_preview_file).
|
||||
"""
|
||||
dest_path = output_path or settings.map_preview_file
|
||||
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
xtile, ytile = deg2num(lat, lng, zoom)
|
||||
x_int, y_int = int(xtile), int(ytile)
|
||||
dx = xtile - x_int
|
||||
dy = ytile - y_int
|
||||
|
||||
# Canvas of 3x3 tiles = 768x768 pixels
|
||||
canvas = Image.new("RGB", (768, 768), color=(229, 227, 223))
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
timeout=10.0, headers={"User-Agent": USER_AGENT}
|
||||
) as client:
|
||||
for r_idx, y in enumerate(range(y_int - 1, y_int + 2)):
|
||||
for c_idx, x in enumerate(range(x_int - 1, x_int + 2)):
|
||||
tile_url = f"https://tile.openstreetmap.org/{zoom}/{x}/{y}.png"
|
||||
with contextlib.suppress(Exception):
|
||||
res = await client.get(tile_url)
|
||||
if res.status_code == 200:
|
||||
tile = Image.open(io.BytesIO(res.content)).convert("RGB")
|
||||
canvas.paste(tile, (c_idx * 256, r_idx * 256))
|
||||
|
||||
# Exact target location within the 768x768 canvas
|
||||
cx = 256 + int(dx * 256)
|
||||
cy = 256 + int(dy * 256)
|
||||
|
||||
# 400x400 crop centered on target coordinates
|
||||
box = (cx - 200, cy - 200, cx + 200, cy + 200)
|
||||
cropped = canvas.crop(box)
|
||||
|
||||
# Draw marker pin centered at (200, 200)
|
||||
# The pin tip touches (200, 200)
|
||||
draw = ImageDraw.Draw(cropped, "RGBA")
|
||||
|
||||
# Ground shadow underneath the pin tip
|
||||
draw.ellipse((192, 198, 208, 204), fill=(40, 40, 40, 140))
|
||||
|
||||
# Golden pin pointer (inverted triangle)
|
||||
draw.polygon(
|
||||
[(188, 184), (212, 184), (200, 200)], fill="#d4a843", outline="#1a1a1a"
|
||||
)
|
||||
|
||||
# Golden pin circular head
|
||||
draw.ellipse((188, 170, 212, 194), fill="#d4a843", outline="#1a1a1a", width=2)
|
||||
|
||||
# Dark center eye
|
||||
draw.ellipse((197, 179, 203, 185), fill="#1a1a1a")
|
||||
|
||||
# Save to disk as PNG
|
||||
cropped.save(dest_path, "PNG", optimize=True)
|
||||
return dest_path
|
||||
@@ -0,0 +1,115 @@
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import RSVP
|
||||
from ..schemas import RSVPCreate, RSVPUpdate, normalize_phone
|
||||
|
||||
|
||||
def create_rsvp(db: Session, rsvp_in: RSVPCreate) -> tuple[str, RSVP | None]:
|
||||
"""Create an RSVP record.
|
||||
|
||||
Returns:
|
||||
(status, rsvp_obj) where status is 'SUCCESS' or 'DUPLICATE'.
|
||||
Raises:
|
||||
ValueError if phone or field normalization fails.
|
||||
"""
|
||||
normalized_phone = normalize_phone(rsvp_in.phone)
|
||||
|
||||
# Check existence beforehand or rely on DB IntegrityError
|
||||
existing = db.execute(
|
||||
select(RSVP).where(RSVP.phone == normalized_phone)
|
||||
).scalar_one_or_none()
|
||||
if existing:
|
||||
return "DUPLICATE", None
|
||||
|
||||
new_rsvp = RSVP(
|
||||
name=rsvp_in.name,
|
||||
phone=normalized_phone,
|
||||
email=rsvp_in.email,
|
||||
)
|
||||
|
||||
try:
|
||||
db.add(new_rsvp)
|
||||
db.commit()
|
||||
db.refresh(new_rsvp)
|
||||
return "SUCCESS", new_rsvp
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
return "DUPLICATE", None
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def get_rsvps(db: Session, search: str | None = None) -> list[RSVP]:
|
||||
"""Retrieve RSVPs, optionally filtered by search term."""
|
||||
query = select(RSVP).order_by(RSVP.created_at.desc())
|
||||
if search:
|
||||
term = f"%{search.strip()}%"
|
||||
query = query.where(
|
||||
or_(
|
||||
RSVP.name.ilike(term),
|
||||
RSVP.phone.ilike(term),
|
||||
RSVP.email.ilike(term),
|
||||
)
|
||||
)
|
||||
return list(db.execute(query).scalars().all())
|
||||
|
||||
|
||||
def get_rsvp_count(db: Session) -> int:
|
||||
"""Get total count of RSVPs."""
|
||||
query = select(RSVP)
|
||||
return len(list(db.execute(query).scalars().all()))
|
||||
|
||||
|
||||
def delete_rsvp(db: Session, rsvp_id: int) -> bool:
|
||||
"""Delete an RSVP record by its ID. Returns True if deleted, False if not found."""
|
||||
rsvp = db.execute(select(RSVP).where(RSVP.id == rsvp_id)).scalar_one_or_none()
|
||||
if not rsvp:
|
||||
return False
|
||||
db.delete(rsvp)
|
||||
db.commit()
|
||||
return True
|
||||
|
||||
|
||||
def update_rsvp(
|
||||
db: Session,
|
||||
rsvp_id: int,
|
||||
update_in: RSVPUpdate,
|
||||
) -> tuple[str, RSVP | None]:
|
||||
"""Update an RSVP record using validated RSVPUpdate schema.
|
||||
|
||||
Returns:
|
||||
("SUCCESS", rsvp)
|
||||
("NOT_FOUND", None)
|
||||
("DUPLICATE", None)
|
||||
"""
|
||||
rsvp = db.execute(select(RSVP).where(RSVP.id == rsvp_id)).scalar_one_or_none()
|
||||
if not rsvp:
|
||||
return "NOT_FOUND", None
|
||||
|
||||
if update_in.phone is not None:
|
||||
existing = db.execute(
|
||||
select(RSVP).where(RSVP.phone == update_in.phone, RSVP.id != rsvp_id)
|
||||
).scalar_one_or_none()
|
||||
if existing:
|
||||
return "DUPLICATE", None
|
||||
rsvp.phone = update_in.phone
|
||||
|
||||
if update_in.name is not None:
|
||||
rsvp.name = update_in.name
|
||||
|
||||
if update_in.email is not None:
|
||||
rsvp.email = update_in.email
|
||||
|
||||
try:
|
||||
db.commit()
|
||||
db.refresh(rsvp)
|
||||
return "SUCCESS", rsvp
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
return "DUPLICATE", None
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
@@ -0,0 +1,29 @@
|
||||
[project]
|
||||
name = "bdinvite"
|
||||
version = "0.1.0"
|
||||
description = "Birthday Invitation RSVP Backend"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
"fastapi[standard]>=0.115.0",
|
||||
"uvicorn>=0.30.0",
|
||||
"sqlalchemy>=2.0.0",
|
||||
"pydantic>=2.0.0",
|
||||
"pydantic-settings>=2.0.0",
|
||||
"pillow>=10.0.0",
|
||||
"httpx>=0.27.0",
|
||||
"pyjwt[crypto]>=2.15.1",
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"httpx>=0.27.0",
|
||||
"pytest>=8.0.0",
|
||||
"pytest-asyncio>=0.23.0",
|
||||
"pyright>=1.1.0",
|
||||
"pytest-playwright>=0.9.0",
|
||||
]
|
||||
|
||||
[tool.pyright]
|
||||
venvPath = "."
|
||||
venv = ".venv"
|
||||
include = ["app", "tests"]
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"venvPath": ".",
|
||||
"venv": ".venv",
|
||||
"include": ["app", "tests"],
|
||||
"pythonVersion": "3.11"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
"""Test suite for bdinvite backend."""
|
||||
@@ -0,0 +1,94 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from app.database import Base, get_db
|
||||
from app.main import app
|
||||
from app.services.config import seed_default_config
|
||||
|
||||
# Shared in-memory SQLite for testing via StaticPool
|
||||
engine = create_engine(
|
||||
"sqlite://",
|
||||
connect_args={"check_same_thread": False},
|
||||
poolclass=StaticPool,
|
||||
)
|
||||
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def db_session():
|
||||
Base.metadata.create_all(bind=engine)
|
||||
session = TestingSessionLocal()
|
||||
seed_default_config(session)
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def client(db_session):
|
||||
def override_get_db():
|
||||
try:
|
||||
yield db_session
|
||||
finally:
|
||||
pass
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def create_test_session(
|
||||
subject: str = "admin-001",
|
||||
email: str = "admin@example.com",
|
||||
groups: list[str] | None = None,
|
||||
) -> tuple[str, str]:
|
||||
"""Helper to create a valid signed session cookie for testing."""
|
||||
from app.auth import Identity, get_auth_adapter, sign_session_cookie
|
||||
|
||||
if groups is None:
|
||||
groups = ["bdinvite_admins"]
|
||||
adapter = get_auth_adapter()
|
||||
identity = Identity(
|
||||
subject=subject,
|
||||
email=email,
|
||||
groups=groups,
|
||||
)
|
||||
session = adapter.session_store.create_session(identity=identity)
|
||||
signed_cookie = sign_session_cookie(session.session_id, adapter.secret_key)
|
||||
return adapter.session_cookie_name, signed_cookie
|
||||
|
||||
|
||||
def login_client(
|
||||
client: TestClient,
|
||||
subject: str = "admin-001",
|
||||
email: str = "admin@example.com",
|
||||
groups: list[str] | None = None,
|
||||
) -> TestClient:
|
||||
"""Sets a valid session cookie on client for an identity with the given groups."""
|
||||
cookie_name, cookie_value = create_test_session(
|
||||
subject=subject,
|
||||
email=email,
|
||||
groups=groups,
|
||||
)
|
||||
client.cookies.set(cookie_name, cookie_value)
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def admin_client(client: TestClient) -> TestClient:
|
||||
login_client(client, groups=["bdinvite_admins"])
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def guest_client(client: TestClient) -> TestClient:
|
||||
login_client(
|
||||
client, subject="guest-001", email="guest@example.com", groups=["guests"]
|
||||
)
|
||||
return client
|
||||
@@ -0,0 +1,281 @@
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from tests.conftest import login_client
|
||||
|
||||
|
||||
def test_admin_endpoints_require_authentication(client: TestClient):
|
||||
"""Anonymous requests to all admin endpoints must receive HTTP 401 Unauthorized."""
|
||||
endpoints = [
|
||||
("GET", "/birthday/api/admin/rsvps"),
|
||||
("DELETE", "/birthday/api/admin/rsvps/1"),
|
||||
("PATCH", "/birthday/api/admin/rsvps/1"),
|
||||
("GET", "/birthday/api/admin/export"),
|
||||
("GET", "/birthday/api/admin/config"),
|
||||
("PUT", "/birthday/api/admin/config"),
|
||||
("PATCH", "/birthday/api/admin/config"),
|
||||
("POST", "/birthday/api/admin/map-preview/generate"),
|
||||
]
|
||||
for method, path in endpoints:
|
||||
res = client.request(method, path)
|
||||
assert res.status_code == 401, f"{method} {path} should require authentication"
|
||||
assert res.json() == {"detail": "Not authenticated"}
|
||||
|
||||
|
||||
def test_remote_user_header_strictly_ignored(client: TestClient):
|
||||
"""Legacy Remote-User header without valid authenticated session must be strictly rejected with HTTP 401."""
|
||||
res = client.get("/birthday/api/admin/rsvps", headers={"Remote-User": "kiskaadee"})
|
||||
assert res.status_code == 401
|
||||
assert res.json() == {"detail": "Not authenticated"}
|
||||
|
||||
# Also verify across other admin routes
|
||||
assert (
|
||||
client.get(
|
||||
"/birthday/api/admin/export", headers={"Remote-User": "kiskaadee"}
|
||||
).status_code
|
||||
== 401
|
||||
)
|
||||
assert (
|
||||
client.get(
|
||||
"/birthday/api/admin/config", headers={"Remote-User": "kiskaadee"}
|
||||
).status_code
|
||||
== 401
|
||||
)
|
||||
assert (
|
||||
client.post(
|
||||
"/birthday/api/admin/map-preview/generate",
|
||||
headers={"Remote-User": "kiskaadee"},
|
||||
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
|
||||
).status_code
|
||||
== 401
|
||||
)
|
||||
|
||||
|
||||
def test_admin_endpoints_authenticated_non_admin_forbidden(guest_client: TestClient):
|
||||
"""Authenticated non-admin users (e.g. guest@example.com with groups: ['guests']) must receive HTTP 403 Forbidden."""
|
||||
endpoints = [
|
||||
("GET", "/birthday/api/admin/rsvps"),
|
||||
("DELETE", "/birthday/api/admin/rsvps/1"),
|
||||
("PATCH", "/birthday/api/admin/rsvps/1"),
|
||||
("GET", "/birthday/api/admin/export"),
|
||||
("GET", "/birthday/api/admin/config"),
|
||||
("PUT", "/birthday/api/admin/config"),
|
||||
("PATCH", "/birthday/api/admin/config"),
|
||||
("POST", "/birthday/api/admin/map-preview/generate"),
|
||||
]
|
||||
for method, path in endpoints:
|
||||
res = guest_client.request(method, path)
|
||||
assert res.status_code == 403, (
|
||||
f"{method} {path} should reject non-admin with 403"
|
||||
)
|
||||
assert "Forbidden" in res.json()["detail"]
|
||||
|
||||
|
||||
def test_remote_user_header_with_non_admin_session_cannot_elevate_privileges(
|
||||
guest_client: TestClient,
|
||||
):
|
||||
"""An attacker passing Remote-User: admin with a non-admin session cookie must still receive HTTP 403."""
|
||||
res = guest_client.get(
|
||||
"/birthday/api/admin/rsvps",
|
||||
headers={"Remote-User": "admin@example.com", "X-Remote-User": "admin"},
|
||||
)
|
||||
assert res.status_code == 403
|
||||
assert "Forbidden" in res.json()["detail"]
|
||||
|
||||
|
||||
def test_admin_endpoints_authenticated_admin_allowed(admin_client: TestClient):
|
||||
"""Authenticated admin user (admin@example.com with groups: ['bdinvite_admins']) succeeds."""
|
||||
res_rsvps = admin_client.get("/birthday/api/admin/rsvps")
|
||||
assert res_rsvps.status_code == 200
|
||||
|
||||
res_export = admin_client.get("/birthday/api/admin/export")
|
||||
assert res_export.status_code == 200
|
||||
|
||||
res_config = admin_client.get("/birthday/api/admin/config")
|
||||
assert res_config.status_code == 200
|
||||
|
||||
|
||||
def test_admin_list_and_search_rsvps(admin_client: TestClient):
|
||||
# Initially 0
|
||||
res = admin_client.get("/birthday/api/admin/rsvps")
|
||||
assert res.status_code == 200
|
||||
assert res.json()["count"] == 0
|
||||
|
||||
# Add 3 invitees
|
||||
admin_client.post(
|
||||
"/birthday/api/rsvp",
|
||||
json={
|
||||
"name": "Carlos Gomez",
|
||||
"phone": "300 111 2233",
|
||||
"email": "carlos@test.com",
|
||||
},
|
||||
)
|
||||
admin_client.post(
|
||||
"/birthday/api/rsvp",
|
||||
json={
|
||||
"name": "Maria Perez",
|
||||
"phone": "315 222 3344",
|
||||
"email": "maria@test.com",
|
||||
},
|
||||
)
|
||||
admin_client.post(
|
||||
"/birthday/api/rsvp",
|
||||
json={"name": "Juan Gomez", "phone": "320 333 4455", "email": None},
|
||||
)
|
||||
|
||||
# List all
|
||||
res = admin_client.get("/birthday/api/admin/rsvps")
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["count"] == 3
|
||||
|
||||
# Search by name
|
||||
res_search = admin_client.get("/birthday/api/admin/rsvps?search=Gomez")
|
||||
assert res_search.status_code == 200
|
||||
search_data = res_search.json()
|
||||
assert search_data["count"] == 2
|
||||
|
||||
# Search by phone substring
|
||||
res_phone = admin_client.get("/birthday/api/admin/rsvps?search=315222")
|
||||
assert res_phone.status_code == 200
|
||||
assert res_phone.json()["count"] == 1
|
||||
assert res_phone.json()["rsvps"][0]["name"] == "Maria Perez"
|
||||
|
||||
|
||||
def test_admin_export_csv(admin_client: TestClient):
|
||||
admin_client.post(
|
||||
"/birthday/api/rsvp",
|
||||
json={
|
||||
"name": "Sofia Vergara",
|
||||
"phone": "301 999 8877",
|
||||
"email": "sofia@hollywood.com",
|
||||
},
|
||||
)
|
||||
|
||||
res = admin_client.get("/birthday/api/admin/export")
|
||||
assert res.status_code == 200
|
||||
assert res.headers["content-type"].startswith("text/csv")
|
||||
assert 'filename="rsvps.csv"' in res.headers["content-disposition"]
|
||||
|
||||
content = res.text
|
||||
lines = (
|
||||
content.strip().split("\r\n")
|
||||
if "\r\n" in content
|
||||
else content.strip().split("\n")
|
||||
)
|
||||
assert lines[0] == "name,phone,email,created_at"
|
||||
assert "Sofia Vergara,3019998877,sofia@hollywood.com" in lines[1]
|
||||
|
||||
|
||||
def test_admin_delete_rsvp(client: TestClient):
|
||||
# Unauthorized without session
|
||||
res_unauth = client.delete("/birthday/api/admin/rsvps/1")
|
||||
assert res_unauth.status_code == 401
|
||||
|
||||
# Login as admin
|
||||
login_client(client)
|
||||
|
||||
# 404 for non-existent RSVP
|
||||
res_404 = client.delete("/birthday/api/admin/rsvps/9999")
|
||||
assert res_404.status_code == 404
|
||||
|
||||
# Create an RSVP
|
||||
client.post(
|
||||
"/birthday/api/rsvp",
|
||||
json={
|
||||
"name": "Lucas Silva",
|
||||
"phone": "300 444 5566",
|
||||
"email": "lucas@test.com",
|
||||
},
|
||||
)
|
||||
list_res = client.get("/birthday/api/admin/rsvps")
|
||||
assert list_res.status_code == 200
|
||||
rsvps = list_res.json()["rsvps"]
|
||||
assert len(rsvps) == 1
|
||||
rsvp_id = rsvps[0]["id"]
|
||||
|
||||
# Delete successfully
|
||||
del_res = client.delete(f"/birthday/api/admin/rsvps/{rsvp_id}")
|
||||
assert del_res.status_code == 204
|
||||
|
||||
# Confirm deletion
|
||||
list_after = client.get("/birthday/api/admin/rsvps")
|
||||
assert list_after.json()["count"] == 0
|
||||
|
||||
|
||||
def test_admin_update_rsvp(client: TestClient):
|
||||
# Unauthorized without session
|
||||
res_unauth = client.patch("/birthday/api/admin/rsvps/1", json={"name": "New Name"})
|
||||
assert res_unauth.status_code == 401
|
||||
|
||||
# Login as admin
|
||||
login_client(client)
|
||||
|
||||
# 404 for non-existent RSVP
|
||||
res_404 = client.patch(
|
||||
"/birthday/api/admin/rsvps/9999",
|
||||
json={"name": "New Name"},
|
||||
)
|
||||
assert res_404.status_code == 404
|
||||
|
||||
# Create two RSVPs
|
||||
client.post(
|
||||
"/birthday/api/rsvp",
|
||||
json={"name": "Person One", "phone": "300 111 2222", "email": "one@test.com"},
|
||||
)
|
||||
client.post(
|
||||
"/birthday/api/rsvp",
|
||||
json={"name": "Person Two", "phone": "300 333 4444", "email": "two@test.com"},
|
||||
)
|
||||
|
||||
list_res = client.get("/birthday/api/admin/rsvps")
|
||||
rsvps = list_res.json()["rsvps"]
|
||||
id_one = next(r["id"] for r in rsvps if r["name"] == "Person One")
|
||||
id_two = next(r["id"] for r in rsvps if r["name"] == "Person Two")
|
||||
assert id_two is not None
|
||||
|
||||
# Update Person One with valid new name and phone
|
||||
patch_res = client.patch(
|
||||
f"/birthday/api/admin/rsvps/{id_one}",
|
||||
json={
|
||||
"name": "Person One Updated",
|
||||
"phone": "+57 300 999 8888",
|
||||
"email": "newone@test.com",
|
||||
},
|
||||
)
|
||||
assert patch_res.status_code == 200
|
||||
updated_data = patch_res.json()
|
||||
assert updated_data["name"] == "Person One Updated"
|
||||
assert updated_data["phone"] == "3009998888"
|
||||
assert updated_data["email"] == "newone@test.com"
|
||||
|
||||
# Attempt to update Person One's phone to Person Two's phone -> 409
|
||||
dup_res = client.patch(
|
||||
f"/birthday/api/admin/rsvps/{id_one}",
|
||||
json={"phone": "300 333 4444"},
|
||||
)
|
||||
assert dup_res.status_code == 409
|
||||
|
||||
# Validation error for invalid phone
|
||||
val_res = client.patch(
|
||||
f"/birthday/api/admin/rsvps/{id_one}",
|
||||
json={"phone": "12345"},
|
||||
)
|
||||
assert val_res.status_code in (400, 422)
|
||||
|
||||
|
||||
def test_admin_config_endpoints_put_and_patch(admin_client: TestClient):
|
||||
"""Both PUT and PATCH /birthday/api/admin/config succeed for authorized admins."""
|
||||
current = admin_client.get("/birthday/api/admin/config").json()
|
||||
assert current["honoree_name"] == "Isabelle Snow"
|
||||
|
||||
# Test PUT
|
||||
payload_put = {**current, "honoree_name": "Isabelle PUT"}
|
||||
res_put = admin_client.put("/birthday/api/admin/config", json=payload_put)
|
||||
assert res_put.status_code == 200
|
||||
assert res_put.json()["honoree_name"] == "Isabelle PUT"
|
||||
|
||||
# Test PATCH
|
||||
payload_patch = {**current, "honoree_name": "Isabelle PATCH"}
|
||||
res_patch = admin_client.patch("/birthday/api/admin/config", json=payload_patch)
|
||||
assert res_patch.status_code == 200
|
||||
assert res_patch.json()["honoree_name"] == "Isabelle PATCH"
|
||||
@@ -0,0 +1,152 @@
|
||||
from dataclasses import FrozenInstanceError
|
||||
|
||||
import pytest
|
||||
from fastapi import Request, Response
|
||||
from fastapi.responses import RedirectResponse
|
||||
|
||||
from app.auth import AuthPort, Identity
|
||||
|
||||
|
||||
class MockAuthAdapter:
|
||||
"""Mock implementation of AuthPort for testing hexagonal boundary compliance."""
|
||||
|
||||
def __init__(self, current_user: Identity | None = None):
|
||||
self._current_user = current_user
|
||||
|
||||
def current_identity(self, request: Request) -> Identity | None:
|
||||
return self._current_user
|
||||
|
||||
def login(self, request: Request) -> Response:
|
||||
return RedirectResponse(url="/auth/login", status_code=302)
|
||||
|
||||
def logout(self, request: Request) -> Response:
|
||||
return RedirectResponse(url="/auth/logout", status_code=302)
|
||||
|
||||
|
||||
class IncompleteAuthAdapter:
|
||||
"""Non-conforming class missing login and logout methods."""
|
||||
|
||||
def current_identity(self, request: Request) -> Identity | None:
|
||||
return None
|
||||
|
||||
|
||||
def create_dummy_request(headers: dict[str, str] | None = None) -> Request:
|
||||
raw_headers = [
|
||||
(k.lower().encode("latin-1"), v.encode("latin-1"))
|
||||
for k, v in (headers or {}).items()
|
||||
]
|
||||
scope = {
|
||||
"type": "http",
|
||||
"method": "GET",
|
||||
"path": "/test",
|
||||
"headers": raw_headers,
|
||||
}
|
||||
return Request(scope)
|
||||
|
||||
|
||||
def test_identity_creation_full():
|
||||
identity = Identity(
|
||||
subject="user-123",
|
||||
email="test@example.com",
|
||||
name="Test User",
|
||||
groups=["admin", "family"],
|
||||
)
|
||||
assert identity.subject == "user-123"
|
||||
assert identity.email == "test@example.com"
|
||||
assert identity.name == "Test User"
|
||||
assert identity.groups == ["admin", "family"]
|
||||
assert identity.has_group("admin") is True
|
||||
assert identity.has_group("stranger") is False
|
||||
|
||||
|
||||
def test_identity_creation_defaults():
|
||||
identity = Identity(
|
||||
subject="user-456",
|
||||
email="minimal@example.com",
|
||||
)
|
||||
assert identity.subject == "user-456"
|
||||
assert identity.email == "minimal@example.com"
|
||||
assert identity.name is None
|
||||
assert identity.groups == []
|
||||
assert identity.has_group("admin") is False
|
||||
|
||||
|
||||
def test_identity_immutability():
|
||||
identity = Identity(
|
||||
subject="user-789",
|
||||
email="immutable@example.com",
|
||||
)
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
identity.subject = "new-subject" # type: ignore[misc]
|
||||
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
identity.email = "new@example.com" # type: ignore[misc]
|
||||
|
||||
|
||||
def test_identity_validation_subject():
|
||||
with pytest.raises(ValueError, match="subject must be a non-empty string"):
|
||||
Identity(subject="", email="test@example.com")
|
||||
|
||||
with pytest.raises(ValueError, match="subject must be a non-empty string"):
|
||||
Identity(subject=" ", email="test@example.com")
|
||||
|
||||
|
||||
def test_identity_validation_email():
|
||||
with pytest.raises(ValueError, match="email must be a non-empty string"):
|
||||
Identity(subject="user-1", email="")
|
||||
|
||||
with pytest.raises(ValueError, match="email must be a non-empty string"):
|
||||
Identity(subject="user-1", email=" ")
|
||||
|
||||
|
||||
def test_identity_validation_name():
|
||||
with pytest.raises(TypeError, match="name must be a string or None"):
|
||||
Identity(subject="user-1", email="test@example.com", name=123) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_identity_validation_groups():
|
||||
with pytest.raises(TypeError, match="groups must be a list of strings"):
|
||||
Identity(subject="user-1", email="test@example.com", groups="not-a-list") # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(TypeError, match="groups items must be strings"):
|
||||
Identity(subject="user-1", email="test@example.com", groups=[123]) # type: ignore[list-item]
|
||||
|
||||
|
||||
def test_auth_port_protocol_conformance():
|
||||
adapter = MockAuthAdapter()
|
||||
assert isinstance(adapter, AuthPort)
|
||||
|
||||
|
||||
def test_auth_port_protocol_non_conformance():
|
||||
incomplete = IncompleteAuthAdapter()
|
||||
assert not isinstance(incomplete, AuthPort)
|
||||
|
||||
|
||||
def test_auth_port_current_identity_resolution():
|
||||
expected_identity = Identity(
|
||||
subject="admin-1",
|
||||
email="admin@example.com",
|
||||
name="Admin",
|
||||
groups=["admin"],
|
||||
)
|
||||
authenticated_port: AuthPort = MockAuthAdapter(current_user=expected_identity)
|
||||
unauthenticated_port: AuthPort = MockAuthAdapter(current_user=None)
|
||||
|
||||
req = create_dummy_request()
|
||||
assert authenticated_port.current_identity(req) == expected_identity
|
||||
assert unauthenticated_port.current_identity(req) is None
|
||||
|
||||
|
||||
def test_auth_port_login_logout_contract():
|
||||
port: AuthPort = MockAuthAdapter()
|
||||
req = create_dummy_request()
|
||||
|
||||
login_resp = port.login(req)
|
||||
assert isinstance(login_resp, Response)
|
||||
assert login_resp.status_code == 302
|
||||
assert login_resp.headers["location"] == "/auth/login"
|
||||
|
||||
logout_resp = port.logout(req)
|
||||
assert isinstance(logout_resp, Response)
|
||||
assert logout_resp.status_code == 302
|
||||
assert logout_resp.headers["location"] == "/auth/logout"
|
||||
@@ -0,0 +1,135 @@
|
||||
import contextlib
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Generator
|
||||
|
||||
import pytest
|
||||
import uvicorn
|
||||
from playwright.sync_api import Browser, BrowserContext, Page, sync_playwright
|
||||
|
||||
from app.main import app
|
||||
|
||||
APP_HOST = "127.0.0.1"
|
||||
APP_PORT = 8000
|
||||
BASE_URL = f"http://{APP_HOST}:{APP_PORT}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def live_server() -> Generator[str, None, None]:
|
||||
"""Start uvicorn server in a background thread for browser testing."""
|
||||
config = uvicorn.Config(
|
||||
app,
|
||||
host=APP_HOST,
|
||||
port=APP_PORT,
|
||||
log_level="warning",
|
||||
)
|
||||
server = uvicorn.Server(config)
|
||||
thread = threading.Thread(target=server.run, daemon=True)
|
||||
thread.start()
|
||||
|
||||
# Wait for server readiness
|
||||
import httpx
|
||||
|
||||
ready = False
|
||||
for _ in range(50):
|
||||
with contextlib.suppress(Exception):
|
||||
r = httpx.get(f"{BASE_URL}/birthday/api/docs", timeout=0.5)
|
||||
if r.status_code == 200:
|
||||
ready = True
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
assert ready, "Server failed to start in time"
|
||||
yield BASE_URL
|
||||
server.should_exit = True
|
||||
thread.join(timeout=2)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def browser_instance() -> Generator[Browser, None, None]:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
yield browser
|
||||
browser.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def browser_context(browser_instance: Browser) -> Generator[BrowserContext, None, None]:
|
||||
context = browser_instance.new_context()
|
||||
yield context
|
||||
context.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def page(browser_context: BrowserContext) -> Generator[Page, None, None]:
|
||||
pg = browser_context.new_page()
|
||||
yield pg
|
||||
pg.close()
|
||||
|
||||
|
||||
def test_browser_sso_complete_interactive_loop(
|
||||
live_server: str,
|
||||
browser_context: BrowserContext,
|
||||
page: Page,
|
||||
):
|
||||
"""Complete browser SSO acceptance test (CP7).
|
||||
|
||||
Verifies:
|
||||
1. Browser navigates to /birthday/admin -> redirected to OIDC login form.
|
||||
2. Form submitted with admin@example.com / password123.
|
||||
3. Browser redirects back through callback -> receives HttpOnly cookie -> arrives on Admin Dashboard.
|
||||
4. Admin Dashboard renders RSVPs table and authenticated user info.
|
||||
5. Clicking 'Logout' button revokes session -> returns to unauthenticated state.
|
||||
"""
|
||||
# 1. Unauthenticated navigation to /birthday/admin -> redirected to OIDC login form
|
||||
admin_url = f"{live_server}/birthday/admin"
|
||||
page.goto(admin_url)
|
||||
page.wait_for_url("**/authorize**", timeout=10000)
|
||||
assert "8088" in page.url or "authorize" in page.url
|
||||
|
||||
# 2. Submit test credentials
|
||||
page.fill("input[name='username']", "admin@example.com")
|
||||
if page.query_selector("input[name='password']"):
|
||||
page.fill("input[name='password']", "password123")
|
||||
page.click("input[type='submit']")
|
||||
|
||||
# 3. Callback completes, sets HttpOnly cookie, and lands on Admin Dashboard
|
||||
page.wait_for_url("**/birthday/admin", timeout=10000)
|
||||
assert page.url.endswith("/birthday/admin")
|
||||
|
||||
cookies = browser_context.cookies()
|
||||
session_cookie = next(
|
||||
(c for c in cookies if c.get("name") == "bdinvite_session"), None
|
||||
)
|
||||
assert session_cookie is not None, "bdinvite_session cookie must be set"
|
||||
assert session_cookie.get("httpOnly") is True, "Session cookie must be HttpOnly"
|
||||
|
||||
# 4. Admin Dashboard renders RSVPs table and user info
|
||||
page.wait_for_selector("text=Respuestas", timeout=10000)
|
||||
user_info_elem = page.locator("[data-testid='user-info']")
|
||||
user_info_elem.wait_for(state="visible", timeout=10000)
|
||||
user_text = user_info_elem.text_content() or ""
|
||||
assert "admin" in user_text.lower(), f"Expected admin user info, got: {user_text}"
|
||||
|
||||
# Verify RSVPs table / UI content is visible
|
||||
assert page.locator("nav").is_visible()
|
||||
|
||||
# 5. Clicking 'Logout' button revokes session -> returns to unauthenticated state
|
||||
logout_btn = page.locator("button:has-text('Logout')")
|
||||
assert logout_btn.is_visible()
|
||||
logout_btn.click()
|
||||
|
||||
# UI displays unauthenticated state screen
|
||||
page.wait_for_selector("[data-testid='unauthenticated-state']", timeout=10000)
|
||||
assert page.locator("[data-testid='unauthenticated-state']").is_visible()
|
||||
assert page.locator("text=Sesión Finalizada").is_visible()
|
||||
|
||||
# Re-clicking login initiates fresh OIDC flow
|
||||
page.locator("[data-testid='login-btn']").click()
|
||||
page.wait_for_url("**/authorize**", timeout=10000)
|
||||
assert "authorize" in page.url
|
||||
|
||||
# Attempting to access /birthday/admin again redirects to login
|
||||
page.goto(admin_url)
|
||||
page.wait_for_url("**/authorize**", timeout=10000)
|
||||
assert "authorize" in page.url
|
||||
@@ -0,0 +1,115 @@
|
||||
from tests.conftest import login_client
|
||||
|
||||
|
||||
def test_get_config_public(client):
|
||||
response = client.get("/birthday/api/config")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["title"] == "Birthday Party"
|
||||
assert data["honoree_name"] == "Isabelle Snow"
|
||||
assert data["event_date"] == "2026-10-28"
|
||||
assert data["event_time"] == "19:00"
|
||||
assert data["event_timezone"] == "America/Bogota"
|
||||
assert data["countdown_label"] == "NOS VEMOS EN"
|
||||
|
||||
|
||||
def test_get_config_admin(client):
|
||||
res_unauth = client.get("/birthday/api/admin/config")
|
||||
assert res_unauth.status_code == 401
|
||||
|
||||
login_client(client)
|
||||
res_auth = client.get("/birthday/api/admin/config")
|
||||
assert res_auth.status_code == 200
|
||||
assert res_auth.json()["honoree_name"] == "Isabelle Snow"
|
||||
|
||||
|
||||
def test_update_config_requires_admin(client):
|
||||
update_payload = {
|
||||
"title": "Fiesta de Cumpleaños",
|
||||
"invitation_text": "Estás invitado a la fiesta de",
|
||||
"honoree_name": "Isabelle",
|
||||
"event_date": "2026-11-15",
|
||||
"event_time": "20:00",
|
||||
"event_timezone": "America/Bogota",
|
||||
"address_name": "Restaurante Central",
|
||||
"address_lines": "Cra 7 # 12-34\nBogotá",
|
||||
"map_preview_url": "https://example.com/map.png",
|
||||
"map_url": "https://maps.google.com/?q=Bogota",
|
||||
"rsvp_heading": "¿Nos vemos?",
|
||||
"rsvp_cta": "CONFIRMAR",
|
||||
"submit_label": "AHÍ ESTARÉ",
|
||||
"msg_success": "¡Perfecto!",
|
||||
"msg_success_greeting": "Gracias, {name}.",
|
||||
"msg_duplicate": "Ya estás registrado.",
|
||||
"msg_error": "Error.",
|
||||
"msg_config_error": "Error al cargar.",
|
||||
"countdown_label": "FALTAN",
|
||||
"countdown_in_progress": "EN VIVO",
|
||||
"countdown_finished": "TERMINADO",
|
||||
}
|
||||
# Without session -> 401
|
||||
res = client.put("/birthday/api/admin/config", json=update_payload)
|
||||
assert res.status_code == 401
|
||||
|
||||
# With admin session -> 200
|
||||
login_client(client)
|
||||
res_auth = client.put(
|
||||
"/birthday/api/admin/config",
|
||||
json=update_payload,
|
||||
)
|
||||
assert res_auth.status_code == 200
|
||||
data = res_auth.json()
|
||||
assert data["title"] == "Fiesta de Cumpleaños"
|
||||
assert data["honoree_name"] == "Isabelle"
|
||||
assert data["event_date"] == "2026-11-15"
|
||||
|
||||
# Public endpoint reflects updated config immediately
|
||||
res_pub = client.get("/birthday/api/config")
|
||||
assert res_pub.status_code == 200
|
||||
assert res_pub.json()["title"] == "Fiesta de Cumpleaños"
|
||||
|
||||
|
||||
def test_update_config_invalid_timezone(admin_client):
|
||||
invalid_payload = {
|
||||
"title": "Party",
|
||||
"invitation_text": "Invited",
|
||||
"honoree_name": "Name",
|
||||
"event_date": "2026-11-15",
|
||||
"event_time": "20:00",
|
||||
"event_timezone": "NonExistent/Invalid_Timezone",
|
||||
"address_name": "Place",
|
||||
"address_lines": "Line 1",
|
||||
"map_preview_url": "https://example.com/map.png",
|
||||
"map_url": "https://maps.google.com",
|
||||
"rsvp_heading": "¿Nos vemos?",
|
||||
"rsvp_cta": "CONFIRMA",
|
||||
"submit_label": "ENVIAR",
|
||||
"msg_success": "OK",
|
||||
"msg_success_greeting": "Hola {name}",
|
||||
"msg_duplicate": "Dup",
|
||||
"msg_error": "Err",
|
||||
"msg_config_error": "CfgErr",
|
||||
"countdown_label": "FALTAN",
|
||||
"countdown_in_progress": "CURSO",
|
||||
"countdown_finished": "FIN",
|
||||
}
|
||||
res = admin_client.put(
|
||||
"/birthday/api/admin/config",
|
||||
json=invalid_payload,
|
||||
)
|
||||
assert res.status_code == 422
|
||||
|
||||
|
||||
def test_spa_catch_all(client):
|
||||
res = client.get("/birthday", follow_redirects=False)
|
||||
assert res.status_code == 307
|
||||
assert res.headers["location"] == "/birthday/"
|
||||
|
||||
res_followed = client.get("/birthday", follow_redirects=True)
|
||||
assert res_followed.status_code == 200
|
||||
|
||||
res_subpath = client.get("/birthday/admin")
|
||||
assert res_subpath.status_code == 200
|
||||
|
||||
res_font = client.get("/birthday/fonts/display.woff2")
|
||||
assert res_font.status_code == 200
|
||||
@@ -0,0 +1,444 @@
|
||||
from typing import Annotated
|
||||
|
||||
import pytest
|
||||
from fastapi import Depends, FastAPI, HTTPException, Request
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.auth import (
|
||||
Identity,
|
||||
InMemorySessionStore,
|
||||
OIDCAuthAdapter,
|
||||
OIDCClient,
|
||||
get_auth_adapter,
|
||||
get_current_identity,
|
||||
require_admin,
|
||||
require_authenticated,
|
||||
require_group,
|
||||
sign_session_cookie,
|
||||
)
|
||||
|
||||
LIVE_ISSUER = "http://localhost:8088/default"
|
||||
CLIENT_ID = "bdinvite-client"
|
||||
CLIENT_SECRET = "bdinvite-secret"
|
||||
REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
|
||||
|
||||
|
||||
def create_dummy_request(
|
||||
headers: dict[str, str] | None = None,
|
||||
cookies: dict[str, str] | None = None,
|
||||
) -> Request:
|
||||
"""Construct a lightweight ASGI Request instance for unit testing dependencies."""
|
||||
raw_headers: list[tuple[bytes, bytes]] = [
|
||||
(k.lower().encode("latin-1"), v.encode("latin-1"))
|
||||
for k, v in (headers or {}).items()
|
||||
]
|
||||
if cookies:
|
||||
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
|
||||
raw_headers.append((b"cookie", cookie_header.encode("latin-1")))
|
||||
|
||||
scope = {
|
||||
"type": "http",
|
||||
"method": "GET",
|
||||
"path": "/test",
|
||||
"headers": raw_headers,
|
||||
}
|
||||
return Request(scope)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def oidc_client() -> OIDCClient:
|
||||
return OIDCClient(
|
||||
issuer=LIVE_ISSUER,
|
||||
client_id=CLIENT_ID,
|
||||
client_secret=CLIENT_SECRET,
|
||||
redirect_uri=REDIRECT_URI,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_adapter(oidc_client: OIDCClient) -> OIDCAuthAdapter:
|
||||
return OIDCAuthAdapter(
|
||||
oidc_client=oidc_client,
|
||||
session_cookie_name="bdinvite_session",
|
||||
session_store=InMemorySessionStore(),
|
||||
cookie_secure=False,
|
||||
cookie_samesite="lax",
|
||||
session_max_age=3600,
|
||||
secret_key="test-session-secret",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_app() -> FastAPI:
|
||||
"""Isolated FastAPI test harness registering dependency endpoints."""
|
||||
app = FastAPI(title="Dependency Test Harness")
|
||||
|
||||
event_planners_dep = require_group("event_planners")
|
||||
|
||||
@app.get("/test/identity")
|
||||
def route_identity(
|
||||
identity: Annotated[Identity | None, Depends(get_current_identity)],
|
||||
):
|
||||
if identity is None:
|
||||
return {"authenticated": False, "identity": None}
|
||||
return {
|
||||
"authenticated": True,
|
||||
"subject": identity.subject,
|
||||
"email": identity.email,
|
||||
"groups": identity.groups,
|
||||
}
|
||||
|
||||
@app.get("/test/authenticated")
|
||||
def route_authenticated(
|
||||
identity: Annotated[Identity, Depends(require_authenticated)],
|
||||
):
|
||||
return {
|
||||
"subject": identity.subject,
|
||||
"email": identity.email,
|
||||
"groups": identity.groups,
|
||||
}
|
||||
|
||||
@app.get("/test/admin")
|
||||
def route_admin(admin: Annotated[Identity, Depends(require_admin)]):
|
||||
return {
|
||||
"subject": admin.subject,
|
||||
"email": admin.email,
|
||||
"groups": admin.groups,
|
||||
}
|
||||
|
||||
@app.get("/test/custom-group")
|
||||
def route_custom_group(member: Annotated[Identity, Depends(event_planners_dep)]):
|
||||
return {
|
||||
"subject": member.subject,
|
||||
"groups": member.groups,
|
||||
}
|
||||
|
||||
return app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_client(test_app: FastAPI) -> TestClient:
|
||||
return TestClient(test_app)
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 1. Direct Unit Tests: FastAPI Dependency Functions in Isolation
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_unit_get_current_identity_anonymous():
|
||||
"""get_current_identity yields None when request has no authentication credentials."""
|
||||
req = create_dummy_request()
|
||||
identity = get_current_identity(req)
|
||||
assert identity is None
|
||||
|
||||
|
||||
def test_unit_get_current_identity_with_valid_session(auth_adapter: OIDCAuthAdapter):
|
||||
"""get_current_identity resolves domain Identity when valid session cookie is provided."""
|
||||
expected = Identity(
|
||||
subject="alice-001",
|
||||
email="alice@example.com",
|
||||
groups=["users"],
|
||||
)
|
||||
session = auth_adapter.session_store.create_session(identity=expected)
|
||||
signed_cookie = sign_session_cookie(session.session_id, auth_adapter.secret_key)
|
||||
req = create_dummy_request(cookies={"bdinvite_session": signed_cookie})
|
||||
|
||||
resolved = get_current_identity(req, adapter=auth_adapter)
|
||||
assert resolved == expected
|
||||
|
||||
|
||||
def test_unit_get_current_identity_with_tampered_or_expired_cookie(
|
||||
auth_adapter: OIDCAuthAdapter,
|
||||
):
|
||||
"""get_current_identity safely yields None for tampered or expired sessions."""
|
||||
# 1. Tampered signature
|
||||
req_tampered = create_dummy_request(
|
||||
cookies={"bdinvite_session": "invalid_session_id.deadbeef"}
|
||||
)
|
||||
assert get_current_identity(req_tampered, adapter=auth_adapter) is None
|
||||
|
||||
# 2. Expired session
|
||||
exp_session = auth_adapter.session_store.create_session(
|
||||
identity=Identity(subject="exp-user", email="exp@example.com"),
|
||||
max_age_seconds=-1,
|
||||
)
|
||||
signed_exp = sign_session_cookie(exp_session.session_id, auth_adapter.secret_key)
|
||||
req_expired = create_dummy_request(cookies={"bdinvite_session": signed_exp})
|
||||
assert get_current_identity(req_expired, adapter=auth_adapter) is None
|
||||
|
||||
|
||||
def test_unit_require_authenticated():
|
||||
"""require_authenticated returns Identity if present, raises HTTP 401 if anonymous."""
|
||||
valid_identity = Identity(
|
||||
subject="user-123",
|
||||
email="user123@example.com",
|
||||
groups=["guests"],
|
||||
)
|
||||
|
||||
# Authenticated user passes cleanly
|
||||
result = require_authenticated(identity=valid_identity)
|
||||
assert result == valid_identity
|
||||
|
||||
# Anonymous user (identity=None) raises HTTP 401
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
require_authenticated(identity=None)
|
||||
assert exc_info.value.status_code == 401
|
||||
assert exc_info.value.detail == "Not authenticated"
|
||||
|
||||
# Default / un-injected call raises HTTP 401
|
||||
with pytest.raises(HTTPException) as exc_info_default:
|
||||
require_authenticated()
|
||||
assert exc_info_default.value.status_code == 401
|
||||
|
||||
|
||||
def test_unit_require_group_factory():
|
||||
"""require_group produces dependencies enforcing specific group membership."""
|
||||
group_dep = require_group("special_ops")
|
||||
assert callable(group_dep)
|
||||
assert "special_ops" in group_dep.__name__
|
||||
|
||||
user_with_group = Identity(
|
||||
subject="op-1",
|
||||
email="op1@example.com",
|
||||
groups=["special_ops", "staff"],
|
||||
)
|
||||
user_without_group = Identity(
|
||||
subject="user-2",
|
||||
email="user2@example.com",
|
||||
groups=["staff"],
|
||||
)
|
||||
|
||||
# 1. Authorized member yields Identity
|
||||
assert group_dep(identity=user_with_group) == user_with_group
|
||||
|
||||
# 2. Authenticated user missing the group raises HTTP 403
|
||||
with pytest.raises(HTTPException) as exc_info_403:
|
||||
group_dep(identity=user_without_group)
|
||||
assert exc_info_403.value.status_code == 403
|
||||
assert "Forbidden" in exc_info_403.value.detail
|
||||
|
||||
# 3. Anonymous caller raises HTTP 401
|
||||
with pytest.raises(HTTPException) as exc_info_401:
|
||||
group_dep(identity=None)
|
||||
assert exc_info_401.value.status_code == 401
|
||||
|
||||
|
||||
def test_unit_require_admin():
|
||||
"""require_admin enforces bdinvite_admins group membership."""
|
||||
admin_identity = Identity(
|
||||
subject="admin-1",
|
||||
email="admin@example.com",
|
||||
groups=["bdinvite_admins"],
|
||||
)
|
||||
guest_identity = Identity(
|
||||
subject="guest-1",
|
||||
email="guest@example.com",
|
||||
groups=["guests"],
|
||||
)
|
||||
|
||||
# Admin yields Identity
|
||||
assert require_admin(identity=admin_identity) == admin_identity
|
||||
|
||||
# Non-admin raises HTTP 403
|
||||
with pytest.raises(HTTPException) as exc_403:
|
||||
require_admin(identity=guest_identity)
|
||||
assert exc_403.value.status_code == 403
|
||||
|
||||
# Anonymous raises HTTP 401
|
||||
with pytest.raises(HTTPException) as exc_401:
|
||||
require_admin(identity=None)
|
||||
assert exc_401.value.status_code == 401
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 2. HTTP Integration Tests: FastAPI Dependency Test Harness
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_http_anonymous_request_yields_none_on_get_current_identity(
|
||||
test_client: TestClient,
|
||||
):
|
||||
"""Anonymous request yields None on get_current_identity endpoint."""
|
||||
resp = test_client.get("/test/identity")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json() == {"authenticated": False, "identity": None}
|
||||
|
||||
|
||||
def test_http_anonymous_request_raises_401_on_require_authenticated(
|
||||
test_client: TestClient,
|
||||
):
|
||||
"""Anonymous request raises HTTP 401 Unauthorized on require_authenticated."""
|
||||
resp = test_client.get("/test/authenticated")
|
||||
assert resp.status_code == 401
|
||||
assert resp.json()["detail"] == "Not authenticated"
|
||||
|
||||
|
||||
def test_http_anonymous_request_raises_401_on_require_admin(
|
||||
test_client: TestClient,
|
||||
):
|
||||
"""Anonymous request raises HTTP 401 Unauthorized on require_admin."""
|
||||
resp = test_client.get("/test/admin")
|
||||
assert resp.status_code == 401
|
||||
assert resp.json()["detail"] == "Not authenticated"
|
||||
|
||||
|
||||
def test_http_authenticated_non_admin_raises_403_on_require_admin(
|
||||
test_client: TestClient,
|
||||
):
|
||||
"""Authenticated non-admin user (guest@example.com with groups: ['guests']) raises HTTP 403."""
|
||||
adapter = get_auth_adapter()
|
||||
guest_identity = Identity(
|
||||
subject="guest-001",
|
||||
email="guest@example.com",
|
||||
groups=["guests"],
|
||||
)
|
||||
session = adapter.session_store.create_session(identity=guest_identity)
|
||||
signed_cookie = sign_session_cookie(session.session_id, adapter.secret_key)
|
||||
test_client.cookies.set(adapter.session_cookie_name, signed_cookie)
|
||||
|
||||
# 1. get_current_identity yields the guest identity
|
||||
resp_id = test_client.get("/test/identity")
|
||||
assert resp_id.status_code == 200
|
||||
assert resp_id.json()["authenticated"] is True
|
||||
assert resp_id.json()["subject"] == "guest-001"
|
||||
assert resp_id.json()["groups"] == ["guests"]
|
||||
|
||||
# 2. require_authenticated succeeds
|
||||
resp_auth = test_client.get("/test/authenticated")
|
||||
assert resp_auth.status_code == 200
|
||||
assert resp_auth.json()["subject"] == "guest-001"
|
||||
|
||||
# 3. require_admin raises HTTP 403 Forbidden
|
||||
resp_admin = test_client.get("/test/admin")
|
||||
assert resp_admin.status_code == 403
|
||||
assert "Forbidden" in resp_admin.json()["detail"]
|
||||
|
||||
|
||||
def test_http_authenticated_admin_yields_identity_on_require_admin(
|
||||
test_client: TestClient,
|
||||
):
|
||||
"""Authenticated admin user (admin@example.com with groups: ['bdinvite_admins']) yields Identity."""
|
||||
adapter = get_auth_adapter()
|
||||
admin_identity = Identity(
|
||||
subject="admin-001",
|
||||
email="admin@example.com",
|
||||
groups=["bdinvite_admins"],
|
||||
)
|
||||
session = adapter.session_store.create_session(identity=admin_identity)
|
||||
signed_cookie = sign_session_cookie(session.session_id, adapter.secret_key)
|
||||
test_client.cookies.set(adapter.session_cookie_name, signed_cookie)
|
||||
|
||||
# 1. get_current_identity yields admin identity
|
||||
resp_id = test_client.get("/test/identity")
|
||||
assert resp_id.status_code == 200
|
||||
assert resp_id.json()["subject"] == "admin-001"
|
||||
|
||||
# 2. require_authenticated yields admin identity
|
||||
resp_auth = test_client.get("/test/authenticated")
|
||||
assert resp_auth.status_code == 200
|
||||
assert resp_auth.json()["subject"] == "admin-001"
|
||||
|
||||
# 3. require_admin successfully yields the Identity object
|
||||
resp_admin = test_client.get("/test/admin")
|
||||
assert resp_admin.status_code == 200
|
||||
data = resp_admin.json()
|
||||
assert data["subject"] == "admin-001"
|
||||
assert data["email"] == "admin@example.com"
|
||||
assert data["groups"] == ["bdinvite_admins"]
|
||||
|
||||
|
||||
def test_http_custom_group_requirement(test_client: TestClient):
|
||||
"""require_group enforces arbitrary group membership correctly."""
|
||||
adapter = get_auth_adapter()
|
||||
|
||||
# User without event_planners group -> 403
|
||||
user_identity = Identity(
|
||||
subject="user-planner-no",
|
||||
email="planner_no@example.com",
|
||||
groups=["volunteers"],
|
||||
)
|
||||
session_no = adapter.session_store.create_session(identity=user_identity)
|
||||
signed_no = sign_session_cookie(session_no.session_id, adapter.secret_key)
|
||||
test_client.cookies.set(adapter.session_cookie_name, signed_no)
|
||||
|
||||
resp_denied = test_client.get("/test/custom-group")
|
||||
assert resp_denied.status_code == 403
|
||||
|
||||
# User with event_planners group -> 200
|
||||
planner_identity = Identity(
|
||||
subject="user-planner-yes",
|
||||
email="planner_yes@example.com",
|
||||
groups=["volunteers", "event_planners"],
|
||||
)
|
||||
session_yes = adapter.session_store.create_session(identity=planner_identity)
|
||||
signed_yes = sign_session_cookie(session_yes.session_id, adapter.secret_key)
|
||||
test_client.cookies.set(adapter.session_cookie_name, signed_yes)
|
||||
|
||||
resp_allowed = test_client.get("/test/custom-group")
|
||||
assert resp_allowed.status_code == 200
|
||||
assert resp_allowed.json()["subject"] == "user-planner-yes"
|
||||
|
||||
|
||||
def test_http_bearer_token_authorization(
|
||||
test_client: TestClient,
|
||||
oidc_client: OIDCClient,
|
||||
):
|
||||
"""Bearer token containing admin groups satisfies require_admin; non-admin raises 403."""
|
||||
# 1. Authenticate admin user against IdP to obtain verified ID token
|
||||
admin_token_resp, _ = oidc_client.authenticate_with_password(
|
||||
username="admin@example.com",
|
||||
password="password123",
|
||||
scopes=["openid", "profile", "email"],
|
||||
)
|
||||
admin_headers = {"Authorization": f"Bearer {admin_token_resp.id_token}"}
|
||||
resp_admin = test_client.get("/test/admin", headers=admin_headers)
|
||||
assert resp_admin.status_code == 200
|
||||
assert resp_admin.json()["subject"] == "admin-001"
|
||||
|
||||
# 2. Authenticate guest user against IdP to obtain verified ID token
|
||||
guest_token_resp, _ = oidc_client.authenticate_with_password(
|
||||
username="guest@example.com",
|
||||
password="password123",
|
||||
scopes=["openid", "profile", "email"],
|
||||
)
|
||||
guest_headers = {"Authorization": f"Bearer {guest_token_resp.id_token}"}
|
||||
resp_guest = test_client.get("/test/admin", headers=guest_headers)
|
||||
assert resp_guest.status_code == 403
|
||||
|
||||
|
||||
def test_http_remote_user_header_spoofing_rejected(test_client: TestClient):
|
||||
"""Remote-User and other unverified request headers cannot spoof identity or bypass dependencies."""
|
||||
spoof_headers = {
|
||||
"Remote-User": "admin@example.com",
|
||||
"X-Remote-User": "admin-001",
|
||||
"X-User-Groups": "bdinvite_admins",
|
||||
}
|
||||
|
||||
# All protected dependency endpoints reject unverified headers
|
||||
resp_id = test_client.get("/test/identity", headers=spoof_headers)
|
||||
assert resp_id.status_code == 200
|
||||
assert resp_id.json() == {"authenticated": False, "identity": None}
|
||||
|
||||
resp_auth = test_client.get("/test/authenticated", headers=spoof_headers)
|
||||
assert resp_auth.status_code == 401
|
||||
|
||||
resp_admin = test_client.get("/test/admin", headers=spoof_headers)
|
||||
assert resp_admin.status_code == 401
|
||||
|
||||
|
||||
def test_fastapi_dependency_overrides(test_app: FastAPI, test_client: TestClient):
|
||||
"""FastAPI dependency_overrides works as expected with require_admin and get_current_identity."""
|
||||
mock_admin = Identity(
|
||||
subject="mocked-admin",
|
||||
email="mocked@example.com",
|
||||
groups=["bdinvite_admins"],
|
||||
)
|
||||
|
||||
test_app.dependency_overrides[require_admin] = lambda: mock_admin
|
||||
try:
|
||||
resp = test_client.get("/test/admin")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["subject"] == "mocked-admin"
|
||||
finally:
|
||||
test_app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,348 @@
|
||||
from dataclasses import FrozenInstanceError
|
||||
|
||||
import pytest
|
||||
from fastapi import Request, Response
|
||||
|
||||
from app.auth import (
|
||||
AuthPort,
|
||||
Identity,
|
||||
InvalidTokenError,
|
||||
OIDCAuthAdapter,
|
||||
OIDCClient,
|
||||
)
|
||||
|
||||
LIVE_ISSUER = "http://localhost:8088/default"
|
||||
CLIENT_ID = "bdinvite-client"
|
||||
CLIENT_SECRET = "bdinvite-secret"
|
||||
REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def oidc_client() -> OIDCClient:
|
||||
return OIDCClient(
|
||||
issuer=LIVE_ISSUER,
|
||||
client_id=CLIENT_ID,
|
||||
client_secret=CLIENT_SECRET,
|
||||
redirect_uri=REDIRECT_URI,
|
||||
groups_claim="groups",
|
||||
)
|
||||
|
||||
|
||||
def create_dummy_request(
|
||||
headers: dict[str, str] | None = None,
|
||||
cookies: dict[str, str] | None = None,
|
||||
) -> Request:
|
||||
raw_headers = [
|
||||
(k.lower().encode("latin-1"), v.encode("latin-1"))
|
||||
for k, v in (headers or {}).items()
|
||||
]
|
||||
if cookies:
|
||||
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
|
||||
raw_headers.append((b"cookie", cookie_header.encode("latin-1")))
|
||||
|
||||
scope = {
|
||||
"type": "http",
|
||||
"method": "GET",
|
||||
"path": "/birthday/api/admin/rsvps",
|
||||
"headers": raw_headers,
|
||||
}
|
||||
return Request(scope)
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 1. Identity Resolution & Mapping Unit Tests
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_identity_resolution_standard_claims(oidc_client: OIDCClient):
|
||||
"""Standard identity claims (sub, email, name, groups) map correctly to Identity domain model."""
|
||||
claims = {
|
||||
"sub": "user-42",
|
||||
"email": "user42@example.com",
|
||||
"name": "Douglas Adams",
|
||||
"groups": ["author", "scifi"],
|
||||
}
|
||||
identity = oidc_client.extract_identity(claims)
|
||||
|
||||
assert isinstance(identity, Identity)
|
||||
assert identity.subject == "user-42"
|
||||
assert identity.email == "user42@example.com"
|
||||
assert identity.name == "Douglas Adams"
|
||||
assert identity.groups == ["author", "scifi"]
|
||||
assert identity.has_group("author") is True
|
||||
assert identity.has_group("nonexistent") is False
|
||||
|
||||
|
||||
def test_identity_resolution_missing_email_and_name_defaults(oidc_client: OIDCClient):
|
||||
"""Missing email falls back to synthetic local address, and missing name defaults to None."""
|
||||
claims = {
|
||||
"sub": "svc-worker-99",
|
||||
}
|
||||
identity = oidc_client.extract_identity(claims)
|
||||
|
||||
assert identity.subject == "svc-worker-99"
|
||||
assert identity.email == f"svc-worker-99@{CLIENT_ID}.local"
|
||||
assert identity.name is None
|
||||
assert identity.groups == []
|
||||
|
||||
|
||||
def test_identity_resolution_missing_subject_raises_invalid_token(
|
||||
oidc_client: OIDCClient,
|
||||
):
|
||||
"""Missing or empty sub claim raises InvalidTokenError."""
|
||||
with pytest.raises(InvalidTokenError, match="missing required 'sub' claim"):
|
||||
oidc_client.extract_identity({})
|
||||
|
||||
with pytest.raises(InvalidTokenError, match="missing required 'sub' claim"):
|
||||
oidc_client.extract_identity({"sub": " ", "email": "valid@example.com"})
|
||||
|
||||
|
||||
def test_identity_groups_extraction_clean_defaults(oidc_client: OIDCClient):
|
||||
"""Missing, None, non-list, or empty groups claim cleanly defaults to empty list."""
|
||||
# Missing groups key
|
||||
assert oidc_client.extract_identity({"sub": "u1"}).groups == []
|
||||
|
||||
# None value
|
||||
assert oidc_client.extract_identity({"sub": "u1", "groups": None}).groups == []
|
||||
|
||||
# Empty list
|
||||
assert oidc_client.extract_identity({"sub": "u1", "groups": []}).groups == []
|
||||
|
||||
# Single string group
|
||||
assert oidc_client.extract_identity(
|
||||
{"sub": "u1", "groups": "single_role"}
|
||||
).groups == ["single_role"]
|
||||
|
||||
# Tuple / Set collections
|
||||
assert oidc_client.extract_identity(
|
||||
{"sub": "u1", "groups": ("admin", "editor")}
|
||||
).groups == ["admin", "editor"]
|
||||
|
||||
# Discard non-string, empty strings, and trim whitespace
|
||||
claims = {"sub": "u1", "groups": [" admin ", "", " ", 123, None, "editor"]}
|
||||
assert oidc_client.extract_identity(claims).groups == ["admin", "editor"]
|
||||
|
||||
# Deduplicate while preserving order
|
||||
claims_dup = {"sub": "u1", "groups": ["alpha", "beta", "alpha", "gamma", "beta"]}
|
||||
assert oidc_client.extract_identity(claims_dup).groups == ["alpha", "beta", "gamma"]
|
||||
|
||||
|
||||
def test_identity_groups_configurable_claim_path():
|
||||
"""Group extraction respects configured group claim path, including nested paths."""
|
||||
# Custom top-level path
|
||||
custom_client = OIDCClient(
|
||||
issuer=LIVE_ISSUER,
|
||||
client_id=CLIENT_ID,
|
||||
groups_claim="roles",
|
||||
)
|
||||
claims = {"sub": "u1", "roles": ["superadmin", "operator"], "groups": ["ignored"]}
|
||||
assert custom_client.extract_identity(claims).groups == ["superadmin", "operator"]
|
||||
|
||||
# Nested path (e.g. Keycloak realm_access.roles)
|
||||
nested_client = OIDCClient(
|
||||
issuer=LIVE_ISSUER,
|
||||
client_id=CLIENT_ID,
|
||||
groups_claim="realm_access.roles",
|
||||
)
|
||||
claims_nested = {
|
||||
"sub": "u1",
|
||||
"realm_access": {"roles": ["app_admin", "user"]},
|
||||
}
|
||||
assert nested_client.extract_identity(claims_nested).groups == ["app_admin", "user"]
|
||||
|
||||
# Nested path missing
|
||||
assert (
|
||||
nested_client.extract_identity({"sub": "u1", "realm_access": {}}).groups == []
|
||||
)
|
||||
assert nested_client.extract_identity({"sub": "u1"}).groups == []
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 2. Seeded Fixture Users Verification (Live Integration)
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_live_fixture_admin_user_authentication(oidc_client: OIDCClient):
|
||||
"""Authenticating with admin@example.com resolves to Identity with bdinvite_admins group."""
|
||||
token_resp, identity = oidc_client.authenticate_with_password(
|
||||
username="admin@example.com",
|
||||
password="password123",
|
||||
scopes=["openid", "profile", "email"],
|
||||
)
|
||||
|
||||
assert isinstance(identity, Identity)
|
||||
assert identity.subject == "admin-001"
|
||||
assert identity.email == "admin@example.com"
|
||||
assert identity.name == "Admin User"
|
||||
assert identity.groups == ["bdinvite_admins"]
|
||||
assert identity.has_group("bdinvite_admins") is True
|
||||
assert identity.has_group("guests") is False
|
||||
|
||||
# Verify ID token claims match domain model
|
||||
assert token_resp.claims["sub"] == "admin-001"
|
||||
assert token_resp.claims["email"] == "admin@example.com"
|
||||
assert token_resp.claims["groups"] == ["bdinvite_admins"]
|
||||
|
||||
|
||||
def test_live_fixture_guest_user_authentication(oidc_client: OIDCClient):
|
||||
"""Authenticating with guest@example.com resolves to Identity with guests group."""
|
||||
token_resp, identity = oidc_client.authenticate_with_password(
|
||||
username="guest@example.com",
|
||||
password="password123",
|
||||
scopes=["openid", "profile", "email"],
|
||||
)
|
||||
|
||||
assert isinstance(identity, Identity)
|
||||
assert identity.subject == "guest-001"
|
||||
assert identity.email == "guest@example.com"
|
||||
assert identity.name == "Guest User"
|
||||
assert identity.groups == ["guests"]
|
||||
assert identity.has_group("guests") is True
|
||||
assert identity.has_group("bdinvite_admins") is False
|
||||
|
||||
# Verify ID token claims match domain model
|
||||
assert token_resp.claims["sub"] == "guest-001"
|
||||
assert token_resp.claims["email"] == "guest@example.com"
|
||||
assert token_resp.claims["groups"] == ["guests"]
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 3. Identity Origin Integrity & Immutability Tests
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_identity_origin_integrity_rejection_of_unvalidated_request_headers(
|
||||
oidc_client: OIDCClient,
|
||||
):
|
||||
"""Application adapter rejects constructing Identity from raw request headers or client data."""
|
||||
adapter = OIDCAuthAdapter(oidc_client=oidc_client)
|
||||
|
||||
# Attacker passes spoofed Remote-User or X-User headers
|
||||
spoofed_request = create_dummy_request(
|
||||
headers={
|
||||
"Remote-User": "admin@example.com",
|
||||
"Remote-Groups": "bdinvite_admins",
|
||||
"X-Forwarded-User": "admin-001",
|
||||
}
|
||||
)
|
||||
|
||||
# Adapter must strictly refuse to manufacture an Identity from unvalidated request headers
|
||||
resolved = adapter.current_identity(spoofed_request)
|
||||
assert resolved is None
|
||||
|
||||
|
||||
def test_identity_origin_integrity_rejection_of_tampered_token(oidc_client: OIDCClient):
|
||||
"""Identity cannot be extracted from a tampered or forged token."""
|
||||
# Obtain a genuine token for admin
|
||||
token_resp, _ = oidc_client.authenticate_with_password(
|
||||
username="admin@example.com",
|
||||
password="password123",
|
||||
)
|
||||
valid_id_token = token_resp.id_token
|
||||
|
||||
# Case 1: Tampered signature
|
||||
tampered_sig_token = valid_id_token[:-10] + "FORGED_SIG"
|
||||
with pytest.raises(InvalidTokenError):
|
||||
oidc_client.extract_identity_from_token(tampered_sig_token)
|
||||
|
||||
# Case 2: Adapter with tampered token in Authorization header returns None
|
||||
bad_request = create_dummy_request(
|
||||
headers={"Authorization": f"Bearer {tampered_sig_token}"}
|
||||
)
|
||||
adapter = OIDCAuthAdapter(oidc_client=oidc_client)
|
||||
assert adapter.current_identity(bad_request) is None
|
||||
|
||||
|
||||
def test_identity_immutability():
|
||||
"""Identity instance is frozen and cannot be mutated after creation."""
|
||||
identity = Identity(
|
||||
subject="admin-001",
|
||||
email="admin@example.com",
|
||||
name="Admin User",
|
||||
groups=["bdinvite_admins"],
|
||||
)
|
||||
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
identity.groups = ["guests"] # type: ignore[misc]
|
||||
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
identity.subject = "hacked-sub" # type: ignore[misc]
|
||||
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
identity.email = "hacked@example.com" # type: ignore[misc]
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 4. AuthPort Protocol Conformance & Adapter Tests
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_oidc_auth_adapter_conforms_to_auth_port(oidc_client: OIDCClient):
|
||||
"""OIDCAuthAdapter satisfies the AuthPort protocol runtime contract."""
|
||||
adapter = OIDCAuthAdapter(oidc_client=oidc_client)
|
||||
assert isinstance(adapter, AuthPort)
|
||||
|
||||
|
||||
def test_oidc_auth_adapter_current_identity_with_valid_bearer(oidc_client: OIDCClient):
|
||||
"""OIDCAuthAdapter extracts valid Identity from Authorization: Bearer token."""
|
||||
token_resp, expected_identity = oidc_client.authenticate_with_password(
|
||||
username="admin@example.com",
|
||||
password="password123",
|
||||
)
|
||||
|
||||
adapter = OIDCAuthAdapter(oidc_client=oidc_client)
|
||||
req = create_dummy_request(
|
||||
headers={"Authorization": f"Bearer {token_resp.id_token}"}
|
||||
)
|
||||
|
||||
resolved = adapter.current_identity(req)
|
||||
assert resolved == expected_identity
|
||||
assert resolved is not None
|
||||
assert resolved.subject == "admin-001"
|
||||
assert resolved.has_group("bdinvite_admins") is True
|
||||
|
||||
|
||||
def test_oidc_auth_adapter_current_identity_with_valid_cookie(oidc_client: OIDCClient):
|
||||
"""OIDCAuthAdapter extracts valid Identity from session cookie."""
|
||||
token_resp, expected_identity = oidc_client.authenticate_with_password(
|
||||
username="guest@example.com",
|
||||
password="password123",
|
||||
)
|
||||
|
||||
adapter = OIDCAuthAdapter(
|
||||
oidc_client=oidc_client, session_cookie_name="bdinvite_session"
|
||||
)
|
||||
req = create_dummy_request(cookies={"bdinvite_session": token_resp.id_token})
|
||||
|
||||
resolved = adapter.current_identity(req)
|
||||
assert resolved == expected_identity
|
||||
assert resolved is not None
|
||||
assert resolved.subject == "guest-001"
|
||||
assert resolved.has_group("guests") is True
|
||||
|
||||
|
||||
def test_oidc_auth_adapter_login_redirect(oidc_client: OIDCClient):
|
||||
"""OIDCAuthAdapter login returns 302 redirect to OIDC authorization endpoint."""
|
||||
adapter = OIDCAuthAdapter(oidc_client=oidc_client)
|
||||
req = create_dummy_request()
|
||||
|
||||
response = adapter.login(req)
|
||||
assert isinstance(response, Response)
|
||||
assert response.status_code == 302
|
||||
assert "location" in response.headers
|
||||
assert response.headers["location"].startswith(f"{LIVE_ISSUER}/authorize?")
|
||||
|
||||
|
||||
def test_oidc_auth_adapter_logout_redirect_and_clears_cookie(oidc_client: OIDCClient):
|
||||
"""OIDCAuthAdapter logout returns 302 redirect and deletes the session cookie."""
|
||||
adapter = OIDCAuthAdapter(
|
||||
oidc_client=oidc_client, session_cookie_name="bdinvite_session"
|
||||
)
|
||||
req = create_dummy_request()
|
||||
|
||||
response = adapter.logout(req)
|
||||
assert isinstance(response, Response)
|
||||
assert response.status_code == 302
|
||||
# Verify cookie deletion header exists
|
||||
assert "set-cookie" in response.headers
|
||||
assert "bdinvite_session" in response.headers["set-cookie"]
|
||||
@@ -0,0 +1,173 @@
|
||||
from unittest.mock import ANY, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.config import settings
|
||||
from app.services.map_preview import (
|
||||
deg2num,
|
||||
extract_coordinates_from_text,
|
||||
is_google_maps_host,
|
||||
validate_google_maps_url_format,
|
||||
)
|
||||
from tests.conftest import login_client
|
||||
|
||||
|
||||
def test_is_google_maps_host():
|
||||
assert is_google_maps_host("maps.app.goo.gl")
|
||||
assert is_google_maps_host("share.google")
|
||||
assert is_google_maps_host("goo.gl")
|
||||
assert is_google_maps_host("maps.google.com")
|
||||
assert is_google_maps_host("google.com")
|
||||
assert is_google_maps_host("www.google.com")
|
||||
assert is_google_maps_host("google.es")
|
||||
assert is_google_maps_host("maps.google.co.uk")
|
||||
|
||||
assert not is_google_maps_host("example.com")
|
||||
assert not is_google_maps_host("bing.com")
|
||||
assert not is_google_maps_host("evilgoogle.com")
|
||||
|
||||
|
||||
def test_validate_google_maps_url_format():
|
||||
validate_google_maps_url_format("https://maps.app.goo.gl/354784424357732")
|
||||
validate_google_maps_url_format(
|
||||
"https://www.google.com/maps/place/Fresco/@34.1,-118.2,17z"
|
||||
)
|
||||
validate_google_maps_url_format("https://maps.google.com/?q=34.1,-118.2")
|
||||
|
||||
with pytest.raises(ValueError, match="no puede estar vacía"):
|
||||
validate_google_maps_url_format("")
|
||||
|
||||
with pytest.raises(ValueError, match="comenzar con http"):
|
||||
validate_google_maps_url_format("ftp://maps.google.com")
|
||||
|
||||
with pytest.raises(ValueError, match="enlace de Google Maps válido"):
|
||||
validate_google_maps_url_format("https://apple.com/maps")
|
||||
|
||||
|
||||
def test_extract_coordinates_from_text():
|
||||
# 1. @lat,lng
|
||||
coords = extract_coordinates_from_text(
|
||||
"https://google.com/maps/place/Venue/@34.143245,-118.255132,17z"
|
||||
)
|
||||
assert coords == (34.143245, -118.255132)
|
||||
|
||||
# 2. !3dlat!4dlng
|
||||
coords = extract_coordinates_from_text(
|
||||
"https://google.com/maps/data=!4m6!3m5!1s0x0!8m2!3d4.6534!4d-74.0564"
|
||||
)
|
||||
assert coords == (4.6534, -74.0564)
|
||||
|
||||
# 3. Query params: q=lat,lng
|
||||
coords = extract_coordinates_from_text(
|
||||
"https://maps.google.com/?q=34.1432,-118.2551"
|
||||
)
|
||||
assert coords == (34.1432, -118.2551)
|
||||
|
||||
# 4. Query params: ll=lat,lng
|
||||
coords = extract_coordinates_from_text(
|
||||
"https://maps.google.com/maps?ll=34.1432,-118.2551&z=16"
|
||||
)
|
||||
assert coords == (34.1432, -118.2551)
|
||||
|
||||
# 5. Non-coordinate text
|
||||
assert (
|
||||
extract_coordinates_from_text("https://maps.google.com/?q=Eiffel+Tower") is None
|
||||
)
|
||||
|
||||
|
||||
def test_deg2num():
|
||||
xtile, ytile = deg2num(34.1432, -118.2551, 16)
|
||||
assert int(xtile) == 11240
|
||||
assert int(ytile) == 26148
|
||||
|
||||
|
||||
@patch("app.routes.admin.resolve_google_maps_coordinates")
|
||||
@patch("app.routes.admin.generate_map_preview_image")
|
||||
def test_admin_generate_map_preview_endpoint(
|
||||
mock_generate, mock_resolve, client, tmp_path
|
||||
):
|
||||
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
|
||||
mock_generate.return_value = tmp_path / "map_preview.png"
|
||||
|
||||
# Test without auth -> 401
|
||||
resp = client.post(
|
||||
"/birthday/api/admin/map-preview/generate",
|
||||
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
|
||||
)
|
||||
assert resp.status_code == 401
|
||||
|
||||
# Test with auth -> 200
|
||||
login_client(client)
|
||||
resp = client.post(
|
||||
"/birthday/api/admin/map-preview/generate",
|
||||
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert "/birthday/api/map-preview.png" in data["map_preview_url"]
|
||||
assert data["lat"] == 34.1432
|
||||
assert data["lng"] == -118.2551
|
||||
mock_resolve.assert_called_once_with(
|
||||
"https://maps.google.com/?q=34.1,-118.2", fallback_query=ANY
|
||||
)
|
||||
mock_generate.assert_called_once_with(34.1432, -118.2551)
|
||||
|
||||
|
||||
@patch("app.routes.admin.resolve_google_maps_coordinates")
|
||||
@patch("app.routes.admin.generate_map_preview_image")
|
||||
def test_config_update_triggers_generator_only_when_map_url_changes(
|
||||
mock_generate, mock_resolve, admin_client, tmp_path
|
||||
):
|
||||
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
|
||||
mock_generate.return_value = tmp_path / "map_preview.png"
|
||||
|
||||
# Get current config
|
||||
current = admin_client.get("/birthday/api/admin/config").json()
|
||||
orig_map_url = current["map_url"]
|
||||
assert orig_map_url == "https://maps.google.com/?q=Fresco+Ristorante+Glendale+CA"
|
||||
|
||||
# 1. Update config WITHOUT changing map_url -> generator NOT called
|
||||
update_payload = {**current}
|
||||
update_payload["honoree_name"] = "Updated Honoree"
|
||||
resp = admin_client.put("/birthday/api/admin/config", json=update_payload)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["honoree_name"] == "Updated Honoree"
|
||||
mock_resolve.assert_not_called()
|
||||
mock_generate.assert_not_called()
|
||||
|
||||
# 2. Update config WITH new map_url -> generator CALLED
|
||||
update_payload["map_url"] = "https://maps.google.com/?q=34.1432,-118.2551"
|
||||
resp = admin_client.put("/birthday/api/admin/config", json=update_payload)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["map_url"] == "https://maps.google.com/?q=34.1432,-118.2551"
|
||||
assert resp.json()["map_preview_url"] == "/birthday/api/map-preview.png"
|
||||
mock_resolve.assert_called_once_with(
|
||||
"https://maps.google.com/?q=34.1432,-118.2551", fallback_query=ANY
|
||||
)
|
||||
mock_generate.assert_called_once_with(34.1432, -118.2551)
|
||||
|
||||
|
||||
def test_config_update_rejects_invalid_map_url(admin_client):
|
||||
current = admin_client.get("/birthday/api/admin/config").json()
|
||||
bad_payload = {**current, "map_url": "https://invalid-non-google-url.com/something"}
|
||||
|
||||
resp = admin_client.put("/birthday/api/admin/config", json=bad_payload)
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
def test_get_map_preview_serving(client, tmp_path, monkeypatch):
|
||||
# Case 1: file exists
|
||||
test_img = tmp_path / "map_preview.png"
|
||||
test_img.write_bytes(b"\x89PNG\r\n\x1a\nfakeimagebytes")
|
||||
monkeypatch.setattr(settings, "DATA_DIR", str(tmp_path))
|
||||
|
||||
resp = client.get("/birthday/api/map-preview.png")
|
||||
assert resp.status_code == 200
|
||||
assert resp.headers["content-type"] == "image/png"
|
||||
assert resp.content == b"\x89PNG\r\n\x1a\nfakeimagebytes"
|
||||
|
||||
# Case 2: file does not exist -> redirects to fallback
|
||||
test_img.unlink()
|
||||
resp_fallback = client.get("/birthday/api/map-preview.png", follow_redirects=False)
|
||||
assert resp_fallback.status_code == 307
|
||||
assert "tile.openstreetmap.org" in resp_fallback.headers["location"]
|
||||
@@ -0,0 +1,320 @@
|
||||
import base64
|
||||
import json
|
||||
import urllib.parse
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.auth import (
|
||||
Identity,
|
||||
InvalidStateError,
|
||||
InvalidTokenError,
|
||||
MismatchedNonceError,
|
||||
OIDCClient,
|
||||
compute_code_challenge,
|
||||
generate_code_verifier,
|
||||
generate_nonce,
|
||||
generate_state,
|
||||
)
|
||||
|
||||
LIVE_ISSUER = "http://localhost:8088/default"
|
||||
CLIENT_ID = "bdinvite-client"
|
||||
CLIENT_SECRET = "bdinvite-secret"
|
||||
REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def oidc_client() -> OIDCClient:
|
||||
return OIDCClient(
|
||||
issuer=LIVE_ISSUER,
|
||||
client_id=CLIENT_ID,
|
||||
client_secret=CLIENT_SECRET,
|
||||
redirect_uri=REDIRECT_URI,
|
||||
)
|
||||
|
||||
|
||||
def test_pkce_generation_and_challenge():
|
||||
"""Verify PKCE code_verifier generation and S256 derivation per RFC 7636."""
|
||||
verifier = generate_code_verifier(64)
|
||||
assert len(verifier) == 64
|
||||
# RFC 7636 Section 4.1 unreserved characters
|
||||
unreserved = set(
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"
|
||||
)
|
||||
assert all(c in unreserved for c in verifier)
|
||||
|
||||
# Length bounds validation
|
||||
with pytest.raises(ValueError, match="between 43 and 128"):
|
||||
generate_code_verifier(42)
|
||||
with pytest.raises(ValueError, match="between 43 and 128"):
|
||||
generate_code_verifier(129)
|
||||
|
||||
# RFC 7636 Appendix B test vector verification
|
||||
appendix_b_verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
|
||||
expected_challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
|
||||
derived_challenge = compute_code_challenge(appendix_b_verifier)
|
||||
assert derived_challenge == expected_challenge
|
||||
|
||||
|
||||
def test_state_and_nonce_generation():
|
||||
"""Verify cryptographic randomness and uniqueness for state and nonce."""
|
||||
s1 = generate_state()
|
||||
s2 = generate_state()
|
||||
assert len(s1) >= 32
|
||||
assert s1 != s2
|
||||
|
||||
n1 = generate_nonce()
|
||||
n2 = generate_nonce()
|
||||
assert len(n1) >= 32
|
||||
assert n1 != n2
|
||||
|
||||
|
||||
def test_dynamic_discovery_parsing(oidc_client: OIDCClient):
|
||||
"""Dynamic discovery configuration is fetched and parsed correctly from the issuer."""
|
||||
doc = oidc_client.get_discovery_document()
|
||||
assert doc["issuer"] == LIVE_ISSUER
|
||||
assert oidc_client.authorization_endpoint == f"{LIVE_ISSUER}/authorize"
|
||||
assert oidc_client.token_endpoint == f"{LIVE_ISSUER}/token"
|
||||
assert oidc_client.jwks_uri == f"{LIVE_ISSUER}/jwks"
|
||||
|
||||
# Cached discovery returns identical object without additional fetch
|
||||
doc_cached = oidc_client.get_discovery_document()
|
||||
assert doc_cached is doc
|
||||
|
||||
|
||||
def test_dynamic_discovery_failure():
|
||||
"""Unreachable or invalid discovery URL raises DiscoveryError with HTTP 502."""
|
||||
from app.auth.oidc import DiscoveryError
|
||||
|
||||
broken_client = OIDCClient(
|
||||
issuer="http://localhost:59999/nonexistent",
|
||||
client_id=CLIENT_ID,
|
||||
redirect_uri=REDIRECT_URI,
|
||||
timeout=1.0,
|
||||
)
|
||||
with pytest.raises(DiscoveryError) as exc_info:
|
||||
broken_client.get_discovery_document()
|
||||
assert exc_info.value.status_code == 502
|
||||
|
||||
|
||||
def test_authorization_request_contains_pkce_state_and_nonce(oidc_client: OIDCClient):
|
||||
"""Authorization request contains required PKCE challenge, state, and nonce parameters."""
|
||||
auth_req = oidc_client.create_authorization_url()
|
||||
|
||||
parsed = urllib.parse.urlparse(auth_req.url)
|
||||
assert parsed.scheme == "http"
|
||||
assert parsed.netloc == "localhost:8088"
|
||||
assert parsed.path == "/default/authorize"
|
||||
|
||||
qs = urllib.parse.parse_qs(parsed.query)
|
||||
assert qs["response_type"] == ["code"]
|
||||
assert qs["client_id"] == [CLIENT_ID]
|
||||
assert qs["redirect_uri"] == [REDIRECT_URI]
|
||||
assert qs["state"] == [auth_req.state]
|
||||
assert qs["nonce"] == [auth_req.nonce]
|
||||
assert qs["code_challenge_method"] == ["S256"]
|
||||
|
||||
# Verify code_challenge matches SHA256 of code_verifier
|
||||
expected_challenge = compute_code_challenge(auth_req.code_verifier)
|
||||
assert qs["code_challenge"] == [expected_challenge]
|
||||
|
||||
|
||||
def test_rejection_of_invalid_state_400(oidc_client: OIDCClient):
|
||||
"""Rejection of missing or unregistered state with HTTP 400."""
|
||||
with pytest.raises(InvalidStateError) as exc_info:
|
||||
oidc_client.validate_state("unregistered_state_token")
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
with pytest.raises(InvalidStateError) as exc_info:
|
||||
oidc_client.validate_state("")
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
with pytest.raises(InvalidStateError) as exc_info:
|
||||
oidc_client.validate_state(None) # type: ignore[arg-type]
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
# In exchange_code, untracked state must also be rejected with HTTP 400
|
||||
with pytest.raises(InvalidStateError) as exc_info:
|
||||
oidc_client.exchange_code(code="dummy_code", state="unregistered_state")
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
|
||||
def test_live_oidc_successful_code_exchange_and_id_token_validation(
|
||||
oidc_client: OIDCClient,
|
||||
):
|
||||
"""End-to-end integration test: code exchange, ID token validation, and Identity extraction."""
|
||||
# 1. Create authorization request with PKCE and transaction secrets
|
||||
auth_req = oidc_client.create_authorization_url()
|
||||
|
||||
# 2. Simulate authorization sign-in against mock OIDC provider
|
||||
with httpx.Client() as http:
|
||||
resp = http.post(
|
||||
auth_req.url,
|
||||
data={
|
||||
"username": "alice",
|
||||
"claims": json.dumps(
|
||||
{
|
||||
"email": "alice@example.com",
|
||||
"name": "Alice In Chains",
|
||||
"groups": ["family", "vip"],
|
||||
}
|
||||
),
|
||||
},
|
||||
follow_redirects=False,
|
||||
)
|
||||
assert resp.status_code == 302, (
|
||||
f"Expected 302 redirect from mock IdP, got {resp.status_code}"
|
||||
)
|
||||
redirect_url = resp.headers["location"]
|
||||
|
||||
qs = urllib.parse.parse_qs(urllib.parse.urlparse(redirect_url).query)
|
||||
assert "code" in qs
|
||||
assert qs["state"] == [auth_req.state]
|
||||
code = qs["code"][0]
|
||||
|
||||
# 3. Exchange authorization code with token endpoint
|
||||
token_resp = oidc_client.exchange_code(code=code, state=auth_req.state)
|
||||
|
||||
# 4. Verify cryptographic validation and claim assertions
|
||||
assert token_resp.id_token
|
||||
assert token_resp.token_type == "Bearer"
|
||||
assert token_resp.claims["iss"] == LIVE_ISSUER
|
||||
assert token_resp.claims["aud"] == CLIENT_ID
|
||||
assert token_resp.claims["nonce"] == auth_req.nonce
|
||||
assert token_resp.claims["sub"] in ["alice", "admin-001"]
|
||||
assert token_resp.claims["email"] == "alice@example.com"
|
||||
assert token_resp.claims["name"] == "Alice In Chains"
|
||||
assert token_resp.claims["groups"] == ["family", "vip"]
|
||||
|
||||
# 5. Verify mapping to Identity domain model
|
||||
identity = oidc_client.extract_identity(token_resp.claims)
|
||||
assert isinstance(identity, Identity)
|
||||
assert identity.subject in ["alice", "admin-001"]
|
||||
assert identity.email == "alice@example.com"
|
||||
assert identity.name == "Alice In Chains"
|
||||
assert identity.groups == ["family", "vip"]
|
||||
assert identity.has_group("vip") is True
|
||||
|
||||
|
||||
def test_rejection_of_mismatched_nonce_401(oidc_client: OIDCClient):
|
||||
"""Rejection of mismatched nonce claim in returned ID token with HTTP 401."""
|
||||
auth_req = oidc_client.create_authorization_url()
|
||||
|
||||
with httpx.Client() as http:
|
||||
resp = http.post(
|
||||
auth_req.url,
|
||||
data={"username": "bob"},
|
||||
follow_redirects=False,
|
||||
)
|
||||
redirect_url = resp.headers["location"]
|
||||
|
||||
code = urllib.parse.parse_qs(urllib.parse.urlparse(redirect_url).query)["code"][0]
|
||||
token_resp = oidc_client.exchange_code(code=code, state=auth_req.state)
|
||||
|
||||
# Verifying valid token against wrong nonce MUST raise MismatchedNonceError (HTTP 401)
|
||||
with pytest.raises(MismatchedNonceError) as exc_info:
|
||||
oidc_client.verify_id_token(
|
||||
token_resp.id_token, nonce="completely_different_nonce"
|
||||
)
|
||||
assert exc_info.value.status_code == 401
|
||||
assert "does not match expected nonce" in str(exc_info.value.detail)
|
||||
|
||||
# Verifying with the correct nonce succeeds
|
||||
verified = oidc_client.verify_id_token(token_resp.id_token, nonce=auth_req.nonce)
|
||||
assert verified["sub"] in ["bob", "admin-001"]
|
||||
|
||||
|
||||
def test_rejection_of_tampered_id_token_signature_401(oidc_client: OIDCClient):
|
||||
"""Rejection of tampered ID token signature with HTTP 401."""
|
||||
auth_req = oidc_client.create_authorization_url()
|
||||
|
||||
with httpx.Client() as http:
|
||||
resp = http.post(
|
||||
auth_req.url,
|
||||
data={"username": "charlie"},
|
||||
follow_redirects=False,
|
||||
)
|
||||
redirect_url = resp.headers["location"]
|
||||
|
||||
code = urllib.parse.parse_qs(urllib.parse.urlparse(redirect_url).query)["code"][0]
|
||||
token_resp = oidc_client.exchange_code(code=code, state=auth_req.state)
|
||||
original_id_token = token_resp.id_token
|
||||
|
||||
# Case 1: Tamper the cryptographic signature portion
|
||||
tampered_sig_token = original_id_token[:-12] + "TAMPERED_SIG"
|
||||
with pytest.raises(InvalidTokenError) as exc_info:
|
||||
oidc_client.verify_id_token(tampered_sig_token, nonce=auth_req.nonce)
|
||||
assert exc_info.value.status_code == 401
|
||||
assert "signature is invalid or tampered" in str(exc_info.value.detail)
|
||||
|
||||
# Case 2: Tamper the payload while preserving original signature
|
||||
parts = original_id_token.split(".")
|
||||
assert len(parts) == 3
|
||||
# Decode and tamper payload
|
||||
payload_raw = parts[1] + "=="
|
||||
payload = json.loads(base64.urlsafe_b64decode(payload_raw))
|
||||
payload["sub"] = "mallory_attacker"
|
||||
tampered_payload_b64 = (
|
||||
base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
|
||||
)
|
||||
tampered_payload_token = f"{parts[0]}.{tampered_payload_b64}.{parts[2]}"
|
||||
|
||||
with pytest.raises(InvalidTokenError) as exc_info:
|
||||
oidc_client.verify_id_token(tampered_payload_token, nonce=auth_req.nonce)
|
||||
assert exc_info.value.status_code == 401
|
||||
|
||||
|
||||
def test_rejection_of_wrong_issuer_and_audience_401(oidc_client: OIDCClient):
|
||||
"""Rejection of ID token when issuer or audience does not match client configuration."""
|
||||
auth_req = oidc_client.create_authorization_url()
|
||||
|
||||
with httpx.Client() as http:
|
||||
resp = http.post(
|
||||
auth_req.url,
|
||||
data={"username": "david"},
|
||||
follow_redirects=False,
|
||||
)
|
||||
redirect_url = resp.headers["location"]
|
||||
|
||||
code = urllib.parse.parse_qs(urllib.parse.urlparse(redirect_url).query)["code"][0]
|
||||
token_resp = oidc_client.exchange_code(code=code, state=auth_req.state)
|
||||
|
||||
# Client configured with mismatched audience
|
||||
wrong_aud_client = OIDCClient(
|
||||
issuer=LIVE_ISSUER,
|
||||
client_id="other-audience-client",
|
||||
redirect_uri=REDIRECT_URI,
|
||||
)
|
||||
with pytest.raises(InvalidTokenError) as exc_info:
|
||||
wrong_aud_client.verify_id_token(token_resp.id_token, nonce=auth_req.nonce)
|
||||
assert exc_info.value.status_code == 401
|
||||
assert "claims validation failed" in str(exc_info.value.detail)
|
||||
|
||||
# Client configured with mismatched issuer
|
||||
wrong_iss_client = OIDCClient(
|
||||
issuer="http://localhost:8088/wrong_issuer",
|
||||
client_id=CLIENT_ID,
|
||||
redirect_uri=REDIRECT_URI,
|
||||
discovery_doc=oidc_client.get_discovery_document(),
|
||||
)
|
||||
with pytest.raises(InvalidTokenError) as exc_info:
|
||||
wrong_iss_client.verify_id_token(token_resp.id_token, nonce=auth_req.nonce)
|
||||
assert exc_info.value.status_code == 401
|
||||
|
||||
|
||||
def test_architectural_isolation_no_domain_route_crypto_imports():
|
||||
"""Verify architectural isolation: zero application domain routes import OIDC/crypto directly."""
|
||||
import pathlib
|
||||
|
||||
routes_dir = pathlib.Path(__file__).parent.parent / "app" / "routes"
|
||||
disallowed_terms = ["jwt", "cryptography", "PyJWKClient", "OIDCClient"]
|
||||
|
||||
for route_file in routes_dir.glob("*.py"):
|
||||
content = route_file.read_text(encoding="utf-8")
|
||||
for term in disallowed_terms:
|
||||
assert f"import {term}" not in content, (
|
||||
f"{route_file.name} violates isolation by importing {term}"
|
||||
)
|
||||
assert f"from {term}" not in content, (
|
||||
f"{route_file.name} violates isolation by importing from {term}"
|
||||
)
|
||||
@@ -0,0 +1,103 @@
|
||||
import pytest
|
||||
|
||||
from app.services.rsvp import normalize_phone
|
||||
|
||||
|
||||
def test_normalize_phone_valid_cases():
|
||||
cases = [
|
||||
("+57 300 123 4567", "3001234567"),
|
||||
("300-123-4567", "3001234567"),
|
||||
("3001234567", "3001234567"),
|
||||
("(300) 123 4567", "3001234567"),
|
||||
("57300123 4567", "3001234567"),
|
||||
("+573159998877", "3159998877"),
|
||||
("320 000 0000", "3200000000"),
|
||||
]
|
||||
for raw, expected in cases:
|
||||
assert normalize_phone(raw) == expected
|
||||
|
||||
|
||||
def test_normalize_phone_invalid_cases():
|
||||
invalid_cases = [
|
||||
"123456", # Too short
|
||||
"1234567890", # Doesn't start with 3
|
||||
"+1 555 123 4567", # US format
|
||||
"30012345678", # Too long
|
||||
"", # Empty
|
||||
"abcdefghij", # Non-digits
|
||||
]
|
||||
for raw in invalid_cases:
|
||||
with pytest.raises(ValueError, match="Formato de teléfono inválido"):
|
||||
normalize_phone(raw)
|
||||
|
||||
|
||||
def test_submit_rsvp_success(client):
|
||||
payload = {
|
||||
"name": "Andrés García",
|
||||
"phone": "+57 300 123 4567",
|
||||
"email": "andres@example.com",
|
||||
}
|
||||
response = client.post("/birthday/api/rsvp", json=payload)
|
||||
assert response.status_code == 201
|
||||
data = response.json()
|
||||
assert data["result"] == "SUCCESS"
|
||||
assert data["name"] == "Andrés García"
|
||||
|
||||
|
||||
def test_submit_rsvp_duplicate(client):
|
||||
payload = {
|
||||
"name": "Andrés García",
|
||||
"phone": "300 123 4567",
|
||||
"email": "andres@example.com",
|
||||
}
|
||||
# First submission
|
||||
res1 = client.post("/birthday/api/rsvp", json=payload)
|
||||
assert res1.status_code == 201
|
||||
|
||||
# Second submission with same phone in different format
|
||||
payload2 = {
|
||||
"name": "Andrés Felipe García",
|
||||
"phone": "+57 300-123-4567",
|
||||
"email": "other@example.com",
|
||||
}
|
||||
res2 = client.post("/birthday/api/rsvp", json=payload2)
|
||||
assert res2.status_code == 409
|
||||
data = res2.json()
|
||||
assert data["result"] == "DUPLICATE"
|
||||
|
||||
|
||||
def test_submit_rsvp_validation_error_phone(client):
|
||||
payload = {
|
||||
"name": "Camila",
|
||||
"phone": "999 123 4567", # doesn't start with 3
|
||||
}
|
||||
response = client.post("/birthday/api/rsvp", json=payload)
|
||||
assert response.status_code == 422
|
||||
data = response.json()
|
||||
assert data["result"] == "VALIDATION_ERROR"
|
||||
assert "phone" in data["errors"]
|
||||
|
||||
|
||||
def test_submit_rsvp_validation_error_name(client):
|
||||
payload = {
|
||||
"name": " ",
|
||||
"phone": "300 123 4567",
|
||||
}
|
||||
response = client.post("/birthday/api/rsvp", json=payload)
|
||||
assert response.status_code == 422
|
||||
data = response.json()
|
||||
assert data["result"] == "VALIDATION_ERROR"
|
||||
assert "name" in data["errors"]
|
||||
|
||||
|
||||
def test_submit_rsvp_validation_error_email(client):
|
||||
payload = {
|
||||
"name": "Camila",
|
||||
"phone": "300 123 4567",
|
||||
"email": "invalid-email-string",
|
||||
}
|
||||
response = client.post("/birthday/api/rsvp", json=payload)
|
||||
assert response.status_code == 422
|
||||
data = response.json()
|
||||
assert data["result"] == "VALIDATION_ERROR"
|
||||
assert "email" in data["errors"]
|
||||
@@ -0,0 +1,452 @@
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.auth import (
|
||||
InvalidPKCEError,
|
||||
InvalidStateError,
|
||||
InvalidTokenError,
|
||||
MismatchedNonceError,
|
||||
OIDCClient,
|
||||
get_auth_adapter,
|
||||
)
|
||||
from app.config import Settings
|
||||
from tests.conftest import login_client
|
||||
|
||||
LIVE_ISSUER = "http://localhost:8088/default"
|
||||
CLIENT_ID = "bdinvite-client"
|
||||
CLIENT_SECRET = "bdinvite-secret"
|
||||
REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def oidc_client() -> OIDCClient:
|
||||
return OIDCClient(
|
||||
issuer=LIVE_ISSUER,
|
||||
client_id=CLIENT_ID,
|
||||
client_secret=CLIENT_SECRET,
|
||||
redirect_uri=REDIRECT_URI,
|
||||
)
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 1. CSRF State Hardening: Forged / Invalid / Expired State returns HTTP 400
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_forged_or_invalid_csrf_state_returns_400(
|
||||
client: TestClient, oidc_client: OIDCClient
|
||||
):
|
||||
"""Forged, tampered, missing, or expired CSRF state returns HTTP 400 Bad Request."""
|
||||
# 1. Direct unit assertion: oidc_client rejects unknown state with InvalidStateError (400)
|
||||
with pytest.raises(InvalidStateError) as exc_info:
|
||||
oidc_client.validate_state("forged_attacker_state_token")
|
||||
assert exc_info.value.status_code == 400
|
||||
assert "Invalid or expired state" in exc_info.value.detail
|
||||
|
||||
with pytest.raises(InvalidStateError) as exc_info_empty:
|
||||
oidc_client.validate_state("")
|
||||
assert exc_info_empty.value.status_code == 400
|
||||
|
||||
# 2. HTTP callback endpoint with forged state -> 400 Bad Request
|
||||
res_forged = client.get(
|
||||
"/birthday/api/auth/callback",
|
||||
params={"code": "dummy_authorization_code", "state": "forged_csrf_state"},
|
||||
)
|
||||
assert res_forged.status_code == 400
|
||||
assert "state" in res_forged.json().get("detail", "").lower()
|
||||
|
||||
# 3. HTTP callback endpoint with empty state -> 400 Bad Request
|
||||
res_empty = client.get(
|
||||
"/birthday/api/auth/callback",
|
||||
params={"code": "dummy_authorization_code", "state": ""},
|
||||
)
|
||||
assert res_empty.status_code == 400
|
||||
|
||||
|
||||
def test_replayed_csrf_state_returns_400(oidc_client: OIDCClient):
|
||||
"""CSRF state token is single-use: replay after successful validation returns HTTP 400."""
|
||||
auth_req = oidc_client.create_authorization_url()
|
||||
state = auth_req.state
|
||||
|
||||
# First consumption succeeds
|
||||
tx = oidc_client.validate_state(state)
|
||||
assert tx.state == state
|
||||
|
||||
# Replaying same state fails with HTTP 400
|
||||
with pytest.raises(InvalidStateError) as exc_info:
|
||||
oidc_client.validate_state(state)
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 2. Cryptographic Signature Hardening: Forged / Tampered Token returns HTTP 401
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_forged_or_tampered_id_token_signature_returns_401(oidc_client: OIDCClient):
|
||||
"""Forged or tampered ID token signature is rejected cryptographically with HTTP 401 Unauthorized."""
|
||||
# Obtain a genuine token response from the live OIDC test fixture
|
||||
token_resp, _ = oidc_client.authenticate_with_password(
|
||||
username="admin@example.com",
|
||||
password="password123",
|
||||
)
|
||||
valid_id_token = token_resp.id_token
|
||||
parts = valid_id_token.split(".")
|
||||
assert len(parts) == 3
|
||||
|
||||
# Case A: Corrupted cryptographic signature
|
||||
tampered_sig_token = f"{parts[0]}.{parts[1]}.CORRUPTED_SIGNATURE_BYTES"
|
||||
with pytest.raises(InvalidTokenError) as exc_info_sig:
|
||||
oidc_client.verify_id_token(tampered_sig_token)
|
||||
assert exc_info_sig.value.status_code == 401
|
||||
assert "signature is invalid or tampered" in str(exc_info_sig.value.detail).lower()
|
||||
|
||||
# Case B: Tampered payload (privilege escalation attempt) with original signature
|
||||
payload_bytes = base64.urlsafe_b64decode(parts[1] + "==")
|
||||
claims = json.loads(payload_bytes)
|
||||
claims["sub"] = "hacked_admin_identity"
|
||||
claims["groups"] = ["bdinvite_admins", "root"]
|
||||
tampered_payload_b64 = (
|
||||
base64.urlsafe_b64encode(json.dumps(claims).encode()).decode().rstrip("=")
|
||||
)
|
||||
tampered_token = f"{parts[0]}.{tampered_payload_b64}.{parts[2]}"
|
||||
|
||||
with pytest.raises(InvalidTokenError) as exc_info_tampered:
|
||||
oidc_client.verify_id_token(tampered_token)
|
||||
assert exc_info_tampered.value.status_code == 401
|
||||
|
||||
# Case C: Malformed non-JWT string
|
||||
with pytest.raises(InvalidTokenError) as exc_info_malformed:
|
||||
oidc_client.verify_id_token("not-a-valid-jwt-token-at-all")
|
||||
assert exc_info_malformed.value.status_code == 401
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 3. Nonce Verification & Replay Protection: Mismatched Nonce returns HTTP 401
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_mismatched_or_replayed_nonce_returns_401(oidc_client: OIDCClient):
|
||||
"""Mismatched or missing nonce in ID token returns HTTP 401 Unauthorized."""
|
||||
auth_req = oidc_client.create_authorization_url()
|
||||
|
||||
with httpx.Client() as http:
|
||||
resp = http.post(
|
||||
auth_req.url,
|
||||
data={"username": "guest@example.com"},
|
||||
follow_redirects=False,
|
||||
)
|
||||
assert resp.status_code == 302
|
||||
redirect_url = resp.headers["location"]
|
||||
|
||||
code = urllib.parse.parse_qs(urllib.parse.urlparse(redirect_url).query)["code"][0]
|
||||
token_resp = oidc_client.exchange_code(code=code, state=auth_req.state)
|
||||
token = token_resp.id_token
|
||||
|
||||
# Case A: Valid token verified against a mismatched expected nonce -> 401
|
||||
with pytest.raises(MismatchedNonceError) as exc_info:
|
||||
oidc_client.verify_id_token(token, nonce="forged_or_replayed_nonce_999")
|
||||
assert exc_info.value.status_code == 401
|
||||
assert "does not match expected nonce" in str(exc_info.value.detail).lower()
|
||||
|
||||
# Case B: Correct nonce succeeds
|
||||
verified = oidc_client.verify_id_token(token, nonce=auth_req.nonce)
|
||||
assert verified["nonce"] == auth_req.nonce
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 4. PKCE Verification: Missing or Invalid code_verifier returns HTTP 401
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_missing_or_invalid_pkce_code_verifier_returns_401(oidc_client: OIDCClient):
|
||||
"""Missing, out-of-range, or invalid PKCE code_verifier returns HTTP 401 Unauthorized."""
|
||||
# Case A: Missing code_verifier when state is None -> 401
|
||||
with pytest.raises(InvalidPKCEError) as exc_missing:
|
||||
oidc_client.exchange_code(code="test_code", code_verifier=None)
|
||||
assert exc_missing.value.status_code == 401
|
||||
|
||||
# Case B: Empty code_verifier -> 401
|
||||
with pytest.raises(InvalidPKCEError) as exc_empty:
|
||||
oidc_client.exchange_code(code="test_code", code_verifier=" ")
|
||||
assert exc_empty.value.status_code == 401
|
||||
|
||||
# Case C: code_verifier too short (< 43 characters per RFC 7636) -> 401
|
||||
with pytest.raises(InvalidPKCEError) as exc_short:
|
||||
oidc_client.exchange_code(code="test_code", code_verifier="short_verifier_123")
|
||||
assert exc_short.value.status_code == 401
|
||||
|
||||
# Case D: code_verifier too long (> 128 characters) -> 401
|
||||
with pytest.raises(InvalidPKCEError) as exc_long:
|
||||
oidc_client.exchange_code(code="test_code", code_verifier="a" * 129)
|
||||
assert exc_long.value.status_code == 401
|
||||
|
||||
# Case E: code_verifier with invalid characters (non-unreserved) -> 401
|
||||
with pytest.raises(InvalidPKCEError) as exc_invalid_chars:
|
||||
oidc_client.exchange_code(
|
||||
code="test_code",
|
||||
code_verifier="valid_length_verifier_with_illegal_characters_$$$$$!@@@#%^&*()",
|
||||
)
|
||||
assert exc_invalid_chars.value.status_code == 401
|
||||
|
||||
# Case F: Integration with mock OIDC server: valid code exchanged with mismatched code_verifier -> 401
|
||||
auth_req = oidc_client.create_authorization_url()
|
||||
with httpx.Client() as http:
|
||||
resp = http.post(
|
||||
auth_req.url,
|
||||
data={"username": "guest@example.com"},
|
||||
follow_redirects=False,
|
||||
)
|
||||
assert resp.status_code == 302
|
||||
code = urllib.parse.parse_qs(
|
||||
urllib.parse.urlparse(resp.headers["location"]).query
|
||||
)["code"][0]
|
||||
|
||||
with pytest.raises(InvalidPKCEError) as exc_mismatch:
|
||||
oidc_client.exchange_code(
|
||||
code=code,
|
||||
code_verifier="mismatched_code_verifier_that_does_not_hash_to_the_challenge_123456",
|
||||
nonce=auth_req.nonce,
|
||||
)
|
||||
assert exc_mismatch.value.status_code == 401
|
||||
assert "pkce verification failed" in str(exc_mismatch.value.detail).lower()
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 5. Token & Session Expiration: Expired ID Token / Cookie returns HTTP 401
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_expired_id_token_returns_401(
|
||||
oidc_client: OIDCClient, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
"""Expired ID token is rejected with HTTP 401 Unauthorized."""
|
||||
import datetime
|
||||
|
||||
import jwt.api_jwt
|
||||
|
||||
# Obtain a genuine token to get signing key and claims structure
|
||||
token_resp, _ = oidc_client.authenticate_with_password(
|
||||
username="guest@example.com",
|
||||
password="password123",
|
||||
)
|
||||
|
||||
# Valid token verified with current time passes
|
||||
verified = oidc_client.verify_id_token(token_resp.id_token)
|
||||
assert verified["sub"] == "guest-001"
|
||||
|
||||
# Fast forward time into the future past token exp claim
|
||||
class FutureDateTime(datetime.datetime):
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return datetime.datetime(2099, 1, 1, tzinfo=tz)
|
||||
|
||||
monkeypatch.setattr(jwt.api_jwt, "datetime", FutureDateTime)
|
||||
with pytest.raises(InvalidTokenError) as exc_info:
|
||||
oidc_client.verify_id_token(token_resp.id_token)
|
||||
assert exc_info.value.status_code == 401
|
||||
assert "expired" in str(exc_info.value.detail).lower()
|
||||
|
||||
|
||||
def test_expired_session_cookie_returns_401(client: TestClient):
|
||||
"""Expired session cookie returns HTTP 401 Unauthorized across all protected endpoints."""
|
||||
login_client(client, email="admin@example.com", groups=["bdinvite_admins"])
|
||||
adapter = get_auth_adapter()
|
||||
|
||||
# Manually expire the session in the session store
|
||||
cookie_val = client.cookies.get(adapter.session_cookie_name)
|
||||
assert cookie_val is not None
|
||||
session_id = adapter.parse_session_cookie(cookie_val)
|
||||
assert session_id is not None
|
||||
|
||||
session = adapter.session_store.get_session(session_id)
|
||||
assert session is not None
|
||||
session.created_at = time.time() - 99999 # Far in the past
|
||||
session.expires_at = time.time() - 100.0 # Expired
|
||||
|
||||
# Request with expired session returns HTTP 401
|
||||
res_me = client.get("/birthday/api/auth/me")
|
||||
assert res_me.status_code == 401
|
||||
assert res_me.json() == {"detail": "Not authenticated"}
|
||||
|
||||
res_admin = client.get("/birthday/api/admin/rsvps")
|
||||
assert res_admin.status_code == 401
|
||||
assert res_admin.json() == {"detail": "Not authenticated"}
|
||||
|
||||
res_config = client.get("/birthday/api/admin/config")
|
||||
assert res_config.status_code == 401
|
||||
assert res_config.json() == {"detail": "Not authenticated"}
|
||||
|
||||
|
||||
def test_tampered_session_cookie_signature_returns_401(client: TestClient):
|
||||
"""Session cookie with tampered cryptographic signature returns HTTP 401 Unauthorized."""
|
||||
login_client(client, email="admin@example.com", groups=["bdinvite_admins"])
|
||||
adapter = get_auth_adapter()
|
||||
valid_cookie = client.cookies.get(adapter.session_cookie_name)
|
||||
assert valid_cookie is not None
|
||||
|
||||
# Tamper cookie signature
|
||||
tampered_cookie = valid_cookie[:-6] + "BADSIG"
|
||||
client.cookies.set(adapter.session_cookie_name, tampered_cookie)
|
||||
|
||||
res = client.get("/birthday/api/auth/me")
|
||||
assert res.status_code == 401
|
||||
|
||||
res_admin = client.get("/birthday/api/admin/rsvps")
|
||||
assert res_admin.status_code == 401
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 6. Authorization Barrier: Authenticated Non-Admin returns HTTP 403 Forbidden
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_authenticated_non_admin_accessing_admin_apis_returns_403(
|
||||
guest_client: TestClient,
|
||||
):
|
||||
"""Authenticated non-admin user (guest@example.com with groups: ['guests']) receives HTTP 403."""
|
||||
admin_endpoints = [
|
||||
("GET", "/birthday/api/admin/rsvps"),
|
||||
("DELETE", "/birthday/api/admin/rsvps/1"),
|
||||
("PATCH", "/birthday/api/admin/rsvps/1"),
|
||||
("GET", "/birthday/api/admin/export"),
|
||||
("GET", "/birthday/api/admin/config"),
|
||||
("PUT", "/birthday/api/admin/config"),
|
||||
("PATCH", "/birthday/api/admin/config"),
|
||||
("POST", "/birthday/api/admin/map-preview/generate"),
|
||||
]
|
||||
for method, path in admin_endpoints:
|
||||
res = guest_client.request(method, path)
|
||||
assert res.status_code == 403, (
|
||||
f"{method} {path} must return 403 Forbidden for non-admin"
|
||||
)
|
||||
assert "Forbidden" in res.json().get("detail", "")
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 7. Legacy Remote-User Header Barrier: Returns HTTP 401 Unauthorized
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_legacy_remote_user_header_without_session_returns_401(client: TestClient):
|
||||
"""Legacy Remote-User header without an active authenticated session returns HTTP 401."""
|
||||
headers_to_test = [
|
||||
{"Remote-User": "admin@example.com"},
|
||||
{"Remote-User": "admin", "X-Remote-User": "admin"},
|
||||
{"remote-user": "admin@example.com"},
|
||||
{"REMOTE_USER": "admin@example.com"},
|
||||
]
|
||||
|
||||
for headers in headers_to_test:
|
||||
res_rsvps = client.get("/birthday/api/admin/rsvps", headers=headers)
|
||||
assert res_rsvps.status_code == 401
|
||||
assert res_rsvps.json() == {"detail": "Not authenticated"}
|
||||
|
||||
res_config = client.get("/birthday/api/admin/config", headers=headers)
|
||||
assert res_config.status_code == 401
|
||||
|
||||
res_me = client.get("/birthday/api/auth/me", headers=headers)
|
||||
assert res_me.status_code == 401
|
||||
|
||||
|
||||
def test_legacy_remote_user_header_cannot_escalate_non_admin_session(
|
||||
guest_client: TestClient,
|
||||
):
|
||||
"""An attacker passing Remote-User: admin with an active non-admin session cookie receives HTTP 403."""
|
||||
res = guest_client.get(
|
||||
"/birthday/api/admin/rsvps",
|
||||
headers={
|
||||
"Remote-User": "admin@example.com",
|
||||
"X-Remote-User": "admin",
|
||||
"X-User-Groups": "bdinvite_admins",
|
||||
},
|
||||
)
|
||||
assert res.status_code == 403
|
||||
assert "Forbidden" in res.json().get("detail", "")
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 8. Deployment Independence: Direct Standalone vs Homelab Production Mode
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_deployment_independence_multi_mode_configuration():
|
||||
"""Verify application configuration correctly handles Direct Standalone and Homelab Production modes."""
|
||||
# 1. Direct Standalone Mode (local development / testing)
|
||||
dev_settings = Settings(
|
||||
OIDC_ISSUER="http://localhost:8088/default",
|
||||
OIDC_CLIENT_ID="bdinvite-client",
|
||||
OIDC_CLIENT_SECRET="bdinvite-secret",
|
||||
OIDC_REDIRECT_URI="http://localhost:8000/birthday/api/auth/callback",
|
||||
SESSION_COOKIE_SECURE=False,
|
||||
SESSION_COOKIE_NAME="bdinvite_session",
|
||||
)
|
||||
assert dev_settings.is_standalone is True
|
||||
assert dev_settings.is_production is False
|
||||
assert dev_settings.SESSION_COOKIE_SECURE is False
|
||||
|
||||
# 2. Homelab Production Mode (behind Traefik TLS proxy with Authelia)
|
||||
prod_settings = Settings(
|
||||
SERVICE_DOMAIN="demos.roadtotech.me",
|
||||
OIDC_ISSUER="https://auth.roadtotech.me",
|
||||
OIDC_CLIENT_ID="bdinvite-client",
|
||||
OIDC_CLIENT_SECRET="production-secure-secret-key",
|
||||
OIDC_REDIRECT_URI="https://demos.roadtotech.me/birthday/api/auth/callback",
|
||||
SESSION_COOKIE_SECURE=True,
|
||||
SESSION_COOKIE_NAME="bdinvite_session",
|
||||
)
|
||||
assert prod_settings.is_standalone is False
|
||||
assert prod_settings.is_production is True
|
||||
assert prod_settings.SESSION_COOKIE_SECURE is True
|
||||
assert prod_settings.OIDC_ISSUER == "https://auth.roadtotech.me"
|
||||
assert (
|
||||
prod_settings.OIDC_REDIRECT_URI
|
||||
== "https://demos.roadtotech.me/birthday/api/auth/callback"
|
||||
)
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 9. Static Architectural Assertion: Zero Runtime Occurrences of Remote-User
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_static_architectural_assertion_no_runtime_remote_user():
|
||||
"""Verify that neither backend/app/ nor frontend/src/ contains runtime references to Remote-User."""
|
||||
root_dir = Path(__file__).resolve().parent.parent.parent
|
||||
backend_app_dir = root_dir / "backend" / "app"
|
||||
frontend_src_dir = root_dir / "frontend" / "src"
|
||||
|
||||
assert backend_app_dir.is_dir()
|
||||
assert frontend_src_dir.is_dir()
|
||||
|
||||
# Disallowed patterns in runtime source files
|
||||
disallowed = ["remote-user", "remote_user"]
|
||||
|
||||
violations: list[str] = []
|
||||
|
||||
# Check backend runtime source files
|
||||
for py_file in backend_app_dir.rglob("*.py"):
|
||||
content = py_file.read_text(encoding="utf-8").lower()
|
||||
for term in disallowed:
|
||||
if term in content:
|
||||
violations.append(f"{py_file}: contains '{term}'")
|
||||
|
||||
# Check frontend runtime source files
|
||||
for src_file in frontend_src_dir.rglob("*"):
|
||||
if src_file.suffix in [".ts", ".tsx", ".js", ".jsx"]:
|
||||
content = src_file.read_text(encoding="utf-8").lower()
|
||||
for term in disallowed:
|
||||
if term in content:
|
||||
violations.append(f"{src_file}: contains '{term}'")
|
||||
|
||||
assert not violations, (
|
||||
"Architectural boundary violated by runtime Remote-User occurrences:\n"
|
||||
+ "\n".join(violations)
|
||||
)
|
||||
@@ -0,0 +1,429 @@
|
||||
import pytest
|
||||
from fastapi import Request
|
||||
from fastapi.responses import Response as StarletteResponse
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.auth import (
|
||||
Identity,
|
||||
InMemorySessionStore,
|
||||
OIDCAuthAdapter,
|
||||
OIDCClient,
|
||||
sign_session_cookie,
|
||||
unsign_session_cookie,
|
||||
)
|
||||
from app.routes.auth import get_auth_adapter
|
||||
|
||||
LIVE_ISSUER = "http://localhost:8088/default"
|
||||
CLIENT_ID = "bdinvite-client"
|
||||
CLIENT_SECRET = "bdinvite-secret"
|
||||
REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
|
||||
|
||||
|
||||
def create_dummy_request(
|
||||
headers: dict[str, str] | None = None,
|
||||
cookies: dict[str, str] | None = None,
|
||||
) -> Request:
|
||||
"""Helper to construct dummy Request instances for unit testing."""
|
||||
raw_headers: list[tuple[bytes, bytes]] = [
|
||||
(k.lower().encode("latin-1"), v.encode("latin-1"))
|
||||
for k, v in (headers or {}).items()
|
||||
]
|
||||
if cookies:
|
||||
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
|
||||
raw_headers.append((b"cookie", cookie_header.encode("latin-1")))
|
||||
|
||||
scope = {
|
||||
"type": "http",
|
||||
"method": "GET",
|
||||
"path": "/test",
|
||||
"headers": raw_headers,
|
||||
}
|
||||
return Request(scope)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def oidc_client() -> OIDCClient:
|
||||
return OIDCClient(
|
||||
issuer=LIVE_ISSUER,
|
||||
client_id=CLIENT_ID,
|
||||
client_secret=CLIENT_SECRET,
|
||||
redirect_uri=REDIRECT_URI,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_adapter(oidc_client: OIDCClient) -> OIDCAuthAdapter:
|
||||
return OIDCAuthAdapter(
|
||||
oidc_client=oidc_client,
|
||||
session_cookie_name="bdinvite_session",
|
||||
session_store=InMemorySessionStore(),
|
||||
cookie_secure=False,
|
||||
cookie_samesite="lax",
|
||||
session_max_age=3600,
|
||||
secret_key="test-session-secret",
|
||||
)
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# Unit Tests: Session Store & Cookie Security
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_session_store_lifecycle():
|
||||
"""Verify session creation, retrieval, and explicit deletion."""
|
||||
store = InMemorySessionStore()
|
||||
identity = Identity(subject="user-1", email="user1@example.com")
|
||||
|
||||
session = store.create_session(identity=identity, max_age_seconds=60)
|
||||
assert session.session_id is not None
|
||||
assert len(session.session_id) >= 32
|
||||
assert session.identity == identity
|
||||
assert session.is_authenticated is True
|
||||
assert session.is_expired() is False
|
||||
|
||||
retrieved = store.get_session(session.session_id)
|
||||
assert retrieved is not None
|
||||
assert retrieved.session_id == session.session_id
|
||||
assert retrieved.identity == identity
|
||||
|
||||
# Explicit deletion
|
||||
assert store.delete_session(session.session_id) is True
|
||||
assert store.get_session(session.session_id) is None
|
||||
assert store.delete_session(session.session_id) is False
|
||||
|
||||
|
||||
def test_session_store_expiration():
|
||||
"""Verify that expired sessions are rejected and pruned."""
|
||||
store = InMemorySessionStore()
|
||||
identity = Identity(subject="user-exp", email="exp@example.com")
|
||||
|
||||
# Create session that expires immediately (max_age_seconds = -1)
|
||||
session = store.create_session(identity=identity, max_age_seconds=-1)
|
||||
assert session.is_expired() is True
|
||||
|
||||
# Retrieval should return None and prune
|
||||
assert store.get_session(session.session_id) is None
|
||||
|
||||
|
||||
def test_session_store_fixation_protection():
|
||||
"""Verify Session Fixation Barrier in SessionStore: pre-auth session is destroyed upon login."""
|
||||
store = InMemorySessionStore()
|
||||
|
||||
# Pre-authentication session (anonymous)
|
||||
pre_auth = store.create_session(identity=None, max_age_seconds=300)
|
||||
pre_auth_id = pre_auth.session_id
|
||||
assert pre_auth.is_authenticated is False
|
||||
assert store.get_session(pre_auth_id) is not None
|
||||
|
||||
# Authenticate: create post-auth session providing pre_auth_session_id
|
||||
auth_identity = Identity(subject="user-auth", email="auth@example.com")
|
||||
post_auth = store.create_session(
|
||||
identity=auth_identity,
|
||||
max_age_seconds=300,
|
||||
pre_auth_session_id=pre_auth_id,
|
||||
)
|
||||
post_auth_id = post_auth.session_id
|
||||
|
||||
# 1. Fresh identifier generated
|
||||
assert post_auth_id != pre_auth_id
|
||||
# 2. Pre-auth session ID is eradicated and can NEVER be used
|
||||
assert store.get_session(pre_auth_id) is None
|
||||
# 3. Post-auth session resolves to authenticated identity
|
||||
retrieved_post = store.get_session(post_auth_id)
|
||||
assert retrieved_post is not None
|
||||
assert retrieved_post.identity == auth_identity
|
||||
|
||||
|
||||
def test_hmac_cookie_signing_and_tamper_detection():
|
||||
"""Verify HMAC-SHA256 signature verification detects tampering."""
|
||||
secret = "my-secret-key"
|
||||
session_id = "random_session_token_12345"
|
||||
|
||||
signed = sign_session_cookie(session_id, secret)
|
||||
assert "." in signed
|
||||
assert signed.startswith(session_id)
|
||||
|
||||
# Valid unsign
|
||||
unsigned = unsign_session_cookie(signed, secret)
|
||||
assert unsigned == session_id
|
||||
|
||||
# Tampered session ID payload
|
||||
tampered_payload = "forged_id" + signed[len(session_id) :]
|
||||
assert unsign_session_cookie(tampered_payload, secret) is None
|
||||
|
||||
# Tampered signature
|
||||
tampered_sig = signed[:-4] + "dead"
|
||||
assert unsign_session_cookie(tampered_sig, secret) is None
|
||||
|
||||
# Wrong secret key
|
||||
assert unsign_session_cookie(signed, "wrong-secret-key") is None
|
||||
|
||||
# Malformed cookies
|
||||
assert unsign_session_cookie("no-dot-in-string", secret) is None
|
||||
assert unsign_session_cookie("", secret) is None
|
||||
assert unsign_session_cookie(None, secret) is None
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# Unit Tests: Adapter Contract & Security Invariants
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_adapter_session_cookie_security_invariants(auth_adapter: OIDCAuthAdapter):
|
||||
"""Verify session cookie enforces HttpOnly=True, SameSite, and configurable Secure flag."""
|
||||
response = StarletteResponse()
|
||||
auth_adapter.set_session_cookie(response, "test-session-id")
|
||||
|
||||
set_cookie = response.headers.get("set-cookie", "")
|
||||
assert "bdinvite_session=" in set_cookie
|
||||
# Security Invariant: HttpOnly MUST be True
|
||||
assert "httponly" in set_cookie.lower()
|
||||
# SameSite must be set
|
||||
assert "samesite=lax" in set_cookie.lower()
|
||||
# When cookie_secure is False (local/test), Secure attribute is omitted
|
||||
assert "secure" not in set_cookie.lower()
|
||||
|
||||
# When cookie_secure is True (production), Secure attribute is enforced
|
||||
prod_adapter = OIDCAuthAdapter(
|
||||
oidc_client=auth_adapter.oidc_client,
|
||||
cookie_secure=True,
|
||||
)
|
||||
prod_response = StarletteResponse()
|
||||
prod_adapter.set_session_cookie(prod_response, "prod-session-id")
|
||||
prod_cookie = prod_response.headers.get("set-cookie", "")
|
||||
assert "secure" in prod_cookie.lower()
|
||||
assert "httponly" in prod_cookie.lower()
|
||||
|
||||
|
||||
def test_adapter_current_identity_resolution(auth_adapter: OIDCAuthAdapter):
|
||||
"""Verify current_identity resolution across valid, anonymous, tampered, and expired states."""
|
||||
identity = Identity(subject="alice-1", email="alice@example.com")
|
||||
|
||||
# 1. Anonymous request (no cookie) -> None
|
||||
anon_req = create_dummy_request()
|
||||
assert auth_adapter.current_identity(anon_req) is None
|
||||
|
||||
# 2. Valid authenticated session -> Identity
|
||||
session = auth_adapter.session_store.create_session(identity=identity)
|
||||
signed_cookie = sign_session_cookie(session.session_id, auth_adapter.secret_key)
|
||||
valid_req = create_dummy_request(cookies={"bdinvite_session": signed_cookie})
|
||||
resolved = auth_adapter.current_identity(valid_req)
|
||||
assert resolved == identity
|
||||
|
||||
# 3. Unknown / non-existent session ID -> None
|
||||
fake_signed = sign_session_cookie(
|
||||
"non-existent-session-id", auth_adapter.secret_key
|
||||
)
|
||||
unknown_req = create_dummy_request(cookies={"bdinvite_session": fake_signed})
|
||||
assert auth_adapter.current_identity(unknown_req) is None
|
||||
|
||||
# 4. Tampered cookie signature -> None (safely rejected, no crash)
|
||||
tampered_cookie = signed_cookie[:-4] + "ffff"
|
||||
tampered_req = create_dummy_request(cookies={"bdinvite_session": tampered_cookie})
|
||||
assert auth_adapter.current_identity(tampered_req) is None
|
||||
|
||||
# 5. Malformed cookie -> None
|
||||
malformed_req = create_dummy_request(cookies={"bdinvite_session": "not-valid;;bad"})
|
||||
assert auth_adapter.current_identity(malformed_req) is None
|
||||
|
||||
# 6. Expired session -> None
|
||||
expired_session = auth_adapter.session_store.create_session(
|
||||
identity=identity, max_age_seconds=-10
|
||||
)
|
||||
exp_cookie = sign_session_cookie(
|
||||
expired_session.session_id, auth_adapter.secret_key
|
||||
)
|
||||
exp_req = create_dummy_request(cookies={"bdinvite_session": exp_cookie})
|
||||
assert auth_adapter.current_identity(exp_req) is None
|
||||
|
||||
|
||||
def test_adapter_session_fixation_barrier(auth_adapter: OIDCAuthAdapter):
|
||||
"""Verify that authenticating rotates the session identifier and invalidates the pre-auth session."""
|
||||
# Establish pre-authentication session
|
||||
pre_session = auth_adapter.session_store.create_session(identity=None)
|
||||
pre_id = pre_session.session_id
|
||||
pre_signed = sign_session_cookie(pre_id, auth_adapter.secret_key)
|
||||
|
||||
pre_req = create_dummy_request(cookies={"bdinvite_session": pre_signed})
|
||||
assert auth_adapter.current_identity(pre_req) is None
|
||||
|
||||
# Successful authentication transitions session
|
||||
user_identity = Identity(subject="victim-01", email="victim@example.com")
|
||||
resp = StarletteResponse()
|
||||
post_session = auth_adapter.create_session(
|
||||
identity=user_identity,
|
||||
request=pre_req,
|
||||
response=resp,
|
||||
)
|
||||
post_id = post_session.session_id
|
||||
|
||||
# Invariant: pre_auth_session_id != post_auth_session_id
|
||||
assert pre_id != post_id
|
||||
|
||||
# Invariant: pre_auth_session_id is defunct and not authenticated
|
||||
assert auth_adapter.session_store.get_session(pre_id) is None
|
||||
assert auth_adapter.current_identity(pre_req) is None
|
||||
|
||||
# Invariant: post_auth_session_id is valid and authenticated
|
||||
post_signed = sign_session_cookie(post_id, auth_adapter.secret_key)
|
||||
post_req = create_dummy_request(cookies={"bdinvite_session": post_signed})
|
||||
assert auth_adapter.current_identity(post_req) == user_identity
|
||||
|
||||
|
||||
def test_adapter_logout_revocation(auth_adapter: OIDCAuthAdapter):
|
||||
"""Verify that logout revokes session on server and clears the browser cookie."""
|
||||
identity = Identity(subject="bob-1", email="bob@example.com")
|
||||
session = auth_adapter.session_store.create_session(identity=identity)
|
||||
signed_cookie = sign_session_cookie(session.session_id, auth_adapter.secret_key)
|
||||
|
||||
req = create_dummy_request(cookies={"bdinvite_session": signed_cookie})
|
||||
assert auth_adapter.current_identity(req) == identity
|
||||
|
||||
# Terminate session
|
||||
logout_resp = auth_adapter.logout(req)
|
||||
assert logout_resp.status_code == 302
|
||||
|
||||
# Storage revocation check
|
||||
assert auth_adapter.session_store.get_session(session.session_id) is None
|
||||
# Subsequent resolution must be anonymous
|
||||
assert auth_adapter.current_identity(req) is None
|
||||
|
||||
# Cookie clearance check (Max-Age=0)
|
||||
set_cookie_header = logout_resp.headers.get("set-cookie", "")
|
||||
assert "bdinvite_session" in set_cookie_header
|
||||
assert "max-age=0" in set_cookie_header.lower()
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# Integration Tests: HTTP Endpoints (/birthday/api/auth/*)
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_http_anonymous_request_resolves_to_unauthorized(client: TestClient):
|
||||
"""Anonymous request to /me returns HTTP 401."""
|
||||
resp = client.get("/birthday/api/auth/me")
|
||||
assert resp.status_code == 401
|
||||
assert resp.json()["detail"] == "Not authenticated"
|
||||
|
||||
|
||||
def test_http_login_issues_httponly_samesite_cookie(client: TestClient):
|
||||
"""Direct login against IdP issues an HttpOnly, SameSite session cookie."""
|
||||
resp = client.post(
|
||||
"/birthday/api/auth/login",
|
||||
json={"username": "guest@example.com", "password": "password123"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["subject"] == "guest-001"
|
||||
assert data["email"] == "guest@example.com"
|
||||
|
||||
# Verify cookie attributes
|
||||
set_cookie = resp.headers.get("set-cookie", "")
|
||||
assert "bdinvite_session=" in set_cookie
|
||||
assert "httponly" in set_cookie.lower()
|
||||
assert "samesite=lax" in set_cookie.lower()
|
||||
|
||||
|
||||
def test_http_session_fixation_rotation_on_login(client: TestClient):
|
||||
"""Verify that an existing pre-authentication session cookie is rotated upon login."""
|
||||
# 1. Start with an anonymous / pre-authentication session
|
||||
resp_pre = client.get("/birthday/api/auth/login", follow_redirects=False)
|
||||
assert resp_pre.status_code == 302
|
||||
pre_auth_cookie = resp_pre.cookies.get("bdinvite_session")
|
||||
assert pre_auth_cookie is not None
|
||||
|
||||
# 2. Pre-auth session resolves to unauthorized
|
||||
resp_anon = client.get(
|
||||
"/birthday/api/auth/me", cookies={"bdinvite_session": pre_auth_cookie}
|
||||
)
|
||||
assert resp_anon.status_code == 401
|
||||
|
||||
# 3. Authenticate while presenting pre_auth_cookie
|
||||
resp_login = client.post(
|
||||
"/birthday/api/auth/login",
|
||||
json={"username": "admin@example.com", "password": "password123"},
|
||||
cookies={"bdinvite_session": pre_auth_cookie},
|
||||
)
|
||||
assert resp_login.status_code == 200
|
||||
post_auth_cookie = resp_login.cookies.get("bdinvite_session")
|
||||
assert post_auth_cookie is not None
|
||||
|
||||
# 4. Security Invariant: pre_auth != post_auth
|
||||
assert pre_auth_cookie != post_auth_cookie
|
||||
|
||||
# 5. Pre-auth cookie MUST NOT have been promoted
|
||||
resp_old = client.get(
|
||||
"/birthday/api/auth/me", cookies={"bdinvite_session": pre_auth_cookie}
|
||||
)
|
||||
assert resp_old.status_code == 401
|
||||
|
||||
# 6. Post-auth cookie resolves to authenticated user
|
||||
resp_valid = client.get(
|
||||
"/birthday/api/auth/me", cookies={"bdinvite_session": post_auth_cookie}
|
||||
)
|
||||
assert resp_valid.status_code == 200
|
||||
assert resp_valid.json()["subject"] == "admin-001"
|
||||
assert "bdinvite_admins" in resp_valid.json()["groups"]
|
||||
|
||||
|
||||
def test_http_tampered_cookie_rejected(client: TestClient):
|
||||
"""Requests with tampered or forged cookies are safely rejected with HTTP 401."""
|
||||
# Attempt request with random tampered cookie
|
||||
resp = client.get(
|
||||
"/birthday/api/auth/me",
|
||||
cookies={"bdinvite_session": "forged_session_id.invalid_signature_hash"},
|
||||
)
|
||||
assert resp.status_code == 401
|
||||
assert resp.json()["detail"] == "Not authenticated"
|
||||
|
||||
|
||||
def test_http_expired_cookie_rejected(client: TestClient):
|
||||
"""Requests presenting an expired session cookie are rejected with HTTP 401."""
|
||||
adapter = get_auth_adapter()
|
||||
expired_session = adapter.session_store.create_session(
|
||||
identity=Identity(subject="expired-user", email="exp@test.com"),
|
||||
max_age_seconds=-10,
|
||||
)
|
||||
signed_cookie = sign_session_cookie(expired_session.session_id, adapter.secret_key)
|
||||
|
||||
resp = client.get(
|
||||
"/birthday/api/auth/me",
|
||||
cookies={"bdinvite_session": signed_cookie},
|
||||
)
|
||||
assert resp.status_code == 401
|
||||
|
||||
|
||||
def test_http_logout_invalidates_session_and_clears_cookie(client: TestClient):
|
||||
"""POST /birthday/api/auth/logout invalidates session and clears cookie with Max-Age=0."""
|
||||
# 1. Login to obtain session
|
||||
login_resp = client.post(
|
||||
"/birthday/api/auth/login",
|
||||
json={"username": "guest@example.com", "password": "password123"},
|
||||
)
|
||||
assert login_resp.status_code == 200
|
||||
cookie_val = login_resp.cookies.get("bdinvite_session")
|
||||
assert cookie_val is not None
|
||||
|
||||
# Verify session is authenticated
|
||||
me_resp = client.get(
|
||||
"/birthday/api/auth/me", cookies={"bdinvite_session": cookie_val}
|
||||
)
|
||||
assert me_resp.status_code == 200
|
||||
|
||||
# 2. Logout via POST
|
||||
logout_resp = client.post(
|
||||
"/birthday/api/auth/logout", cookies={"bdinvite_session": cookie_val}
|
||||
)
|
||||
assert logout_resp.status_code == 200
|
||||
assert logout_resp.json()["status"] == "ok"
|
||||
|
||||
# Verify cookie clearance header
|
||||
set_cookie = logout_resp.headers.get("set-cookie", "")
|
||||
assert "bdinvite_session" in set_cookie
|
||||
assert "max-age=0" in set_cookie.lower()
|
||||
|
||||
# 3. Subsequent request with the same cookie is rejected
|
||||
me_after = client.get(
|
||||
"/birthday/api/auth/me", cookies={"bdinvite_session": cookie_val}
|
||||
)
|
||||
assert me_after.status_code == 401
|
||||
Generated
+2175
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,43 @@
|
||||
services:
|
||||
bdinvite:
|
||||
build: .
|
||||
container_name: bdinvite
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
environment:
|
||||
- BASE_PATH=/birthday
|
||||
- SERVICE_DOMAIN=${SERVICE_DOMAIN:-demos.roadtotech.me}
|
||||
- OIDC_ISSUER=${OIDC_ISSUER:-https://auth.roadtotech.me}
|
||||
- OIDC_CLIENT_ID=${OIDC_CLIENT_ID:-bdinvite-client}
|
||||
- OIDC_CLIENT_SECRET=${OIDC_CLIENT_SECRET}
|
||||
- OIDC_REDIRECT_URI=${OIDC_REDIRECT_URI:-https://demos.roadtotech.me/birthday/api/auth/callback}
|
||||
- OIDC_GROUPS_CLAIM=${OIDC_GROUPS_CLAIM:-groups}
|
||||
- SESSION_COOKIE_NAME=${SESSION_COOKIE_NAME:-bdinvite_session}
|
||||
- SESSION_COOKIE_SECURE=${SESSION_COOKIE_SECURE:-true}
|
||||
- SESSION_COOKIE_SAMESITE=${SESSION_COOKIE_SAMESITE:-lax}
|
||||
- SESSION_SECRET_KEY=${SESSION_SECRET_KEY}
|
||||
networks:
|
||||
- proxy-net
|
||||
labels:
|
||||
- "diun.enable=false"
|
||||
- "traefik.enable=true"
|
||||
|
||||
# Workload router (invitation, admin, and APIs)
|
||||
- "traefik.http.routers.bdinvite.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
|
||||
- "traefik.http.routers.bdinvite.entrypoints=websecure"
|
||||
- "traefik.http.routers.bdinvite.tls=true"
|
||||
- "traefik.http.routers.bdinvite.priority=10"
|
||||
- "traefik.http.routers.bdinvite.service=bdinvite-svc"
|
||||
|
||||
# HTTP to HTTPS redirect
|
||||
- "traefik.http.routers.bdinvite-red.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
|
||||
- "traefik.http.routers.bdinvite-red.entrypoints=web"
|
||||
- "traefik.http.routers.bdinvite-red.middlewares=https-redirect@docker"
|
||||
|
||||
# Service target
|
||||
- "traefik.http.services.bdinvite-svc.loadbalancer.server.port=8000"
|
||||
|
||||
networks:
|
||||
proxy-net:
|
||||
external: true
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
+376
@@ -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.
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"$schema": "https://biomejs.dev/schemas/2.5.14/schema.json",
|
||||
"vcs": {
|
||||
"enabled": true,
|
||||
"clientKind": "git",
|
||||
"useIgnoreFile": true,
|
||||
"root": ".."
|
||||
},
|
||||
"files": {
|
||||
"ignoreUnknown": true,
|
||||
"includes": ["src/**", "vite.config.ts"]
|
||||
},
|
||||
"formatter": {
|
||||
"enabled": true,
|
||||
"indentStyle": "space",
|
||||
"indentWidth": 2,
|
||||
"lineWidth": 90
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"rules": {
|
||||
"preset": "recommended",
|
||||
"correctness": {
|
||||
"useExhaustiveDependencies": "warn"
|
||||
}
|
||||
}
|
||||
},
|
||||
"javascript": {
|
||||
"formatter": {
|
||||
"quoteStyle": "double",
|
||||
"semicolons": "always"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/birthday/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||
<meta name="theme-color" content="#0a0a0a" />
|
||||
<title>Birthday Party — Invitación</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+1834
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "bdinvite-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview",
|
||||
"lint": "biome check .",
|
||||
"lint:fix": "biome check --write .",
|
||||
"format": "biome format --write ."
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.26.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.10",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@vitejs/plugin-react": "^4.3.2",
|
||||
"typescript": "^5.6.2",
|
||||
"vite": "^5.4.8"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,27 @@
|
||||
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
|
||||
import { AdminLayout } from "./admin/AdminLayout";
|
||||
import { ConfigEditor } from "./admin/ConfigEditor";
|
||||
import { RsvpTable } from "./admin/RsvpTable";
|
||||
import { Invitation } from "./invitation/Invitation";
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<BrowserRouter basename="/birthday">
|
||||
<Routes>
|
||||
{/* Guest Public Route */}
|
||||
<Route path="/" element={<Invitation />} />
|
||||
|
||||
{/* Authelia-Protected Admin Dashboard */}
|
||||
<Route path="/admin" element={<AdminLayout />}>
|
||||
<Route index element={<RsvpTable />} />
|
||||
<Route path="config" element={<ConfigEditor />} />
|
||||
</Route>
|
||||
|
||||
{/* Catch-all fallback */}
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,307 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Link, NavLink, Outlet } from "react-router-dom";
|
||||
import { type CurrentUser, fetchCurrentUser, logoutUser } from "../api/client";
|
||||
import { Spinner } from "../components/Spinner";
|
||||
|
||||
export function AdminLayout() {
|
||||
const [user, setUser] = useState<CurrentUser | null>(null);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [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;
|
||||
fetchCurrentUser()
|
||||
.then((userData) => {
|
||||
if (isMounted) {
|
||||
setUser(userData);
|
||||
setLoading(false);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (isMounted) {
|
||||
setLoading(false);
|
||||
window.location.href = "/birthday/api/auth/login";
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleLogout = useCallback(async () => {
|
||||
try {
|
||||
await logoutUser();
|
||||
} catch (err) {
|
||||
console.error("Logout failed:", err);
|
||||
}
|
||||
setUser(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",
|
||||
}}
|
||||
>
|
||||
<Spinner size={36} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (loggedOut || !user) {
|
||||
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, #e0be75)",
|
||||
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, #c5a059)",
|
||||
color: "#0a0a0a",
|
||||
fontWeight: 600,
|
||||
borderRadius: "4px",
|
||||
textDecoration: "none",
|
||||
fontSize: "0.9rem",
|
||||
}}
|
||||
>
|
||||
Iniciar Sesión
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
minHeight: "100vh",
|
||||
backgroundColor: "#0f0f10",
|
||||
color: "#f0f0f0",
|
||||
fontFamily: "var(--font-body)",
|
||||
}}
|
||||
>
|
||||
{/* Admin Navigation Bar */}
|
||||
<header
|
||||
style={{
|
||||
borderBottom: "1px solid rgba(255, 255, 255, 0.1)",
|
||||
backgroundColor: "#161618",
|
||||
padding: "1rem 1.8rem",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
flexWrap: "wrap",
|
||||
gap: "1rem",
|
||||
}}
|
||||
>
|
||||
<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>
|
||||
|
||||
<nav style={{ display: "flex", alignItems: "center", gap: "1.4rem" }}>
|
||||
<NavLink
|
||||
to="/admin"
|
||||
end
|
||||
style={({ isActive }) => ({
|
||||
color: isActive ? "var(--color-gold-light)" : "rgba(255, 255, 255, 0.7)",
|
||||
textDecoration: "none",
|
||||
fontSize: "0.88rem",
|
||||
fontWeight: 500,
|
||||
borderBottom: isActive
|
||||
? "2px solid var(--color-gold)"
|
||||
: "2px solid transparent",
|
||||
paddingBottom: "0.25rem",
|
||||
transition: "all 0.2s ease",
|
||||
})}
|
||||
>
|
||||
Respuestas
|
||||
</NavLink>
|
||||
<NavLink
|
||||
to="/admin/config"
|
||||
style={({ isActive }) => ({
|
||||
color: isActive ? "var(--color-gold-light)" : "rgba(255, 255, 255, 0.7)",
|
||||
textDecoration: "none",
|
||||
fontSize: "0.88rem",
|
||||
fontWeight: 500,
|
||||
borderBottom: isActive
|
||||
? "2px solid var(--color-gold)"
|
||||
: "2px solid transparent",
|
||||
paddingBottom: "0.25rem",
|
||||
transition: "all 0.2s ease",
|
||||
})}
|
||||
>
|
||||
Configuración
|
||||
</NavLink>
|
||||
<Link
|
||||
to="/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
style={{
|
||||
color: "rgba(255, 255, 255, 0.5)",
|
||||
textDecoration: "none",
|
||||
fontSize: "0.82rem",
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
gap: "0.3rem",
|
||||
}}
|
||||
>
|
||||
<span>Ver Pública</span>
|
||||
<span>↗</span>
|
||||
</Link>
|
||||
</nav>
|
||||
|
||||
{/* User Info and Logout Button */}
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "1.2rem", flexWrap: "wrap" }}>
|
||||
<div
|
||||
style={{
|
||||
fontSize: "0.85rem",
|
||||
color: "rgba(255, 255, 255, 0.8)",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "0.4rem",
|
||||
}}
|
||||
>
|
||||
<span style={{ color: "var(--color-gold, #c5a059)" }}>👤</span>
|
||||
<span data-testid="user-info">{user.name || user.email}</span>
|
||||
{user.name && user.email && user.name !== user.email && (
|
||||
<span
|
||||
data-testid="user-email"
|
||||
style={{ fontSize: "0.8rem", color: "rgba(255, 255, 255, 0.5)" }}
|
||||
>
|
||||
({user.email})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleLogout}
|
||||
style={{
|
||||
background: "transparent",
|
||||
border: "1px solid rgba(255, 255, 255, 0.2)",
|
||||
color: "#f0f0f0",
|
||||
padding: "0.35rem 0.75rem",
|
||||
borderRadius: "4px",
|
||||
cursor: "pointer",
|
||||
fontSize: "0.82rem",
|
||||
fontWeight: 500,
|
||||
transition: "all 0.2s ease",
|
||||
}}
|
||||
onMouseOver={(e) => {
|
||||
e.currentTarget.style.borderColor = "rgba(255, 255, 255, 0.4)";
|
||||
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.05)";
|
||||
}}
|
||||
onMouseOut={(e) => {
|
||||
e.currentTarget.style.borderColor = "rgba(255, 255, 255, 0.2)";
|
||||
e.currentTarget.style.backgroundColor = "transparent";
|
||||
}}
|
||||
>
|
||||
Logout
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Main Admin Content Container */}
|
||||
<div
|
||||
style={{
|
||||
maxWidth: "1000px",
|
||||
margin: "0 auto",
|
||||
padding: "2rem 1.5rem",
|
||||
}}
|
||||
>
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,505 @@
|
||||
import { type FormEvent, useEffect, useState } from "react";
|
||||
import { fetchAdminConfig, regenerateMapPreview, updateAdminConfig } from "../api/client";
|
||||
import { Button } from "../components/Button";
|
||||
import { Field } from "../components/Field";
|
||||
import { Spinner } from "../components/Spinner";
|
||||
import type { InvitationConfig } from "../types/config";
|
||||
|
||||
export function ConfigEditor() {
|
||||
const [formData, setFormData] = useState<InvitationConfig | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [regeneratingMap, setRegeneratingMap] = useState(false);
|
||||
const [mapNotice, setMapNotice] = useState<{
|
||||
type: "success" | "error";
|
||||
msg: string;
|
||||
} | null>(null);
|
||||
const [feedback, setFeedback] = useState<{
|
||||
type: "success" | "error";
|
||||
msg: string;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
async function load() {
|
||||
try {
|
||||
const data = await fetchAdminConfig();
|
||||
setFormData(data);
|
||||
} catch (err) {
|
||||
setFeedback({
|
||||
type: "error",
|
||||
msg: err instanceof Error ? err.message : "Error al cargar la configuración.",
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
load();
|
||||
}, []);
|
||||
|
||||
function handleChange(field: keyof InvitationConfig, value: string) {
|
||||
if (!formData) return;
|
||||
setFormData({ ...formData, [field]: value });
|
||||
}
|
||||
|
||||
async function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!formData || saving) return;
|
||||
|
||||
setSaving(true);
|
||||
setFeedback(null);
|
||||
|
||||
try {
|
||||
const { id, updated_at, ...cleanPayload } = formData;
|
||||
const updated = await updateAdminConfig(cleanPayload);
|
||||
setFormData(updated);
|
||||
setFeedback({ type: "success", msg: "¡Configuración guardada exitosamente!" });
|
||||
} catch (err) {
|
||||
setFeedback({
|
||||
type: "error",
|
||||
msg: err instanceof Error ? err.message : "Error al guardar.",
|
||||
});
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRegenerateMap() {
|
||||
if (!formData?.map_url || regeneratingMap) return;
|
||||
setRegeneratingMap(true);
|
||||
setMapNotice(null);
|
||||
|
||||
try {
|
||||
const res = await regenerateMapPreview(formData.map_url);
|
||||
setFormData({ ...formData, map_preview_url: res.map_preview_url });
|
||||
setMapNotice({
|
||||
type: "success",
|
||||
msg: `¡Vista previa regenerada con éxito! (Coordenadas: ${res.lat.toFixed(4)}, ${res.lng.toFixed(4)})`,
|
||||
});
|
||||
} catch (err) {
|
||||
setMapNotice({
|
||||
type: "error",
|
||||
msg: err instanceof Error ? err.message : "Error al regenerar el mapa.",
|
||||
});
|
||||
} finally {
|
||||
setRegeneratingMap(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{ padding: "4rem", textAlign: "center" }}>
|
||||
<Spinner size={32} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!formData) {
|
||||
return (
|
||||
<div style={{ color: "var(--color-error)", padding: "2rem" }}>
|
||||
{feedback?.msg || "No se pudo cargar la configuración."}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "2.5rem" }}>
|
||||
<div>
|
||||
<h2
|
||||
style={{
|
||||
fontSize: "1.4rem",
|
||||
fontWeight: 600,
|
||||
color: "#ffffff",
|
||||
marginBottom: "0.4rem",
|
||||
}}
|
||||
>
|
||||
Editar Contenido de la Invitación
|
||||
</h2>
|
||||
<p
|
||||
style={{
|
||||
fontSize: "0.88rem",
|
||||
color: "rgba(255, 255, 255, 0.6)",
|
||||
marginBottom: "1.8rem",
|
||||
}}
|
||||
>
|
||||
Los cambios guardados se reflejan inmediatamente en la invitación pública.
|
||||
</p>
|
||||
|
||||
{feedback && (
|
||||
<div
|
||||
style={{
|
||||
padding: "0.9rem 1.2rem",
|
||||
borderRadius: "4px",
|
||||
marginBottom: "1.8rem",
|
||||
backgroundColor:
|
||||
feedback.type === "success"
|
||||
? "rgba(46, 204, 113, 0.15)"
|
||||
: "var(--color-error-bg)",
|
||||
border: `1px solid ${feedback.type === "success" ? "#2ecc71" : "var(--color-error)"}`,
|
||||
color: feedback.type === "success" ? "#2ecc71" : "#ff8b80",
|
||||
fontSize: "0.88rem",
|
||||
}}
|
||||
>
|
||||
{feedback.msg}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))",
|
||||
gap: "1rem",
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
label="Título Principal"
|
||||
value={formData.title}
|
||||
onChange={(e) => handleChange("title", e.target.value)}
|
||||
required
|
||||
/>
|
||||
<Field
|
||||
label="Nombre del Homenajeado(a)"
|
||||
value={formData.honoree_name}
|
||||
onChange={(e) => handleChange("honoree_name", e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Field
|
||||
label="Texto de Invitación"
|
||||
value={formData.invitation_text}
|
||||
onChange={(e) => handleChange("invitation_text", e.target.value)}
|
||||
required
|
||||
/>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))",
|
||||
gap: "1rem",
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
label="Fecha del Evento (YYYY-MM-DD)"
|
||||
value={formData.event_date}
|
||||
onChange={(e) => handleChange("event_date", e.target.value)}
|
||||
required
|
||||
/>
|
||||
<Field
|
||||
label="Hora del Evento (HH:MM)"
|
||||
value={formData.event_time}
|
||||
onChange={(e) => handleChange("event_time", e.target.value)}
|
||||
required
|
||||
/>
|
||||
<Field
|
||||
label="Zona Horaria IANA"
|
||||
value={formData.event_timezone}
|
||||
onChange={(e) => handleChange("event_timezone", e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))",
|
||||
gap: "1rem",
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
label="Nombre del Lugar"
|
||||
value={formData.address_name}
|
||||
onChange={(e) => handleChange("address_name", e.target.value)}
|
||||
required
|
||||
/>
|
||||
<Field
|
||||
label="Enlace a Google Maps (map_url)"
|
||||
value={formData.map_url}
|
||||
onChange={(e) => handleChange("map_url", e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: "1.4rem" }}>
|
||||
<label
|
||||
htmlFor="address_lines"
|
||||
style={{
|
||||
display: "block",
|
||||
fontSize: "0.72rem",
|
||||
fontWeight: 500,
|
||||
letterSpacing: "0.15em",
|
||||
textTransform: "uppercase",
|
||||
color: "var(--color-text-muted)",
|
||||
marginBottom: "0.45rem",
|
||||
}}
|
||||
>
|
||||
Dirección (una línea por renglón)
|
||||
</label>
|
||||
<textarea
|
||||
id="address_lines"
|
||||
rows={3}
|
||||
value={formData.address_lines}
|
||||
onChange={(e) => handleChange("address_lines", e.target.value)}
|
||||
style={{
|
||||
width: "100%",
|
||||
padding: "0.85rem 1rem",
|
||||
backgroundColor: "rgba(255, 255, 255, 0.05)",
|
||||
border: "1px solid var(--color-gold-border)",
|
||||
borderRadius: "4px",
|
||||
color: "var(--color-text)",
|
||||
fontSize: "0.95rem",
|
||||
outline: "none",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
backgroundColor: "rgba(255, 255, 255, 0.03)",
|
||||
border: "1px solid rgba(212, 168, 67, 0.2)",
|
||||
borderRadius: "6px",
|
||||
padding: "1.2rem",
|
||||
marginBottom: "1.4rem",
|
||||
display: "flex",
|
||||
flexWrap: "wrap",
|
||||
gap: "1.5rem",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
{/* Visual circular thumbnail preview */}
|
||||
<div
|
||||
style={{
|
||||
width: "80px",
|
||||
height: "80px",
|
||||
borderRadius: "50%",
|
||||
overflow: "hidden",
|
||||
border: "1.5px solid var(--color-gold)",
|
||||
backgroundColor: "#151515",
|
||||
flexShrink: 0,
|
||||
boxShadow: "0 2px 10px rgba(0,0,0,0.5)",
|
||||
}}
|
||||
>
|
||||
{formData.map_preview_url ? (
|
||||
<img
|
||||
src={formData.map_preview_url}
|
||||
alt="Vista previa mapa"
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
objectFit: "cover",
|
||||
display: "block",
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
height: "100%",
|
||||
fontSize: "0.7rem",
|
||||
color: "var(--color-text-muted)",
|
||||
}}
|
||||
>
|
||||
Sin mapa
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div style={{ flex: 1, minWidth: "240px" }}>
|
||||
<Field
|
||||
label="URL de Imagen Previa del Mapa (map_preview_url)"
|
||||
value={formData.map_preview_url}
|
||||
onChange={(e) => handleChange("map_preview_url", e.target.value)}
|
||||
required
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
marginTop: "0.8rem",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "1rem",
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={regeneratingMap || !formData.map_url}
|
||||
onClick={handleRegenerateMap}
|
||||
style={{ padding: "0.55rem 1.1rem", fontSize: "0.75rem" }}
|
||||
>
|
||||
{regeneratingMap ? (
|
||||
<>
|
||||
<Spinner size={14} />
|
||||
<span style={{ marginLeft: "0.5rem" }}>Generando...</span>
|
||||
</>
|
||||
) : (
|
||||
"🗺️ Regenerar Mapa"
|
||||
)}
|
||||
</Button>
|
||||
<span
|
||||
style={{
|
||||
fontSize: "0.75rem",
|
||||
color: "var(--color-text-muted)",
|
||||
}}
|
||||
>
|
||||
Genera la imagen en disco sin guardar aún en la BD.
|
||||
</span>
|
||||
</div>
|
||||
{mapNotice && (
|
||||
<div
|
||||
style={{
|
||||
marginTop: "0.6rem",
|
||||
fontSize: "0.8rem",
|
||||
color:
|
||||
mapNotice.type === "success"
|
||||
? "var(--color-gold)"
|
||||
: "var(--color-error)",
|
||||
}}
|
||||
>
|
||||
{mapNotice.msg}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))",
|
||||
gap: "1rem",
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
label="Encabezado del Formulario"
|
||||
value={formData.rsvp_heading}
|
||||
onChange={(e) => handleChange("rsvp_heading", e.target.value)}
|
||||
required
|
||||
/>
|
||||
<Field
|
||||
label="Texto del Botón CTA Inicial"
|
||||
value={formData.rsvp_cta}
|
||||
onChange={(e) => handleChange("rsvp_cta", e.target.value)}
|
||||
required
|
||||
/>
|
||||
<Field
|
||||
label="Texto del Botón de Envío"
|
||||
value={formData.submit_label}
|
||||
onChange={(e) => handleChange("submit_label", e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: "repeat(auto-fit, minmax(250px, 1fr))",
|
||||
gap: "1rem",
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
label="Mensaje de Confirmación Éxito"
|
||||
value={formData.msg_success}
|
||||
onChange={(e) => handleChange("msg_success", e.target.value)}
|
||||
required
|
||||
/>
|
||||
<Field
|
||||
label="Saludo de Éxito ({name})"
|
||||
value={formData.msg_success_greeting}
|
||||
onChange={(e) => handleChange("msg_success_greeting", e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Field
|
||||
label="Mensaje para Teléfono Duplicado"
|
||||
value={formData.msg_duplicate}
|
||||
onChange={(e) => handleChange("msg_duplicate", e.target.value)}
|
||||
required
|
||||
/>
|
||||
|
||||
<div style={{ marginTop: "2rem" }}>
|
||||
<Button type="submit" variant="primary" disabled={saving}>
|
||||
{saving ? "Guardando..." : "Guardar Cambios"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Live Plain-Text Preview Section */}
|
||||
<div
|
||||
style={{
|
||||
borderTop: "1px solid rgba(255, 255, 255, 0.1)",
|
||||
paddingTop: "2rem",
|
||||
}}
|
||||
>
|
||||
<h3
|
||||
style={{
|
||||
fontSize: "1.1rem",
|
||||
fontWeight: 600,
|
||||
color: "var(--color-gold-light)",
|
||||
textTransform: "uppercase",
|
||||
letterSpacing: "0.1em",
|
||||
marginBottom: "1rem",
|
||||
}}
|
||||
>
|
||||
Vista Previa de Composición (Texto)
|
||||
</h3>
|
||||
<div
|
||||
style={{
|
||||
backgroundColor: "#161618",
|
||||
border: "1px solid rgba(255, 255, 255, 0.08)",
|
||||
borderRadius: "6px",
|
||||
padding: "1.8rem",
|
||||
lineHeight: 1.8,
|
||||
fontSize: "0.92rem",
|
||||
maxWidth: "500px",
|
||||
}}
|
||||
>
|
||||
<p style={{ fontSize: "1.5rem", fontWeight: 700, color: "#ffffff" }}>
|
||||
{formData.title}
|
||||
</p>
|
||||
<p
|
||||
style={{
|
||||
letterSpacing: "0.15em",
|
||||
textTransform: "uppercase",
|
||||
color: "rgba(255, 255, 255, 0.6)",
|
||||
}}
|
||||
>
|
||||
{formData.invitation_text}
|
||||
</p>
|
||||
<p
|
||||
style={{
|
||||
fontSize: "1.3rem",
|
||||
color: "var(--color-gold-light)",
|
||||
margin: "0.6rem 0",
|
||||
}}
|
||||
>
|
||||
{formData.honoree_name}
|
||||
</p>
|
||||
<p style={{ color: "#ffffff" }}>
|
||||
📅 {formData.event_date} · ⏰ {formData.event_time} ({formData.event_timezone}
|
||||
)
|
||||
</p>
|
||||
<p style={{ color: "#ffffff", marginTop: "0.4rem" }}>
|
||||
📍 {formData.address_name} — {formData.address_lines.replace(/\n/g, ", ")}
|
||||
</p>
|
||||
<div
|
||||
style={{
|
||||
marginTop: "1rem",
|
||||
paddingTop: "0.8rem",
|
||||
borderTop: "1px dashed rgba(255, 255, 255, 0.15)",
|
||||
}}
|
||||
>
|
||||
<p style={{ color: "var(--color-gold)" }}>CTA: {formData.rsvp_cta}</p>
|
||||
<p style={{ color: "var(--color-text-dim)", fontSize: "0.82rem" }}>
|
||||
Éxito: "{formData.msg_success}"{" "}
|
||||
{formData.msg_success_greeting.replace("{name}", "[Nombre]")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,619 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import {
|
||||
deleteAdminRsvp,
|
||||
fetchAdminRsvps,
|
||||
getExportCsvUrl,
|
||||
updateAdminRsvp,
|
||||
} from "../api/client";
|
||||
import { Button } from "../components/Button";
|
||||
import { Spinner } from "../components/Spinner";
|
||||
import { useConfig } from "../hooks/useConfig";
|
||||
import type { RSVPAdminItem } from "../types/config";
|
||||
|
||||
export function RsvpTable() {
|
||||
const { config } = useConfig();
|
||||
const [rsvps, setRsvps] = useState<RSVPAdminItem[]>([]);
|
||||
const [count, setCount] = useState<number>(0);
|
||||
const [search, setSearch] = useState<string>("");
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [deletingId, setDeletingId] = useState<number | null>(null);
|
||||
const [editingId, setEditingId] = useState<number | null>(null);
|
||||
const [editForm, setEditForm] = useState<{ name: string; phone: string; email: string }>({
|
||||
name: "",
|
||||
phone: "",
|
||||
email: "",
|
||||
});
|
||||
const [savingId, setSavingId] = useState<number | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const loadData = useCallback(async (searchTerm = "") => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await fetchAdminRsvps(searchTerm);
|
||||
setRsvps(data.rsvps);
|
||||
setCount(data.count);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error al cargar las respuestas.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadData(search);
|
||||
}, [search, loadData]);
|
||||
|
||||
function formatDate(isoStr: string) {
|
||||
if (!isoStr) return "—";
|
||||
try {
|
||||
// Ensure ISO string without an explicit offset is treated as UTC
|
||||
const normalizedIso =
|
||||
!isoStr.endsWith("Z") && !isoStr.includes("+") && !isoStr.includes("-", 10)
|
||||
? `${isoStr}Z`
|
||||
: isoStr;
|
||||
const d = new Date(normalizedIso);
|
||||
return d.toLocaleDateString("es-CO", {
|
||||
timeZone: config?.event_timezone || "America/Bogota",
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
} catch {
|
||||
return isoStr;
|
||||
}
|
||||
}
|
||||
|
||||
function formatPhone(phone: string) {
|
||||
if (phone.length === 10) {
|
||||
return `${phone.slice(0, 3)} ${phone.slice(3, 6)} ${phone.slice(6)}`;
|
||||
}
|
||||
return phone;
|
||||
}
|
||||
|
||||
async function handleDelete(id: number, name: string) {
|
||||
const confirmed = window.confirm(
|
||||
`¿Estás seguro de que deseas eliminar la confirmación de "${name}"? Esta acción no se puede deshacer.`,
|
||||
);
|
||||
if (!confirmed) return;
|
||||
|
||||
setDeletingId(id);
|
||||
setError(null);
|
||||
try {
|
||||
await deleteAdminRsvp(id);
|
||||
setRsvps((prev) => prev.filter((r) => r.id !== id));
|
||||
setCount((prev) => Math.max(0, prev - 1));
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof Error ? err.message : "Error al eliminar el asistente.",
|
||||
);
|
||||
} finally {
|
||||
setDeletingId(null);
|
||||
}
|
||||
}
|
||||
|
||||
function startEditing(row: RSVPAdminItem) {
|
||||
setEditingId(row.id);
|
||||
setEditForm({
|
||||
name: row.name,
|
||||
phone: row.phone,
|
||||
email: row.email || "",
|
||||
});
|
||||
setError(null);
|
||||
}
|
||||
|
||||
function cancelEditing() {
|
||||
setEditingId(null);
|
||||
setError(null);
|
||||
}
|
||||
|
||||
async function handleSaveEdit(id: number) {
|
||||
if (!editForm.name.trim()) {
|
||||
setError("El nombre no puede estar vacío.");
|
||||
return;
|
||||
}
|
||||
if (!editForm.phone.trim()) {
|
||||
setError("El teléfono no puede estar vacío.");
|
||||
return;
|
||||
}
|
||||
|
||||
setSavingId(id);
|
||||
setError(null);
|
||||
try {
|
||||
const updated = await updateAdminRsvp(id, {
|
||||
name: editForm.name.trim(),
|
||||
phone: editForm.phone.trim(),
|
||||
email: editForm.email.trim() || null,
|
||||
});
|
||||
setRsvps((prev) => prev.map((r) => (r.id === id ? updated : r)));
|
||||
setEditingId(null);
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof Error ? err.message : "Error al actualizar el asistente.",
|
||||
);
|
||||
} finally {
|
||||
setSavingId(null);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Top action bar: Count, Search, Export */}
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
flexWrap: "wrap",
|
||||
gap: "1.2rem",
|
||||
marginBottom: "1.8rem",
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<h2 style={{ fontSize: "1.4rem", fontWeight: 600, color: "#ffffff" }}>
|
||||
Asistentes Confirmados
|
||||
</h2>
|
||||
<p
|
||||
style={{
|
||||
fontSize: "0.88rem",
|
||||
color: "rgba(255, 255, 255, 0.6)",
|
||||
marginTop: "0.2rem",
|
||||
}}
|
||||
>
|
||||
Total de registros:{" "}
|
||||
<strong style={{ color: "var(--color-gold-light)" }}>{count}</strong>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{ display: "flex", alignItems: "center", gap: "1rem", flexWrap: "wrap" }}
|
||||
>
|
||||
<input
|
||||
type="search"
|
||||
placeholder="Buscar por nombre, tel..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
style={{
|
||||
padding: "0.6rem 1rem",
|
||||
borderRadius: "4px",
|
||||
backgroundColor: "rgba(255, 255, 255, 0.08)",
|
||||
border: "1px solid rgba(255, 255, 255, 0.2)",
|
||||
color: "#ffffff",
|
||||
fontSize: "0.88rem",
|
||||
outline: "none",
|
||||
minWidth: "220px",
|
||||
}}
|
||||
/>
|
||||
|
||||
<a
|
||||
href={getExportCsvUrl()}
|
||||
download="rsvps.csv"
|
||||
style={{ textDecoration: "none" }}
|
||||
>
|
||||
<Button
|
||||
variant="outline"
|
||||
style={{ padding: "0.6rem 1.2rem", fontSize: "0.75rem" }}
|
||||
>
|
||||
Descargar CSV ⤓
|
||||
</Button>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div
|
||||
style={{
|
||||
padding: "1rem",
|
||||
backgroundColor: "var(--color-error-bg)",
|
||||
border: "1px solid var(--color-error)",
|
||||
borderRadius: "4px",
|
||||
color: "#ff8b80",
|
||||
marginBottom: "1.5rem",
|
||||
fontSize: "0.88rem",
|
||||
}}
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Table container */}
|
||||
<div
|
||||
style={{
|
||||
backgroundColor: "#161618",
|
||||
borderRadius: "6px",
|
||||
border: "1px solid rgba(255, 255, 255, 0.08)",
|
||||
overflowX: "auto",
|
||||
}}
|
||||
>
|
||||
<table
|
||||
style={{
|
||||
width: "100%",
|
||||
borderCollapse: "collapse",
|
||||
textAlign: "left",
|
||||
fontSize: "0.88rem",
|
||||
}}
|
||||
>
|
||||
<thead>
|
||||
<tr
|
||||
style={{
|
||||
borderBottom: "1px solid rgba(255, 255, 255, 0.12)",
|
||||
backgroundColor: "rgba(255, 255, 255, 0.03)",
|
||||
color: "rgba(255, 255, 255, 0.6)",
|
||||
fontSize: "0.75rem",
|
||||
letterSpacing: "0.1em",
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
<th style={{ padding: "0.9rem 1.2rem" }}>Nombre</th>
|
||||
<th style={{ padding: "0.9rem 1.2rem" }}>Teléfono</th>
|
||||
<th style={{ padding: "0.9rem 1.2rem" }}>Correo</th>
|
||||
<th style={{ padding: "0.9rem 1.2rem" }}>Fecha de Registro</th>
|
||||
<th style={{ padding: "0.9rem 1.2rem", textAlign: "right" }}>Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td colSpan={5} style={{ padding: "3rem", textAlign: "center" }}>
|
||||
<Spinner size={28} />
|
||||
</td>
|
||||
</tr>
|
||||
) : rsvps.length === 0 ? (
|
||||
<tr>
|
||||
<td
|
||||
colSpan={5}
|
||||
style={{
|
||||
padding: "3rem",
|
||||
textAlign: "center",
|
||||
color: "rgba(255, 255, 255, 0.5)",
|
||||
}}
|
||||
>
|
||||
{search
|
||||
? "No se encontraron coincidencias."
|
||||
: "Aún no hay confirmaciones registradas."}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
rsvps.map((row) => (
|
||||
<tr
|
||||
key={row.id}
|
||||
style={{
|
||||
borderBottom: "1px solid rgba(255, 255, 255, 0.06)",
|
||||
backgroundColor:
|
||||
editingId === row.id
|
||||
? "rgba(212, 168, 67, 0.08)"
|
||||
: "transparent",
|
||||
transition: "background-color 0.15s ease",
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
if (editingId !== row.id) {
|
||||
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.04)";
|
||||
}
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
if (editingId !== row.id) {
|
||||
e.currentTarget.style.backgroundColor = "transparent";
|
||||
}
|
||||
}}
|
||||
>
|
||||
<td
|
||||
style={{
|
||||
padding: editingId === row.id ? "0.5rem 0.8rem" : "0.9rem 1.2rem",
|
||||
fontWeight: 500,
|
||||
color: "#ffffff",
|
||||
}}
|
||||
>
|
||||
{editingId === row.id ? (
|
||||
<input
|
||||
type="text"
|
||||
value={editForm.name}
|
||||
onChange={(e) =>
|
||||
setEditForm((prev) => ({ ...prev, name: e.target.value }))
|
||||
}
|
||||
disabled={savingId === row.id}
|
||||
placeholder="Nombre completo"
|
||||
style={{
|
||||
width: "100%",
|
||||
minWidth: "120px",
|
||||
backgroundColor: "rgba(0, 0, 0, 0.5)",
|
||||
border: "1px solid var(--color-gold)",
|
||||
borderRadius: "4px",
|
||||
color: "#ffffff",
|
||||
padding: "0.4rem 0.6rem",
|
||||
fontSize: "0.85rem",
|
||||
boxSizing: "border-box",
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
row.name
|
||||
)}
|
||||
</td>
|
||||
<td
|
||||
style={{
|
||||
padding: editingId === row.id ? "0.5rem 0.8rem" : "0.9rem 1.2rem",
|
||||
color: "var(--color-gold-light)",
|
||||
}}
|
||||
>
|
||||
{editingId === row.id ? (
|
||||
<input
|
||||
type="tel"
|
||||
value={editForm.phone}
|
||||
onChange={(e) =>
|
||||
setEditForm((prev) => ({ ...prev, phone: e.target.value }))
|
||||
}
|
||||
disabled={savingId === row.id}
|
||||
placeholder="300 123 4567"
|
||||
style={{
|
||||
width: "100%",
|
||||
minWidth: "110px",
|
||||
backgroundColor: "rgba(0, 0, 0, 0.5)",
|
||||
border: "1px solid var(--color-gold)",
|
||||
borderRadius: "4px",
|
||||
color: "var(--color-gold-light)",
|
||||
padding: "0.4rem 0.6rem",
|
||||
fontSize: "0.85rem",
|
||||
boxSizing: "border-box",
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
formatPhone(row.phone)
|
||||
)}
|
||||
</td>
|
||||
<td
|
||||
style={{
|
||||
padding: editingId === row.id ? "0.5rem 0.8rem" : "0.9rem 1.2rem",
|
||||
color: "rgba(255, 255, 255, 0.7)",
|
||||
}}
|
||||
>
|
||||
{editingId === row.id ? (
|
||||
<input
|
||||
type="email"
|
||||
value={editForm.email}
|
||||
onChange={(e) =>
|
||||
setEditForm((prev) => ({ ...prev, email: e.target.value }))
|
||||
}
|
||||
disabled={savingId === row.id}
|
||||
placeholder="Opcional"
|
||||
style={{
|
||||
width: "100%",
|
||||
minWidth: "120px",
|
||||
backgroundColor: "rgba(0, 0, 0, 0.5)",
|
||||
border: "1px solid var(--color-gold)",
|
||||
borderRadius: "4px",
|
||||
color: "rgba(255, 255, 255, 0.9)",
|
||||
padding: "0.4rem 0.6rem",
|
||||
fontSize: "0.85rem",
|
||||
boxSizing: "border-box",
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
row.email || "—"
|
||||
)}
|
||||
</td>
|
||||
<td
|
||||
style={{
|
||||
padding: "0.9rem 1.2rem",
|
||||
color: "rgba(255, 255, 255, 0.5)",
|
||||
fontSize: "0.8rem",
|
||||
}}
|
||||
>
|
||||
{formatDate(row.created_at)}
|
||||
</td>
|
||||
<td style={{ padding: "0.9rem 1.2rem", textAlign: "right", whiteSpace: "nowrap" }}>
|
||||
{editingId === row.id ? (
|
||||
<div style={{ display: "inline-flex", alignItems: "center", gap: "0.4rem" }}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={savingId === row.id}
|
||||
onClick={() => handleSaveEdit(row.id)}
|
||||
style={{
|
||||
background: "rgba(76, 175, 80, 0.15)",
|
||||
border: "1px solid rgba(76, 175, 80, 0.4)",
|
||||
borderRadius: "4px",
|
||||
color: "#81c784",
|
||||
padding: "0.45rem 0.65rem",
|
||||
cursor: savingId === row.id ? "not-allowed" : "pointer",
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
transition: "all 0.15s ease",
|
||||
outline: "none",
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
if (savingId !== row.id) {
|
||||
e.currentTarget.style.backgroundColor = "rgba(76, 175, 80, 0.3)";
|
||||
e.currentTarget.style.borderColor = "#81c784";
|
||||
}
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.backgroundColor = "rgba(76, 175, 80, 0.15)";
|
||||
e.currentTarget.style.borderColor = "rgba(76, 175, 80, 0.4)";
|
||||
}}
|
||||
title="Guardar cambios"
|
||||
aria-label="Guardar cambios"
|
||||
>
|
||||
{savingId === row.id ? (
|
||||
<Spinner size={14} />
|
||||
) : (
|
||||
<svg
|
||||
width="15"
|
||||
height="15"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
role="img"
|
||||
aria-label="Guardar"
|
||||
>
|
||||
<polyline points="20 6 9 17 4 12" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={savingId === row.id}
|
||||
onClick={cancelEditing}
|
||||
style={{
|
||||
background: "rgba(255, 255, 255, 0.08)",
|
||||
border: "1px solid rgba(255, 255, 255, 0.2)",
|
||||
borderRadius: "4px",
|
||||
color: "rgba(255, 255, 255, 0.7)",
|
||||
padding: "0.45rem 0.65rem",
|
||||
cursor: savingId === row.id ? "not-allowed" : "pointer",
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
transition: "all 0.15s ease",
|
||||
outline: "none",
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
if (savingId !== row.id) {
|
||||
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.18)";
|
||||
e.currentTarget.style.color = "#ffffff";
|
||||
}
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.08)";
|
||||
e.currentTarget.style.color = "rgba(255, 255, 255, 0.7)";
|
||||
}}
|
||||
title="Cancelar edición"
|
||||
aria-label="Cancelar edición"
|
||||
>
|
||||
<svg
|
||||
width="15"
|
||||
height="15"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
role="img"
|
||||
aria-label="Cancelar"
|
||||
>
|
||||
<line x1="18" y1="6" x2="6" y2="18" />
|
||||
<line x1="6" y1="6" x2="18" y2="18" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: "inline-flex", alignItems: "center", gap: "0.4rem" }}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={deletingId === row.id || editingId !== null}
|
||||
onClick={() => startEditing(row)}
|
||||
style={{
|
||||
background: "rgba(212, 168, 67, 0.1)",
|
||||
border: "1px solid rgba(212, 168, 67, 0.35)",
|
||||
borderRadius: "4px",
|
||||
color: "var(--color-gold)",
|
||||
padding: "0.45rem 0.65rem",
|
||||
cursor:
|
||||
deletingId === row.id || editingId !== null ? "not-allowed" : "pointer",
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
transition: "all 0.15s ease",
|
||||
outline: "none",
|
||||
opacity: editingId !== null && editingId !== row.id ? 0.35 : 1,
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
if (deletingId !== row.id && editingId === null) {
|
||||
e.currentTarget.style.backgroundColor = "rgba(212, 168, 67, 0.25)";
|
||||
e.currentTarget.style.borderColor = "var(--color-gold-light)";
|
||||
}
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.backgroundColor = "rgba(212, 168, 67, 0.1)";
|
||||
e.currentTarget.style.borderColor = "rgba(212, 168, 67, 0.35)";
|
||||
}}
|
||||
title={`Editar confirmación de ${row.name}`}
|
||||
aria-label={`Editar confirmación de ${row.name}`}
|
||||
>
|
||||
<svg
|
||||
width="15"
|
||||
height="15"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
role="img"
|
||||
aria-label="Editar"
|
||||
>
|
||||
<path d="M12 20h9" />
|
||||
<path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={deletingId === row.id || editingId !== null}
|
||||
onClick={() => handleDelete(row.id, row.name)}
|
||||
style={{
|
||||
background: "rgba(255, 82, 82, 0.1)",
|
||||
border: "1px solid rgba(255, 82, 82, 0.35)",
|
||||
borderRadius: "4px",
|
||||
color: "#ff5252",
|
||||
padding: "0.45rem 0.65rem",
|
||||
cursor:
|
||||
deletingId === row.id || editingId !== null ? "not-allowed" : "pointer",
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
transition: "all 0.15s ease",
|
||||
outline: "none",
|
||||
opacity: editingId !== null && editingId !== row.id ? 0.35 : 1,
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
if (deletingId !== row.id && editingId === null) {
|
||||
e.currentTarget.style.backgroundColor = "rgba(255, 82, 82, 0.25)";
|
||||
e.currentTarget.style.borderColor = "#ff5252";
|
||||
}
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.backgroundColor = "rgba(255, 82, 82, 0.1)";
|
||||
e.currentTarget.style.borderColor = "rgba(255, 82, 82, 0.35)";
|
||||
}}
|
||||
title={`Eliminar confirmación de ${row.name}`}
|
||||
aria-label={`Eliminar confirmación de ${row.name}`}
|
||||
>
|
||||
{deletingId === row.id ? (
|
||||
<Spinner size={14} />
|
||||
) : (
|
||||
<svg
|
||||
width="15"
|
||||
height="15"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
role="img"
|
||||
aria-label="Eliminar"
|
||||
>
|
||||
<polyline points="3 6 5 6 21 6" />
|
||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
|
||||
<line x1="10" y1="11" x2="10" y2="17" />
|
||||
<line x1="14" y1="11" x2="14" y2="17" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import type {
|
||||
InvitationConfig,
|
||||
RSVPApiResult,
|
||||
RSVPAdminItem,
|
||||
RSVPListResponse,
|
||||
RSVPRequest,
|
||||
RSVPUpdateRequest,
|
||||
} from "../types/config";
|
||||
|
||||
const BASE_API = "/birthday/api";
|
||||
|
||||
export async function fetchConfig(): Promise<InvitationConfig> {
|
||||
const res = await fetch(`${BASE_API}/config`, {
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to load config: HTTP ${res.status}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function submitRsvp(data: RSVPRequest): Promise<RSVPApiResult> {
|
||||
try {
|
||||
const res = await fetch(`${BASE_API}/rsvp`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
const json = await res.json();
|
||||
return json as RSVPApiResult;
|
||||
} catch {
|
||||
return { result: "ERROR" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchAdminRsvps(search?: string): Promise<RSVPListResponse> {
|
||||
const url = new URL(`${BASE_API}/admin/rsvps`, window.location.origin);
|
||||
if (search?.trim()) {
|
||||
url.searchParams.set("search", search.trim());
|
||||
}
|
||||
|
||||
const res = await fetch(url.toString(), {
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Error fetching admin RSVPs: HTTP ${res.status}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function fetchAdminConfig(): Promise<InvitationConfig> {
|
||||
const res = await fetch(`${BASE_API}/admin/config`, {
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Error fetching admin config: HTTP ${res.status}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function updateAdminConfig(
|
||||
config: Omit<InvitationConfig, "id" | "updated_at">,
|
||||
): Promise<InvitationConfig> {
|
||||
const res = await fetch(`${BASE_API}/admin/config`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
body: JSON.stringify(config),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorJson = await res.json().catch(() => null);
|
||||
const msg = errorJson?.errors
|
||||
? Object.values(errorJson.errors).join(", ")
|
||||
: `HTTP ${res.status}`;
|
||||
throw new Error(`Error saving configuration: ${msg}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export function getExportCsvUrl(): string {
|
||||
return `${BASE_API}/admin/export`;
|
||||
}
|
||||
|
||||
export interface GenerateMapPreviewResponse {
|
||||
map_preview_url: string;
|
||||
lat: number;
|
||||
lng: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export async function regenerateMapPreview(
|
||||
mapUrl?: string,
|
||||
): Promise<GenerateMapPreviewResponse> {
|
||||
const res = await fetch(`${BASE_API}/admin/map-preview/generate`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
body: JSON.stringify({ map_url: mapUrl }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorJson = await res.json().catch(() => null);
|
||||
const msg =
|
||||
errorJson?.detail ||
|
||||
(errorJson?.errors
|
||||
? Object.values(errorJson.errors).join(", ")
|
||||
: `HTTP ${res.status}`);
|
||||
throw new Error(msg || "Error al regenerar vista previa del mapa.");
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function deleteAdminRsvp(rsvpId: number): Promise<void> {
|
||||
const res = await fetch(`${BASE_API}/admin/rsvps/${rsvpId}`, {
|
||||
method: "DELETE",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
|
||||
if (!res.ok && res.status !== 204) {
|
||||
const errorJson = await res.json().catch(() => null);
|
||||
const msg = errorJson?.detail || `HTTP ${res.status}`;
|
||||
throw new Error(`Error al eliminar asistente: ${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateAdminRsvp(
|
||||
rsvpId: number,
|
||||
data: RSVPUpdateRequest,
|
||||
): Promise<RSVPAdminItem> {
|
||||
const res = await fetch(`${BASE_API}/admin/rsvps/${rsvpId}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorJson = await res.json().catch(() => null);
|
||||
const msg =
|
||||
errorJson?.detail ||
|
||||
(errorJson?.errors
|
||||
? Object.values(errorJson.errors).join(", ")
|
||||
: `HTTP ${res.status}`);
|
||||
throw new Error(msg || "Error al actualizar asistente.");
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export interface CurrentUser {
|
||||
subject: string;
|
||||
email: string;
|
||||
name: string | null;
|
||||
groups: string[];
|
||||
}
|
||||
|
||||
export async function fetchCurrentUser(): Promise<CurrentUser> {
|
||||
const res = await fetch(`${BASE_API}/auth/me`, {
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Unauthenticated: HTTP ${res.status}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function logoutUser(): Promise<void> {
|
||||
await fetch(`${BASE_API}/auth/logout`, {
|
||||
method: "POST",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { ButtonHTMLAttributes } from "react";
|
||||
|
||||
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: "primary" | "secondary" | "outline";
|
||||
fullWidth?: boolean;
|
||||
}
|
||||
|
||||
export function Button({
|
||||
children,
|
||||
variant = "primary",
|
||||
fullWidth = false,
|
||||
disabled,
|
||||
style,
|
||||
...props
|
||||
}: ButtonProps) {
|
||||
const isPrimary = variant === "primary";
|
||||
const isOutline = variant === "outline";
|
||||
|
||||
return (
|
||||
<button
|
||||
disabled={disabled}
|
||||
style={{
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
padding: "0.85rem 1.8rem",
|
||||
fontSize: "0.85rem",
|
||||
fontWeight: 600,
|
||||
letterSpacing: "0.18em",
|
||||
textTransform: "uppercase",
|
||||
borderRadius: "4px",
|
||||
border: isOutline
|
||||
? "1px solid var(--color-gold)"
|
||||
: isPrimary
|
||||
? "1px solid var(--color-gold)"
|
||||
: "1px solid rgba(255, 255, 255, 0.2)",
|
||||
backgroundColor: isPrimary
|
||||
? "var(--color-gold)"
|
||||
: isOutline
|
||||
? "transparent"
|
||||
: "rgba(255, 255, 255, 0.08)",
|
||||
color: isPrimary ? "#0a0a0a" : "var(--color-text)",
|
||||
opacity: disabled ? 0.6 : 1,
|
||||
cursor: disabled ? "not-allowed" : "pointer",
|
||||
transition: "all 0.2s ease",
|
||||
width: fullWidth ? "100%" : "auto",
|
||||
...style,
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { InputHTMLAttributes } from "react";
|
||||
|
||||
interface FieldProps extends InputHTMLAttributes<HTMLInputElement> {
|
||||
label: string;
|
||||
error?: string;
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
export function Field({ label, id, error, hint, disabled, style, ...props }: FieldProps) {
|
||||
const inputId = id || `field-${label.toLowerCase().replace(/\s+/g, "-")}`;
|
||||
const errorId = `${inputId}-error`;
|
||||
const hintId = `${inputId}-hint`;
|
||||
|
||||
return (
|
||||
<div style={{ marginBottom: "1.4rem", width: "100%", textAlign: "left" }}>
|
||||
<label
|
||||
htmlFor={inputId}
|
||||
style={{
|
||||
display: "block",
|
||||
fontSize: "0.72rem",
|
||||
fontWeight: 500,
|
||||
letterSpacing: "0.15em",
|
||||
textTransform: "uppercase",
|
||||
color: "var(--color-text-muted)",
|
||||
marginBottom: "0.45rem",
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</label>
|
||||
<input
|
||||
id={inputId}
|
||||
disabled={disabled}
|
||||
aria-invalid={Boolean(error)}
|
||||
aria-describedby={error ? errorId : hint ? hintId : undefined}
|
||||
style={{
|
||||
width: "100%",
|
||||
padding: "0.85rem 1rem",
|
||||
backgroundColor: "rgba(255, 255, 255, 0.05)",
|
||||
border: error
|
||||
? "1px solid var(--color-error)"
|
||||
: "1px solid var(--color-gold-border)",
|
||||
borderRadius: "4px",
|
||||
color: "var(--color-text)",
|
||||
fontSize: "0.95rem",
|
||||
outline: "none",
|
||||
transition: "border-color 0.2s ease, box-shadow 0.2s ease",
|
||||
...style,
|
||||
}}
|
||||
onFocus={(e) => {
|
||||
if (!error) {
|
||||
e.currentTarget.style.borderColor = "var(--color-gold-border-focus)";
|
||||
e.currentTarget.style.boxShadow = "0 0 0 2px rgba(212, 168, 67, 0.15)";
|
||||
}
|
||||
}}
|
||||
onBlur={(e) => {
|
||||
if (!error) {
|
||||
e.currentTarget.style.borderColor = "var(--color-gold-border)";
|
||||
e.currentTarget.style.boxShadow = "none";
|
||||
}
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
{hint && !error && (
|
||||
<span
|
||||
id={hintId}
|
||||
style={{
|
||||
display: "block",
|
||||
fontSize: "0.72rem",
|
||||
color: "var(--color-text-dim)",
|
||||
marginTop: "0.3rem",
|
||||
}}
|
||||
>
|
||||
{hint}
|
||||
</span>
|
||||
)}
|
||||
{error && (
|
||||
<span
|
||||
id={errorId}
|
||||
role="alert"
|
||||
style={{
|
||||
display: "block",
|
||||
fontSize: "0.75rem",
|
||||
color: "var(--color-error)",
|
||||
marginTop: "0.35rem",
|
||||
}}
|
||||
>
|
||||
{error}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
export function Spinner({ size = 24 }: { size?: number }) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: "inline-block",
|
||||
width: size,
|
||||
height: size,
|
||||
border: "2px solid rgba(212, 168, 67, 0.25)",
|
||||
borderTopColor: "var(--color-gold)",
|
||||
borderRadius: "50%",
|
||||
animation: "spin 0.8s linear infinite",
|
||||
}}
|
||||
aria-label="Cargando..."
|
||||
role="status"
|
||||
>
|
||||
<style>{`
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { fetchConfig } from "../api/client";
|
||||
import type { InvitationConfig } from "../types/config";
|
||||
|
||||
export type ConfigStatus = "loading" | "success" | "error";
|
||||
|
||||
export function useConfig() {
|
||||
const [config, setConfig] = useState<InvitationConfig | null>(null);
|
||||
const [status, setStatus] = useState<ConfigStatus>("loading");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setStatus("loading");
|
||||
setError(null);
|
||||
try {
|
||||
const data = await fetchConfig();
|
||||
setConfig(data);
|
||||
setStatus("success");
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error al cargar la configuración");
|
||||
setStatus("error");
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
return { config, status, error, reload: load };
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export type CountdownState = "counting" | "in_progress" | "finished";
|
||||
|
||||
export interface CountdownResult {
|
||||
days: string;
|
||||
hours: string;
|
||||
minutes: string;
|
||||
seconds: string;
|
||||
state: CountdownState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates UTC epoch milliseconds for a local datetime in a specified IANA timezone.
|
||||
*/
|
||||
function getTargetUtcMillis(dateStr: string, timeStr: string, timeZone: string): number {
|
||||
try {
|
||||
const [year, month, day] = dateStr.split("-").map(Number);
|
||||
const [hours, minutes] = timeStr.split(":").map(Number);
|
||||
|
||||
// Initial guess as UTC
|
||||
const utcGuess = new Date(Date.UTC(year, month - 1, day, hours, minutes, 0));
|
||||
|
||||
const dtf = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone,
|
||||
year: "numeric",
|
||||
month: "numeric",
|
||||
day: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "numeric",
|
||||
second: "numeric",
|
||||
hour12: false,
|
||||
});
|
||||
|
||||
const parts = dtf.formatToParts(utcGuess);
|
||||
const p: Record<string, number> = {};
|
||||
for (const part of parts) {
|
||||
if (part.type !== "literal") {
|
||||
p[part.type] = Number(part.value);
|
||||
}
|
||||
}
|
||||
|
||||
const asLocalInTz = Date.UTC(
|
||||
p.year,
|
||||
p.month - 1,
|
||||
p.day,
|
||||
p.hour === 24 ? 0 : p.hour,
|
||||
p.minute,
|
||||
p.second,
|
||||
);
|
||||
const offset = asLocalInTz - utcGuess.getTime();
|
||||
return utcGuess.getTime() - offset;
|
||||
} catch {
|
||||
// Fallback if timezone is unparseable
|
||||
return new Date(`${dateStr}T${timeStr}:00`).getTime();
|
||||
}
|
||||
}
|
||||
|
||||
export function useCountdown(
|
||||
eventDate: string,
|
||||
eventTime: string,
|
||||
eventTimezone: string,
|
||||
): CountdownResult {
|
||||
const [result, setResult] = useState<CountdownResult>({
|
||||
days: "00",
|
||||
hours: "00",
|
||||
minutes: "00",
|
||||
seconds: "00",
|
||||
state: "counting",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!eventDate || !eventTime) return;
|
||||
|
||||
const targetTime = getTargetUtcMillis(
|
||||
eventDate,
|
||||
eventTime,
|
||||
eventTimezone || "America/Bogota",
|
||||
);
|
||||
|
||||
// Typical party duration window: 6 hours
|
||||
const eventDurationMs = 6 * 60 * 60 * 1000;
|
||||
|
||||
function update() {
|
||||
const now = Date.now();
|
||||
const diff = targetTime - now;
|
||||
|
||||
if (diff > 0) {
|
||||
const totalSeconds = Math.floor(diff / 1000);
|
||||
const days = Math.floor(totalSeconds / (3600 * 24));
|
||||
const hours = Math.floor((totalSeconds % (3600 * 24)) / 3600);
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
|
||||
setResult({
|
||||
days: String(days).padStart(2, "0"),
|
||||
hours: String(hours).padStart(2, "0"),
|
||||
minutes: String(minutes).padStart(2, "0"),
|
||||
seconds: String(seconds).padStart(2, "0"),
|
||||
state: "counting",
|
||||
});
|
||||
} else if (Math.abs(diff) < eventDurationMs) {
|
||||
setResult({
|
||||
days: "00",
|
||||
hours: "00",
|
||||
minutes: "00",
|
||||
seconds: "00",
|
||||
state: "in_progress",
|
||||
});
|
||||
} else {
|
||||
setResult({
|
||||
days: "00",
|
||||
hours: "00",
|
||||
minutes: "00",
|
||||
seconds: "00",
|
||||
state: "finished",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
update();
|
||||
const interval = setInterval(update, 1000);
|
||||
return () => clearInterval(interval);
|
||||
}, [eventDate, eventTime, eventTimezone]);
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { submitRsvp } from "../api/client";
|
||||
|
||||
const SESSION_STORAGE_KEY = "bdinvite:rsvp-submitted";
|
||||
|
||||
export type RsvpFormState = "idle" | "submitting" | "success" | "duplicate" | "error";
|
||||
|
||||
export interface FormErrors {
|
||||
name?: string;
|
||||
phone?: string;
|
||||
email?: string;
|
||||
}
|
||||
|
||||
export function useRsvpForm() {
|
||||
const [name, setName] = useState("");
|
||||
const [phone, setPhone] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [confirmedName, setConfirmedName] = useState("");
|
||||
|
||||
const [formState, setFormState] = useState<RsvpFormState>("idle");
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
|
||||
// Check sessionStorage on mount for existing submission in this session
|
||||
useEffect(() => {
|
||||
try {
|
||||
const stored = sessionStorage.getItem(SESSION_STORAGE_KEY);
|
||||
if (stored) {
|
||||
const parsed = JSON.parse(stored);
|
||||
if (parsed?.name) {
|
||||
setConfirmedName(parsed.name);
|
||||
setFormState("success");
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore sessionStorage read errors
|
||||
}
|
||||
}, []);
|
||||
|
||||
function validate(): boolean {
|
||||
const newErrors: FormErrors = {};
|
||||
|
||||
const cleanName = name.trim();
|
||||
if (!cleanName) {
|
||||
newErrors.name = "Por favor, ingresa tu nombre completo.";
|
||||
}
|
||||
|
||||
// Colombian mobile format: 10 digits starting with 3, optionally +57
|
||||
const digits = phone.replace(/\D/g, "");
|
||||
let normalized = digits;
|
||||
if (normalized.startsWith("57") && normalized.length === 12) {
|
||||
normalized = normalized.slice(2);
|
||||
}
|
||||
|
||||
if (normalized.length !== 10 || !normalized.startsWith("3")) {
|
||||
newErrors.phone =
|
||||
"Ingresa un número móvil válido de 10 dígitos (ej: 300 123 4567).";
|
||||
}
|
||||
|
||||
if (email?.trim()) {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email.trim())) {
|
||||
newErrors.email = "Ingresa un correo electrónico válido.";
|
||||
}
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!validate()) return;
|
||||
|
||||
setFormState("submitting");
|
||||
|
||||
// Clean phone
|
||||
let digits = phone.replace(/\D/g, "");
|
||||
if (digits.startsWith("57") && digits.length === 12) {
|
||||
digits = digits.slice(2);
|
||||
}
|
||||
|
||||
const payload = {
|
||||
name: name.trim(),
|
||||
phone: digits,
|
||||
email: email.trim() || null,
|
||||
};
|
||||
|
||||
const result = await submitRsvp(payload);
|
||||
|
||||
if (result.result === "SUCCESS") {
|
||||
setConfirmedName(result.name);
|
||||
setFormState("success");
|
||||
try {
|
||||
sessionStorage.setItem(
|
||||
SESSION_STORAGE_KEY,
|
||||
JSON.stringify({ name: result.name, timestamp: Date.now() }),
|
||||
);
|
||||
} catch {
|
||||
// Ignore storage write issues
|
||||
}
|
||||
} else if (result.result === "DUPLICATE") {
|
||||
setFormState("duplicate");
|
||||
} else if (result.result === "VALIDATION_ERROR") {
|
||||
setFormState("idle");
|
||||
setErrors(result.errors);
|
||||
} else {
|
||||
setFormState("error");
|
||||
}
|
||||
}
|
||||
|
||||
function retry() {
|
||||
setFormState("idle");
|
||||
}
|
||||
|
||||
return {
|
||||
name,
|
||||
setName,
|
||||
phone,
|
||||
setPhone,
|
||||
email,
|
||||
setEmail,
|
||||
confirmedName,
|
||||
formState,
|
||||
errors,
|
||||
submit,
|
||||
retry,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import type { CountdownState } from "../hooks/useCountdown";
|
||||
|
||||
interface CountdownProps {
|
||||
days: string;
|
||||
hours: string;
|
||||
minutes: string;
|
||||
seconds: string;
|
||||
state: CountdownState;
|
||||
label?: string;
|
||||
inProgressLabel?: string;
|
||||
finishedLabel?: string;
|
||||
}
|
||||
|
||||
export function Countdown({
|
||||
days,
|
||||
hours,
|
||||
minutes,
|
||||
seconds,
|
||||
state,
|
||||
label = "NOS VEMOS EN",
|
||||
inProgressLabel = "EVENTO EN CURSO",
|
||||
finishedLabel = "EVENTO FINALIZADO",
|
||||
}: CountdownProps) {
|
||||
if (state === "in_progress") {
|
||||
return (
|
||||
<div style={{ textAlign: "center", margin: "1.8rem 0" }}>
|
||||
<p
|
||||
style={{
|
||||
fontSize: "1.1rem",
|
||||
fontWeight: 600,
|
||||
letterSpacing: "0.2em",
|
||||
color: "var(--color-gold-light)",
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
{inProgressLabel}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (state === "finished") {
|
||||
return (
|
||||
<div style={{ textAlign: "center", margin: "1.8rem 0" }}>
|
||||
<p
|
||||
style={{
|
||||
fontSize: "0.95rem",
|
||||
fontWeight: 500,
|
||||
letterSpacing: "0.18em",
|
||||
color: "var(--color-text-dim)",
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
{finishedLabel}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ textAlign: "center", margin: "1.8rem 0" }}>
|
||||
<p
|
||||
style={{
|
||||
fontSize: "0.78rem",
|
||||
fontWeight: 600,
|
||||
letterSpacing: "0.25em",
|
||||
color: "var(--color-gold-light)",
|
||||
textTransform: "uppercase",
|
||||
marginBottom: "0.75rem",
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</p>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: "0.6rem",
|
||||
fontSize: "1.8rem",
|
||||
fontWeight: 300,
|
||||
letterSpacing: "0.08em",
|
||||
fontVariantNumeric: "tabular-nums",
|
||||
color: "var(--color-text)",
|
||||
}}
|
||||
>
|
||||
<div style={{ textAlign: "center" }}>
|
||||
<span>{days}</span>
|
||||
<span
|
||||
style={{
|
||||
display: "block",
|
||||
fontSize: "0.58rem",
|
||||
letterSpacing: "0.15em",
|
||||
color: "var(--color-text-dim)",
|
||||
marginTop: "0.2rem",
|
||||
}}
|
||||
>
|
||||
DÍAS
|
||||
</span>
|
||||
</div>
|
||||
<span style={{ color: "var(--color-gold)", opacity: 0.7, marginTop: "-0.8rem" }}>
|
||||
:
|
||||
</span>
|
||||
<div style={{ textAlign: "center" }}>
|
||||
<span>{hours}</span>
|
||||
<span
|
||||
style={{
|
||||
display: "block",
|
||||
fontSize: "0.58rem",
|
||||
letterSpacing: "0.15em",
|
||||
color: "var(--color-text-dim)",
|
||||
marginTop: "0.2rem",
|
||||
}}
|
||||
>
|
||||
HORAS
|
||||
</span>
|
||||
</div>
|
||||
<span style={{ color: "var(--color-gold)", opacity: 0.7, marginTop: "-0.8rem" }}>
|
||||
:
|
||||
</span>
|
||||
<div style={{ textAlign: "center" }}>
|
||||
<span>{minutes}</span>
|
||||
<span
|
||||
style={{
|
||||
display: "block",
|
||||
fontSize: "0.58rem",
|
||||
letterSpacing: "0.15em",
|
||||
color: "var(--color-text-dim)",
|
||||
marginTop: "0.2rem",
|
||||
}}
|
||||
>
|
||||
MIN
|
||||
</span>
|
||||
</div>
|
||||
<span style={{ color: "var(--color-gold)", opacity: 0.7, marginTop: "-0.8rem" }}>
|
||||
:
|
||||
</span>
|
||||
<div style={{ textAlign: "center" }}>
|
||||
<span>{seconds}</span>
|
||||
<span
|
||||
style={{
|
||||
display: "block",
|
||||
fontSize: "0.58rem",
|
||||
letterSpacing: "0.15em",
|
||||
color: "var(--color-text-dim)",
|
||||
marginTop: "0.2rem",
|
||||
}}
|
||||
>
|
||||
SEG
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { Button } from "../components/Button";
|
||||
import { Spinner } from "../components/Spinner";
|
||||
import { useConfig } from "../hooks/useConfig";
|
||||
import { useRsvpForm } from "../hooks/useRsvpForm";
|
||||
import { InvitationHero } from "./InvitationHero";
|
||||
import { ParticleBackground } from "./ParticleBackground";
|
||||
import { RsvpForm } from "./RsvpForm";
|
||||
import { RsvpResult } from "./RsvpResult";
|
||||
|
||||
export function Invitation() {
|
||||
const { config, status, error, reload } = useConfig();
|
||||
const rsvpForm = useRsvpForm();
|
||||
const [showDetailsOnly, setShowDetailsOnly] = useState(false);
|
||||
const rsvpSectionRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
function scrollToRsvp() {
|
||||
if (rsvpSectionRef.current) {
|
||||
rsvpSectionRef.current.scrollIntoView({ behavior: "smooth" });
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Loading Configuration State
|
||||
if (status === "loading") {
|
||||
return (
|
||||
<main
|
||||
style={{
|
||||
minHeight: "100vh",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: "1.2rem",
|
||||
backgroundColor: "var(--color-bg)",
|
||||
}}
|
||||
>
|
||||
<Spinner size={36} />
|
||||
<p
|
||||
style={{
|
||||
fontSize: "0.82rem",
|
||||
letterSpacing: "0.2em",
|
||||
color: "var(--color-text-muted)",
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
Cargando invitación...
|
||||
</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Configuration Error State
|
||||
if (status === "error" || !config) {
|
||||
return (
|
||||
<main
|
||||
style={{
|
||||
minHeight: "100vh",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
padding: "2rem",
|
||||
textAlign: "center",
|
||||
backgroundColor: "var(--color-bg)",
|
||||
}}
|
||||
>
|
||||
<h2
|
||||
style={{
|
||||
fontSize: "1.3rem",
|
||||
fontWeight: 600,
|
||||
letterSpacing: "0.15em",
|
||||
color: "var(--color-gold-light)",
|
||||
textTransform: "uppercase",
|
||||
marginBottom: "1rem",
|
||||
}}
|
||||
>
|
||||
No pudimos cargar la invitación
|
||||
</h2>
|
||||
<p
|
||||
style={{
|
||||
fontSize: "0.92rem",
|
||||
color: "var(--color-text-muted)",
|
||||
marginBottom: "2rem",
|
||||
maxWidth: "360px",
|
||||
lineHeight: 1.6,
|
||||
}}
|
||||
>
|
||||
{error || "Por favor, verifica tu conexión e inténtalo nuevamente."}
|
||||
</p>
|
||||
<Button variant="primary" onClick={reload}>
|
||||
REINTENTAR
|
||||
</Button>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Loaded Invitation Page Flow
|
||||
return (
|
||||
<div style={{ position: "relative", minHeight: "100vh" }}>
|
||||
{/* Background ambient particle canvas */}
|
||||
<ParticleBackground />
|
||||
|
||||
<main
|
||||
style={{
|
||||
position: "relative",
|
||||
zIndex: 1,
|
||||
width: "100%",
|
||||
maxWidth: "480px",
|
||||
margin: "0 auto",
|
||||
boxShadow: "0 0 50px rgba(0, 0, 0, 0.8)",
|
||||
backgroundColor: "rgba(10, 10, 10, 0.85)",
|
||||
backdropFilter: "blur(2px)",
|
||||
}}
|
||||
>
|
||||
{/* Section 1: Invitation Hero */}
|
||||
<InvitationHero
|
||||
config={config}
|
||||
onCtaClick={() => {
|
||||
setShowDetailsOnly(false);
|
||||
scrollToRsvp();
|
||||
}}
|
||||
onShowDetailsClick={() => {
|
||||
setShowDetailsOnly(true);
|
||||
scrollToRsvp();
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Section 2: RSVP / Confirmation Flow */}
|
||||
<div
|
||||
id="rsvp-section"
|
||||
ref={rsvpSectionRef}
|
||||
style={{
|
||||
minHeight: "80vh",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
padding: "2.5rem 1.8rem 4rem 1.8rem",
|
||||
borderTop: "1px solid var(--color-gold-border)",
|
||||
position: "relative",
|
||||
}}
|
||||
>
|
||||
{showDetailsOnly ? (
|
||||
<RsvpResult
|
||||
formState="idle"
|
||||
confirmedName=""
|
||||
config={config}
|
||||
onRetry={() => setShowDetailsOnly(false)}
|
||||
isDetailsOnly={true}
|
||||
onBackToForm={() => setShowDetailsOnly(false)}
|
||||
/>
|
||||
) : rsvpForm.formState === "idle" || rsvpForm.formState === "submitting" ? (
|
||||
<RsvpForm
|
||||
config={config}
|
||||
name={rsvpForm.name}
|
||||
setName={rsvpForm.setName}
|
||||
phone={rsvpForm.phone}
|
||||
setPhone={rsvpForm.setPhone}
|
||||
email={rsvpForm.email}
|
||||
setEmail={rsvpForm.setEmail}
|
||||
formState={rsvpForm.formState}
|
||||
errors={rsvpForm.errors}
|
||||
onSubmit={rsvpForm.submit}
|
||||
onShowDetails={() => setShowDetailsOnly(true)}
|
||||
/>
|
||||
) : (
|
||||
<RsvpResult
|
||||
formState={rsvpForm.formState}
|
||||
confirmedName={rsvpForm.confirmedName}
|
||||
config={config}
|
||||
onRetry={rsvpForm.retry}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import type { InvitationConfig } from "../types/config";
|
||||
import { RsvpCta } from "./RsvpCta";
|
||||
|
||||
interface InvitationHeroProps {
|
||||
config: InvitationConfig;
|
||||
onCtaClick: () => void;
|
||||
onShowDetailsClick?: () => void;
|
||||
}
|
||||
|
||||
export function InvitationHero({
|
||||
config,
|
||||
onCtaClick,
|
||||
onShowDetailsClick,
|
||||
}: InvitationHeroProps) {
|
||||
// Parse date into Month, Day, and Day of Week
|
||||
const [year, monthNum, dayNum] = config.event_date.split("-").map(Number);
|
||||
const dateObj = new Date(year, (monthNum || 1) - 1, dayNum || 1);
|
||||
|
||||
const monthsEs = [
|
||||
"ENE",
|
||||
"FEB",
|
||||
"MAR",
|
||||
"ABR",
|
||||
"MAY",
|
||||
"JUN",
|
||||
"JUL",
|
||||
"AGO",
|
||||
"SEP",
|
||||
"OCT",
|
||||
"NOV",
|
||||
"DIC",
|
||||
];
|
||||
const daysEs = [
|
||||
"DOMINGO",
|
||||
"LUNES",
|
||||
"MARTES",
|
||||
"MIÉRCOLES",
|
||||
"JUEVES",
|
||||
"VIERNES",
|
||||
"SÁBADO",
|
||||
];
|
||||
|
||||
const monthStr = monthsEs[(monthNum || 1) - 1] || "OCT";
|
||||
const dayNameStr = daysEs[dateObj.getDay()] || "VIERNES";
|
||||
const dayStr = String(dayNum || 28);
|
||||
|
||||
// Format 24h time to 12h AM/PM if applicable
|
||||
const [hStr, mStr] = config.event_time.split(":");
|
||||
let formattedTime = config.event_time;
|
||||
if (hStr) {
|
||||
const h = parseInt(hStr, 10);
|
||||
const m = mStr || "00";
|
||||
const ampm = h >= 12 ? "PM" : "AM";
|
||||
const h12 = h % 12 || 12;
|
||||
formattedTime = `${h12}:${m} ${ampm}`;
|
||||
}
|
||||
|
||||
return (
|
||||
<section
|
||||
style={{
|
||||
width: "100%",
|
||||
maxWidth: "480px",
|
||||
minHeight: "100vh",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
padding: "3.5rem 1.8rem 2.5rem 1.8rem",
|
||||
textAlign: "center",
|
||||
margin: "0 auto",
|
||||
position: "relative",
|
||||
zIndex: 1,
|
||||
}}
|
||||
>
|
||||
{/* 1. Header: Script Birthday Party */}
|
||||
<div style={{ marginTop: "1rem" }}>
|
||||
<h1
|
||||
style={{
|
||||
fontFamily: "var(--font-display)",
|
||||
fontSize: "clamp(3.2rem, 12vw, 4.4rem)",
|
||||
fontWeight: 400,
|
||||
lineHeight: 1.15,
|
||||
color: "var(--color-text)",
|
||||
textShadow: "0 2px 20px rgba(212, 168, 67, 0.35)",
|
||||
}}
|
||||
>
|
||||
{config.title || "Birthday Party"}
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
{/* 2. Invitation wording & Honoree name */}
|
||||
<div style={{ margin: "2rem 0" }}>
|
||||
<p
|
||||
style={{
|
||||
fontSize: "0.78rem",
|
||||
fontWeight: 400,
|
||||
letterSpacing: "0.24em",
|
||||
textTransform: "uppercase",
|
||||
color: "var(--color-text-muted)",
|
||||
lineHeight: 1.8,
|
||||
maxWidth: "320px",
|
||||
margin: "0 auto",
|
||||
}}
|
||||
>
|
||||
{config.invitation_text}
|
||||
</p>
|
||||
|
||||
<h2
|
||||
style={{
|
||||
fontFamily: "var(--font-display)",
|
||||
fontSize: "clamp(2.6rem, 10vw, 3.6rem)",
|
||||
fontWeight: 400,
|
||||
color: "var(--color-gold-light)",
|
||||
marginTop: "1.4rem",
|
||||
textShadow: "0 2px 18px rgba(212, 168, 67, 0.4)",
|
||||
}}
|
||||
>
|
||||
{config.honoree_name}
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
{/* 3. Event metadata date block */}
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: "1.2rem",
|
||||
margin: "1.5rem 0",
|
||||
fontSize: "0.88rem",
|
||||
letterSpacing: "0.18em",
|
||||
color: "var(--color-text)",
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
<span style={{ fontWeight: 500, minWidth: "75px" }}>{dayNameStr}</span>
|
||||
|
||||
{/* Divider & Day Box */}
|
||||
<div
|
||||
style={{
|
||||
borderLeft: "1px solid rgba(255, 255, 255, 0.25)",
|
||||
borderRight: "1px solid rgba(255, 255, 255, 0.25)",
|
||||
padding: "0 1.2rem",
|
||||
textAlign: "center",
|
||||
}}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
display: "block",
|
||||
fontSize: "0.68rem",
|
||||
letterSpacing: "0.2em",
|
||||
color: "var(--color-text-muted)",
|
||||
marginBottom: "0.15rem",
|
||||
}}
|
||||
>
|
||||
{monthStr}
|
||||
</span>
|
||||
<span
|
||||
style={{
|
||||
display: "block",
|
||||
fontSize: "1.7rem",
|
||||
fontWeight: 700,
|
||||
lineHeight: 1,
|
||||
letterSpacing: "0.05em",
|
||||
}}
|
||||
>
|
||||
{dayStr}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<span style={{ fontWeight: 500, minWidth: "75px" }}>{formattedTime}</span>
|
||||
</div>
|
||||
|
||||
{/* 4. RSVP Call to action */}
|
||||
<div
|
||||
style={{
|
||||
marginBottom: "1rem",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
gap: "0.8rem",
|
||||
}}
|
||||
>
|
||||
<RsvpCta label={config.rsvp_cta} onClick={onCtaClick} />
|
||||
{onShowDetailsClick && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onShowDetailsClick}
|
||||
style={{
|
||||
background: "none",
|
||||
border: "none",
|
||||
color: "var(--color-text-muted)",
|
||||
fontSize: "0.74rem",
|
||||
letterSpacing: "0.14em",
|
||||
textTransform: "uppercase",
|
||||
cursor: "pointer",
|
||||
padding: "0.3rem 0.6rem",
|
||||
textDecoration: "underline",
|
||||
textUnderlineOffset: "3px",
|
||||
opacity: 0.8,
|
||||
transition: "opacity 0.2s ease, color 0.2s ease",
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.opacity = "1";
|
||||
e.currentTarget.style.color = "var(--color-gold)";
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.opacity = "0.8";
|
||||
e.currentTarget.style.color = "var(--color-text-muted)";
|
||||
}}
|
||||
>
|
||||
¿Ya confirmaste? Ver ubicación y mapa
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { useState } from "react";
|
||||
|
||||
interface MapPreviewProps {
|
||||
previewUrl: string;
|
||||
mapUrl: string;
|
||||
venueName: string;
|
||||
}
|
||||
|
||||
export function MapPreview({ previewUrl, mapUrl, venueName }: MapPreviewProps) {
|
||||
const [imgError, setImgError] = useState(false);
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
|
||||
return (
|
||||
<div style={{ textAlign: "center", margin: "1.6rem 0" }}>
|
||||
<a
|
||||
href={mapUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onMouseEnter={() => setIsHovered(true)}
|
||||
onMouseLeave={() => setIsHovered(false)}
|
||||
onFocus={() => setIsHovered(true)}
|
||||
onBlur={() => setIsHovered(false)}
|
||||
style={{
|
||||
display: "inline-block",
|
||||
textDecoration: "none",
|
||||
color: "inherit",
|
||||
outline: "none",
|
||||
}}
|
||||
aria-label={`Ver ubicación de ${venueName} en Google Maps`}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: "140px",
|
||||
height: "140px",
|
||||
margin: "0 auto",
|
||||
borderRadius: "50%",
|
||||
overflow: "hidden",
|
||||
border: `1.5px solid ${isHovered ? "var(--color-gold-border-focus)" : "var(--color-gold-border)"}`,
|
||||
boxShadow: isHovered
|
||||
? "0 6px 24px rgba(0, 0, 0, 0.7), 0 0 20px rgba(212, 168, 67, 0.3)"
|
||||
: "0 4px 20px rgba(0, 0, 0, 0.5), 0 0 15px rgba(212, 168, 67, 0.15)",
|
||||
transform: isHovered ? "scale(1.06)" : "scale(1)",
|
||||
transition:
|
||||
"transform 0.25s ease, border-color 0.25s ease, box-shadow 0.25s ease",
|
||||
position: "relative",
|
||||
backgroundColor: "#1a1a1a",
|
||||
}}
|
||||
>
|
||||
{!imgError && previewUrl ? (
|
||||
<img
|
||||
src={previewUrl}
|
||||
alt={`Mapa de ${venueName}`}
|
||||
onError={() => setImgError(true)}
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
objectFit: "cover",
|
||||
display: "block",
|
||||
filter: "contrast(1.1) brightness(0.9)",
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
color: "var(--color-gold)",
|
||||
backgroundColor: "#151515",
|
||||
padding: "0.5rem",
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
width="28"
|
||||
height="28"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
role="img"
|
||||
aria-label="Icono de mapa"
|
||||
>
|
||||
<title>Icono de mapa</title>
|
||||
<path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" />
|
||||
<circle cx="12" cy="10" r="3" />
|
||||
</svg>
|
||||
<span
|
||||
style={{
|
||||
fontSize: "0.65rem",
|
||||
letterSpacing: "0.1em",
|
||||
marginTop: "0.3rem",
|
||||
color: "var(--color-text-muted)",
|
||||
}}
|
||||
>
|
||||
MAPA
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<span
|
||||
style={{
|
||||
display: "inline-block",
|
||||
fontSize: "0.74rem",
|
||||
fontWeight: 600,
|
||||
letterSpacing: "0.22em",
|
||||
color: "var(--color-gold-light)",
|
||||
textTransform: "uppercase",
|
||||
marginTop: "0.9rem",
|
||||
transition: "color 0.2s ease",
|
||||
}}
|
||||
>
|
||||
VER UBICACIÓN ↗
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
interface Particle {
|
||||
x: number;
|
||||
y: number;
|
||||
radius: number;
|
||||
baseOpacity: number;
|
||||
blur: number;
|
||||
goldR: number;
|
||||
goldG: number;
|
||||
goldB: number;
|
||||
vx: number;
|
||||
vy: number;
|
||||
twinkleSpeed: number;
|
||||
twinklePhase: number;
|
||||
}
|
||||
|
||||
export function ParticleBackground() {
|
||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return;
|
||||
|
||||
let animationFrameId: number;
|
||||
canvas.width = window.innerWidth;
|
||||
canvas.height = window.innerHeight;
|
||||
let width = canvas.width;
|
||||
let height = canvas.height;
|
||||
|
||||
const prefersReducedMotion = window.matchMedia(
|
||||
"(prefers-reduced-motion: reduce)",
|
||||
).matches;
|
||||
|
||||
const particleCount = width > 768 ? 120 : 80;
|
||||
const particles: Particle[] = [];
|
||||
|
||||
function createParticle(): Particle {
|
||||
const bias = Math.random();
|
||||
let x = 0;
|
||||
let y = 0;
|
||||
|
||||
if (bias < 0.4) {
|
||||
// Upper-left quadrant
|
||||
x = Math.random() * width * 0.55;
|
||||
y = Math.random() * height * 0.45;
|
||||
} else if (bias < 0.8) {
|
||||
// Lower-right quadrant
|
||||
x = width * 0.45 + Math.random() * width * 0.55;
|
||||
y = height * 0.55 + Math.random() * height * 0.45;
|
||||
} else {
|
||||
// Sparse center
|
||||
x = Math.random() * width;
|
||||
y = Math.random() * height;
|
||||
}
|
||||
|
||||
// Golden hues: amber, champagne, warm gold
|
||||
const goldPalette = [
|
||||
{ r: 212, g: 168, b: 67 }, // Classic gold #d4a843
|
||||
{ r: 240, g: 214, b: 138 }, // Light gold #f0d68a
|
||||
{ r: 255, g: 223, b: 140 }, // Bright champagne
|
||||
{ r: 180, g: 140, b: 50 }, // Deep amber
|
||||
];
|
||||
const color = goldPalette[Math.floor(Math.random() * goldPalette.length)];
|
||||
|
||||
return {
|
||||
x,
|
||||
y,
|
||||
radius: 1.5 + Math.random() * 5.5,
|
||||
baseOpacity: 0.15 + Math.random() * 0.55,
|
||||
blur: 2 + Math.random() * 8,
|
||||
goldR: color.r,
|
||||
goldG: color.g,
|
||||
goldB: color.b,
|
||||
vx: (Math.random() - 0.5) * 0.25,
|
||||
vy: (Math.random() - 0.5) * 0.25,
|
||||
twinkleSpeed: 0.006 + Math.random() * 0.018,
|
||||
twinklePhase: Math.random() * Math.PI * 2,
|
||||
};
|
||||
}
|
||||
|
||||
for (let i = 0; i < particleCount; i++) {
|
||||
particles.push(createParticle());
|
||||
}
|
||||
|
||||
function renderFrame() {
|
||||
if (!ctx) return;
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
|
||||
for (const p of particles) {
|
||||
p.twinklePhase += p.twinkleSpeed;
|
||||
const currentOpacity = Math.max(
|
||||
0.05,
|
||||
p.baseOpacity + Math.sin(p.twinklePhase) * 0.25,
|
||||
);
|
||||
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2);
|
||||
|
||||
// Soft bokeh glow
|
||||
ctx.shadowBlur = p.blur;
|
||||
ctx.shadowColor = `rgba(${p.goldR}, ${p.goldG}, ${p.goldB}, ${currentOpacity})`;
|
||||
ctx.fillStyle = `rgba(${p.goldR}, ${p.goldG}, ${p.goldB}, ${currentOpacity})`;
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
|
||||
if (!prefersReducedMotion) {
|
||||
p.x += p.vx;
|
||||
p.y += p.vy;
|
||||
|
||||
// Wrap edges
|
||||
if (p.x < -10) p.x = width + 10;
|
||||
if (p.x > width + 10) p.x = -10;
|
||||
if (p.y < -10) p.y = height + 10;
|
||||
if (p.y > height + 10) p.y = -10;
|
||||
}
|
||||
}
|
||||
|
||||
if (!prefersReducedMotion) {
|
||||
animationFrameId = requestAnimationFrame(renderFrame);
|
||||
}
|
||||
}
|
||||
|
||||
// Initial render
|
||||
renderFrame();
|
||||
|
||||
function handleResize() {
|
||||
if (!canvas) return;
|
||||
canvas.width = window.innerWidth;
|
||||
canvas.height = window.innerHeight;
|
||||
width = canvas.width;
|
||||
height = canvas.height;
|
||||
if (prefersReducedMotion) {
|
||||
renderFrame();
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("resize", handleResize);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("resize", handleResize);
|
||||
if (animationFrameId) {
|
||||
cancelAnimationFrame(animationFrameId);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
style={{
|
||||
position: "fixed",
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
pointerEvents: "none",
|
||||
zIndex: 0,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
interface RsvpCtaProps {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
export function RsvpCta({ label, onClick }: RsvpCtaProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
style={{
|
||||
display: "inline-flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
background: "none",
|
||||
border: "none",
|
||||
color: "var(--color-gold-light)",
|
||||
cursor: "pointer",
|
||||
padding: "0.8rem 1.4rem",
|
||||
borderRadius: "8px",
|
||||
outline: "none",
|
||||
transition: "all 0.25s ease",
|
||||
}}
|
||||
onFocus={(e) => {
|
||||
e.currentTarget.style.boxShadow = "0 0 0 2px var(--color-gold-border-focus)";
|
||||
}}
|
||||
onBlur={(e) => {
|
||||
e.currentTarget.style.boxShadow = "none";
|
||||
}}
|
||||
aria-label={`${label} — Desplazarse al formulario de confirmación`}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
fontSize: "0.75rem",
|
||||
fontWeight: 600,
|
||||
letterSpacing: "0.26em",
|
||||
textTransform: "uppercase",
|
||||
marginBottom: "0.5rem",
|
||||
transition: "letter-spacing 0.2s ease, color 0.2s ease",
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
<span
|
||||
style={{
|
||||
fontSize: "1.2rem",
|
||||
lineHeight: 1,
|
||||
animation: "bounceSoft 2s infinite ease-in-out",
|
||||
}}
|
||||
aria-hidden="true"
|
||||
>
|
||||
↓
|
||||
</span>
|
||||
<style>{`
|
||||
@keyframes bounceSoft {
|
||||
0%, 100% { transform: translateY(0); }
|
||||
50% { transform: translateY(5px); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
span { animation: none !important; }
|
||||
}
|
||||
`}</style>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user