Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
713a582769 | ||
|
|
d9b589ccda | ||
|
|
b0dea63c3f | ||
|
|
f20fb0fc98 | ||
|
|
d7618d574c | ||
|
|
670f4f836d | ||
|
|
b2cee24472 | ||
|
|
79c3e8252c | ||
|
|
42927b9858 | ||
|
|
338dc20126 | ||
|
|
6880b74b60 | ||
|
|
c44ecfc14b | ||
|
|
c8264b3d76 | ||
|
|
818413b4f4 |
No files matched your search
@@ -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
|
||||||
+1
-1
@@ -73,7 +73,7 @@
|
|||||||
## Future
|
## Future
|
||||||
|
|
||||||
- [ ] Font selection (visual comparison of candidates)
|
- [ ] Font selection (visual comparison of candidates)
|
||||||
- [ ] Application-owned map preview asset (replace URL with static file)
|
- [x] Application-owned map preview asset (replace URL with static file)
|
||||||
- [ ] Miniature rendered invitation preview in admin config editor
|
- [ ] Miniature rendered invitation preview in admin config editor
|
||||||
- [ ] Enhanced admin features (edit/delete RSVP, attendance status, guest count)
|
- [ ] Enhanced admin features (edit/delete RSVP, attendance status, guest count)
|
||||||
- [ ] CSV import
|
- [ ] CSV import
|
||||||
@@ -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,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,215 @@
|
|||||||
|
from typing import Literal, Optional
|
||||||
|
|
||||||
|
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: Optional[SessionStore] = None,
|
||||||
|
cookie_secure: Optional[bool] = None,
|
||||||
|
cookie_samesite: Optional[Literal["lax", "strict", "none"]] = None,
|
||||||
|
session_max_age: Optional[int] = None,
|
||||||
|
secret_key: Optional[str] = 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: Optional[str]) -> Optional[str]:
|
||||||
|
"""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) -> Optional[Identity]:
|
||||||
|
"""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()
|
||||||
|
try:
|
||||||
|
return self.oidc_client.extract_identity_from_token(token)
|
||||||
|
except Exception:
|
||||||
|
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
|
||||||
|
try:
|
||||||
|
return self.oidc_client.extract_identity_from_token(raw_cookie)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def set_session_cookie(
|
||||||
|
self,
|
||||||
|
response: Response,
|
||||||
|
session_id: str,
|
||||||
|
max_age: Optional[int] = 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: Optional[Identity] = None,
|
||||||
|
request: Optional[Request] = None,
|
||||||
|
response: Optional[Response] = None,
|
||||||
|
pre_auth_session_id: Optional[str] = None,
|
||||||
|
max_age_seconds: Optional[int] = 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,106 @@
|
|||||||
|
from collections.abc import Callable
|
||||||
|
from typing import Annotated, Optional, 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: Optional[OIDCAuthAdapter] = 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: OIDCAuthAdapter = Depends(get_auth_adapter),
|
||||||
|
) -> Optional[Identity]:
|
||||||
|
"""Resolves the active Identity from the session/adapter, or None if unauthenticated."""
|
||||||
|
resolved_adapter: OIDCAuthAdapter = (
|
||||||
|
get_auth_adapter() if isinstance(cast(object, adapter), DependsClass) else adapter
|
||||||
|
)
|
||||||
|
return resolved_adapter.current_identity(request)
|
||||||
|
|
||||||
|
|
||||||
|
def require_authenticated(
|
||||||
|
identity: Optional[Identity] = Depends(get_current_identity),
|
||||||
|
) -> Identity:
|
||||||
|
"""Enforces authentication, raising HTTP 401 Unauthorized if anonymous."""
|
||||||
|
if isinstance(cast(object, identity), DependsClass) or identity is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="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: Identity = Depends(require_authenticated),
|
||||||
|
) -> 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[Optional[Identity], 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,36 @@
|
|||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
@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: Optional[str] = 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,672 @@
|
|||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import secrets
|
||||||
|
import string
|
||||||
|
import time
|
||||||
|
import urllib.parse
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from fastapi import HTTPException, status
|
||||||
|
import httpx
|
||||||
|
import jwt
|
||||||
|
|
||||||
|
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: Optional[str] = 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: Optional[str] = None
|
||||||
|
refresh_token: Optional[str] = None
|
||||||
|
token_type: Optional[str] = None
|
||||||
|
expires_in: Optional[int] = 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: Optional[OIDCConfig] = None,
|
||||||
|
*,
|
||||||
|
issuer: Optional[str] = None,
|
||||||
|
client_id: Optional[str] = None,
|
||||||
|
client_secret: Optional[str] = None,
|
||||||
|
redirect_uri: Optional[str] = None,
|
||||||
|
scopes: Optional[list[str]] = None,
|
||||||
|
groups_claim: Optional[str] = None,
|
||||||
|
discovery_doc: Optional[dict[str, Any]] = 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: Optional[dict[str, Any]] = discovery_doc
|
||||||
|
self._jwks_client: Optional[jwt.PyJWKClient] = 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) -> Optional[str]:
|
||||||
|
doc = self.get_discovery_document()
|
||||||
|
val = doc.get("userinfo_endpoint")
|
||||||
|
return str(val) if val else None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def end_session_endpoint(self) -> Optional[str]:
|
||||||
|
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: Optional[str]) -> 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: Optional[str] = None,
|
||||||
|
nonce: Optional[str] = None,
|
||||||
|
code_verifier: Optional[str] = None,
|
||||||
|
scopes: Optional[list[str]] = None,
|
||||||
|
extra_params: Optional[dict[str, str]] = 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:
|
||||||
|
try:
|
||||||
|
jwk_set = jwks_client.get_jwk_set()
|
||||||
|
if jwk_set and len(jwk_set.keys) == 1:
|
||||||
|
return jwk_set.keys[0]
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
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: Optional[str] = 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: Optional[str] = None,
|
||||||
|
code_verifier: Optional[str] = None,
|
||||||
|
nonce: Optional[str] = None,
|
||||||
|
extra_token_params: Optional[dict[str, str]] = 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: Optional[httpx.BasicAuth] = 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] = {}
|
||||||
|
try:
|
||||||
|
parsed = response.json()
|
||||||
|
if isinstance(parsed, dict):
|
||||||
|
error_data = parsed
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
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: Optional[str] = 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: Optional[list[str]] = 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: Optional[httpx.BasicAuth] = 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 Optional, 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) -> Optional[Identity]:
|
||||||
|
"""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,181 @@
|
|||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import secrets
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any, Optional, Protocol, runtime_checkable
|
||||||
|
|
||||||
|
from .identity import Identity
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SessionData:
|
||||||
|
"""Represents an application-level browser session."""
|
||||||
|
|
||||||
|
session_id: str
|
||||||
|
identity: Optional[Identity] = 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: Optional[float] = 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: Optional[Identity] = None,
|
||||||
|
max_age_seconds: int = 86400,
|
||||||
|
pre_auth_session_id: Optional[str] = None,
|
||||||
|
metadata: Optional[dict[str, Any]] = 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) -> Optional[SessionData]:
|
||||||
|
"""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: Optional[Identity] = None,
|
||||||
|
max_age_seconds: int = 86400,
|
||||||
|
pre_auth_session_id: Optional[str] = None,
|
||||||
|
metadata: Optional[dict[str, Any]] = 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) -> Optional[SessionData]:
|
||||||
|
"""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: Optional[str], secret_key: str) -> Optional[str]:
|
||||||
|
"""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",
|
||||||
|
]
|
||||||
@@ -1,14 +1,70 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
|
"""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_NAME: str = "bdinvite"
|
||||||
SERVICE_DOMAIN: str = "demos.roadtotech.me"
|
SERVICE_DOMAIN: str = "demos.roadtotech.me"
|
||||||
BASE_PATH: str = "/birthday"
|
BASE_PATH: str = "/birthday"
|
||||||
APP_PORT: int = 8000
|
APP_PORT: int = 8000
|
||||||
DATABASE_URL: str = "sqlite:///./data/bdinvite.db"
|
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")
|
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()
|
settings = Settings()
|
||||||
|
|
||||||
+31
-4
@@ -8,8 +8,9 @@ from fastapi.middleware.cors import CORSMiddleware
|
|||||||
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
|
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
|
||||||
|
from .config import settings
|
||||||
from .database import Base, SessionLocal, engine
|
from .database import Base, SessionLocal, engine
|
||||||
from .routes import admin, config, rsvp
|
from .routes import admin, auth, config, rsvp
|
||||||
from .services.config import seed_default_config
|
from .services.config import seed_default_config
|
||||||
|
|
||||||
|
|
||||||
@@ -30,8 +31,8 @@ app = FastAPI(
|
|||||||
"API REST para la invitación interactiva de cumpleaños con sistema RSVP.\n\n"
|
"API REST para la invitación interactiva de cumpleaños con sistema RSVP.\n\n"
|
||||||
"### Arquitectura de Seguridad\n"
|
"### Arquitectura de Seguridad\n"
|
||||||
"- **Rutas Públicas (`/birthday/api/*`)**: Acceso abierto para los invitados.\n"
|
"- **Rutas Públicas (`/birthday/api/*`)**: Acceso abierto para los invitados.\n"
|
||||||
"- **Rutas Administrativas (`/birthday/api/admin/*`)**: Protegidas por **Authelia ForwardAuth** "
|
"- **Rutas Administrativas (`/birthday/api/admin/*`)**: Protegidas por autenticación de sesión OIDC "
|
||||||
"a nivel de proxy inverso (Traefik). Cada endpoint valida de forma independiente la cabecera `Remote-User`."
|
"y autorización basada en grupos (`bdinvite_admins`)."
|
||||||
),
|
),
|
||||||
openapi_tags=[
|
openapi_tags=[
|
||||||
{
|
{
|
||||||
@@ -44,7 +45,7 @@ app = FastAPI(
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "Admin",
|
"name": "Admin",
|
||||||
"description": "Gestión de asistentes, descarga CSV y edición de contenido protegida por Authelia.",
|
"description": "Gestión de asistentes, descarga CSV y edición de contenido protegida por autenticación y grupo administrativo.",
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
lifespan=lifespan,
|
lifespan=lifespan,
|
||||||
@@ -89,11 +90,37 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
|
|||||||
# Register API routes with exact path prefixes per specification
|
# Register API routes with exact path prefixes per specification
|
||||||
app.include_router(rsvp.router, prefix="/birthday/api")
|
app.include_router(rsvp.router, prefix="/birthday/api")
|
||||||
app.include_router(config.router, prefix="/birthday/api")
|
app.include_router(config.router, prefix="/birthday/api")
|
||||||
|
app.include_router(auth.router, prefix="/birthday/api")
|
||||||
app.include_router(admin.router, prefix="/birthday/api/admin")
|
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 files and SPA serving
|
||||||
STATIC_DIR = os.path.join(os.path.dirname(__file__), "..", "static")
|
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")
|
ASSETS_DIR = os.path.join(STATIC_DIR, "assets")
|
||||||
|
|
||||||
if os.path.isdir(ASSETS_DIR):
|
if os.path.isdir(ASSETS_DIR):
|
||||||
|
|||||||
+184
-33
@@ -1,49 +1,41 @@
|
|||||||
import csv
|
import csv
|
||||||
import io
|
import io
|
||||||
|
from datetime import UTC, datetime
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Response
|
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..auth import Identity, require_admin
|
||||||
|
from ..config import settings
|
||||||
from ..database import get_db
|
from ..database import get_db
|
||||||
from ..schemas import (
|
from ..schemas import (
|
||||||
|
GenerateMapPreviewRequest,
|
||||||
|
GenerateMapPreviewResponse,
|
||||||
InvitationConfigResponse,
|
InvitationConfigResponse,
|
||||||
InvitationConfigUpdate,
|
InvitationConfigUpdate,
|
||||||
|
RSVPAdminItem,
|
||||||
RSVPListResponse,
|
RSVPListResponse,
|
||||||
|
RSVPUpdate,
|
||||||
)
|
)
|
||||||
from ..services.config import get_config, seed_default_config, update_config
|
from ..services.config import get_config, seed_default_config, update_config
|
||||||
from ..services.rsvp import get_rsvps
|
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"])
|
router = APIRouter(tags=["Admin"])
|
||||||
|
|
||||||
|
AdminDep = Annotated[Identity, Depends(require_admin)]
|
||||||
def require_admin(
|
|
||||||
remote_user: Annotated[
|
|
||||||
str | None,
|
|
||||||
Header(
|
|
||||||
alias="Remote-User",
|
|
||||||
description="Identidad de usuario autenticada e inyectada por Authelia ForwardAuth en el proxy Traefik",
|
|
||||||
examples=["kiskaadee"],
|
|
||||||
),
|
|
||||||
] = None,
|
|
||||||
) -> str:
|
|
||||||
"""Security invariant: require verified Remote-User header from Authelia."""
|
|
||||||
if not remote_user:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=401,
|
|
||||||
detail="Not authenticated",
|
|
||||||
)
|
|
||||||
return remote_user
|
|
||||||
|
|
||||||
|
|
||||||
AdminDep = Annotated[str, Depends(require_admin)]
|
|
||||||
DbDep = Annotated[Session, Depends(get_db)]
|
DbDep = Annotated[Session, Depends(get_db)]
|
||||||
|
|
||||||
ADMIN_401 = {
|
ADMIN_RESPONSES = {
|
||||||
401: {
|
401: {"description": "No autenticado. Se requiere sesión activa de usuario."},
|
||||||
"description": "No autenticado. Se requiere la cabecera `Remote-User` provista por Authelia ForwardAuth."
|
403: {"description": "Acceso denegado. Se requiere pertenecer al grupo 'bdinvite_admins'."},
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
ADMIN_401 = ADMIN_RESPONSES
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
@@ -56,7 +48,7 @@ ADMIN_401 = {
|
|||||||
),
|
),
|
||||||
responses={
|
responses={
|
||||||
200: {"model": RSVPListResponse, "description": "Lista de confirmaciones obtenida."},
|
200: {"model": RSVPListResponse, "description": "Lista de confirmaciones obtenida."},
|
||||||
**ADMIN_401,
|
**ADMIN_RESPONSES,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
def list_rsvps(
|
def list_rsvps(
|
||||||
@@ -77,6 +69,67 @@ def list_rsvps(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@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(
|
@router.get(
|
||||||
"/export",
|
"/export",
|
||||||
summary="Exportar confirmaciones en formato CSV",
|
summary="Exportar confirmaciones en formato CSV",
|
||||||
@@ -89,7 +142,7 @@ def list_rsvps(
|
|||||||
"content": {"text/csv": {}},
|
"content": {"text/csv": {}},
|
||||||
"description": "Descarga del archivo CSV `rsvps.csv`.",
|
"description": "Descarga del archivo CSV `rsvps.csv`.",
|
||||||
},
|
},
|
||||||
**ADMIN_401,
|
**ADMIN_RESPONSES,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
def export_rsvps_csv(
|
def export_rsvps_csv(
|
||||||
@@ -103,7 +156,10 @@ def export_rsvps_csv(
|
|||||||
writer.writerow(["name", "phone", "email", "created_at"])
|
writer.writerow(["name", "phone", "email", "created_at"])
|
||||||
|
|
||||||
for item in rsvps:
|
for item in rsvps:
|
||||||
created_iso = item.created_at.isoformat() if item.created_at else ""
|
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])
|
writer.writerow([item.name, item.phone, item.email or "", created_iso])
|
||||||
|
|
||||||
csv_content = output.getvalue()
|
csv_content = output.getvalue()
|
||||||
@@ -121,7 +177,7 @@ def export_rsvps_csv(
|
|||||||
description="Retorna el objeto completo de configuración para poblar el formulario de administración.",
|
description="Retorna el objeto completo de configuración para poblar el formulario de administración.",
|
||||||
responses={
|
responses={
|
||||||
200: {"model": InvitationConfigResponse, "description": "Configuración obtenida correctamente."},
|
200: {"model": InvitationConfigResponse, "description": "Configuración obtenida correctamente."},
|
||||||
**ADMIN_401,
|
**ADMIN_RESPONSES,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
def get_admin_config(
|
def get_admin_config(
|
||||||
@@ -140,18 +196,113 @@ def get_admin_config(
|
|||||||
summary="Actualizar configuración de la invitación",
|
summary="Actualizar configuración de la invitación",
|
||||||
description=(
|
description=(
|
||||||
"Reemplaza los valores de la configuración singleton del evento. "
|
"Reemplaza los valores de la configuración singleton del evento. "
|
||||||
|
"Si la URL de Google Maps cambió, valida y regenera automáticamente la vista previa del mapa. "
|
||||||
"Aplica validación de fecha ISO, hora en formato militar 24h y zona horaria válida IANA. "
|
"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."
|
"Los cambios toman efecto de inmediato sin requerir recarga del contenedor."
|
||||||
),
|
),
|
||||||
responses={
|
responses={
|
||||||
200: {"model": InvitationConfigResponse, "description": "Configuración actualizada con éxito."},
|
200: {"model": InvitationConfigResponse, "description": "Configuración actualizada con éxito."},
|
||||||
**ADMIN_401,
|
**ADMIN_RESPONSES,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
def update_admin_config(
|
@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,
|
update_in: InvitationConfigUpdate,
|
||||||
admin: AdminDep,
|
admin: AdminDep,
|
||||||
db: DbDep,
|
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)
|
updated = update_config(db, update_in)
|
||||||
return updated
|
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,145 @@
|
|||||||
|
from typing import Annotated, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, status
|
||||||
|
from fastapi.responses import JSONResponse, RedirectResponse
|
||||||
|
|
||||||
|
from ..auth import Identity, OIDCAuthAdapter
|
||||||
|
from ..auth.dependencies import get_auth_adapter
|
||||||
|
from ..schemas import LoginRequest, UserResponse
|
||||||
|
|
||||||
|
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: Optional[Identity] = 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"]
|
||||||
+134
-2
@@ -1,9 +1,28 @@
|
|||||||
import re
|
import re
|
||||||
from datetime import date, datetime
|
from datetime import UTC, date, datetime
|
||||||
from typing import Literal
|
from typing import Literal
|
||||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
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):
|
class RSVPCreate(BaseModel):
|
||||||
@@ -36,6 +55,11 @@ class RSVPCreate(BaseModel):
|
|||||||
raise ValueError("El nombre no puede estar vacío.")
|
raise ValueError("El nombre no puede estar vacío.")
|
||||||
return cleaned
|
return cleaned
|
||||||
|
|
||||||
|
@field_validator("phone")
|
||||||
|
@classmethod
|
||||||
|
def validate_phone(cls, v: str) -> str:
|
||||||
|
return normalize_phone(v)
|
||||||
|
|
||||||
@field_validator("email")
|
@field_validator("email")
|
||||||
@classmethod
|
@classmethod
|
||||||
def validate_email(cls, v: str | None) -> str | None:
|
def validate_email(cls, v: str | None) -> str | None:
|
||||||
@@ -50,6 +74,61 @@ class RSVPCreate(BaseModel):
|
|||||||
return cleaned.lower()
|
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):
|
class RSVPSuccessResponse(BaseModel):
|
||||||
result: Literal["SUCCESS"] = Field(
|
result: Literal["SUCCESS"] = Field(
|
||||||
default="SUCCESS",
|
default="SUCCESS",
|
||||||
@@ -97,6 +176,13 @@ class RSVPAdminItem(BaseModel):
|
|||||||
|
|
||||||
model_config = ConfigDict(from_attributes=True)
|
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):
|
class RSVPListResponse(BaseModel):
|
||||||
count: int = Field(..., description="Cantidad total de confirmaciones encontradas", examples=[37])
|
count: int = Field(..., description="Cantidad total de confirmaciones encontradas", examples=[37])
|
||||||
@@ -275,6 +361,15 @@ class InvitationConfigBase(BaseModel):
|
|||||||
raise ValueError(f"Zona horaria IANA desconocida: {clean}")
|
raise ValueError(f"Zona horaria IANA desconocida: {clean}")
|
||||||
return 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):
|
class InvitationConfigUpdate(InvitationConfigBase):
|
||||||
pass
|
pass
|
||||||
@@ -285,3 +380,40 @@ class InvitationConfigResponse(InvitationConfigBase):
|
|||||||
updated_at: datetime | None = Field(default=None, description="Última modificación en UTC")
|
updated_at: datetime | None = Field(default=None, description="Última modificación en UTC")
|
||||||
|
|
||||||
model_config = ConfigDict(from_attributes=True)
|
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,249 @@
|
|||||||
|
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") or clean_host.endswith(".google"):
|
||||||
|
return True
|
||||||
|
# Regional domains like google.es, google.co, google.com.co
|
||||||
|
if re.match(r"^(?:www\.)?google\.[a-z.]+$", clean_host):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
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 param in qs and qs[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 "q" in qs and qs["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:
|
||||||
|
try:
|
||||||
|
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
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
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"
|
||||||
|
try:
|
||||||
|
res = await client.get(tile_url)
|
||||||
|
if res.status_code == 200:
|
||||||
|
tile = Image.open(io.BytesIO(res.content)).convert("RGB")
|
||||||
|
canvas.paste(tile, (c_idx * 256, r_idx * 256))
|
||||||
|
except Exception:
|
||||||
|
# Keep neutral background tile if individual tile fails
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Exact target location within the 768x768 canvas
|
||||||
|
cx = 256 + int(dx * 256)
|
||||||
|
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
|
||||||
@@ -1,29 +1,9 @@
|
|||||||
import re
|
|
||||||
|
|
||||||
from sqlalchemy import or_, select
|
from sqlalchemy import or_, select
|
||||||
from sqlalchemy.exc import IntegrityError
|
from sqlalchemy.exc import IntegrityError
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from ..models import RSVP
|
from ..models import RSVP
|
||||||
from ..schemas import RSVPCreate
|
from ..schemas import RSVPCreate, RSVPUpdate, normalize_phone
|
||||||
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def create_rsvp(db: Session, rsvp_in: RSVPCreate) -> tuple[str, RSVP | None]:
|
def create_rsvp(db: Session, rsvp_in: RSVPCreate) -> tuple[str, RSVP | None]:
|
||||||
@@ -81,3 +61,57 @@ def get_rsvp_count(db: Session) -> int:
|
|||||||
"""Get total count of RSVPs."""
|
"""Get total count of RSVPs."""
|
||||||
query = select(RSVP)
|
query = select(RSVP)
|
||||||
return len(list(db.execute(query).scalars().all()))
|
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
|
||||||
|
|
||||||
|
|
||||||
@@ -9,6 +9,9 @@ dependencies = [
|
|||||||
"sqlalchemy>=2.0.0",
|
"sqlalchemy>=2.0.0",
|
||||||
"pydantic>=2.0.0",
|
"pydantic>=2.0.0",
|
||||||
"pydantic-settings>=2.0.0",
|
"pydantic-settings>=2.0.0",
|
||||||
|
"pillow>=10.0.0",
|
||||||
|
"httpx>=0.27.0",
|
||||||
|
"pyjwt[crypto]>=2.15.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
[dependency-groups]
|
[dependency-groups]
|
||||||
|
|||||||
@@ -41,3 +41,53 @@ def client(db_session):
|
|||||||
with TestClient(app) as test_client:
|
with TestClient(app) as test_client:
|
||||||
yield test_client
|
yield test_client
|
||||||
app.dependency_overrides.clear()
|
app.dependency_overrides.clear()
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
+196
-21
@@ -1,65 +1,133 @@
|
|||||||
def test_admin_endpoints_require_remote_user(client):
|
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 = [
|
endpoints = [
|
||||||
"/birthday/api/admin/rsvps",
|
("GET", "/birthday/api/admin/rsvps"),
|
||||||
"/birthday/api/admin/export",
|
("DELETE", "/birthday/api/admin/rsvps/1"),
|
||||||
"/birthday/api/admin/config",
|
("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 path in endpoints:
|
for method, path in endpoints:
|
||||||
res = client.get(path)
|
res = client.request(method, path)
|
||||||
assert res.status_code == 401, f"GET {path} should require Remote-User header"
|
assert res.status_code == 401, f"{method} {path} should require authentication"
|
||||||
assert res.json() == {"detail": "Not authenticated"}
|
assert res.json() == {"detail": "Not authenticated"}
|
||||||
|
|
||||||
|
|
||||||
def test_admin_list_and_search_rsvps(client):
|
def test_remote_user_header_strictly_ignored(client: TestClient):
|
||||||
headers = {"Remote-User": "kiskaadee"}
|
"""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
|
# Initially 0
|
||||||
res = client.get("/birthday/api/admin/rsvps", headers=headers)
|
res = admin_client.get("/birthday/api/admin/rsvps")
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
assert res.json()["count"] == 0
|
assert res.json()["count"] == 0
|
||||||
|
|
||||||
# Add 3 invitees
|
# Add 3 invitees
|
||||||
client.post(
|
admin_client.post(
|
||||||
"/birthday/api/rsvp",
|
"/birthday/api/rsvp",
|
||||||
json={"name": "Carlos Gomez", "phone": "300 111 2233", "email": "carlos@test.com"},
|
json={"name": "Carlos Gomez", "phone": "300 111 2233", "email": "carlos@test.com"},
|
||||||
)
|
)
|
||||||
client.post(
|
admin_client.post(
|
||||||
"/birthday/api/rsvp",
|
"/birthday/api/rsvp",
|
||||||
json={"name": "Maria Perez", "phone": "315 222 3344", "email": "maria@test.com"},
|
json={"name": "Maria Perez", "phone": "315 222 3344", "email": "maria@test.com"},
|
||||||
)
|
)
|
||||||
client.post(
|
admin_client.post(
|
||||||
"/birthday/api/rsvp",
|
"/birthday/api/rsvp",
|
||||||
json={"name": "Juan Gomez", "phone": "320 333 4455", "email": None},
|
json={"name": "Juan Gomez", "phone": "320 333 4455", "email": None},
|
||||||
)
|
)
|
||||||
|
|
||||||
# List all
|
# List all
|
||||||
res = client.get("/birthday/api/admin/rsvps", headers=headers)
|
res = admin_client.get("/birthday/api/admin/rsvps")
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
data = res.json()
|
data = res.json()
|
||||||
assert data["count"] == 3
|
assert data["count"] == 3
|
||||||
|
|
||||||
# Search by name
|
# Search by name
|
||||||
res_search = client.get("/birthday/api/admin/rsvps?search=Gomez", headers=headers)
|
res_search = admin_client.get("/birthday/api/admin/rsvps?search=Gomez")
|
||||||
assert res_search.status_code == 200
|
assert res_search.status_code == 200
|
||||||
search_data = res_search.json()
|
search_data = res_search.json()
|
||||||
assert search_data["count"] == 2
|
assert search_data["count"] == 2
|
||||||
|
|
||||||
# Search by phone substring
|
# Search by phone substring
|
||||||
res_phone = client.get("/birthday/api/admin/rsvps?search=315222", headers=headers)
|
res_phone = admin_client.get("/birthday/api/admin/rsvps?search=315222")
|
||||||
assert res_phone.status_code == 200
|
assert res_phone.status_code == 200
|
||||||
assert res_phone.json()["count"] == 1
|
assert res_phone.json()["count"] == 1
|
||||||
assert res_phone.json()["rsvps"][0]["name"] == "Maria Perez"
|
assert res_phone.json()["rsvps"][0]["name"] == "Maria Perez"
|
||||||
|
|
||||||
|
|
||||||
def test_admin_export_csv(client):
|
def test_admin_export_csv(admin_client: TestClient):
|
||||||
headers = {"Remote-User": "kiskaadee"}
|
admin_client.post(
|
||||||
|
|
||||||
client.post(
|
|
||||||
"/birthday/api/rsvp",
|
"/birthday/api/rsvp",
|
||||||
json={"name": "Sofia Vergara", "phone": "301 999 8877", "email": "sofia@hollywood.com"},
|
json={"name": "Sofia Vergara", "phone": "301 999 8877", "email": "sofia@hollywood.com"},
|
||||||
)
|
)
|
||||||
|
|
||||||
res = client.get("/birthday/api/admin/export", headers=headers)
|
res = admin_client.get("/birthday/api/admin/export")
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
assert res.headers["content-type"].startswith("text/csv")
|
assert res.headers["content-type"].startswith("text/csv")
|
||||||
assert 'filename="rsvps.csv"' in res.headers["content-disposition"]
|
assert 'filename="rsvps.csv"' in res.headers["content-disposition"]
|
||||||
@@ -68,3 +136,110 @@ def test_admin_export_csv(client):
|
|||||||
lines = content.strip().split("\r\n") if "\r\n" in content else content.strip().split("\n")
|
lines = content.strip().split("\r\n") if "\r\n" in content else content.strip().split("\n")
|
||||||
assert lines[0] == "name,phone,email,created_at"
|
assert lines[0] == "name,phone,email,created_at"
|
||||||
assert "Sofia Vergara,3019998877,sofia@hollywood.com" in lines[1]
|
assert "Sofia Vergara,3019998877,sofia@hollywood.com" in lines[1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_delete_rsvp(client: TestClient):
|
||||||
|
# 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,154 @@
|
|||||||
|
from dataclasses import FrozenInstanceError
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import Request, Response
|
||||||
|
from fastapi.responses import RedirectResponse
|
||||||
|
from starlette.datastructures import Headers
|
||||||
|
|
||||||
|
from app.auth import AuthPort, Identity
|
||||||
|
|
||||||
|
|
||||||
|
class MockAuthAdapter:
|
||||||
|
"""Mock implementation of AuthPort for testing hexagonal boundary compliance."""
|
||||||
|
|
||||||
|
def __init__(self, current_user: Optional[Identity] = None):
|
||||||
|
self._current_user = current_user
|
||||||
|
|
||||||
|
def current_identity(self, request: Request) -> Optional[Identity]:
|
||||||
|
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) -> Optional[Identity]:
|
||||||
|
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,128 @@
|
|||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from typing 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):
|
||||||
|
try:
|
||||||
|
r = httpx.get(f"{BASE_URL}/birthday/api/docs", timeout=0.5)
|
||||||
|
if r.status_code == 200:
|
||||||
|
ready = True
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
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()
|
||||||
|
|
||||||
|
# Verify navigation returns to unauthenticated state (redirect to OIDC authorize)
|
||||||
|
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
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
|
from tests.conftest import login_client
|
||||||
|
|
||||||
|
|
||||||
def test_get_config_public(client):
|
def test_get_config_public(client):
|
||||||
response = client.get("/birthday/api/config")
|
response = client.get("/birthday/api/config")
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
@@ -14,10 +17,8 @@ def test_get_config_admin(client):
|
|||||||
res_unauth = client.get("/birthday/api/admin/config")
|
res_unauth = client.get("/birthday/api/admin/config")
|
||||||
assert res_unauth.status_code == 401
|
assert res_unauth.status_code == 401
|
||||||
|
|
||||||
res_auth = client.get(
|
login_client(client)
|
||||||
"/birthday/api/admin/config",
|
res_auth = client.get("/birthday/api/admin/config")
|
||||||
headers={"Remote-User": "admin_user"},
|
|
||||||
)
|
|
||||||
assert res_auth.status_code == 200
|
assert res_auth.status_code == 200
|
||||||
assert res_auth.json()["honoree_name"] == "Isabelle Snow"
|
assert res_auth.json()["honoree_name"] == "Isabelle Snow"
|
||||||
|
|
||||||
@@ -46,15 +47,15 @@ def test_update_config_requires_admin(client):
|
|||||||
"countdown_in_progress": "EN VIVO",
|
"countdown_in_progress": "EN VIVO",
|
||||||
"countdown_finished": "TERMINADO",
|
"countdown_finished": "TERMINADO",
|
||||||
}
|
}
|
||||||
# Without Remote-User header -> 401
|
# Without session -> 401
|
||||||
res = client.put("/birthday/api/admin/config", json=update_payload)
|
res = client.put("/birthday/api/admin/config", json=update_payload)
|
||||||
assert res.status_code == 401
|
assert res.status_code == 401
|
||||||
|
|
||||||
# With Remote-User header -> 200
|
# With admin session -> 200
|
||||||
|
login_client(client)
|
||||||
res_auth = client.put(
|
res_auth = client.put(
|
||||||
"/birthday/api/admin/config",
|
"/birthday/api/admin/config",
|
||||||
json=update_payload,
|
json=update_payload,
|
||||||
headers={"Remote-User": "admin_user"},
|
|
||||||
)
|
)
|
||||||
assert res_auth.status_code == 200
|
assert res_auth.status_code == 200
|
||||||
data = res_auth.json()
|
data = res_auth.json()
|
||||||
@@ -68,7 +69,7 @@ def test_update_config_requires_admin(client):
|
|||||||
assert res_pub.json()["title"] == "Fiesta de Cumpleaños"
|
assert res_pub.json()["title"] == "Fiesta de Cumpleaños"
|
||||||
|
|
||||||
|
|
||||||
def test_update_config_invalid_timezone(client):
|
def test_update_config_invalid_timezone(admin_client):
|
||||||
invalid_payload = {
|
invalid_payload = {
|
||||||
"title": "Party",
|
"title": "Party",
|
||||||
"invitation_text": "Invited",
|
"invitation_text": "Invited",
|
||||||
@@ -92,10 +93,9 @@ def test_update_config_invalid_timezone(client):
|
|||||||
"countdown_in_progress": "CURSO",
|
"countdown_in_progress": "CURSO",
|
||||||
"countdown_finished": "FIN",
|
"countdown_finished": "FIN",
|
||||||
}
|
}
|
||||||
res = client.put(
|
res = admin_client.put(
|
||||||
"/birthday/api/admin/config",
|
"/birthday/api/admin/config",
|
||||||
json=invalid_payload,
|
json=invalid_payload,
|
||||||
headers={"Remote-User": "admin_user"},
|
|
||||||
)
|
)
|
||||||
assert res.status_code == 422
|
assert res.status_code == 422
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,438 @@
|
|||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import Depends, FastAPI, HTTPException, Request
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
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: Optional[dict[str, str]] = None,
|
||||||
|
cookies: Optional[dict[str, str]] = 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")
|
||||||
|
|
||||||
|
@app.get("/test/identity")
|
||||||
|
def route_identity(identity: Optional[Identity] = 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: Identity = Depends(require_authenticated)):
|
||||||
|
return {
|
||||||
|
"subject": identity.subject,
|
||||||
|
"email": identity.email,
|
||||||
|
"groups": identity.groups,
|
||||||
|
}
|
||||||
|
|
||||||
|
@app.get("/test/admin")
|
||||||
|
def route_admin(admin: Identity = Depends(require_admin)):
|
||||||
|
return {
|
||||||
|
"subject": admin.subject,
|
||||||
|
"email": admin.email,
|
||||||
|
"groups": admin.groups,
|
||||||
|
}
|
||||||
|
|
||||||
|
@app.get("/test/custom-group")
|
||||||
|
def route_custom_group(member: Identity = Depends(require_group("event_planners"))):
|
||||||
|
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,335 @@
|
|||||||
|
from dataclasses import FrozenInstanceError
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import Request, Response
|
||||||
|
from fastapi.responses import RedirectResponse
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.auth import (
|
||||||
|
AuthPort,
|
||||||
|
Identity,
|
||||||
|
InvalidTokenError,
|
||||||
|
OIDCAuthAdapter,
|
||||||
|
OIDCClient,
|
||||||
|
OIDCConfig,
|
||||||
|
TokenExchangeError,
|
||||||
|
)
|
||||||
|
|
||||||
|
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: Optional[dict[str, str]] = None,
|
||||||
|
cookies: Optional[dict[str, str]] = 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,150 @@
|
|||||||
|
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,306 @@
|
|||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import urllib.parse
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.auth import (
|
||||||
|
Identity,
|
||||||
|
InvalidStateError,
|
||||||
|
InvalidTokenError,
|
||||||
|
MismatchedNonceError,
|
||||||
|
OIDCClient,
|
||||||
|
OIDCConfig,
|
||||||
|
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,432 @@
|
|||||||
|
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,416 @@
|
|||||||
|
import time
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import Request, Response
|
||||||
|
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.config import settings
|
||||||
|
from app.main import app
|
||||||
|
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
+281
@@ -53,8 +53,11 @@ version = "0.1.0"
|
|||||||
source = { virtual = "." }
|
source = { virtual = "." }
|
||||||
dependencies = [
|
dependencies = [
|
||||||
{ name = "fastapi", extra = ["standard"] },
|
{ name = "fastapi", extra = ["standard"] },
|
||||||
|
{ name = "httpx" },
|
||||||
|
{ name = "pillow" },
|
||||||
{ name = "pydantic" },
|
{ name = "pydantic" },
|
||||||
{ name = "pydantic-settings" },
|
{ name = "pydantic-settings" },
|
||||||
|
{ name = "pyjwt", extra = ["crypto"] },
|
||||||
{ name = "sqlalchemy" },
|
{ name = "sqlalchemy" },
|
||||||
{ name = "uvicorn" },
|
{ name = "uvicorn" },
|
||||||
]
|
]
|
||||||
@@ -70,8 +73,11 @@ dev = [
|
|||||||
[package.metadata]
|
[package.metadata]
|
||||||
requires-dist = [
|
requires-dist = [
|
||||||
{ name = "fastapi", extras = ["standard"], specifier = ">=0.115.0" },
|
{ name = "fastapi", extras = ["standard"], specifier = ">=0.115.0" },
|
||||||
|
{ name = "httpx", specifier = ">=0.27.0" },
|
||||||
|
{ name = "pillow", specifier = ">=10.0.0" },
|
||||||
{ name = "pydantic", specifier = ">=2.0.0" },
|
{ name = "pydantic", specifier = ">=2.0.0" },
|
||||||
{ name = "pydantic-settings", specifier = ">=2.0.0" },
|
{ name = "pydantic-settings", specifier = ">=2.0.0" },
|
||||||
|
{ name = "pyjwt", extras = ["crypto"], specifier = ">=2.15.1" },
|
||||||
{ name = "sqlalchemy", specifier = ">=2.0.0" },
|
{ name = "sqlalchemy", specifier = ">=2.0.0" },
|
||||||
{ name = "uvicorn", specifier = ">=0.30.0" },
|
{ name = "uvicorn", specifier = ">=0.30.0" },
|
||||||
]
|
]
|
||||||
@@ -93,6 +99,104 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" },
|
{ url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cffi"
|
||||||
|
version = "2.1.1"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "pycparser", marker = "implementation_name != 'PyPy'" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/70/d2/16d99a0c4948febc0ebd133a13b2f688ff7f8cb04da971e1128872ce0c03/cffi-2.1.1-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12", size = 183838, upload-time = "2026-08-03T21:19:29.637Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/cd/95/31b535a9f0220ae9f357de4a08d57ce89cb417653c2fd9f075f50822a388/cffi-2.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1", size = 184168, upload-time = "2026-08-03T21:19:30.764Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/ad/5a/4707a0dc1f203f5dde5a907b0d4e3c25d71120241048bd5bc6f1bb9d4e71/cffi-2.1.1-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0", size = 211805, upload-time = "2026-08-03T21:19:31.867Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/ad/66/c19feabb28485b6e0bbaaafa90837a1ef5d302e90f2178bd33f17a49879b/cffi-2.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813", size = 218716, upload-time = "2026-08-03T21:19:32.896Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a7/92/500760486c8baab49a7a8a58ba7fc3355ec3974b454b8a09e528efde9e1d/cffi-2.1.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990", size = 205569, upload-time = "2026-08-03T21:19:34.142Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a5/a7/a67c733254d6e7373f7822f8082d8d6beade791e0cf12a7611f376fa61c7/cffi-2.1.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af", size = 204907, upload-time = "2026-08-03T21:19:35.174Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/f7/a4/4399daaf8f7dfee9d7c3327fdb0426ee041cc63edc358b93911ceb2bfc7a/cffi-2.1.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632", size = 217807, upload-time = "2026-08-03T21:19:36.286Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/28/f7/dabe6da2466ecbd82dc62e7342dc6b1065dad990c06f00f0ede9ebf2a0ed/cffi-2.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd", size = 221252, upload-time = "2026-08-03T21:19:37.416Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/ce/87/616202d8e51342c07d2534c510111c4cc37201775ce8f60802c9335d1edd/cffi-2.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a", size = 214214, upload-time = "2026-08-03T21:19:38.507Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/b4/c6/ab025d75d2c26c19b087c0124e75ee31cb65032f4fe345d356d8c507ab97/cffi-2.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa", size = 219408, upload-time = "2026-08-03T21:19:39.809Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/db/e2/7e8109f65445bdc673a7b54f02c677de462db75674220fd1335efc8eb598/cffi-2.1.1-cp311-cp311-win32.whl", hash = "sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3", size = 174470, upload-time = "2026-08-03T21:19:41.246Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/73/c0/77ba02423c2f7d7091143c45cd49e0e6575c4c1967394bb542bd923a9b74/cffi-2.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0", size = 185096, upload-time = "2026-08-03T21:19:42.615Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/7c/47/9f1f85f9672ceda4984dc6c4f8824e8558992a2972c3d3c81fb8eb28d4ba/cffi-2.1.1-cp311-cp311-win_arm64.whl", hash = "sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455", size = 179941, upload-time = "2026-08-03T21:19:43.747Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/10/69/43965eccfdead3b9220015fd1320e117be8c6ed01a62ffab76eeb752f5d5/cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0", size = 184821, upload-time = "2026-08-03T21:19:44.887Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/54/7d/16e5a096677b5e313ca80cd5e5170efa3ea44624a82bb111925522da64b1/cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf", size = 184719, upload-time = "2026-08-03T21:19:46.129Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/80/fb/0bb75b7039588c074b37ae99f40d9bfddf990ecb2fbc346ebccd2e56b9be/cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e", size = 175292, upload-time = "2026-08-03T21:19:55.566Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d9/79/615cc094e2fb508cade7de88d3b4f6c4ec2bab695c97bce9153dc65aadf5/cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a", size = 185919, upload-time = "2026-08-03T21:19:56.89Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/70/c6/d0ea84713fe46b243a436a18fcd47d639732747e21635c8a27191b06dc30/cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80", size = 180093, upload-time = "2026-08-03T21:19:58.155Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/9d/f4/035513d4117049066b4779dc3b7c0c0fdad175fa13731c9f4003f1cd1478/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e", size = 194248, upload-time = "2026-08-03T21:19:59.399Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/76/af/2aeb4dbb5fc41a04161ae9ff1518de7cec08e164f44a8ce6a4cf7fd2cd1d/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c", size = 196908, upload-time = "2026-08-03T21:20:00.746Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a7/46/2e5fdde8555706dd98139a910ca11be02809f3f605ce956f655d0214e100/cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6", size = 184805, upload-time = "2026-08-03T21:20:02.02Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/55/41/4c7042f317b9217502988f0873af87e16ad606dc20f84e546e3e6ce9764c/cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971", size = 184764, upload-time = "2026-08-03T21:20:03.141Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/43/1f/1c3d90d91811c8f86ced9ed637956c54bfe5b79ca98fe976d7f8c8979f6b/cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c", size = 214722, upload-time = "2026-08-03T21:20:04.377Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/37/6f/3b5ce4c3b2192d250f04908f2bfd91ef34552ec8f7716a5d4abdb8d67bb2/cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125", size = 222369, upload-time = "2026-08-03T21:20:05.544Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/02/10/4b3c75dde3d9663c9e02ba05c2668b954f671d4bbe346413ca8c696b295a/cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264", size = 210175, upload-time = "2026-08-03T21:20:06.75Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/df/62/14f74b9543e605d17701dc797b815958b8bb70b7624ce1b832ddad48ed6c/cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3", size = 208670, upload-time = "2026-08-03T21:20:08.04Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/95/95/86342356ff5953b3fb06f7ef7c5bee212d45e770abc7218d451b9148313c/cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2", size = 221824, upload-time = "2026-08-03T21:20:09.274Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/eb/ff/7b3429ff53aafe931ed8a5fc69f481bbef7ba6de87ddcbb63d08f483f613/cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b", size = 225148, upload-time = "2026-08-03T21:20:10.7Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/34/34/a95870b9221e09cf4f2ce3178b1a210abdfe63a1bd357da940418d7b8d15/cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7", size = 223564, upload-time = "2026-08-03T21:20:12.165Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/70/ea/839b50531021a647fb5e929f72cf97bc1ff702b5472166164b5b6e76b851/cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac", size = 175263, upload-time = "2026-08-03T21:20:13.559Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/60/a6/8b149b2c3f2e11aaa1618ef64500b45f50f22c57a977a4dff1aff1f91042/cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d", size = 185688, upload-time = "2026-08-03T21:20:14.69Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/01/9a/11f687cb39d6a3504060d5242f04f48c735afb4d3d533958a20594890cb2/cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973", size = 180078, upload-time = "2026-08-03T21:20:15.917Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d3/7b/d6bbf82b8b96e7391438898c42f5bd96dd02030fd5b64937d248220003e2/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c", size = 194064, upload-time = "2026-08-03T21:20:17.148Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/94/e6/bcc91b283be94735e268487a054004f0aa19947b6348fa367db53230abc8/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb", size = 196720, upload-time = "2026-08-03T21:20:18.268Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d9/99/c4b0c17cacdc9c3b8f280026286a9826d6a208c0f047591a3c3ce99b91fd/cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54", size = 184964, upload-time = "2026-08-03T21:20:19.708Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/b3/a9/9db617d05d7367c1ad0ab00b3aa6e6f9281edd689b4ee9ea0e5a84e89c97/cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72", size = 184962, upload-time = "2026-08-03T21:20:20.833Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/67/b8/b42132ca113dc567d37684437b46ca1dafc885902b02a110a02d5b511857/cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1", size = 222328, upload-time = "2026-08-03T21:20:22.118Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/80/10/c5c0cbf0a657aecf59ef511409734230bf556f05a0d6c9eed7aa5c0a0166/cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062", size = 209985, upload-time = "2026-08-03T21:20:23.401Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d5/6c/bfa0b87b03b9238148beca990292843c9396ba069b54496596594173de7b/cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03", size = 208530, upload-time = "2026-08-03T21:20:24.628Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/e9/02/4e7d553a7ac4b4238b38b3c1b80d486e9d4436f8d2acbf87a0997fe3f402/cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96", size = 221525, upload-time = "2026-08-03T21:20:25.758Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/82/1d/a4aaf9babd75acb4d5f223bff71533bee748dd770a382619a798960ee9ba/cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527", size = 225053, upload-time = "2026-08-03T21:20:26.985Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/81/10/5dc0e7bdd18e22107054288283380fc97a06ae3f1656a106908d666a3c88/cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13", size = 223213, upload-time = "2026-08-03T21:20:28.277Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/0b/e9/d0061c364cde06ee43168a0d076ac1da512cbc380d44767b844ba34fe2b6/cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c", size = 177682, upload-time = "2026-08-03T21:20:44.288Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a7/06/1c3e01e3ba14c39f6d10bfbac52753b7e22259e38088e5cfe1d704918690/cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48", size = 187949, upload-time = "2026-08-03T21:20:45.623Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/87/5b/da4e39efe18eeb89cf580ea9cfc66b6a7c3eadb808fc0cc1d3a295cb5a5d/cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836", size = 182947, upload-time = "2026-08-03T21:20:46.955Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/23/59/40338bf421c5accea1d45158170c87006ef1cd371b05c077e76476949728/cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3", size = 188504, upload-time = "2026-08-03T21:20:29.495Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/7d/47/5ecf1023850036e674c77ec4de86182d309ae344e39e7cba984b7df5d647/cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2", size = 188259, upload-time = "2026-08-03T21:20:31.291Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/2a/9c/92934c3bea9f785b23eba304538c0b4d37a2a96d2431eb3a1bc87a11aa19/cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94", size = 223864, upload-time = "2026-08-03T21:20:32.571Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/4d/45/ba4c93527bc38616a8bd36488acb69a2212d60486794f0c1f318949bbb76/cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc", size = 211538, upload-time = "2026-08-03T21:20:33.808Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/80/e9/b6ef565e452acb932fb0cb5443f44a78efbd1233e566f02b5a83855e9115/cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29", size = 210688, upload-time = "2026-08-03T21:20:34.974Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/9a/95/eff5f0cee78d2eabc7eebffec40d3fc1876b5f3c95582e018bb4b99601f2/cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676", size = 223803, upload-time = "2026-08-03T21:20:36.564Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/fa/01/579d39fb8bef00a335a23d83757b44feb24cd6345a2c451b64cb67b9c362/cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e", size = 226763, upload-time = "2026-08-03T21:20:37.816Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/8d/b0/0b44f47c60b01b57b6e2bbd92343f13a85a1d93bc46ccf6e47e244acd99c/cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f", size = 225688, upload-time = "2026-08-03T21:20:38.959Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/eb/d2/3b7176cb570a1d3e27faf67b72f591af508036e0d8b2be2ef9af9e8c84bb/cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4", size = 182868, upload-time = "2026-08-03T21:20:40.388Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/56/78/31f00c1bcd97c9bbf55f1bfdf5bc809a5de8887473e90bb9960dca825e80/cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e", size = 194104, upload-time = "2026-08-03T21:20:41.725Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/7b/1b/58496f2ed0a35de575250c02a43ab3cc2c04d494a88fed31c1cabc0fd176/cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5", size = 186402, upload-time = "2026-08-03T21:20:43.042Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/c1/8f/9ebe220eab48a093d1a5a5e339ab0dc7316eef3bb04d63c42f0251b61f50/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d", size = 194043, upload-time = "2026-08-03T21:20:48.179Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/ff/69/844bad3ece306c4782c2ecb93597035b6690d48704b803914c199da1e8b3/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b", size = 196737, upload-time = "2026-08-03T21:20:49.457Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/1b/8a/af668013284634733f02d683458a0728739c7d6ddb5e14cb0c20832266fe/cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4", size = 184933, upload-time = "2026-08-03T21:20:50.639Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/0c/75/2f5207ff6d1a613133b23a5203cc0c2a628313b5eb3974d7956ae3c57950/cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8", size = 185002, upload-time = "2026-08-03T21:20:52.173Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/e2/31/9e1313b0a6e30e91b3b3d3fff51ae99c857c07738e3afcce1f7334e1b7ab/cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6", size = 222271, upload-time = "2026-08-03T21:20:53.462Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/50/e3/f6234a833e6e08c7007003074723c406559eecf9b48dfc97471e5a8eb7a0/cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80", size = 209919, upload-time = "2026-08-03T21:20:54.783Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/0d/fc/5f74e293fced6edb51af3a46c4ccf6c23c9943774ecb375ddbd522c76add/cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779", size = 208529, upload-time = "2026-08-03T21:20:56.066Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/44/16/29e6d01b388bef055ecd6ca8244b3f4d336bd09e92d5d892187b9601084e/cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399", size = 221630, upload-time = "2026-08-03T21:20:57.336Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a4/18/fa7f1f6857d5eb88a4ca99ffcbfb7c387a287ccc154c64a73e86314745d7/cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688", size = 225134, upload-time = "2026-08-03T21:20:58.675Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/e0/9f/e8e3dfa04a1b4c241f8c91faacad872b4d4efd051d49764ad4e2fd4b9fea/cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7", size = 223197, upload-time = "2026-08-03T21:20:59.968Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/f8/7e/8debeb04f1ab9fe2a6963964cd6f1aaf7192627b83926586a6a4e089c9fa/cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac", size = 177683, upload-time = "2026-08-03T21:21:14.901Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/e0/31/5158704cc474ab65c1647932e88be78dc0873f47130e253be38bcaf13d01/cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960", size = 187897, upload-time = "2026-08-03T21:21:16.108Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/cc/4b/b3a2da8570c704ffc0f9762cdc3ec0f02c8573798e0b5cf7f11c82bbb70f/cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1", size = 182935, upload-time = "2026-08-03T21:21:17.271Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d0/ef/5443574510a1207e6f6bc38ba6e1f1de36cb48fef07b2728bb896a21f430/cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc", size = 188464, upload-time = "2026-08-03T21:21:01.163Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/7e/ae/a56fa8c4686ad50e148fcbc8d3ae0d03915ff5c30d795058988c24118cef/cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab", size = 188262, upload-time = "2026-08-03T21:21:02.382Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/53/b2/6187f46f2912276a3ae284076109cc5c8680482f11f766ccf26db4a86427/cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e", size = 223779, upload-time = "2026-08-03T21:21:03.553Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/8a/f6/c3ad28bd19f77047a03084424fbd4cbe997303267c14423737324be0385d/cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358", size = 211520, upload-time = "2026-08-03T21:21:04.863Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a0/cd/ccac9013a5bd9fd764de118674ab9c805b5ca10c19270d90ee273f8b2240/cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231", size = 210673, upload-time = "2026-08-03T21:21:06.223Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/52/86/2976131c639aead931c5bee5aba67e4b09fbeb8018b6f282f70803f923a7/cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6", size = 223835, upload-time = "2026-08-03T21:21:07.539Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/ac/0c/33a7aeab2f9c76918c52e084beb39c570db3588133412929e8ec06fab90b/cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94", size = 226705, upload-time = "2026-08-03T21:21:08.774Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/e3/26/2cde30fdde421130bfc18f70395731a6e6b2053c6a1978a5258ff04e72fa/cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5", size = 225539, upload-time = "2026-08-03T21:21:09.911Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/6d/cd/a361394c94b2129d604bb846f624a8e88255a3ee33129c434a00d715e64f/cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66", size = 182707, upload-time = "2026-08-03T21:21:11.226Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/9b/b5/ba2b299993c26577d529b6ae29841f9e15b9fcf004d65f423f4fcf94ade9/cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3", size = 193772, upload-time = "2026-08-03T21:21:12.39Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/aa/29/35e016098c814cd93de9cd320c66b5bfba14dc6ecedd3cb518fa7c408c69/cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692", size = 186360, upload-time = "2026-08-03T21:21:13.636Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "click"
|
name = "click"
|
||||||
version = "8.5.0"
|
version = "8.5.0"
|
||||||
@@ -111,6 +215,75 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
|
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cryptography"
|
||||||
|
version = "50.0.2"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "cffi", marker = "platform_python_implementation != 'PyPy'" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/9d/af/182eb91b0df3fe75c4d9f26fe70684569566745f6ba7e5c9c73a862c5252/cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5", size = 880623, upload-time = "2026-09-30T15:30:04.884Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/e5/56/d194340cc4a57535e82e1bee9e89667ac4b7c13b5d3f59686deae3094dd5/cryptography-50.0.2-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb", size = 3914904, upload-time = "2026-09-30T14:43:44.339Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d9/69/c9bd862c3bf43d6399c433caf002df16e2dffd4be49bdf515cda38038711/cryptography-50.0.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0", size = 4731146, upload-time = "2026-09-30T14:43:47.113Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/21/69/64cef1f702bf6657e0cc186ed1a2891d50d29fb41586b254e1c07adea261/cryptography-50.0.2-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2", size = 4719841, upload-time = "2026-09-30T14:43:49.01Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/38/6b/61a3f8d8c5e1e49a6cddccafc4015cc1c0021360ab0acb4080e7a423644a/cryptography-50.0.2-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480", size = 4738340, upload-time = "2026-09-30T14:43:50.932Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/7b/2e/7212ca32fd43dc91f2f41db20160b268098874b4c9a0e7be94d6835f5b2e/cryptography-50.0.2-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134", size = 5367029, upload-time = "2026-09-30T14:43:52.911Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/1a/f1/b474e930c4d910328780e3940da76f5aa5cbc48ce1fc14e44d239d9ea9db/cryptography-50.0.2-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856", size = 4753050, upload-time = "2026-09-30T14:43:55.272Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/7c/52/9af10e80ac16b0fcc2123f9cbd5e7afbd0fd5075bb7a607c592258a39cda/cryptography-50.0.2-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e", size = 4376724, upload-time = "2026-09-30T14:43:57.24Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/71/37/6202e488cc1eb625ea110c292c6bda92823176e023f427d8d5660ce8d632/cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04", size = 4737859, upload-time = "2026-09-30T14:43:59.541Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/8f/30/e86d7d518489b0ae2497091a35287abcb1a2ce4037837a34afbe9b1d6964/cryptography-50.0.2-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc", size = 5324103, upload-time = "2026-09-30T14:44:01.901Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d3/69/2c833a049475e0a3444e94c7d0aca0aa51d166374a449b09e92ac98138de/cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079", size = 4752576, upload-time = "2026-09-30T14:44:04.545Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/6c/5d/906970b83bbfc1f5bbfb677a143c181f2801f23b6a7204a3b47c42c97e65/cryptography-50.0.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51", size = 4870819, upload-time = "2026-09-30T14:44:06.884Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/68/e3/f2298d3bb55e0c4a91841ec4d01b3f020ba8c5fbf15ccdcc6dcf03f97025/cryptography-50.0.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93", size = 5030152, upload-time = "2026-09-30T14:44:09.443Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/9a/4f/adfc442765721292fff86d314ce385d3249d22db42295c0dd057727b60f3/cryptography-50.0.2-cp311-abi3-win_amd64.whl", hash = "sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c", size = 3824692, upload-time = "2026-09-30T14:44:11.671Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/ce/cb/52eb3770c0d0be2702a98c6e96065ddc0a2877cf0845aa9c23397c142cd4/cryptography-50.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8", size = 3892731, upload-time = "2026-09-30T14:44:13.485Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/19/8e/aa1fc533d4546b127b45de8aa024eb5933d23eff9debfe25931e56861095/cryptography-50.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047", size = 4710431, upload-time = "2026-09-30T14:44:15.427Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/6a/64/72bc3f75176e7e406b748a3e3830432b8c51297b38368713df04dc04898a/cryptography-50.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539", size = 4694824, upload-time = "2026-09-30T14:44:17.69Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/4e/c6/62c77550edfa5ca3f14bf44a1e6739b9fa09d6e998a11d97ed8213bccc98/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1", size = 4716967, upload-time = "2026-09-30T14:44:19.661Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/f4/37/cce70f150c432914460157a6ecc161752e053aa5ec0ef3b3f7dc6e31039a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7", size = 5328676, upload-time = "2026-09-30T14:44:21.744Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/aa/9a/6f2f0304d634ceafdeaf23e84537336664ac419b5d07611675c2ad3f6b7a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18", size = 4727698, upload-time = "2026-09-30T14:44:24.178Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/1d/de/66bcf9244d118663b2e1aaded8990f4640e3d7b7411870a5765f252074d2/cryptography-50.0.2-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37", size = 4354821, upload-time = "2026-09-30T14:44:26.263Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/bd/e6/db28a28c7b6c676addce89136de3d8db49ea825a8c863472e36e42ead4ad/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2", size = 4716748, upload-time = "2026-09-30T14:44:28.447Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/30/96/01546c7f69ea0e2ab790a2e4f0934a4052fb9b388147fbf83c2fd72f1e57/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1", size = 5285085, upload-time = "2026-09-30T14:44:30.704Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/6c/01/03263395f74d50b071e9e66daace3f8bef80493e5d410726f2ba8554736b/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05", size = 4727268, upload-time = "2026-09-30T14:44:32.92Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/eb/94/2bfe8f29ec0cc9c0d99359c4161adf32858e4934b72c6d100d2ac0bbe962/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e", size = 4849503, upload-time = "2026-09-30T14:44:34.969Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/54/44/e80651ecbf0e42b62e2bb5f5768916e07eea72e1297338956a61df361f88/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e", size = 5004057, upload-time = "2026-09-30T14:44:37.064Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/f8/cc/1d33befb3cd7ea7e77d2d73f43f2066471da1b21f24a6156efcaabf6d2e8/cryptography-50.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45", size = 3795868, upload-time = "2026-09-30T14:44:39.71Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/2d/49/93f6a6e7a87c9aa68d44d3e1cdb5fe8f60c90d5d2f46acae9a56892816b8/cryptography-50.0.2-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37", size = 4133708, upload-time = "2026-09-30T14:44:41.807Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/8c/75/32ac2a56243d778805c16ca6a32b8f74fb757df7e28d7ecb560afafb59cf/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a", size = 4956267, upload-time = "2026-09-30T14:44:43.693Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/aa/a4/2c8d734e43d97f0842ee9f1b7b4bfb3d0cf5e19edebf43c2afe6675c2320/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67", size = 4966465, upload-time = "2026-09-30T14:44:45.769Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/c2/58/ee288c829a6f41f6235ae9dd33d82fd19b45442b65b4c8a3da36963d9f7a/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_aarch64.whl", hash = "sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc", size = 4959356, upload-time = "2026-09-30T14:44:48.211Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/92/20/9ded6d51ddd9897f6b6e81fb9ebea7951d7cc5d6c890b0ed8abf77a51a80/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_ppc64le.whl", hash = "sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d", size = 5548822, upload-time = "2026-09-30T14:44:50.86Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/02/a8/8df951850d6b31d2a00218f19e2b3f999523437ed7a819df7fa427942fca/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl", hash = "sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7", size = 5001199, upload-time = "2026-09-30T14:44:53.379Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/8b/f9/36b3022218ce75b7cdf068fb95f809f9bd0d820e4955ef43b90c255cc7ac/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_31_armv7l.whl", hash = "sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408", size = 4629333, upload-time = "2026-09-30T14:44:55.635Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/8c/72/20f99a219f6af47cdd1cbd978c243b92d71496e168a746138af44ded4f29/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_aarch64.whl", hash = "sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b", size = 4958822, upload-time = "2026-09-30T14:44:59.639Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/f2/20/196f112617fb08eb4d608a2a6c422373d46f9cc2857f38fc0667033c0899/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_ppc64le.whl", hash = "sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd", size = 5506351, upload-time = "2026-09-30T14:45:02.267Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/24/95/83378121ef3eaaaf71d4b781577ff794acb39b9e1b87a3f156898c8497ed/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_x86_64.whl", hash = "sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c", size = 5000859, upload-time = "2026-09-30T14:45:05.009Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/22/f7/70fd7ae4d1dbfa7ba29b02e1b9068771519a86027756510b700ce81086a8/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be", size = 5092151, upload-time = "2026-09-30T15:29:15.932Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d4/be/688367b74de86984bd58d8efacfc7c9e68b89a6a22ced0fb4f38db50254a/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020", size = 5286120, upload-time = "2026-09-30T15:29:18.309Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/39/d1/55f8a3f2ef5d1529e16835ef10cf0fe3d559ce237b46dddc440c0bba3649/cryptography-50.0.2-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c", size = 4111557, upload-time = "2026-09-30T15:29:20.155Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/23/ad/ac987755d00e1e64273760228d2635ae38dae2be83e3c6e0d3289d91dec3/cryptography-50.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2", size = 3943588, upload-time = "2026-09-30T15:29:22.265Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d5/8d/6d585339bedf85d45044c85d8412dac53f2bb6f918e8b7777efba1787844/cryptography-50.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd", size = 4756166, upload-time = "2026-09-30T15:29:24.58Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/bf/f1/1c1f6874e8550cfddd4b688ceb38cefb6ed15ceed224d56f133f3d88c214/cryptography-50.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767", size = 4749145, upload-time = "2026-09-30T15:29:26.807Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/c1/63/61b15dc1a8de03fe0adbe3fd7608b3ad5c73bf50993bbcb1faaa930afe33/cryptography-50.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454", size = 4763638, upload-time = "2026-09-30T15:29:28.588Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/fc/35/b345bdfa40c9126df1a9d33236aa98418367931b8725f84fc3ae2b98dc59/cryptography-50.0.2-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd", size = 5382217, upload-time = "2026-09-30T15:29:30.589Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/4f/87/ef344a9e616871f2519c22d6afcda79ddd5d35e9592d95eb6e677608d055/cryptography-50.0.2-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5", size = 4781387, upload-time = "2026-09-30T15:29:32.605Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/90/5b/f2fdb13cd0b96f6f932c8627bb292a45f11c64d21620a8e120aee9a3b848/cryptography-50.0.2-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107", size = 4403790, upload-time = "2026-09-30T15:29:34.374Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/bc/ce/7e4f662b1e3c393513569e402cfc85ac7da0bd3d5435e122a3140219eb2d/cryptography-50.0.2-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602", size = 4764319, upload-time = "2026-09-30T15:29:36.149Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/3c/3f/86ff33ce34cc0de6847fb96e035a1a760d81652e38643f617c02ad32ef7a/cryptography-50.0.2-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227", size = 5338560, upload-time = "2026-09-30T15:29:39.053Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/40/cf/6b5c8e2fd9202d98988ab7cb5cc5c991704c4ad55f492ff408e4969f83f1/cryptography-50.0.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c", size = 4780973, upload-time = "2026-09-30T15:29:41.251Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/10/bf/8d6ebc7dded797bd0f0160d52188021211f011a2b164ef0ae1dac4587465/cryptography-50.0.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e", size = 4897738, upload-time = "2026-09-30T15:29:43.106Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d4/aa/f3f6e0de7e6253b8baa8b2d8fb9d50924fa75cee3d4624bd4bc1208ee923/cryptography-50.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94", size = 5058280, upload-time = "2026-09-30T15:29:44.827Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/f6/b6/a1faf3a27ae9405fb34b1713cc73b2d8a26b04d5c561578fa2e6ef3e5bb9/cryptography-50.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de", size = 3854095, upload-time = "2026-09-30T15:29:46.782Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/1d/7a/f08d34ce09d60f89ebd391e2ebc6ba2b995e6dd7552f41820f8085f94e53/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67", size = 4716035, upload-time = "2026-09-30T15:29:48.681Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/45/67/e18fb65592451a2acb76e9f2fbe14e0f47a8318b4c5430f1633851d03daa/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a", size = 4726917, upload-time = "2026-09-30T15:29:50.608Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/83/28/38fdce17e60f6b825e69fc3b7f75e70a6612759980704697e1de4cbfaf6e/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48", size = 4715341, upload-time = "2026-09-30T15:29:52.522Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/b6/b1/d9121a717e0f893c64bd6ca7702614778d7df2a5c309128a002421788516/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42", size = 4726322, upload-time = "2026-09-30T15:29:54.263Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/36/8b/e6d153808bf353e152abd2fd4d8f09670d956ac78379ac46e60d7efbf04c/cryptography-50.0.2-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81", size = 3873097, upload-time = "2026-09-30T15:29:56.097Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/ca/1d/1271f287ff7170ddafc2aad36260c4eec20ccd2fea70f38455e9d56d427b/cryptography-50.0.2-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452", size = 3805376, upload-time = "2026-09-30T15:29:58.729Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "detect-installer"
|
name = "detect-installer"
|
||||||
version = "0.2.1"
|
version = "0.2.1"
|
||||||
@@ -694,6 +867,91 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" },
|
{ url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pillow"
|
||||||
|
version = "12.3.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/fb/c8/0a78b0e02d7ac54bc03e5321c9220da52f0c2ea83b21f7c40e7f3169c502/pillow-12.3.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756", size = 5392415, upload-time = "2026-07-01T11:53:47.162Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/b2/5b/a02d30018abd97ced9f5a6c63d28597694a00d066516b9c1c6de45859fc9/pillow-12.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37d6d0a00072fd2948eb22bce7e1475f34569d90c87c59f7a2ec59541b77f7a6", size = 4785266, upload-time = "2026-07-01T11:53:49.079Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/c8/98/766667a4be768150a202836acd9fad19c06824ca86c4286d3cf6b274964e/pillow-12.3.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bcb46e2f9feff8d06323983bd83ed00c201fdcab3d74973e7072a889b3979fcd", size = 6263814, upload-time = "2026-07-01T11:53:51.32Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/3b/2d/ede717bc1144f63886c21fd349bb95860b0d1a21149ff16f2bb362b612b6/pillow-12.3.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:23d27a3e0307ec2244cc51e7287b919aa68d097504ebe19df4e76a98a3eea5bd", size = 6934408, upload-time = "2026-07-01T11:53:53.487Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a3/48/9c58b685e69d49c31af6c8eb9012055fab7e665785165c84796e2c73ce72/pillow-12.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4f883547d4b7f0495ebe7056b0cc2aea76094e7a4abc8e933540f3271df27d9c", size = 6337160, upload-time = "2026-07-01T11:53:55.457Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/ff/fa/dc2a5c0ba6df93f67c31d34b808b7ce440b40cdbf96f0b81cde1d1e6fa93/pillow-12.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:236ff70b9312fb68943c703aa842ca6a758abfa45ac187a5e7c1452e96ef72b5", size = 7045172, upload-time = "2026-07-01T11:53:57.736Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/86/a5/444817a4d4c4c2417df00513086ca196f388d8f9ef40c2e4ccd1ad1af54b/pillow-12.3.0-cp311-cp311-win32.whl", hash = "sha256:10e41f0fbf1eec8cfd234b8fe17a4caac7c9d0db4c204d3c173a8f9f6ef3232b", size = 6472232, upload-time = "2026-07-01T11:53:59.767Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/63/c6/4bad1b18d132a50b27e1365e1ab163616f7a5bb56d330f66f9d1d9d4f9d4/pillow-12.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:8e95e1385e4998ae9694eeaa4730ba5457ff61185b3a55e2e7bea0880aef452a", size = 7233653, upload-time = "2026-07-01T11:54:02.066Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/fd/16/00f91ab7760dc842f5aad55217e80fc4a7067a0604535249bc8a2d6d9870/pillow-12.3.0-cp311-cp311-win_arm64.whl", hash = "sha256:ebaea975e03d3141d9d3a507df75c9b3ec90fa9d2ffd07567b3a978d9d790b26", size = 2568195, upload-time = "2026-07-01T11:54:04.622Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/37/bf/fb3ebff8ddcb76aac5a01389251bbbb9519922a9b520d8247c1ca864a25d/pillow-12.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965", size = 5345969, upload-time = "2026-07-01T11:54:06.397Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d8/66/9a386a92561f402389a4fc70c18838bf6d35eb5eb5c6850b4b2dc64f5048/pillow-12.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7", size = 4780323, upload-time = "2026-07-01T11:54:09.351Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/25/27/ac8f99618ffd3dde21db0f4d4b1d2ab00c0880595bfd17df103f7f39fd0c/pillow-12.3.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9", size = 6266838, upload-time = "2026-07-01T11:54:11.71Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/84/21/a35af28dcc61f37ed850a2d64c65c701321dfbf25085e469d5559360cbbf/pillow-12.3.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91", size = 6940830, upload-time = "2026-07-01T11:54:13.732Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/eb/51/8b08617af3ad95e33ce6d7dd2c99ed6c8298f7fb131636303956be022e25/pillow-12.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c", size = 6344383, upload-time = "2026-07-01T11:54:15.756Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/1d/72/cf78ac9780bb93c28328f408973845a309d4d145041665f734572ced1b52/pillow-12.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df", size = 7052934, upload-time = "2026-07-01T11:54:17.721Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/20/20/25e0f4dc178a6bc0696793720055519a0de89e7661dae886992decbd2f81/pillow-12.3.0-cp312-cp312-win32.whl", hash = "sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f", size = 6472684, upload-time = "2026-07-01T11:54:19.839Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/45/89/da2f7971a317f83d807fdd4065c0af40208e59e692cc43d315a71a0e96d1/pillow-12.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09", size = 7227137, upload-time = "2026-07-01T11:54:22.025Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/de/47/4845a0a6c0dbf1db8456bd9fc791f13c5ced7ced20606d08a0aacfd25b49/pillow-12.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510", size = 2568267, upload-time = "2026-07-01T11:54:24.051Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/9d/ac/31fb64e1e7efb5a4b50cd3d92049ba89ac6e4d8d3bb6a74e15048ca3353e/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:21900ce7ba264168cd50defae43cd75d25c833ad4ad6e73ffc5596d12e25ac89", size = 4161684, upload-time = "2026-07-01T11:54:25.934Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/87/b4/9805e23d2b4d77842b468513841fda254ee42f0289d25088340e4ff46e2d/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4e8c2a84d977f50b9daed6eeaf3baef67d00d5d74d932288f02cb94518ee3ace", size = 4255487, upload-time = "2026-07-01T11:54:27.935Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/df/39/ecf519435a200c693fe053a6ee4d835b41cf963a4dfc2551c4e637cb2a71/pillow-12.3.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:ae26d61dfa7a47befdc7572b521024e8745f3d809bd95ca9505a7bba9ef849ec", size = 3696433, upload-time = "2026-07-01T11:54:29.813Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/42/92/2fc3ffad878ae8dd5469ec1bc8eb83b71f48e13efdf68f02709003982a32/pillow-12.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66", size = 5345889, upload-time = "2026-07-01T11:54:31.97Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/10/76/8803c13605b763d33d156c4678fc77f8443389c0c51c8aef707bb02015f4/pillow-12.3.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35", size = 4780109, upload-time = "2026-07-01T11:54:34.026Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/1f/01/e18aff37cb0b4aac47ac90f016d347a49aca667ef97f190b06ac2aabc928/pillow-12.3.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f7401aebd7f581d7f83a439d87d474999317ee099218e5ad25d125290990ba65", size = 6263736, upload-time = "2026-07-01T11:54:36.131Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/f7/62/de5bdd77d935331f4f802edc11e4d82950f642caad6cb2f949837b8560e2/pillow-12.3.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0847a763afefb695bc912d7c131e7e0632d4edc1d8698f58ddabec8e46b8b6d3", size = 6937129, upload-time = "2026-07-01T11:54:38.216Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/70/4d/105627a13300c5e0df1d174230b32fd1273062c96f7745fd552b945d1e1d/pillow-12.3.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:571b9fcb07b97ef3a492028fb3d2dc0993ca23a06138b0315286566d29ef718a", size = 6339562, upload-time = "2026-07-01T11:54:40.354Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/6b/1d/f13de01a553988ab895ba1c722e06cf3144d4f57656fd5b81b6d881f1179/pillow-12.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:756c768d0c9c2955feb7a56c37ea24aea2e369f8d36a88da270b6a9f19e62b5e", size = 7049439, upload-time = "2026-07-01T11:54:42.489Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/c9/f9/066794cca041b969964f779ee5fa66a9498bbf34248ac39c5d7954e4198f/pillow-12.3.0-cp313-cp313-win32.whl", hash = "sha256:a876864214e136f0eb367788dbd7df045f4806801518e2cfe9e13229cfe06d8f", size = 6473287, upload-time = "2026-07-01T11:54:44.9Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a6/9b/7a58e61d62be561da3a356fe2384d4059a6345fc130e23ef1c36a5b81d24/pillow-12.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:1cca606cd25738df4ed873d5ad46bbdb3d83b5cbca291f6b4ff13a4df6b0bbe8", size = 7239691, upload-time = "2026-07-01T11:54:47.141Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/aa/b0/c4ed4f0ef8f8fa5ee8351537db6650bb8189f7e118842978dd6589065692/pillow-12.3.0-cp313-cp313-win_arm64.whl", hash = "sha256:b629de27fda84b42cde7edef0d85f13b958b47f6e9bbcbba9b673c562a89bd8b", size = 2568185, upload-time = "2026-07-01T11:54:49.137Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/dc/01/001f65b68192f0228cc1dbbc8d2530ab5d58b61037ba0587f946fea607cd/pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:9cf95fe4d0f84c82d282745d9bb08ad9f926efa00be4697e767b814ce40d4330", size = 4161736, upload-time = "2026-07-01T11:54:51.156Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/1a/d2/0219746d0fd16fc8a84498e79452375be3797d3ce4044596ce565164b84f/pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:8728f216dcdb6e6d555cf971cb34076139ad74b31fc2c14da4fafc741c5f6217", size = 4255435, upload-time = "2026-07-01T11:54:53.414Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/c8/02/8d0bc62ef0302318c46ff2a512822d2610e81c7aa46c9b3abe6cbaca5ad0/pillow-12.3.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:a45650e8ce7fafffd731db8550230db6b0d306d181a90b67d3e6bca2f1990930", size = 3696262, upload-time = "2026-07-01T11:54:55.739Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/85/e2/73c77d218410b14f5f2d565e8a998d5317b7b9c75368d29985139f7a46f0/pillow-12.3.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ba54cfebe86920a559a7c4d6b9050791c20513650a1952ebe3368c7dc70306f8", size = 5350344, upload-time = "2026-07-01T11:54:57.657Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/c7/da/32c752228ae345f489e3a42499d817b6c3996da7e8a3bc7a04fc806b243b/pillow-12.3.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e158cb00350dc278f3b91551101aa7d12415a66ebf2c91d8d5ac14e56ddd3ad0", size = 4780131, upload-time = "2026-07-01T11:54:59.713Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/b1/9d/8b2c807dbef61a5197c047afe99823787eb66f63daf9fb2432f91d6f0462/pillow-12.3.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e9aeb04d6aef139de265b29683e119b638208f88cf73cdd1658aa07221165321", size = 6263757, upload-time = "2026-07-01T11:55:01.778Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/5c/44/c85361f65dbe00eea8576ee467c768d25129989efb76e94f205e9ca9bb46/pillow-12.3.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:251bf95b67017e27b13d82f5b326234ca62d70f9cf4c2b9032de2358a3b12c7b", size = 6936962, upload-time = "2026-07-01T11:55:03.93Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/18/7e/e483414b35800b86b6f08dbbc7803fb5cd52c4d6f897f47d53ea2c7e6f65/pillow-12.3.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fe3cca2e4e8a592be0f269a1ca4835c25199d9f3ce815c8491048f785b0a0198", size = 6339171, upload-time = "2026-07-01T11:55:05.989Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/f0/f4/68c491844841ede6bed70189546b3ee9731cf9f2cbad396faff5e1ccba45/pillow-12.3.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:23aceaa007d6172b02c277f0cd359c79492bbb14f7072b4ede9fbcaf20648130", size = 7048116, upload-time = "2026-07-01T11:55:08.131Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a3/34/77f3f793fed8efc7d243f21b33c5a3f0d1c97ee70346d3db855587e155ff/pillow-12.3.0-cp314-cp314-win32.whl", hash = "sha256:af8d94b0db561cf68b88a267c5c44b49e134f525d0dc2cb7ed413a66bc23559a", size = 6467209, upload-time = "2026-07-01T11:55:10.408Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/f1/e0/492879f69d94f91f60fc8cd05ba03650e9520afebb2fb7aa12777d7c7f38/pillow-12.3.0-cp314-cp314-win_amd64.whl", hash = "sha256:fdafc9cce40277e0f7a0feabce0ee50dd2fa1800f3b38015e51296b5e814048d", size = 7237707, upload-time = "2026-07-01T11:55:12.745Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/c9/ac/6b11f2875f1c2ac040d84e1bbf9cf22a88038f901ca1037898b280b38365/pillow-12.3.0-cp314-cp314-win_arm64.whl", hash = "sha256:e91206ee562682b51b98ef4b26a6ef48fd84e15fd4c4bc5ec768eb641d206838", size = 2565995, upload-time = "2026-07-01T11:55:14.736Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/52/69/c2208e56af9bfc1913afb24020297a691eb1d4ef688474c8a04913f65e04/pillow-12.3.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:164b31cd1a0490ab6efae01aa5df49da7061be0af1b30e035b6e9a1bfe34ee6e", size = 5352503, upload-time = "2026-07-01T11:55:17.076Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/07/70/e5686d753e898a45d778ff1718dba8516ead6ab6b95d85fc8c4b70650cf2/pillow-12.3.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5afb51d599ea772b8365ae807ae557f18bccfe46ab261fd1c2a9ed700fc6eb17", size = 4782956, upload-time = "2026-07-01T11:55:19.448Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d5/37/25c6692f06927ee973ff18c8d9ee98ad0b4d84ee67a09610c2dd1447958e/pillow-12.3.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3edce1d53195db527e0191f84b71d02022de0540bf43a16ed734ed7537b07385", size = 6322855, upload-time = "2026-07-01T11:55:21.613Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/cc/91/420637fcb8f1bc11029e403b4538e6694744428d8246118e45719f944556/pillow-12.3.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bf16ba1b4d0b6b7c8e534936632270cf70eb00dbe09005bc345b2677b726855c", size = 6989642, upload-time = "2026-07-01T11:55:24.006Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/10/08/b94d7811281ccf0d143a1cf768d1c49e1e54af63e7b708ab2ee3eb87face/pillow-12.3.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:24870b09b224f7ae3c39ed07d10e819d06f8720bc551847b1d623832b5b0e28d", size = 6391281, upload-time = "2026-07-01T11:55:26.252Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d2/87/24233f785f55474dc02ce3e739c5528a77e3a862e9333d1dd7a25cc31f70/pillow-12.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:30f2aa603c41533cc25c05acd0da21636e84a315768feb631c937177db558931", size = 7096716, upload-time = "2026-07-01T11:55:28.318Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/23/26/fcb2f6e37175b04f53570b59937867e2b80ee1685e744023153028fc14f9/pillow-12.3.0-cp314-cp314t-win32.whl", hash = "sha256:4b0a7fe987b14c31ebda6083f74f22b561fd3739bc0ac51e019622e3d72668c7", size = 6474125, upload-time = "2026-07-01T11:55:30.956Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/90/de/3634abee5f1c9e13c56787b7d5517b0ba8d6de51700b95578cf338349c9f/pillow-12.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:962864dc93511324d51ddbb5b9f8731bf71675b93ca612a07441896f4688fb8c", size = 7242939, upload-time = "2026-07-01T11:55:34.044Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/ce/2a/fd13f8eb24de5714a6eb444a3d67e2842c6c576e159a43793adf23051351/pillow-12.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0740a512dc522224c77d9aa5a8d70d8b7d73fb91f2c21125d8d025d3b8990e45", size = 2567506, upload-time = "2026-07-01T11:55:35.988Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/5d/dc/8fdce34ec725a33c81c6ba122b904d6b9024e50ea9ac7bede62fab54506c/pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:0feb2e9d6ad6c9e3c06effe9d00f3f1e618a6643273576b016f591e9315a7139", size = 4162063, upload-time = "2026-07-01T11:55:37.941Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/76/66/2044b9a63d3b84ff048228dfcb7cd9bf0df983e8470971bf7d4c57b693de/pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:9e881fca225083806662a5c43d627d215f258ff43c890f831966c7d7ba9c7402", size = 4255549, upload-time = "2026-07-01T11:55:40.022Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/52/7e/1f67e6f4ece6b582ee4b539decbcc9f848dc245a93ed8cd7338bafef72f1/pillow-12.3.0-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:4998562bf62a445225f22e07c896bb04b35b1b1f2eb6d760584c9c51d7a5f78c", size = 3696331, upload-time = "2026-07-01T11:55:41.98Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/12/40/d306fc2c8e4d45d7f175c77edca7063be7b86fe7fe6e68f4353bf71d808c/pillow-12.3.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:dc624f6bc473dacdf7ef7eb8678d0d08edf15cd94fad6ae5c7d6cc67a4e4902f", size = 5350370, upload-time = "2026-07-01T11:55:44.028Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/dd/44/668fb1437e8ce420f62d6106eb66e44a5971602a4d794615bdf79315d82d/pillow-12.3.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:71d6097b330eea8fd15097780c8e89cb1a8ce7838669f48c5bacd6f663dd4701", size = 4780147, upload-time = "2026-07-01T11:55:46.073Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/0c/08/93fa2e70e30a2d81547e481b6ee2bb9522117221fb1e0ce4b5df70967677/pillow-12.3.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:28ce87c5ab450a9dd970b52e5aca5fe63ed432d18a2eaddd1979a00a1ba24ace", size = 6273659, upload-time = "2026-07-01T11:55:48.264Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/f8/6d/043e96ff814fc31a33077e4cba86082167db520c93632afdf2042febbb0c/pillow-12.3.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6b02afb9b97f65fbca5f31db6a2a3ba21aa93030225f150fa3f249717e938fb4", size = 6947439, upload-time = "2026-07-01T11:55:50.503Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/af/92/ba71d2ee2ac0edf3fa33bd9d5ee9ee080da70b1766f3ca3934f9938ddac9/pillow-12.3.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:1182d52bc2d5e5d7d0949503aa7e36d12f42205dc287e4883f407b1988820d39", size = 6353577, upload-time = "2026-07-01T11:55:52.697Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/0f/ce/e63064e2122923ff687c8ad792d0d736a7b3920a56a46982e81a7fdd25d6/pillow-12.3.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e795b7eb908249c4e43c7c99fac7c2c75dab0c43566e37db472a355f63693d71", size = 7060394, upload-time = "2026-07-01T11:55:55.149Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/54/76/a09cc3ccc8d773a7283d34c38bec1708f9e3cc932093cbc4c5e71ac4060b/pillow-12.3.0-cp315-cp315-win32.whl", hash = "sha256:57b3d78c95ba9059768b10e28b813002261d3f3dfc55cc48b0c988f625175827", size = 6467375, upload-time = "2026-07-01T11:55:57.769Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/3e/03/1846c49ba3b1d5550392a4bbd06d6fb4578e1cd91a803198b5c90f5f7d53/pillow-12.3.0-cp315-cp315-win_amd64.whl", hash = "sha256:fa4ecea169a355be7a3ade2c783e2ed12f0e40d2c5621cda8b3297faf7fbb9f5", size = 7237048, upload-time = "2026-07-01T11:55:59.975Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/fb/bb/89f35dcc79610423f9f195504d7def7f0d1416a711541b42867e25fe3412/pillow-12.3.0-cp315-cp315-win_arm64.whl", hash = "sha256:877c3f311ff35410f690861c4409e7ccbf0cd2f878e50628a28e5a0bb689e658", size = 2566006, upload-time = "2026-07-01T11:56:02.143Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/30/88/707027ba09942dfa2c28759b5c222d769290a41c6d20ea60ec250801941f/pillow-12.3.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:e9871b1ffbfa9656b60aeee92ed5136a5742696006fa322b29ea3d8da0ecc9cf", size = 5352509, upload-time = "2026-07-01T11:56:04.2Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/b0/6d/00352fa25332c2569cd387851f568cc5a4b75a9adbfb37ac4fbce4c02eec/pillow-12.3.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:53aa02d20d10c3d814d536aa4e5ac9b84ca0ff5a88377963b085ad6822f93e64", size = 4783167, upload-time = "2026-07-01T11:56:06.631Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/13/4f/9e049dfa21af7c22427275720e2490267ba8138120add5c4c574deb69782/pillow-12.3.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:446c34dcc4324b084a53b705127dc15717b22c5e140ae0a3c38349d4efec071e", size = 6329237, upload-time = "2026-07-01T11:56:08.868Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/36/16/cf6eeaae8d0fce8dd390a33437cf68c5d5bd73834a2bc6e2f14efda0ab45/pillow-12.3.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cf1845d02ad822a369a49f2bb9345b1614744267682e7a03527dc3bf6eea1777", size = 6997047, upload-time = "2026-07-01T11:56:11.379Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/1e/69/dbf769bdd55f48bf5733cac28edc6364ffaa072ec9ba336266e4fe66be55/pillow-12.3.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:186941b6aef820ad110fb01fb06eb925374dc3a21b17e37ec9a53b250c6fe2d1", size = 6400440, upload-time = "2026-07-01T11:56:13.908Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/a0/e1/ffc9cfc2eea0d178da8018e18e959301ad9d6bc9f3edb7181e748a474b97/pillow-12.3.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:f13c32a3abd6079a66d9526e18dad9b6d280384d49d7c54040cd57b6424041d9", size = 7105895, upload-time = "2026-07-01T11:56:16.575Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/18/f0/a5595c1e8c3ae44b9828cb2f0fa8155e5095ef04d6327b8f61cf44a3df85/pillow-12.3.0-cp315-cp315t-win32.whl", hash = "sha256:1657923d2d45afb66526e5b933e5b3052e6bdea196c90d3abb2424e18c77dae8", size = 6474384, upload-time = "2026-07-01T11:56:18.855Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/e4/04/62bcd9f844984c5938d3b05264a61d797a29d3e0812341a8204af70bbdee/pillow-12.3.0-cp315-cp315t-win_amd64.whl", hash = "sha256:8cd2f7bdda092d99c9fc2fb7391354f306d01443d22785d0cbfafa2e2c8bb418", size = 7243537, upload-time = "2026-07-01T11:56:21.214Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/3d/68/1f3066acedf37673694a7141381d8f811ae97f30d34413d236abe7d489f1/pillow-12.3.0-cp315-cp315t-win_arm64.whl", hash = "sha256:06ff022112bc9cbf83b60f8e028d94ad87b60621706487e65f673de61610ab59", size = 2567491, upload-time = "2026-07-01T11:56:23.506Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/75/18/2e8b40223153ccbc60df07f9e8928dc0c76202aa4e55ae9f53962b6510d6/pillow-12.3.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:b3c777e849237620b022f7f297dd67705f9f5cf1685f09f02e46f93e92725468", size = 5302510, upload-time = "2026-07-01T11:56:25.736Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/46/3e/51fabf59d5ab801ceab709453d3ab6b180083496579549de4c45ced6528a/pillow-12.3.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:b343699e8308bdc51978310e1c959c584e7869cc8c40780058c87da7781a1e94", size = 4736058, upload-time = "2026-07-01T11:56:28.041Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/bf/20/22fe9384b7949e25fb1293bcfc84fb82590ff4ea6b37c95b24d26d793d86/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fbd139c8447d25dd750ab79ee274cc5e1fe80fc56340ab10b18a195e1b6eca3e", size = 5237776, upload-time = "2026-07-01T11:56:30.263Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/08/14/f6ba68107680ffa74b39985f3f30884e41318fbc4250caa423c79b4788bb/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e7e480451b9fa137494bccd3a7d69adbe8ac65a87d97be61e11f1b1050a5bac3", size = 5860358, upload-time = "2026-07-01T11:56:32.68Z" },
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/36/54/0169bc772ec491108b62f644f8ecf1fe5d8ae5ebafde2ee2142210166903/pillow-12.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a", size = 7231786, upload-time = "2026-07-01T11:56:35.046Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pluggy"
|
name = "pluggy"
|
||||||
version = "1.6.0"
|
version = "1.6.0"
|
||||||
@@ -718,6 +976,15 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/e4/04/d52c7016b04b6c5108f26691f9d33ec82a9b65d041f1a9c771137693d618/protobuf-7.36.2-py3-none-any.whl", hash = "sha256:bdb3a345d48db958e6ce1f18e508beb0cc981d64f24088427549c866cd039f1e", size = 179806, upload-time = "2026-09-17T20:07:58.211Z" },
|
{ url = "https://files.pythonhosted.org/packages/e4/04/d52c7016b04b6c5108f26691f9d33ec82a9b65d041f1a9c771137693d618/protobuf-7.36.2-py3-none-any.whl", hash = "sha256:bdb3a345d48db958e6ce1f18e508beb0cc981d64f24088427549c866cd039f1e", size = 179806, upload-time = "2026-09-17T20:07:58.211Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pycparser"
|
||||||
|
version = "3.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pydantic"
|
name = "pydantic"
|
||||||
version = "2.13.5"
|
version = "2.13.5"
|
||||||
@@ -876,6 +1143,20 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" },
|
{ url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pyjwt"
|
||||||
|
version = "2.15.1"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/43/ea/5194e52748b0da83d71e082d75496eaec6e58f419f5e184786ded517e6a9/pyjwt-2.15.1.tar.gz", hash = "sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8", size = 121252, upload-time = "2026-09-28T18:40:42.598Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/50/ca/44de4e75f8aadc457f0634be3b542815078ded46dca30efb960edeecad6e/pyjwt-2.15.1-py3-none-any.whl", hash = "sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193", size = 33860, upload-time = "2026-09-28T18:40:41.429Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[package.optional-dependencies]
|
||||||
|
crypto = [
|
||||||
|
{ name = "cryptography" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pyright"
|
name = "pyright"
|
||||||
version = "1.1.414"
|
version = "1.1.414"
|
||||||
|
|||||||
+16
-14
@@ -7,26 +7,28 @@ services:
|
|||||||
- ./data:/app/data
|
- ./data:/app/data
|
||||||
environment:
|
environment:
|
||||||
- BASE_PATH=/birthday
|
- 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:
|
networks:
|
||||||
- proxy-net
|
- proxy-net
|
||||||
labels:
|
labels:
|
||||||
- "diun.enable=false"
|
- "diun.enable=false"
|
||||||
- "traefik.enable=true"
|
- "traefik.enable=true"
|
||||||
|
|
||||||
# Public router (invitation + public API)
|
# Workload router (invitation, admin, and APIs)
|
||||||
- "traefik.http.routers.bdinvite-public.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
|
- "traefik.http.routers.bdinvite.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
|
||||||
- "traefik.http.routers.bdinvite-public.entrypoints=websecure"
|
- "traefik.http.routers.bdinvite.entrypoints=websecure"
|
||||||
- "traefik.http.routers.bdinvite-public.tls=true"
|
- "traefik.http.routers.bdinvite.tls=true"
|
||||||
- "traefik.http.routers.bdinvite-public.priority=10"
|
- "traefik.http.routers.bdinvite.priority=10"
|
||||||
- "traefik.http.routers.bdinvite-public.service=bdinvite-svc"
|
- "traefik.http.routers.bdinvite.service=bdinvite-svc"
|
||||||
|
|
||||||
# Admin router (Authelia-protected)
|
|
||||||
- "traefik.http.routers.bdinvite-admin.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday/admin`)"
|
|
||||||
- "traefik.http.routers.bdinvite-admin.entrypoints=websecure"
|
|
||||||
- "traefik.http.routers.bdinvite-admin.tls=true"
|
|
||||||
- "traefik.http.routers.bdinvite-admin.priority=20"
|
|
||||||
- "traefik.http.routers.bdinvite-admin.middlewares=authelia-auth@docker"
|
|
||||||
- "traefik.http.routers.bdinvite-admin.service=bdinvite-svc"
|
|
||||||
|
|
||||||
# HTTP to HTTPS redirect
|
# HTTP to HTTPS redirect
|
||||||
- "traefik.http.routers.bdinvite-red.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
|
- "traefik.http.routers.bdinvite-red.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
|
||||||
|
|||||||
@@ -1,6 +1,89 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
import { Link, NavLink, Outlet } from "react-router-dom";
|
import { Link, NavLink, Outlet } from "react-router-dom";
|
||||||
|
import { type CurrentUser, fetchCurrentUser, logoutUser } from "../api/client";
|
||||||
|
import { Spinner } from "../components/Spinner";
|
||||||
|
|
||||||
export function AdminLayout() {
|
export function AdminLayout() {
|
||||||
|
const [user, setUser] = useState<CurrentUser | null>(null);
|
||||||
|
const [loading, setLoading] = useState<boolean>(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
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 = async () => {
|
||||||
|
try {
|
||||||
|
await logoutUser();
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Logout failed:", err);
|
||||||
|
}
|
||||||
|
setUser(null);
|
||||||
|
window.location.href = "/birthday/api/auth/login";
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
minHeight: "100vh",
|
||||||
|
backgroundColor: "#0f0f10",
|
||||||
|
color: "#f0f0f0",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Spinner size={36} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
minHeight: "100vh",
|
||||||
|
backgroundColor: "#0f0f10",
|
||||||
|
color: "#f0f0f0",
|
||||||
|
fontFamily: "var(--font-body)",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
gap: "1rem",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<p>No autenticado. Redirigiendo al inicio de sesión...</p>
|
||||||
|
<a
|
||||||
|
href="/birthday/api/auth/login"
|
||||||
|
style={{
|
||||||
|
color: "var(--color-gold-light, #e0be75)",
|
||||||
|
textDecoration: "underline",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Iniciar sesión
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
@@ -89,6 +172,55 @@ export function AdminLayout() {
|
|||||||
<span>↗</span>
|
<span>↗</span>
|
||||||
</Link>
|
</Link>
|
||||||
</nav>
|
</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>
|
</header>
|
||||||
|
|
||||||
{/* Main Admin Content Container */}
|
{/* Main Admin Content Container */}
|
||||||
@@ -104,3 +236,4 @@ export function AdminLayout() {
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { type FormEvent, useEffect, useState } from "react";
|
import { type FormEvent, useEffect, useState } from "react";
|
||||||
import { fetchAdminConfig, updateAdminConfig } from "../api/client";
|
import { fetchAdminConfig, regenerateMapPreview, updateAdminConfig } from "../api/client";
|
||||||
import { Button } from "../components/Button";
|
import { Button } from "../components/Button";
|
||||||
import { Field } from "../components/Field";
|
import { Field } from "../components/Field";
|
||||||
import { Spinner } from "../components/Spinner";
|
import { Spinner } from "../components/Spinner";
|
||||||
@@ -9,6 +9,11 @@ export function ConfigEditor() {
|
|||||||
const [formData, setFormData] = useState<InvitationConfig | null>(null);
|
const [formData, setFormData] = useState<InvitationConfig | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [saving, setSaving] = useState(false);
|
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<{
|
const [feedback, setFeedback] = useState<{
|
||||||
type: "success" | "error";
|
type: "success" | "error";
|
||||||
msg: string;
|
msg: string;
|
||||||
@@ -58,6 +63,28 @@ export function ConfigEditor() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
<div style={{ padding: "4rem", textAlign: "center" }}>
|
<div style={{ padding: "4rem", textAlign: "center" }}>
|
||||||
@@ -226,12 +253,116 @@ export function ConfigEditor() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</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
|
<Field
|
||||||
label="URL de Imagen Previa del Mapa (map_preview_url)"
|
label="URL de Imagen Previa del Mapa (map_preview_url)"
|
||||||
value={formData.map_preview_url}
|
value={formData.map_preview_url}
|
||||||
onChange={(e) => handleChange("map_preview_url", e.target.value)}
|
onChange={(e) => handleChange("map_preview_url", e.target.value)}
|
||||||
required
|
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
|
<div
|
||||||
style={{
|
style={{
|
||||||
|
|||||||
@@ -1,14 +1,29 @@
|
|||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import { fetchAdminRsvps, getExportCsvUrl } from "../api/client";
|
import {
|
||||||
|
deleteAdminRsvp,
|
||||||
|
fetchAdminRsvps,
|
||||||
|
getExportCsvUrl,
|
||||||
|
updateAdminRsvp,
|
||||||
|
} from "../api/client";
|
||||||
import { Button } from "../components/Button";
|
import { Button } from "../components/Button";
|
||||||
import { Spinner } from "../components/Spinner";
|
import { Spinner } from "../components/Spinner";
|
||||||
|
import { useConfig } from "../hooks/useConfig";
|
||||||
import type { RSVPAdminItem } from "../types/config";
|
import type { RSVPAdminItem } from "../types/config";
|
||||||
|
|
||||||
export function RsvpTable() {
|
export function RsvpTable() {
|
||||||
|
const { config } = useConfig();
|
||||||
const [rsvps, setRsvps] = useState<RSVPAdminItem[]>([]);
|
const [rsvps, setRsvps] = useState<RSVPAdminItem[]>([]);
|
||||||
const [count, setCount] = useState<number>(0);
|
const [count, setCount] = useState<number>(0);
|
||||||
const [search, setSearch] = useState<string>("");
|
const [search, setSearch] = useState<string>("");
|
||||||
const [loading, setLoading] = useState<boolean>(true);
|
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 [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const loadData = useCallback(async (searchTerm = "") => {
|
const loadData = useCallback(async (searchTerm = "") => {
|
||||||
@@ -32,8 +47,14 @@ export function RsvpTable() {
|
|||||||
function formatDate(isoStr: string) {
|
function formatDate(isoStr: string) {
|
||||||
if (!isoStr) return "—";
|
if (!isoStr) return "—";
|
||||||
try {
|
try {
|
||||||
const d = new Date(isoStr);
|
// 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", {
|
return d.toLocaleDateString("es-CO", {
|
||||||
|
timeZone: config?.event_timezone || "America/Bogota",
|
||||||
year: "numeric",
|
year: "numeric",
|
||||||
month: "short",
|
month: "short",
|
||||||
day: "numeric",
|
day: "numeric",
|
||||||
@@ -52,6 +73,71 @@ export function RsvpTable() {
|
|||||||
return phone;
|
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 (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{/* Top action bar: Count, Search, Export */}
|
{/* Top action bar: Count, Search, Export */}
|
||||||
@@ -164,19 +250,20 @@ export function RsvpTable() {
|
|||||||
<th style={{ padding: "0.9rem 1.2rem" }}>Teléfono</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" }}>Correo</th>
|
||||||
<th style={{ padding: "0.9rem 1.2rem" }}>Fecha de Registro</th>
|
<th style={{ padding: "0.9rem 1.2rem" }}>Fecha de Registro</th>
|
||||||
|
<th style={{ padding: "0.9rem 1.2rem", textAlign: "right" }}>Acciones</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={4} style={{ padding: "3rem", textAlign: "center" }}>
|
<td colSpan={5} style={{ padding: "3rem", textAlign: "center" }}>
|
||||||
<Spinner size={28} />
|
<Spinner size={28} />
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
) : rsvps.length === 0 ? (
|
) : rsvps.length === 0 ? (
|
||||||
<tr>
|
<tr>
|
||||||
<td
|
<td
|
||||||
colSpan={4}
|
colSpan={5}
|
||||||
style={{
|
style={{
|
||||||
padding: "3rem",
|
padding: "3rem",
|
||||||
textAlign: "center",
|
textAlign: "center",
|
||||||
@@ -194,36 +281,116 @@ export function RsvpTable() {
|
|||||||
key={row.id}
|
key={row.id}
|
||||||
style={{
|
style={{
|
||||||
borderBottom: "1px solid rgba(255, 255, 255, 0.06)",
|
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",
|
transition: "background-color 0.15s ease",
|
||||||
}}
|
}}
|
||||||
onMouseEnter={(e) => {
|
onMouseEnter={(e) => {
|
||||||
|
if (editingId !== row.id) {
|
||||||
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.04)";
|
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.04)";
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
onMouseLeave={(e) => {
|
onMouseLeave={(e) => {
|
||||||
|
if (editingId !== row.id) {
|
||||||
e.currentTarget.style.backgroundColor = "transparent";
|
e.currentTarget.style.backgroundColor = "transparent";
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<td
|
<td
|
||||||
style={{
|
style={{
|
||||||
padding: "0.9rem 1.2rem",
|
padding: editingId === row.id ? "0.5rem 0.8rem" : "0.9rem 1.2rem",
|
||||||
fontWeight: 500,
|
fontWeight: 500,
|
||||||
color: "#ffffff",
|
color: "#ffffff",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{row.name}
|
{editingId === row.id ? (
|
||||||
</td>
|
<input
|
||||||
<td
|
type="text"
|
||||||
style={{ padding: "0.9rem 1.2rem", color: "var(--color-gold-light)" }}
|
value={editForm.name}
|
||||||
>
|
onChange={(e) =>
|
||||||
{formatPhone(row.phone)}
|
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>
|
||||||
<td
|
<td
|
||||||
style={{
|
style={{
|
||||||
padding: "0.9rem 1.2rem",
|
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)",
|
color: "rgba(255, 255, 255, 0.7)",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{row.email || "—"}
|
{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>
|
||||||
<td
|
<td
|
||||||
style={{
|
style={{
|
||||||
@@ -234,6 +401,212 @@ export function RsvpTable() {
|
|||||||
>
|
>
|
||||||
{formatDate(row.created_at)}
|
{formatDate(row.created_at)}
|
||||||
</td>
|
</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>
|
</tr>
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
@@ -241,5 +614,6 @@ export function RsvpTable() {
|
|||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
import type {
|
import type {
|
||||||
InvitationConfig,
|
InvitationConfig,
|
||||||
RSVPApiResult,
|
RSVPApiResult,
|
||||||
|
RSVPAdminItem,
|
||||||
RSVPListResponse,
|
RSVPListResponse,
|
||||||
RSVPRequest,
|
RSVPRequest,
|
||||||
|
RSVPUpdateRequest,
|
||||||
} from "../types/config";
|
} from "../types/config";
|
||||||
|
|
||||||
const BASE_API = "/birthday/api";
|
const BASE_API = "/birthday/api";
|
||||||
@@ -86,3 +88,97 @@ export async function updateAdminConfig(
|
|||||||
export function getExportCsvUrl(): string {
|
export function getExportCsvUrl(): string {
|
||||||
return `${BASE_API}/admin/export`;
|
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" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useRef } from "react";
|
import { useRef, useState } from "react";
|
||||||
import { Button } from "../components/Button";
|
import { Button } from "../components/Button";
|
||||||
import { Spinner } from "../components/Spinner";
|
import { Spinner } from "../components/Spinner";
|
||||||
import { useConfig } from "../hooks/useConfig";
|
import { useConfig } from "../hooks/useConfig";
|
||||||
@@ -11,6 +11,7 @@ import { RsvpResult } from "./RsvpResult";
|
|||||||
export function Invitation() {
|
export function Invitation() {
|
||||||
const { config, status, error, reload } = useConfig();
|
const { config, status, error, reload } = useConfig();
|
||||||
const rsvpForm = useRsvpForm();
|
const rsvpForm = useRsvpForm();
|
||||||
|
const [showDetailsOnly, setShowDetailsOnly] = useState(false);
|
||||||
const rsvpSectionRef = useRef<HTMLDivElement | null>(null);
|
const rsvpSectionRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
|
||||||
function scrollToRsvp() {
|
function scrollToRsvp() {
|
||||||
@@ -112,7 +113,17 @@ export function Invitation() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{/* Section 1: Invitation Hero */}
|
{/* Section 1: Invitation Hero */}
|
||||||
<InvitationHero config={config} onCtaClick={scrollToRsvp} />
|
<InvitationHero
|
||||||
|
config={config}
|
||||||
|
onCtaClick={() => {
|
||||||
|
setShowDetailsOnly(false);
|
||||||
|
scrollToRsvp();
|
||||||
|
}}
|
||||||
|
onShowDetailsClick={() => {
|
||||||
|
setShowDetailsOnly(true);
|
||||||
|
scrollToRsvp();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Section 2: RSVP / Confirmation Flow */}
|
{/* Section 2: RSVP / Confirmation Flow */}
|
||||||
<div
|
<div
|
||||||
@@ -129,7 +140,16 @@ export function Invitation() {
|
|||||||
position: "relative",
|
position: "relative",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{rsvpForm.formState === "idle" || rsvpForm.formState === "submitting" ? (
|
{showDetailsOnly ? (
|
||||||
|
<RsvpResult
|
||||||
|
formState="idle"
|
||||||
|
confirmedName=""
|
||||||
|
config={config}
|
||||||
|
onRetry={() => setShowDetailsOnly(false)}
|
||||||
|
isDetailsOnly={true}
|
||||||
|
onBackToForm={() => setShowDetailsOnly(false)}
|
||||||
|
/>
|
||||||
|
) : rsvpForm.formState === "idle" || rsvpForm.formState === "submitting" ? (
|
||||||
<RsvpForm
|
<RsvpForm
|
||||||
config={config}
|
config={config}
|
||||||
name={rsvpForm.name}
|
name={rsvpForm.name}
|
||||||
@@ -141,6 +161,7 @@ export function Invitation() {
|
|||||||
formState={rsvpForm.formState}
|
formState={rsvpForm.formState}
|
||||||
errors={rsvpForm.errors}
|
errors={rsvpForm.errors}
|
||||||
onSubmit={rsvpForm.submit}
|
onSubmit={rsvpForm.submit}
|
||||||
|
onShowDetails={() => setShowDetailsOnly(true)}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<RsvpResult
|
<RsvpResult
|
||||||
|
|||||||
@@ -4,9 +4,14 @@ import { RsvpCta } from "./RsvpCta";
|
|||||||
interface InvitationHeroProps {
|
interface InvitationHeroProps {
|
||||||
config: InvitationConfig;
|
config: InvitationConfig;
|
||||||
onCtaClick: () => void;
|
onCtaClick: () => void;
|
||||||
|
onShowDetailsClick?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function InvitationHero({ config, onCtaClick }: InvitationHeroProps) {
|
export function InvitationHero({
|
||||||
|
config,
|
||||||
|
onCtaClick,
|
||||||
|
onShowDetailsClick,
|
||||||
|
}: InvitationHeroProps) {
|
||||||
// Parse date into Month, Day, and Day of Week
|
// Parse date into Month, Day, and Day of Week
|
||||||
const [year, monthNum, dayNum] = config.event_date.split("-").map(Number);
|
const [year, monthNum, dayNum] = config.event_date.split("-").map(Number);
|
||||||
const dateObj = new Date(year, (monthNum || 1) - 1, dayNum || 1);
|
const dateObj = new Date(year, (monthNum || 1) - 1, dayNum || 1);
|
||||||
@@ -167,8 +172,46 @@ export function InvitationHero({ config, onCtaClick }: InvitationHeroProps) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 4. RSVP Call to action */}
|
{/* 4. RSVP Call to action */}
|
||||||
<div style={{ marginBottom: "1rem" }}>
|
<div
|
||||||
|
style={{
|
||||||
|
marginBottom: "1rem",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: "0.8rem",
|
||||||
|
}}
|
||||||
|
>
|
||||||
<RsvpCta label={config.rsvp_cta} onClick={onCtaClick} />
|
<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>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ interface RsvpFormProps {
|
|||||||
formState: RsvpFormState;
|
formState: RsvpFormState;
|
||||||
errors: FormErrors;
|
errors: FormErrors;
|
||||||
onSubmit: () => void;
|
onSubmit: () => void;
|
||||||
|
onShowDetails?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function RsvpForm({
|
export function RsvpForm({
|
||||||
@@ -29,6 +30,7 @@ export function RsvpForm({
|
|||||||
formState,
|
formState,
|
||||||
errors,
|
errors,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
|
onShowDetails,
|
||||||
}: RsvpFormProps) {
|
}: RsvpFormProps) {
|
||||||
const isSubmitting = formState === "submitting";
|
const isSubmitting = formState === "submitting";
|
||||||
|
|
||||||
@@ -107,6 +109,40 @@ export function RsvpForm({
|
|||||||
config.submit_label || "TE VEO AHÍ"
|
config.submit_label || "TE VEO AHÍ"
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
{onShowDetails && (
|
||||||
|
<div style={{ marginTop: "1.4rem" }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onShowDetails}
|
||||||
|
style={{
|
||||||
|
background: "none",
|
||||||
|
border: "none",
|
||||||
|
color: "var(--color-gold)",
|
||||||
|
fontSize: "0.78rem",
|
||||||
|
letterSpacing: "0.14em",
|
||||||
|
textTransform: "uppercase",
|
||||||
|
cursor: "pointer",
|
||||||
|
padding: "0.4rem 0.8rem",
|
||||||
|
borderRadius: "4px",
|
||||||
|
textDecoration: "underline",
|
||||||
|
textUnderlineOffset: "4px",
|
||||||
|
opacity: 0.85,
|
||||||
|
transition: "opacity 0.2s ease, color 0.2s ease",
|
||||||
|
}}
|
||||||
|
onMouseEnter={(e) => {
|
||||||
|
e.currentTarget.style.opacity = "1";
|
||||||
|
e.currentTarget.style.color = "var(--color-gold-light)";
|
||||||
|
}}
|
||||||
|
onMouseLeave={(e) => {
|
||||||
|
e.currentTarget.style.opacity = "0.85";
|
||||||
|
e.currentTarget.style.color = "var(--color-gold)";
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
¿Ya confirmaste? Ver ubicación y mapa ↓
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ interface RsvpResultProps {
|
|||||||
confirmedName: string;
|
confirmedName: string;
|
||||||
config: InvitationConfig;
|
config: InvitationConfig;
|
||||||
onRetry: () => void;
|
onRetry: () => void;
|
||||||
|
isDetailsOnly?: boolean;
|
||||||
|
onBackToForm?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function RsvpResult({
|
export function RsvpResult({
|
||||||
@@ -18,6 +20,8 @@ export function RsvpResult({
|
|||||||
confirmedName,
|
confirmedName,
|
||||||
config,
|
config,
|
||||||
onRetry,
|
onRetry,
|
||||||
|
isDetailsOnly = false,
|
||||||
|
onBackToForm,
|
||||||
}: RsvpResultProps) {
|
}: RsvpResultProps) {
|
||||||
const countdown = useCountdown(
|
const countdown = useCountdown(
|
||||||
config.event_date,
|
config.event_date,
|
||||||
@@ -25,14 +29,108 @@ export function RsvpResult({
|
|||||||
config.event_timezone,
|
config.event_timezone,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (isDetailsOnly) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
width: "100%",
|
||||||
|
maxWidth: "440px",
|
||||||
|
margin: "0 auto",
|
||||||
|
padding: "1.5rem 1.5rem 3.5rem 1.5rem",
|
||||||
|
textAlign: "center",
|
||||||
|
}}
|
||||||
|
aria-live="polite"
|
||||||
|
>
|
||||||
|
<h3
|
||||||
|
style={{
|
||||||
|
fontFamily: "var(--font-display)",
|
||||||
|
fontSize: "clamp(2.8rem, 9vw, 3.6rem)",
|
||||||
|
fontWeight: 400,
|
||||||
|
color: "var(--color-gold-light)",
|
||||||
|
lineHeight: 1.15,
|
||||||
|
marginBottom: "0.4rem",
|
||||||
|
textShadow: "0 2px 20px rgba(212, 168, 67, 0.4)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Ubicación del Evento
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<p
|
||||||
|
style={{
|
||||||
|
fontSize: "0.85rem",
|
||||||
|
fontWeight: 600,
|
||||||
|
letterSpacing: "0.18em",
|
||||||
|
color: "var(--color-gold)",
|
||||||
|
textTransform: "uppercase",
|
||||||
|
marginBottom: "1.5rem",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{config.address_name}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{/* Live Countdown */}
|
||||||
|
<Countdown
|
||||||
|
days={countdown.days}
|
||||||
|
hours={countdown.hours}
|
||||||
|
minutes={countdown.minutes}
|
||||||
|
seconds={countdown.seconds}
|
||||||
|
state={countdown.state}
|
||||||
|
label={config.countdown_label}
|
||||||
|
inProgressLabel={config.countdown_in_progress}
|
||||||
|
finishedLabel={config.countdown_finished}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Decorative divider dot */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "center",
|
||||||
|
gap: "0.4rem",
|
||||||
|
margin: "1.5rem 0",
|
||||||
|
color: "var(--color-gold)",
|
||||||
|
opacity: 0.5,
|
||||||
|
fontSize: "1.2rem",
|
||||||
|
}}
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<span>·</span>
|
||||||
|
<span>·</span>
|
||||||
|
<span>·</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Circular Map Preview and Venue Logistics */}
|
||||||
|
<MapPreview
|
||||||
|
previewUrl={config.map_preview_url}
|
||||||
|
mapUrl={config.map_url}
|
||||||
|
venueName={config.address_name}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<VenueInfo venueName={config.address_name} addressLines={config.address_lines} />
|
||||||
|
|
||||||
|
{onBackToForm && (
|
||||||
|
<div style={{ marginTop: "2.5rem" }}>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={onBackToForm}
|
||||||
|
style={{ fontSize: "0.75rem", padding: "0.6rem 1.4rem" }}
|
||||||
|
>
|
||||||
|
« VOLVER AL FORMULARIO DE ASISTENCIA
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (formState === "duplicate") {
|
if (formState === "duplicate") {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
width: "100%",
|
width: "100%",
|
||||||
maxWidth: "420px",
|
maxWidth: "440px",
|
||||||
margin: "0 auto",
|
margin: "0 auto",
|
||||||
padding: "2.5rem 1.5rem",
|
padding: "1.5rem 1.5rem 3.5rem 1.5rem",
|
||||||
textAlign: "center",
|
textAlign: "center",
|
||||||
}}
|
}}
|
||||||
role="alert"
|
role="alert"
|
||||||
@@ -40,30 +138,59 @@ export function RsvpResult({
|
|||||||
<h3
|
<h3
|
||||||
style={{
|
style={{
|
||||||
fontFamily: "var(--font-display)",
|
fontFamily: "var(--font-display)",
|
||||||
fontSize: "3.2rem",
|
fontSize: "clamp(2.8rem, 9vw, 3.6rem)",
|
||||||
fontWeight: 400,
|
fontWeight: 400,
|
||||||
color: "var(--color-gold-light)",
|
color: "var(--color-gold-light)",
|
||||||
marginBottom: "1rem",
|
marginBottom: "0.8rem",
|
||||||
textShadow: "0 2px 14px rgba(212, 168, 67, 0.3)",
|
textShadow: "0 2px 14px rgba(212, 168, 67, 0.3)",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
¡Ups!
|
¡Ya estás registrado!
|
||||||
</h3>
|
</h3>
|
||||||
<p
|
<p
|
||||||
style={{
|
style={{
|
||||||
fontSize: "0.92rem",
|
fontSize: "0.92rem",
|
||||||
lineHeight: 1.7,
|
lineHeight: 1.7,
|
||||||
color: "var(--color-text-muted)",
|
color: "var(--color-text-muted)",
|
||||||
marginBottom: "2rem",
|
marginBottom: "1.8rem",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{config.msg_duplicate ||
|
{config.msg_duplicate ||
|
||||||
"Parece que ya tenemos tus datos registrados. Si necesitas modificar tu información, ponte en contacto con nosotros."}
|
"Parece que ya tenemos tus datos registrados. ¡Te esperamos!"}
|
||||||
</p>
|
</p>
|
||||||
<Button variant="outline" onClick={onRetry}>
|
|
||||||
|
{/* Live Countdown */}
|
||||||
|
<Countdown
|
||||||
|
days={countdown.days}
|
||||||
|
hours={countdown.hours}
|
||||||
|
minutes={countdown.minutes}
|
||||||
|
seconds={countdown.seconds}
|
||||||
|
state={countdown.state}
|
||||||
|
label={config.countdown_label}
|
||||||
|
inProgressLabel={config.countdown_in_progress}
|
||||||
|
finishedLabel={config.countdown_finished}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Circular Map Preview and Venue Logistics */}
|
||||||
|
<MapPreview
|
||||||
|
previewUrl={config.map_preview_url}
|
||||||
|
mapUrl={config.map_url}
|
||||||
|
venueName={config.address_name}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<VenueInfo venueName={config.address_name} addressLines={config.address_lines} />
|
||||||
|
|
||||||
|
<div style={{ marginTop: "2rem" }}>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={onRetry}
|
||||||
|
style={{ fontSize: "0.75rem", padding: "0.6rem 1.4rem" }}
|
||||||
|
>
|
||||||
VOLVER AL FORMULARIO
|
VOLVER AL FORMULARIO
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,6 +30,13 @@ export interface RSVPRequest {
|
|||||||
email?: string | null;
|
email?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface RSVPUpdateRequest {
|
||||||
|
name?: string;
|
||||||
|
phone?: string;
|
||||||
|
email?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
export type RSVPApiResult =
|
export type RSVPApiResult =
|
||||||
| { result: "SUCCESS"; name: string }
|
| { result: "SUCCESS"; name: string }
|
||||||
| { result: "DUPLICATE" }
|
| { result: "DUPLICATE" }
|
||||||
|
|||||||
+31
-1
@@ -131,12 +131,14 @@ flowchart LR
|
|||||||
subgraph Public
|
subgraph Public
|
||||||
A["GET /birthday/api/config"]
|
A["GET /birthday/api/config"]
|
||||||
B["POST /birthday/api/rsvp"]
|
B["POST /birthday/api/rsvp"]
|
||||||
|
G["GET /birthday/api/map-preview.png"]
|
||||||
end
|
end
|
||||||
subgraph Admin["Admin (Remote-User required)"]
|
subgraph Admin["Admin (Remote-User required)"]
|
||||||
C["GET /birthday/api/admin/rsvps"]
|
C["GET /birthday/api/admin/rsvps"]
|
||||||
D["GET /birthday/api/admin/export"]
|
D["GET /birthday/api/admin/export"]
|
||||||
E["GET /birthday/api/admin/config"]
|
E["GET /birthday/api/admin/config"]
|
||||||
F["PUT /birthday/api/admin/config"]
|
F["PUT /birthday/api/admin/config"]
|
||||||
|
H["POST /birthday/api/admin/map-preview/generate"]
|
||||||
end
|
end
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -150,6 +152,14 @@ Serves the invitation configuration to the guest frontend.
|
|||||||
- **Response `200`:** Full `InvitationConfig` object — all fields from the config table.
|
- **Response `200`:** Full `InvitationConfig` object — all fields from the config table.
|
||||||
- **Response `500`:** `{"result": "ERROR"}` (if no config row exists — should not happen after seeding)
|
- **Response `500`:** `{"result": "ERROR"}` (if no config row exists — should not happen after seeding)
|
||||||
|
|
||||||
|
#### `GET /birthday/api/map-preview.png`
|
||||||
|
|
||||||
|
Serves the locally generated OpenStreetMap static crop image centered on the event venue.
|
||||||
|
|
||||||
|
- **Auth:** None (public)
|
||||||
|
- **Response `200`:** `image/png` static file with caching headers (`Cache-Control: public, max-age=300`).
|
||||||
|
- **Fallback:** 307 Redirect to default OSM tile if the image file has not yet been generated.
|
||||||
|
|
||||||
#### `POST /birthday/api/rsvp`
|
#### `POST /birthday/api/rsvp`
|
||||||
|
|
||||||
Submit an RSVP.
|
Submit an RSVP.
|
||||||
@@ -245,8 +255,28 @@ Update configuration (full object replacement).
|
|||||||
- `event_date` is a valid ISO 8601 date
|
- `event_date` is a valid ISO 8601 date
|
||||||
- `event_time` is a valid `HH:MM` (24-hour) string
|
- `event_time` is a valid `HH:MM` (24-hour) string
|
||||||
- `event_timezone` is a valid IANA timezone identifier
|
- `event_timezone` is a valid IANA timezone identifier
|
||||||
- URL fields are valid URLs
|
- `map_url` is a valid Google Maps URL format (`maps.app.goo.gl`, `goo.gl`, or `google.com/maps`)
|
||||||
- Text fields are non-empty where required
|
- Text fields are non-empty where required
|
||||||
|
- **Conditional Map Regeneration:**
|
||||||
|
- If `map_url` changed compared to the stored singleton, the backend automatically resolves destination coordinates, generates a fresh OpenStreetMap stitched preview PNG on disk, and points `map_preview_url` to `/birthday/api/map-preview.png`.
|
||||||
|
- If `map_url` did not change, no external network calls or image generation occur.
|
||||||
|
|
||||||
|
#### `POST /birthday/api/admin/map-preview/generate`
|
||||||
|
|
||||||
|
Regenerates the venue map preview image on disk without requiring full configuration updates or database writes.
|
||||||
|
|
||||||
|
- **Request body:** Optional JSON `{"map_url": "..."}`. If omitted, uses the currently persisted `map_url`.
|
||||||
|
- **Response `200`:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"map_preview_url": "/birthday/api/map-preview.png?t=1759338600",
|
||||||
|
"lat": 34.1432,
|
||||||
|
"lng": -118.2551,
|
||||||
|
"message": "Vista previa del mapa generada con éxito."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- **Error `422`:** If the provided URL cannot be parsed into valid geographic coordinates.
|
||||||
|
- **Side Effect:** Writes `data/map_preview.png` directly to disk, cache-busting via the returned timestamp.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -82,13 +82,13 @@ Catches all `/birthday/*` traffic that does not match a higher-priority router.
|
|||||||
|
|
||||||
| Property | Value |
|
| Property | Value |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Rule | ``Host(`demos.roadtotech.me`) && PathPrefix(`/birthday/admin`)`` |
|
| Rule | ``Host(`demos.roadtotech.me`) && (PathPrefix(`/birthday/admin`) || PathPrefix(`/birthday/api/admin`))`` |
|
||||||
| Entrypoint | `websecure` (port 443) |
|
| Entrypoint | `websecure` (port 443) |
|
||||||
| TLS | Enabled |
|
| TLS | Enabled |
|
||||||
| Middleware | `authelia-auth@docker` (ForwardAuth) |
|
| Middleware | `authelia-auth@docker` (ForwardAuth) |
|
||||||
| Priority | 20 |
|
| Priority | 20 |
|
||||||
|
|
||||||
Higher priority ensures `/birthday/admin/*` requests are intercepted before the generic public router.
|
Higher priority ensures `/birthday/admin/*` and `/birthday/api/admin/*` requests are intercepted before the generic public router.
|
||||||
|
|
||||||
### 4.3 HTTP Redirect Router — `bdinvite-red`
|
### 4.3 HTTP Redirect Router — `bdinvite-red`
|
||||||
|
|
||||||
@@ -160,7 +160,7 @@ services:
|
|||||||
- "traefik.http.routers.bdinvite-public.service=bdinvite-svc"
|
- "traefik.http.routers.bdinvite-public.service=bdinvite-svc"
|
||||||
|
|
||||||
# Admin router (Authelia-protected)
|
# Admin router (Authelia-protected)
|
||||||
- "traefik.http.routers.bdinvite-admin.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday/admin`)"
|
- "traefik.http.routers.bdinvite-admin.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && (PathPrefix(`/birthday/admin`) || PathPrefix(`/birthday/api/admin`))"
|
||||||
- "traefik.http.routers.bdinvite-admin.entrypoints=websecure"
|
- "traefik.http.routers.bdinvite-admin.entrypoints=websecure"
|
||||||
- "traefik.http.routers.bdinvite-admin.tls=true"
|
- "traefik.http.routers.bdinvite-admin.tls=true"
|
||||||
- "traefik.http.routers.bdinvite-admin.priority=20"
|
- "traefik.http.routers.bdinvite-admin.priority=20"
|
||||||
|
|||||||
Reference in new issue
Block a user