refactor(auth): enforce ruff and pyright standards, add router-level auth, and enhance logged-out UI

- Apply repository standards for ruff check and ruff format across backend
- Enforce strict typing annotations (PEP 604) for pyright compliance
- Add router-level dependency protection to admin.py (dependencies=[Depends(require_admin)])
- Incorporate dedicated logged-out UI screen in AdminLayout.tsx
- Update browser SSO acceptance test to verify the logged-out state and re-login
This commit is contained in:
kiskaadee committed 2026-10-07 06:48:57 -05:00
1 parent 381a6275c6
commit 8ce9a73176
25 files changed
+621 -285

No files matched your search

+41 -25
View File
@@ -1,4 +1,5 @@
from typing import Literal, Optional import contextlib
from typing import Literal
from fastapi import Request, Response from fastapi import Request, Response
from fastapi.responses import RedirectResponse from fastapi.responses import RedirectResponse
@@ -23,11 +24,11 @@ class OIDCAuthAdapter(AuthPort):
self, self,
oidc_client: OIDCClient, oidc_client: OIDCClient,
session_cookie_name: str = settings.SESSION_COOKIE_NAME, session_cookie_name: str = settings.SESSION_COOKIE_NAME,
session_store: Optional[SessionStore] = None, session_store: SessionStore | None = None,
cookie_secure: Optional[bool] = None, cookie_secure: bool | None = None,
cookie_samesite: Optional[Literal["lax", "strict", "none"]] = None, cookie_samesite: Literal["lax", "strict", "none"] | None = None,
session_max_age: Optional[int] = None, session_max_age: int | None = None,
secret_key: Optional[str] = None, secret_key: str | None = None,
) -> None: ) -> None:
self.oidc_client = oidc_client self.oidc_client = oidc_client
self.session_cookie_name = session_cookie_name self.session_cookie_name = session_cookie_name
@@ -35,21 +36,31 @@ class OIDCAuthAdapter(AuthPort):
session_store if session_store is not None else InMemorySessionStore() session_store if session_store is not None else InMemorySessionStore()
) )
self.cookie_secure: bool = ( self.cookie_secure: bool = (
cookie_secure if cookie_secure is not None else settings.SESSION_COOKIE_SECURE cookie_secure
if cookie_secure is not None
else settings.SESSION_COOKIE_SECURE
) )
self.cookie_samesite: Literal["lax", "strict", "none"] = ( self.cookie_samesite: Literal["lax", "strict", "none"] = (
cookie_samesite if cookie_samesite is not None else settings.SESSION_COOKIE_SAMESITE cookie_samesite
if cookie_samesite is not None
else settings.SESSION_COOKIE_SAMESITE
) )
self.session_max_age: int = ( self.session_max_age: int = (
session_max_age if session_max_age is not None else settings.SESSION_MAX_AGE_SECONDS session_max_age
if session_max_age is not None
else settings.SESSION_MAX_AGE_SECONDS
) )
self.secret_key: str = ( self.secret_key: str = (
secret_key if secret_key is not None else settings.SESSION_SECRET_KEY secret_key if secret_key is not None else settings.SESSION_SECRET_KEY
) )
def parse_session_cookie(self, cookie_value: Optional[str]) -> Optional[str]: def parse_session_cookie(self, cookie_value: str | None) -> str | None:
"""Extract and verify session_id from cookie, safely rejecting tampered cookies.""" """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(): if (
not cookie_value
or not isinstance(cookie_value, str)
or not cookie_value.strip()
):
return None return None
# 1. Attempt HMAC signature verification # 1. Attempt HMAC signature verification
@@ -71,7 +82,7 @@ class OIDCAuthAdapter(AuthPort):
return None return None
def current_identity(self, request: Request) -> Optional[Identity]: def current_identity(self, request: Request) -> Identity | None:
"""Resolve the validated identity associated with the incoming request. """Resolve the validated identity associated with the incoming request.
Identity Origin Integrity: Identity Origin Integrity:
@@ -83,9 +94,8 @@ class OIDCAuthAdapter(AuthPort):
auth_header = request.headers.get("Authorization") auth_header = request.headers.get("Authorization")
if auth_header and auth_header.startswith("Bearer "): if auth_header and auth_header.startswith("Bearer "):
token = auth_header[7:].strip() token = auth_header[7:].strip()
try: with contextlib.suppress(Exception):
return self.oidc_client.extract_identity_from_token(token) return self.oidc_client.extract_identity_from_token(token)
except Exception:
return None return None
# 2. Browser session cookie # 2. Browser session cookie
@@ -105,16 +115,15 @@ class OIDCAuthAdapter(AuthPort):
return None return None
# Fallback for backward compatibility with CP3 token-in-cookie tests # Fallback for backward compatibility with CP3 token-in-cookie tests
try: with contextlib.suppress(Exception):
return self.oidc_client.extract_identity_from_token(raw_cookie) return self.oidc_client.extract_identity_from_token(raw_cookie)
except Exception:
return None return None
def set_session_cookie( def set_session_cookie(
self, self,
response: Response, response: Response,
session_id: str, session_id: str,
max_age: Optional[int] = None, max_age: int | None = None,
) -> None: ) -> None:
"""Issue session cookie enforcing HttpOnly=True, SameSite, and configurable Secure flag.""" """Issue session cookie enforcing HttpOnly=True, SameSite, and configurable Secure flag."""
signed_val = sign_session_cookie(session_id, self.secret_key) signed_val = sign_session_cookie(session_id, self.secret_key)
@@ -140,11 +149,11 @@ class OIDCAuthAdapter(AuthPort):
def create_session( def create_session(
self, self,
identity: Optional[Identity] = None, identity: Identity | None = None,
request: Optional[Request] = None, request: Request | None = None,
response: Optional[Response] = None, response: Response | None = None,
pre_auth_session_id: Optional[str] = None, pre_auth_session_id: str | None = None,
max_age_seconds: Optional[int] = None, max_age_seconds: int | None = None,
) -> SessionData: ) -> SessionData:
"""Create session with Session Fixation Protection. """Create session with Session Fixation Protection.
@@ -172,7 +181,9 @@ class OIDCAuthAdapter(AuthPort):
assert session.session_id != candidate_pre_auth assert session.session_id != candidate_pre_auth
if response is not None: if response is not None:
self.set_session_cookie(response, session.session_id, max_age=effective_max_age) self.set_session_cookie(
response, session.session_id, max_age=effective_max_age
)
return session return session
@@ -183,8 +194,13 @@ class OIDCAuthAdapter(AuthPort):
# Issue pre-authentication session if request does not already possess one # Issue pre-authentication session if request does not already possess one
raw_cookie = request.cookies.get(self.session_cookie_name) raw_cookie = request.cookies.get(self.session_cookie_name)
existing_session_id = self.parse_session_cookie(raw_cookie) if raw_cookie else None existing_session_id = (
if not existing_session_id or self.session_store.get_session(existing_session_id) is None: 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( pre_auth = self.session_store.create_session(
identity=None, identity=None,
max_age_seconds=self.session_max_age, max_age_seconds=self.session_max_age,
+10 -8
View File
@@ -1,5 +1,5 @@
from collections.abc import Callable from collections.abc import Callable
from typing import Annotated, Optional, cast from typing import Annotated, cast
from fastapi import Depends, HTTPException, Request, status from fastapi import Depends, HTTPException, Request, status
from fastapi.params import Depends as DependsClass from fastapi.params import Depends as DependsClass
@@ -10,7 +10,7 @@ from .identity import Identity
from .oidc import OIDCClient from .oidc import OIDCClient
from .session import InMemorySessionStore from .session import InMemorySessionStore
_auth_adapter_instance: Optional[OIDCAuthAdapter] = None _auth_adapter_instance: OIDCAuthAdapter | None = None
def get_auth_adapter() -> OIDCAuthAdapter: def get_auth_adapter() -> OIDCAuthAdapter:
@@ -38,17 +38,19 @@ def get_auth_adapter() -> OIDCAuthAdapter:
def get_current_identity( def get_current_identity(
request: Request, request: Request,
adapter: OIDCAuthAdapter = Depends(get_auth_adapter), adapter: Annotated[OIDCAuthAdapter | None, Depends(get_auth_adapter)] = None,
) -> Optional[Identity]: ) -> Identity | None:
"""Resolves the active Identity from the session/adapter, or None if unauthenticated.""" """Resolves the active Identity from the session/adapter, or None if unauthenticated."""
resolved_adapter: OIDCAuthAdapter = ( resolved_adapter: OIDCAuthAdapter = (
get_auth_adapter() if isinstance(cast(object, adapter), DependsClass) else adapter get_auth_adapter()
if adapter is None or isinstance(cast(object, adapter), DependsClass)
else adapter
) )
return resolved_adapter.current_identity(request) return resolved_adapter.current_identity(request)
def require_authenticated( def require_authenticated(
identity: Optional[Identity] = Depends(get_current_identity), identity: Annotated[Identity | None, Depends(get_current_identity)] = None,
) -> Identity: ) -> Identity:
"""Enforces authentication, raising HTTP 401 Unauthorized if anonymous.""" """Enforces authentication, raising HTTP 401 Unauthorized if anonymous."""
if isinstance(cast(object, identity), DependsClass) or identity is None: if isinstance(cast(object, identity), DependsClass) or identity is None:
@@ -67,7 +69,7 @@ def require_group(group_name: str) -> Callable[..., Identity]:
""" """
def _group_dependency( def _group_dependency(
identity: Identity = Depends(require_authenticated), identity: Annotated[Identity | None, Depends(require_authenticated)] = None,
) -> Identity: ) -> Identity:
if isinstance(cast(object, identity), DependsClass) or identity is None: if isinstance(cast(object, identity), DependsClass) or identity is None:
raise HTTPException( raise HTTPException(
@@ -90,7 +92,7 @@ def require_group(group_name: str) -> Callable[..., Identity]:
require_admin: Callable[..., Identity] = require_group("bdinvite_admins") require_admin: Callable[..., Identity] = require_group("bdinvite_admins")
CurrentIdentityDep = Annotated[Optional[Identity], Depends(get_current_identity)] CurrentIdentityDep = Annotated[Identity | None, Depends(get_current_identity)]
AuthenticatedDep = Annotated[Identity, Depends(require_authenticated)] AuthenticatedDep = Annotated[Identity, Depends(require_authenticated)]
AdminDep = Annotated[Identity, Depends(require_admin)] AdminDep = Annotated[Identity, Depends(require_admin)]
+1 -2
View File
@@ -1,5 +1,4 @@
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Optional
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -14,7 +13,7 @@ class Identity:
subject: str subject: str
email: str email: str
name: Optional[str] = None name: str | None = None
groups: list[str] = field(default_factory=list) groups: list[str] = field(default_factory=list)
def __post_init__(self) -> None: def __post_init__(self) -> None:
+115 -64
View File
@@ -1,15 +1,16 @@
import base64 import base64
import contextlib
import hashlib import hashlib
import secrets import secrets
import string import string
import time import time
import urllib.parse import urllib.parse
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any, Optional from typing import Any
from fastapi import HTTPException, status
import httpx import httpx
import jwt import jwt
from fastapi import HTTPException, status
from .identity import Identity from .identity import Identity
@@ -38,14 +39,18 @@ class OIDCError(HTTPException):
class InvalidStateError(OIDCError): class InvalidStateError(OIDCError):
"""Raised when the state parameter is missing, invalid, or expired (CSRF protection).""" """Raised when the state parameter is missing, invalid, or expired (CSRF protection)."""
def __init__(self, detail: str = "Invalid, missing, or expired state parameter") -> None: def __init__(
self, detail: str = "Invalid, missing, or expired state parameter"
) -> None:
super().__init__(status_code=status.HTTP_400_BAD_REQUEST, detail=detail) super().__init__(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)
class MismatchedNonceError(OIDCError): class MismatchedNonceError(OIDCError):
"""Raised when the nonce in the ID token does not match the request nonce (Replay protection).""" """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: def __init__(
self, detail: str = "Mismatched or missing nonce claim in ID token"
) -> None:
super().__init__(status_code=status.HTTP_401_UNAUTHORIZED, detail=detail) super().__init__(status_code=status.HTTP_401_UNAUTHORIZED, detail=detail)
@@ -59,14 +64,18 @@ class InvalidTokenError(OIDCError):
class DiscoveryError(OIDCError): class DiscoveryError(OIDCError):
"""Raised when dynamic OIDC discovery configuration cannot be retrieved or parsed.""" """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: 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) super().__init__(status_code=status.HTTP_502_BAD_GATEWAY, detail=detail)
class TokenExchangeError(OIDCError): class TokenExchangeError(OIDCError):
"""Raised when the token endpoint returns an error during authorization code exchange.""" """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: def __init__(
self, detail: str = "Failed to exchange authorization code for tokens"
) -> None:
super().__init__(status_code=status.HTTP_400_BAD_REQUEST, detail=detail) super().__init__(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)
@@ -83,7 +92,7 @@ class OIDCConfig:
issuer: str issuer: str
client_id: str client_id: str
client_secret: Optional[str] = None client_secret: str | None = None
redirect_uri: str = "http://localhost:8000/birthday/api/auth/callback" redirect_uri: str = "http://localhost:8000/birthday/api/auth/callback"
scopes: list[str] = field(default_factory=lambda: list(DEFAULT_SCOPES)) scopes: list[str] = field(default_factory=lambda: list(DEFAULT_SCOPES))
groups_claim: str = "groups" groups_claim: str = "groups"
@@ -136,10 +145,10 @@ class TokenResponse:
"""Result of token endpoint exchange and cryptographic validation.""" """Result of token endpoint exchange and cryptographic validation."""
id_token: str id_token: str
access_token: Optional[str] = None access_token: str | None = None
refresh_token: Optional[str] = None refresh_token: str | None = None
token_type: Optional[str] = None token_type: str | None = None
expires_in: Optional[int] = None expires_in: int | None = None
raw: dict[str, Any] = field(default_factory=dict) raw: dict[str, Any] = field(default_factory=dict)
claims: dict[str, Any] = field(default_factory=dict) claims: dict[str, Any] = field(default_factory=dict)
@@ -147,14 +156,18 @@ class TokenResponse:
def generate_code_verifier(length: int = 64) -> str: def generate_code_verifier(length: int = 64) -> str:
"""Generate cryptographically secure PKCE code_verifier (RFC 7636 Section 4.1).""" """Generate cryptographically secure PKCE code_verifier (RFC 7636 Section 4.1)."""
if not (43 <= length <= 128): if not (43 <= length <= 128):
raise ValueError("PKCE code_verifier length must be between 43 and 128 characters") raise ValueError(
"PKCE code_verifier length must be between 43 and 128 characters"
)
return "".join(secrets.choice(PKCE_CHARSET) for _ in range(length)) return "".join(secrets.choice(PKCE_CHARSET) for _ in range(length))
def compute_code_challenge(code_verifier: str) -> str: def compute_code_challenge(code_verifier: str) -> str:
"""Derive PKCE code_challenge using SHA-256 (RFC 7636 Section 4.2).""" """Derive PKCE code_challenge using SHA-256 (RFC 7636 Section 4.2)."""
if not (43 <= len(code_verifier) <= 128): if not (43 <= len(code_verifier) <= 128):
raise ValueError("PKCE code_verifier length must be between 43 and 128 characters") raise ValueError(
"PKCE code_verifier length must be between 43 and 128 characters"
)
digest = hashlib.sha256(code_verifier.encode("ascii")).digest() digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
return base64.urlsafe_b64encode(digest).decode("ascii").rstrip("=") return base64.urlsafe_b64encode(digest).decode("ascii").rstrip("=")
@@ -174,15 +187,15 @@ class OIDCClient:
def __init__( def __init__(
self, self,
config: Optional[OIDCConfig] = None, config: OIDCConfig | None = None,
*, *,
issuer: Optional[str] = None, issuer: str | None = None,
client_id: Optional[str] = None, client_id: str | None = None,
client_secret: Optional[str] = None, client_secret: str | None = None,
redirect_uri: Optional[str] = None, redirect_uri: str | None = None,
scopes: Optional[list[str]] = None, scopes: list[str] | None = None,
groups_claim: Optional[str] = None, groups_claim: str | None = None,
discovery_doc: Optional[dict[str, Any]] = None, discovery_doc: dict[str, Any] | None = None,
timeout: float = 10.0, timeout: float = 10.0,
max_state_age_seconds: float = 600.0, max_state_age_seconds: float = 600.0,
) -> None: ) -> None:
@@ -190,20 +203,23 @@ class OIDCClient:
self.config = config self.config = config
else: else:
if not issuer or not client_id: if not issuer or not client_id:
raise ValueError("Both 'issuer' and 'client_id' are required if 'config' is not supplied") raise ValueError(
"Both 'issuer' and 'client_id' are required if 'config' is not supplied"
)
self.config = OIDCConfig( self.config = OIDCConfig(
issuer=issuer, issuer=issuer,
client_id=client_id, client_id=client_id,
client_secret=client_secret, client_secret=client_secret,
redirect_uri=redirect_uri or "http://localhost:8000/birthday/api/auth/callback", redirect_uri=redirect_uri
or "http://localhost:8000/birthday/api/auth/callback",
scopes=scopes if scopes is not None else list(DEFAULT_SCOPES), scopes=scopes if scopes is not None else list(DEFAULT_SCOPES),
groups_claim=groups_claim or "groups", groups_claim=groups_claim or "groups",
) )
self.timeout = timeout self.timeout = timeout
self.max_state_age_seconds = max_state_age_seconds self.max_state_age_seconds = max_state_age_seconds
self._discovery_doc: Optional[dict[str, Any]] = discovery_doc self._discovery_doc: dict[str, Any] | None = discovery_doc
self._jwks_client: Optional[jwt.PyJWKClient] = None self._jwks_client: jwt.PyJWKClient | None = None
self._transactions: dict[str, OIDCTransaction] = {} self._transactions: dict[str, OIDCTransaction] = {}
def get_discovery_document(self, refresh: bool = False) -> dict[str, Any]: def get_discovery_document(self, refresh: bool = False) -> dict[str, Any]:
@@ -221,19 +237,25 @@ class OIDCClient:
) )
data = response.json() data = response.json()
if not isinstance(data, dict): if not isinstance(data, dict):
raise DiscoveryError("Discovery document root must be a JSON object") raise DiscoveryError(
"Discovery document root must be a JSON object"
)
self._discovery_doc = data self._discovery_doc = data
return data return data
except DiscoveryError: except DiscoveryError:
raise raise
except Exception as e: except Exception as e:
raise DiscoveryError(f"Failed to fetch discovery document from {discovery_url}: {e}") from e raise DiscoveryError(
f"Failed to fetch discovery document from {discovery_url}: {e}"
) from e
def _get_discovery_field(self, field_name: str) -> str: def _get_discovery_field(self, field_name: str) -> str:
doc = self.get_discovery_document() doc = self.get_discovery_document()
val = doc.get(field_name) val = doc.get(field_name)
if not val or not isinstance(val, str): if not val or not isinstance(val, str):
raise DiscoveryError(f"Discovery document missing required field: {field_name}") raise DiscoveryError(
f"Discovery document missing required field: {field_name}"
)
return val return val
@property @property
@@ -249,13 +271,13 @@ class OIDCClient:
return self._get_discovery_field("jwks_uri") return self._get_discovery_field("jwks_uri")
@property @property
def userinfo_endpoint(self) -> Optional[str]: def userinfo_endpoint(self) -> str | None:
doc = self.get_discovery_document() doc = self.get_discovery_document()
val = doc.get("userinfo_endpoint") val = doc.get("userinfo_endpoint")
return str(val) if val else None return str(val) if val else None
@property @property
def end_session_endpoint(self) -> Optional[str]: def end_session_endpoint(self) -> str | None:
doc = self.get_discovery_document() doc = self.get_discovery_document()
val = doc.get("end_session_endpoint") val = doc.get("end_session_endpoint")
return str(val) if val else None return str(val) if val else None
@@ -276,7 +298,9 @@ class OIDCClient:
def get_jwks_client(self, refresh: bool = False) -> jwt.PyJWKClient: def get_jwks_client(self, refresh: bool = False) -> jwt.PyJWKClient:
"""Obtain or cache PyJWKClient for signing key resolution.""" """Obtain or cache PyJWKClient for signing key resolution."""
if self._jwks_client is None or refresh: if self._jwks_client is None or refresh:
self._jwks_client = jwt.PyJWKClient(self.jwks_uri, cache_jwk_set=True, lifespan=3600) self._jwks_client = jwt.PyJWKClient(
self.jwks_uri, cache_jwk_set=True, lifespan=3600
)
return self._jwks_client return self._jwks_client
def save_transaction(self, transaction: OIDCTransaction) -> None: def save_transaction(self, transaction: OIDCTransaction) -> None:
@@ -287,13 +311,14 @@ class OIDCClient:
def _prune_expired_transactions(self) -> None: def _prune_expired_transactions(self) -> None:
now = time.time() now = time.time()
expired = [ expired = [
s for s, tx in self._transactions.items() s
for s, tx in self._transactions.items()
if now - tx.created_at > self.max_state_age_seconds if now - tx.created_at > self.max_state_age_seconds
] ]
for s in expired: for s in expired:
self._transactions.pop(s, None) self._transactions.pop(s, None)
def validate_state(self, state: Optional[str]) -> OIDCTransaction: def validate_state(self, state: str | None) -> OIDCTransaction:
"""Validate state parameter against pending transactions, rejecting CSRF attacks with HTTP 400.""" """Validate state parameter against pending transactions, rejecting CSRF attacks with HTTP 400."""
self._prune_expired_transactions() self._prune_expired_transactions()
if not state or not isinstance(state, str) or not state.strip(): if not state or not isinstance(state, str) or not state.strip():
@@ -307,16 +332,18 @@ class OIDCClient:
def create_authorization_url( def create_authorization_url(
self, self,
state: Optional[str] = None, state: str | None = None,
nonce: Optional[str] = None, nonce: str | None = None,
code_verifier: Optional[str] = None, code_verifier: str | None = None,
scopes: Optional[list[str]] = None, scopes: list[str] | None = None,
extra_params: Optional[dict[str, str]] = None, extra_params: dict[str, str] | None = None,
) -> AuthorizationRequest: ) -> AuthorizationRequest:
"""Generate authorization URL with PKCE (S256), cryptographic state, and nonce.""" """Generate authorization URL with PKCE (S256), cryptographic state, and nonce."""
actual_state = state if state is not None else generate_state() actual_state = state if state is not None else generate_state()
actual_nonce = nonce if nonce is not None else generate_nonce() 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() actual_verifier = (
code_verifier if code_verifier is not None else generate_code_verifier()
)
code_challenge = compute_code_challenge(actual_verifier) code_challenge = compute_code_challenge(actual_verifier)
@@ -357,22 +384,24 @@ class OIDCClient:
try: try:
return jwks_client.get_signing_key_from_jwt(token) return jwks_client.get_signing_key_from_jwt(token)
except jwt.PyJWKClientError as e: except jwt.PyJWKClientError as e:
try: with contextlib.suppress(Exception):
jwk_set = jwks_client.get_jwk_set() jwk_set = jwks_client.get_jwk_set()
if jwk_set and len(jwk_set.keys) == 1: if jwk_set and len(jwk_set.keys) == 1:
return jwk_set.keys[0] return jwk_set.keys[0]
except Exception:
pass
raise InvalidTokenError(f"Signing key not found in JWKS: {e}") from e raise InvalidTokenError(f"Signing key not found in JWKS: {e}") from e
except jwt.DecodeError as e: except jwt.DecodeError as e:
raise InvalidTokenError(f"ID token signature is invalid or tampered: {e}") from e raise InvalidTokenError(
f"ID token signature is invalid or tampered: {e}"
) from e
except Exception as e: except Exception as e:
raise InvalidTokenError(f"Error resolving signing key from JWKS: {e}") from e raise InvalidTokenError(
f"Error resolving signing key from JWKS: {e}"
) from e
def verify_id_token( def verify_id_token(
self, self,
id_token: str, id_token: str,
nonce: Optional[str] = None, nonce: str | None = None,
leeway: float = 60.0, leeway: float = 60.0,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Cryptographically validate returned ID token. """Cryptographically validate returned ID token.
@@ -408,7 +437,9 @@ class OIDCClient:
except jwt.ExpiredSignatureError as e: except jwt.ExpiredSignatureError as e:
raise InvalidTokenError(f"ID token has expired: {e}") from e raise InvalidTokenError(f"ID token has expired: {e}") from e
except (jwt.InvalidSignatureError, jwt.DecodeError) as e: except (jwt.InvalidSignatureError, jwt.DecodeError) as e:
raise InvalidTokenError(f"ID token signature is invalid or tampered: {e}") from e raise InvalidTokenError(
f"ID token signature is invalid or tampered: {e}"
) from e
except (jwt.InvalidAudienceError, jwt.InvalidIssuerError) as e: except (jwt.InvalidAudienceError, jwt.InvalidIssuerError) as e:
raise InvalidTokenError(f"ID token claims validation failed: {e}") from e raise InvalidTokenError(f"ID token claims validation failed: {e}") from e
except jwt.PyJWTError as e: except jwt.PyJWTError as e:
@@ -427,10 +458,10 @@ class OIDCClient:
def exchange_code( def exchange_code(
self, self,
code: str, code: str,
state: Optional[str] = None, state: str | None = None,
code_verifier: Optional[str] = None, code_verifier: str | None = None,
nonce: Optional[str] = None, nonce: str | None = None,
extra_token_params: Optional[dict[str, str]] = None, extra_token_params: dict[str, str] | None = None,
) -> TokenResponse: ) -> TokenResponse:
"""Exchange authorization code for tokens using PKCE code_verifier and cryptographically verify ID token.""" """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(): if not code or not isinstance(code, str) or not code.strip():
@@ -455,11 +486,17 @@ class OIDCClient:
elif resolved_verifier is None: elif resolved_verifier is None:
raise InvalidPKCEError("Missing PKCE code_verifier") raise InvalidPKCEError("Missing PKCE code_verifier")
if resolved_verifier is None or not isinstance(resolved_verifier, str) or not resolved_verifier.strip(): if (
resolved_verifier is None
or not isinstance(resolved_verifier, str)
or not resolved_verifier.strip()
):
raise InvalidPKCEError("Missing or invalid PKCE code_verifier") raise InvalidPKCEError("Missing or invalid PKCE code_verifier")
# Validate code_verifier length and character set per RFC 7636 # 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): if not (43 <= len(resolved_verifier) <= 128) or not all(
c in PKCE_CHARSET for c in resolved_verifier
):
raise InvalidPKCEError( raise InvalidPKCEError(
"Invalid PKCE code_verifier: length must be between 43 and 128 unreserved characters" "Invalid PKCE code_verifier: length must be between 43 and 128 unreserved characters"
) )
@@ -473,7 +510,7 @@ class OIDCClient:
if extra_token_params: if extra_token_params:
data.update(extra_token_params) data.update(extra_token_params)
auth: Optional[httpx.BasicAuth] = None auth: httpx.BasicAuth | None = None
if self.config.client_secret: if self.config.client_secret:
auth = httpx.BasicAuth(self.config.client_id, self.config.client_secret) auth = httpx.BasicAuth(self.config.client_id, self.config.client_secret)
data["client_id"] = self.config.client_id data["client_id"] = self.config.client_id
@@ -497,19 +534,23 @@ class OIDCClient:
headers={"Accept": "application/json"}, headers={"Accept": "application/json"},
) )
except Exception as e: except Exception as e:
raise TokenExchangeError(f"Failed to communicate with token endpoint: {e}") from e raise TokenExchangeError(
f"Failed to communicate with token endpoint: {e}"
) from e
if response.status_code != 200: if response.status_code != 200:
error_data: dict[str, Any] = {} error_data: dict[str, Any] = {}
try: with contextlib.suppress(Exception):
parsed = response.json() parsed = response.json()
if isinstance(parsed, dict): if isinstance(parsed, dict):
error_data = parsed error_data = parsed
except Exception:
pass
err_desc = str(error_data.get("error_description", "")).lower() err_desc = str(error_data.get("error_description", "")).lower()
err_code = str(error_data.get("error", "")).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: if (
"pkce" in err_desc
or "code_verifier" in err_desc
or "invalid_grant" in err_code
):
raise InvalidPKCEError( raise InvalidPKCEError(
f"PKCE verification failed: {error_data.get('error_description') or error_data.get('error') or response.text}" f"PKCE verification failed: {error_data.get('error_description') or error_data.get('error') or response.text}"
) )
@@ -564,13 +605,21 @@ class OIDCClient:
email = f"{subject}@{self.config.client_id}.local" email = f"{subject}@{self.config.client_id}.local"
name_val = claims.get("name") name_val = claims.get("name")
name = str(name_val).strip() if name_val and isinstance(name_val, str) and name_val.strip() else None 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) raw_groups = _extract_claim_path(claims, self.config.groups_claim)
if isinstance(raw_groups, str): if isinstance(raw_groups, str):
groups = [raw_groups.strip()] if raw_groups.strip() else [] groups = [raw_groups.strip()] if raw_groups.strip() else []
elif isinstance(raw_groups, (list, tuple, set)): elif isinstance(raw_groups, (list, tuple, set)):
groups = [str(g).strip() for g in raw_groups if isinstance(g, str) and str(g).strip()] groups = [
str(g).strip()
for g in raw_groups
if isinstance(g, str) and str(g).strip()
]
else: else:
groups = [] groups = []
@@ -587,7 +636,7 @@ class OIDCClient:
def extract_identity_from_token( def extract_identity_from_token(
self, self,
id_token: str, id_token: str,
nonce: Optional[str] = None, nonce: str | None = None,
leeway: float = 60.0, leeway: float = 60.0,
) -> Identity: ) -> Identity:
"""Cryptographically verify ID token and extract domain Identity with origin integrity.""" """Cryptographically verify ID token and extract domain Identity with origin integrity."""
@@ -598,7 +647,7 @@ class OIDCClient:
self, self,
username: str, username: str,
password: str, password: str,
scopes: Optional[list[str]] = None, scopes: list[str] | None = None,
) -> tuple[TokenResponse, Identity]: ) -> tuple[TokenResponse, Identity]:
"""Authenticate using resource owner password credentials against IdP and extract Identity. """Authenticate using resource owner password credentials against IdP and extract Identity.
@@ -618,7 +667,7 @@ class OIDCClient:
"scope": " ".join(query_scopes), "scope": " ".join(query_scopes),
} }
auth: Optional[httpx.BasicAuth] = None auth: httpx.BasicAuth | None = None
if self.config.client_secret: if self.config.client_secret:
auth = httpx.BasicAuth(self.config.client_id, self.config.client_secret) auth = httpx.BasicAuth(self.config.client_id, self.config.client_secret)
data["client_secret"] = self.config.client_secret data["client_secret"] = self.config.client_secret
@@ -639,7 +688,9 @@ class OIDCClient:
headers={"Accept": "application/json"}, headers={"Accept": "application/json"},
) )
except Exception as e: except Exception as e:
raise TokenExchangeError(f"Failed to communicate with token endpoint: {e}") from e raise TokenExchangeError(
f"Failed to communicate with token endpoint: {e}"
) from e
if response.status_code != 200: if response.status_code != 200:
raise TokenExchangeError( raise TokenExchangeError(
+2 -2
View File
@@ -1,4 +1,4 @@
from typing import Optional, Protocol, runtime_checkable from typing import Protocol, runtime_checkable
from fastapi import Request, Response from fastapi import Request, Response
@@ -13,7 +13,7 @@ class AuthPort(Protocol):
mechanisms (such as OIDC, OAuth, ForwardAuth, or session providers). mechanisms (such as OIDC, OAuth, ForwardAuth, or session providers).
""" """
def current_identity(self, request: Request) -> Optional[Identity]: def current_identity(self, request: Request) -> Identity | None:
"""Resolve the validated identity associated with the incoming request. """Resolve the validated identity associated with the incoming request.
Returns None if the request is unauthenticated or credentials/session are invalid. Returns None if the request is unauthenticated or credentials/session are invalid.
+16 -13
View File
@@ -4,7 +4,7 @@ import secrets
import threading import threading
import time import time
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any, Optional, Protocol, runtime_checkable from typing import Any, Protocol, runtime_checkable
from .identity import Identity from .identity import Identity
@@ -14,7 +14,7 @@ class SessionData:
"""Represents an application-level browser session.""" """Represents an application-level browser session."""
session_id: str session_id: str
identity: Optional[Identity] = None identity: Identity | None = None
created_at: float = field(default_factory=time.time) created_at: float = field(default_factory=time.time)
expires_at: float = 0.0 expires_at: float = 0.0
metadata: dict[str, Any] = field(default_factory=dict) metadata: dict[str, Any] = field(default_factory=dict)
@@ -24,7 +24,7 @@ class SessionData:
"""Return True if session has a verified identity.""" """Return True if session has a verified identity."""
return self.identity is not None return self.identity is not None
def is_expired(self, current_time: Optional[float] = None) -> bool: def is_expired(self, current_time: float | None = None) -> bool:
"""Check whether the session has passed its expiration timestamp.""" """Check whether the session has passed its expiration timestamp."""
now = current_time if current_time is not None else time.time() now = current_time if current_time is not None else time.time()
return now >= self.expires_at return now >= self.expires_at
@@ -36,15 +36,15 @@ class SessionStore(Protocol):
def create_session( def create_session(
self, self,
identity: Optional[Identity] = None, identity: Identity | None = None,
max_age_seconds: int = 86400, max_age_seconds: int = 86400,
pre_auth_session_id: Optional[str] = None, pre_auth_session_id: str | None = None,
metadata: Optional[dict[str, Any]] = None, metadata: dict[str, Any] | None = None,
) -> SessionData: ) -> SessionData:
"""Create a fresh session. If pre_auth_session_id is provided, invalidate it (Session Fixation Protection).""" """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]: def get_session(self, session_id: str) -> SessionData | None:
"""Retrieve a session by its identifier. Returns None if absent or expired.""" """Retrieve a session by its identifier. Returns None if absent or expired."""
... ...
@@ -70,10 +70,10 @@ class InMemorySessionStore:
def create_session( def create_session(
self, self,
identity: Optional[Identity] = None, identity: Identity | None = None,
max_age_seconds: int = 86400, max_age_seconds: int = 86400,
pre_auth_session_id: Optional[str] = None, pre_auth_session_id: str | None = None,
metadata: Optional[dict[str, Any]] = None, metadata: dict[str, Any] | None = None,
) -> SessionData: ) -> SessionData:
"""Create a brand new session, enforcing the Session Fixation Barrier.""" """Create a brand new session, enforcing the Session Fixation Barrier."""
with self._lock: with self._lock:
@@ -87,7 +87,10 @@ class InMemorySessionStore:
# Generate fresh, unguessable cryptographic token # Generate fresh, unguessable cryptographic token
while True: while True:
new_session_id = secrets.token_urlsafe(32) new_session_id = secrets.token_urlsafe(32)
if new_session_id != pre_auth_session_id and new_session_id not in self._sessions: if (
new_session_id != pre_auth_session_id
and new_session_id not in self._sessions
):
break break
session = SessionData( session = SessionData(
@@ -100,7 +103,7 @@ class InMemorySessionStore:
self._sessions[new_session_id] = session self._sessions[new_session_id] = session
return session return session
def get_session(self, session_id: str) -> Optional[SessionData]: def get_session(self, session_id: str) -> SessionData | None:
"""Fetch session, automatically purging if expired.""" """Fetch session, automatically purging if expired."""
if not session_id or not isinstance(session_id, str): if not session_id or not isinstance(session_id, str):
return None return None
@@ -149,7 +152,7 @@ def sign_session_cookie(session_id: str, secret_key: str) -> str:
return f"{session_id}.{mac}" return f"{session_id}.{mac}"
def unsign_session_cookie(cookie_val: Optional[str], secret_key: str) -> Optional[str]: def unsign_session_cookie(cookie_val: str | None, secret_key: str) -> str | None:
"""Verify HMAC-SHA256 signature and return verified session_id, or None if tampered/invalid.""" """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(): if not cookie_val or not isinstance(cookie_val, str) or not cookie_val.strip():
return None return None
-1
View File
@@ -67,4 +67,3 @@ class Settings(BaseSettings):
settings = Settings() settings = Settings()
+3 -1
View File
@@ -129,7 +129,9 @@ if os.path.isdir(ASSETS_DIR):
@app.get("/birthday", include_in_schema=False) @app.get("/birthday", include_in_schema=False)
async def redirect_birthday_slash(): async def redirect_birthday_slash():
return RedirectResponse(url="/birthday/", status_code=status.HTTP_307_TEMPORARY_REDIRECT) return RedirectResponse(
url="/birthday/", status_code=status.HTTP_307_TEMPORARY_REDIRECT
)
@app.get("/birthday/", include_in_schema=False) @app.get("/birthday/", include_in_schema=False)
+18 -6
View File
@@ -15,7 +15,9 @@ class RSVP(Base):
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(100), nullable=False) name: Mapped[str] = mapped_column(String(100), nullable=False)
phone: Mapped[str] = mapped_column(String(20), nullable=False, unique=True, index=True) phone: Mapped[str] = mapped_column(
String(20), nullable=False, unique=True, index=True
)
email: Mapped[str | None] = mapped_column(String(255), nullable=True) email: Mapped[str | None] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column( created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=utc_now DateTime(timezone=True), nullable=False, default=utc_now
@@ -26,14 +28,20 @@ class InvitationConfig(Base):
__tablename__ = "invitation_config" __tablename__ = "invitation_config"
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=1) id: Mapped[int] = mapped_column(Integer, primary_key=True, default=1)
title: Mapped[str] = mapped_column(String(200), nullable=False, default="Birthday Party") title: Mapped[str] = mapped_column(
String(200), nullable=False, default="Birthday Party"
)
invitation_text: Mapped[str] = mapped_column( invitation_text: Mapped[str] = mapped_column(
String(500), String(500),
nullable=False, nullable=False,
default="You're invited to the birthday party honoring", default="You're invited to the birthday party honoring",
) )
honoree_name: Mapped[str] = mapped_column(String(200), nullable=False, default="Isabelle Snow") honoree_name: Mapped[str] = mapped_column(
event_date: Mapped[str] = mapped_column(String(20), nullable=False, default="2026-10-28") String(200), nullable=False, default="Isabelle Snow"
)
event_date: Mapped[str] = mapped_column(
String(20), nullable=False, default="2026-10-28"
)
event_time: Mapped[str] = mapped_column(String(10), nullable=False, default="19:00") event_time: Mapped[str] = mapped_column(String(10), nullable=False, default="19:00")
event_timezone: Mapped[str] = mapped_column( event_timezone: Mapped[str] = mapped_column(
String(50), nullable=False, default="America/Bogota" String(50), nullable=False, default="America/Bogota"
@@ -56,11 +64,15 @@ class InvitationConfig(Base):
nullable=False, nullable=False,
default="https://maps.google.com/?q=Fresco+Ristorante+Glendale+CA", default="https://maps.google.com/?q=Fresco+Ristorante+Glendale+CA",
) )
rsvp_heading: Mapped[str] = mapped_column(String(100), nullable=False, default="¿Nos vemos?") rsvp_heading: Mapped[str] = mapped_column(
String(100), nullable=False, default="¿Nos vemos?"
)
rsvp_cta: Mapped[str] = mapped_column( rsvp_cta: Mapped[str] = mapped_column(
String(100), nullable=False, default="CONFIRMA TU ASISTENCIA" String(100), nullable=False, default="CONFIRMA TU ASISTENCIA"
) )
submit_label: Mapped[str] = mapped_column(String(100), nullable=False, default="TE VEO AHÍ") submit_label: Mapped[str] = mapped_column(
String(100), nullable=False, default="TE VEO AHÍ"
)
msg_success: Mapped[str] = mapped_column( msg_success: Mapped[str] = mapped_column(
String(300), String(300),
nullable=False, nullable=False,
+39 -14
View File
@@ -25,19 +25,20 @@ from ..services.map_preview import (
) )
from ..services.rsvp import delete_rsvp, get_rsvps, update_rsvp from ..services.rsvp import delete_rsvp, get_rsvps, update_rsvp
router = APIRouter(tags=["Admin"]) router = APIRouter(tags=["Admin"], dependencies=[Depends(require_admin)])
AdminDep = Annotated[Identity, Depends(require_admin)] AdminDep = Annotated[Identity, Depends(require_admin)]
DbDep = Annotated[Session, Depends(get_db)] DbDep = Annotated[Session, Depends(get_db)]
ADMIN_RESPONSES = { ADMIN_RESPONSES = {
401: {"description": "No autenticado. Se requiere sesión activa de usuario."}, 401: {"description": "No autenticado. Se requiere sesión activa de usuario."},
403: {"description": "Acceso denegado. Se requiere pertenecer al grupo 'bdinvite_admins'."}, 403: {
"description": "Acceso denegado. Se requiere pertenecer al grupo 'bdinvite_admins'."
},
} }
ADMIN_401 = ADMIN_RESPONSES ADMIN_401 = ADMIN_RESPONSES
@router.get( @router.get(
"/rsvps", "/rsvps",
response_model=RSVPListResponse, response_model=RSVPListResponse,
@@ -47,7 +48,10 @@ ADMIN_401 = ADMIN_RESPONSES
"Permite filtrado por coincidencia parcial (`?search=`) sobre nombre, teléfono o correo." "Permite filtrado por coincidencia parcial (`?search=`) sobre nombre, teléfono o correo."
), ),
responses={ responses={
200: {"model": RSVPListResponse, "description": "Lista de confirmaciones obtenida."}, 200: {
"model": RSVPListResponse,
"description": "Lista de confirmaciones obtenida.",
},
**ADMIN_RESPONSES, **ADMIN_RESPONSES,
}, },
) )
@@ -100,10 +104,15 @@ def delete_rsvp_endpoint(
summary="Editar una confirmación de asistencia", summary="Editar una confirmación de asistencia",
description="Actualiza el nombre, teléfono o correo de un asistente confirmado.", description="Actualiza el nombre, teléfono o correo de un asistente confirmado.",
responses={ responses={
200: {"model": RSVPAdminItem, "description": "Registro actualizado exitosamente."}, 200: {
"model": RSVPAdminItem,
"description": "Registro actualizado exitosamente.",
},
400: {"description": "Error de validación en los campos proporcionados."}, 400: {"description": "Error de validación en los campos proporcionados."},
404: {"description": "Registro no encontrado."}, 404: {"description": "Registro no encontrado."},
409: {"description": "El número de teléfono ya está registrado por otro asistente."}, 409: {
"description": "El número de teléfono ya está registrado por otro asistente."
},
**ADMIN_RESPONSES, **ADMIN_RESPONSES,
}, },
) )
@@ -129,7 +138,6 @@ def update_rsvp_endpoint(
return updated return updated
@router.get( @router.get(
"/export", "/export",
summary="Exportar confirmaciones en formato CSV", summary="Exportar confirmaciones en formato CSV",
@@ -158,7 +166,11 @@ def export_rsvps_csv(
for item in rsvps: for item in rsvps:
created_iso = "" created_iso = ""
if item.created_at: if item.created_at:
dt = item.created_at if item.created_at.tzinfo else item.created_at.replace(tzinfo=UTC) dt = (
item.created_at
if item.created_at.tzinfo
else item.created_at.replace(tzinfo=UTC)
)
created_iso = dt.isoformat() 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])
@@ -176,7 +188,10 @@ def export_rsvps_csv(
summary="Obtener configuración editable", summary="Obtener configuración editable",
description="Retorna el objeto completo de configuración para poblar el formulario de administración.", description="Retorna el objeto completo de configuración para poblar el formulario de administración.",
responses={ responses={
200: {"model": InvitationConfigResponse, "description": "Configuración obtenida correctamente."}, 200: {
"model": InvitationConfigResponse,
"description": "Configuración obtenida correctamente.",
},
**ADMIN_RESPONSES, **ADMIN_RESPONSES,
}, },
) )
@@ -201,7 +216,10 @@ def get_admin_config(
"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_RESPONSES, **ADMIN_RESPONSES,
}, },
) )
@@ -216,7 +234,10 @@ def get_admin_config(
"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_RESPONSES, **ADMIN_RESPONSES,
}, },
) )
@@ -262,7 +283,10 @@ async def update_admin_config(
"sin realizar escrituras innecesarias a la base de datos." "sin realizar escrituras innecesarias a la base de datos."
), ),
responses={ responses={
200: {"model": GenerateMapPreviewResponse, "description": "Vista previa generada exitosamente."}, 200: {
"model": GenerateMapPreviewResponse,
"description": "Vista previa generada exitosamente.",
},
**ADMIN_RESPONSES, **ADMIN_RESPONSES,
}, },
) )
@@ -282,7 +306,9 @@ async def regenerate_map_preview_endpoint(
target_url = current.map_url target_url = current.map_url
try: try:
fallback = f"{current.address_lines}\n{current.address_name}" if current else None fallback = (
f"{current.address_lines}\n{current.address_name}" if current else None
)
lat, lng, _ = await resolve_google_maps_coordinates( lat, lng, _ = await resolve_google_maps_coordinates(
target_url, fallback_query=fallback target_url, fallback_query=fallback
) )
@@ -305,4 +331,3 @@ async def regenerate_map_preview_endpoint(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Error al generar la vista previa del mapa: {err}", detail=f"Error al generar la vista previa del mapa: {err}",
) from err ) from err
+9 -5
View File
@@ -1,7 +1,7 @@
from typing import Annotated, Optional from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, status from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, status
from fastapi.responses import JSONResponse, RedirectResponse from fastapi.responses import RedirectResponse
from ..auth import Identity, OIDCAuthAdapter from ..auth import Identity, OIDCAuthAdapter
from ..auth.dependencies import get_auth_adapter from ..auth.dependencies import get_auth_adapter
@@ -71,13 +71,17 @@ def direct_login_endpoint(
def callback_endpoint( def callback_endpoint(
request: Request, request: Request,
adapter: AuthAdapterDep, adapter: AuthAdapterDep,
code: Annotated[str, Query(description="Código de autorización devuelto por el IdP")], 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")], state: Annotated[str, Query(description="Token de estado para validación CSRF")],
): ):
token_response = adapter.oidc_client.exchange_code(code=code, state=state) token_response = adapter.oidc_client.exchange_code(code=code, state=state)
identity = adapter.oidc_client.extract_identity(token_response.claims) identity = adapter.oidc_client.extract_identity(token_response.claims)
redirect_response = RedirectResponse(url="/birthday/admin", status_code=status.HTTP_302_FOUND) redirect_response = RedirectResponse(
url="/birthday/admin", status_code=status.HTTP_302_FOUND
)
adapter.create_session( adapter.create_session(
identity=identity, identity=identity,
request=request, request=request,
@@ -96,7 +100,7 @@ def me_endpoint(
request: Request, request: Request,
adapter: AuthAdapterDep, adapter: AuthAdapterDep,
): ):
identity: Optional[Identity] = adapter.current_identity(request) identity: Identity | None = adapter.current_identity(request)
if identity is None: if identity is None:
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
+42 -18
View File
@@ -6,7 +6,6 @@ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator
def normalize_phone(raw: str) -> str: def normalize_phone(raw: str) -> str:
"""Normalize Colombian mobile numbers. """Normalize Colombian mobile numbers.
@@ -127,8 +126,6 @@ class RSVPUpdate(BaseModel):
return cleaned.lower() return cleaned.lower()
class RSVPSuccessResponse(BaseModel): class RSVPSuccessResponse(BaseModel):
result: Literal["SUCCESS"] = Field( result: Literal["SUCCESS"] = Field(
default="SUCCESS", default="SUCCESS",
@@ -168,11 +165,27 @@ class RSVPErrorResponse(BaseModel):
class RSVPAdminItem(BaseModel): class RSVPAdminItem(BaseModel):
id: int = Field(..., description="Identificador único del registro en base de datos", examples=[1]) id: int = Field(
name: str = Field(..., description="Nombre completo del asistente", examples=["Ana García"]) ...,
phone: str = Field(..., description="Número telefónico normalizado a 10 dígitos", examples=["3001234567"]) description="Identificador único del registro en base de datos",
email: str | None = Field(default=None, description="Correo electrónico registrado", examples=["ana@example.com"]) examples=[1],
created_at: datetime = Field(..., description="Marca de tiempo UTC de la confirmación") )
name: str = Field(
..., description="Nombre completo del asistente", examples=["Ana García"]
)
phone: str = Field(
...,
description="Número telefónico normalizado a 10 dígitos",
examples=["3001234567"],
)
email: str | None = Field(
default=None,
description="Correo electrónico registrado",
examples=["ana@example.com"],
)
created_at: datetime = Field(
..., description="Marca de tiempo UTC de la confirmación"
)
model_config = ConfigDict(from_attributes=True) model_config = ConfigDict(from_attributes=True)
@@ -183,10 +196,13 @@ class RSVPAdminItem(BaseModel):
return dt.isoformat() return dt.isoformat()
class RSVPListResponse(BaseModel): class RSVPListResponse(BaseModel):
count: int = Field(..., description="Cantidad total de confirmaciones encontradas", examples=[37]) count: int = Field(
rsvps: list[RSVPAdminItem] = Field(..., description="Lista de asistentes confirmados") ..., description="Cantidad total de confirmaciones encontradas", examples=[37]
)
rsvps: list[RSVPAdminItem] = Field(
..., description="Lista de asistentes confirmados"
)
class InvitationConfigBase(BaseModel): class InvitationConfigBase(BaseModel):
@@ -376,8 +392,12 @@ class InvitationConfigUpdate(InvitationConfigBase):
class InvitationConfigResponse(InvitationConfigBase): class InvitationConfigResponse(InvitationConfigBase):
id: int = Field(default=1, description="Identificador único del registro singleton (siempre 1)") id: int = Field(
updated_at: datetime | None = Field(default=None, description="Última modificación en UTC") default=1, description="Identificador único del registro singleton (siempre 1)"
)
updated_at: datetime | None = Field(
default=None, description="Última modificación en UTC"
)
model_config = ConfigDict(from_attributes=True) model_config = ConfigDict(from_attributes=True)
@@ -390,7 +410,6 @@ class InvitationConfigResponse(InvitationConfigBase):
return dt.isoformat() return dt.isoformat()
class GenerateMapPreviewRequest(BaseModel): class GenerateMapPreviewRequest(BaseModel):
map_url: str | None = Field( map_url: str | None = Field(
default=None, default=None,
@@ -400,14 +419,18 @@ class GenerateMapPreviewRequest(BaseModel):
class GenerateMapPreviewResponse(BaseModel): class GenerateMapPreviewResponse(BaseModel):
map_preview_url: str = Field(description="URL para acceder a la imagen de vista previa generada") map_preview_url: str = Field(
description="URL para acceder a la imagen de vista previa generada"
)
lat: float = Field(description="Latitud resuelta") lat: float = Field(description="Latitud resuelta")
lng: float = Field(description="Longitud resuelta") lng: float = Field(description="Longitud resuelta")
message: str = Field(default="Vista previa generada con éxito") message: str = Field(default="Vista previa generada con éxito")
class LoginRequest(BaseModel): class LoginRequest(BaseModel):
username: str = Field(..., description="Nombre de usuario o correo para autenticación OIDC") username: str = Field(
..., description="Nombre de usuario o correo para autenticación OIDC"
)
password: str = Field(..., description="Contraseña de usuario") password: str = Field(..., description="Contraseña de usuario")
@@ -415,5 +438,6 @@ class UserResponse(BaseModel):
subject: str = Field(..., description="Identificador único del usuario (sub)") subject: str = Field(..., description="Identificador único del usuario (sub)")
email: str = Field(..., description="Correo electrónico del usuario") email: str = Field(..., description="Correo electrónico del usuario")
name: str | None = Field(default=None, description="Nombre visible 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") groups: list[str] = Field(
default_factory=list, description="Grupos o roles asignados al usuario"
)
+19 -17
View File
@@ -1,3 +1,4 @@
import contextlib
import io import io
import math import math
import re import re
@@ -27,12 +28,10 @@ def is_google_maps_host(host: str) -> bool:
return True return True
if clean_host.startswith("maps.google."): if clean_host.startswith("maps.google."):
return True return True
if clean_host == "google.com" or clean_host.endswith(".google.com") or clean_host.endswith(".google"): if clean_host == "google.com" or clean_host.endswith((".google.com", ".google")):
return True return True
# Regional domains like google.es, google.co, google.com.co # Regional domains like google.es, google.co, google.com.co
if re.match(r"^(?:www\.)?google\.[a-z.]+$", clean_host): return bool(re.match(r"^(?:www\.)?google\.[a-z.]+$", clean_host))
return True
return False
def validate_google_maps_url_format(url: str) -> None: def validate_google_maps_url_format(url: str) -> None:
@@ -74,7 +73,7 @@ def extract_coordinates_from_text(text: str) -> tuple[float, float] | None:
if parsed.query: if parsed.query:
qs = parse_qs(parsed.query) qs = parse_qs(parsed.query)
for param in ("q", "ll", "destination"): for param in ("q", "ll", "destination"):
if param in qs and qs[param]: if qs.get(param):
val = qs[param][0].strip() val = qs[param][0].strip()
m = re.match(r"^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$", val) m = re.match(r"^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$", val)
if m: if m:
@@ -118,7 +117,9 @@ async def resolve_google_maps_coordinates(
if hop_coords: if hop_coords:
return hop_coords[0], hop_coords[1], resolved_url return hop_coords[0], hop_coords[1], resolved_url
except httpx.RequestError as exc: except httpx.RequestError as exc:
raise ValueError(f"No se pudo resolver el enlace de Google Maps: {exc}") from exc raise ValueError(
f"No se pudo resolver el enlace de Google Maps: {exc}"
) from exc
# Try extraction on the final resolved destination URL # Try extraction on the final resolved destination URL
final_coords = extract_coordinates_from_text(resolved_url) final_coords = extract_coordinates_from_text(resolved_url)
@@ -129,7 +130,7 @@ async def resolve_google_maps_coordinates(
parsed = urlparse(resolved_url) parsed = urlparse(resolved_url)
qs = parse_qs(parsed.query) qs = parse_qs(parsed.query)
query_text = None query_text = None
if "q" in qs and qs["q"]: if qs.get("q"):
query_text = qs["q"][0] query_text = qs["q"][0]
elif "/place/" in parsed.path: elif "/place/" in parsed.path:
# e.g. /maps/place/Fresco+Ristorante/... # e.g. /maps/place/Fresco+Ristorante/...
@@ -153,9 +154,11 @@ async def resolve_google_maps_coordinates(
candidates.append(query_text) candidates.append(query_text)
if candidates: if candidates:
async with httpx.AsyncClient(timeout=8.0, headers={"User-Agent": USER_AGENT}) as client: async with httpx.AsyncClient(
timeout=8.0, headers={"User-Agent": USER_AGENT}
) as client:
for candidate in candidates: for candidate in candidates:
try: with contextlib.suppress(Exception):
nom_res = await client.get( nom_res = await client.get(
"https://nominatim.openstreetmap.org/search", "https://nominatim.openstreetmap.org/search",
params={"q": candidate, "format": "json", "limit": 1}, params={"q": candidate, "format": "json", "limit": 1},
@@ -167,8 +170,6 @@ async def resolve_google_maps_coordinates(
lng = float(results[0]["lon"]) lng = float(results[0]["lon"])
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0: if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
return lat, lng, resolved_url return lat, lng, resolved_url
except Exception:
pass
raise ValueError( raise ValueError(
"No se pudieron extraer las coordenadas de la URL de Google Maps. " "No se pudieron extraer las coordenadas de la URL de Google Maps. "
@@ -207,18 +208,17 @@ async def generate_map_preview_image(
# Canvas of 3x3 tiles = 768x768 pixels # Canvas of 3x3 tiles = 768x768 pixels
canvas = Image.new("RGB", (768, 768), color=(229, 227, 223)) canvas = Image.new("RGB", (768, 768), color=(229, 227, 223))
async with httpx.AsyncClient(timeout=10.0, headers={"User-Agent": USER_AGENT}) as client: async with httpx.AsyncClient(
timeout=10.0, headers={"User-Agent": USER_AGENT}
) as client:
for r_idx, y in enumerate(range(y_int - 1, y_int + 2)): for 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)): for c_idx, x in enumerate(range(x_int - 1, x_int + 2)):
tile_url = f"https://tile.openstreetmap.org/{zoom}/{x}/{y}.png" tile_url = f"https://tile.openstreetmap.org/{zoom}/{x}/{y}.png"
try: with contextlib.suppress(Exception):
res = await client.get(tile_url) res = await client.get(tile_url)
if res.status_code == 200: if res.status_code == 200:
tile = Image.open(io.BytesIO(res.content)).convert("RGB") tile = Image.open(io.BytesIO(res.content)).convert("RGB")
canvas.paste(tile, (c_idx * 256, r_idx * 256)) 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 # Exact target location within the 768x768 canvas
cx = 256 + int(dx * 256) cx = 256 + int(dx * 256)
@@ -236,7 +236,9 @@ async def generate_map_preview_image(
draw.ellipse((192, 198, 208, 204), fill=(40, 40, 40, 140)) draw.ellipse((192, 198, 208, 204), fill=(40, 40, 40, 140))
# Golden pin pointer (inverted triangle) # Golden pin pointer (inverted triangle)
draw.polygon([(188, 184), (212, 184), (200, 200)], fill="#d4a843", outline="#1a1a1a") draw.polygon(
[(188, 184), (212, 184), (200, 200)], fill="#d4a843", outline="#1a1a1a"
)
# Golden pin circular head # Golden pin circular head
draw.ellipse((188, 170, 212, 194), fill="#d4a843", outline="#1a1a1a", width=2) draw.ellipse((188, 170, 212, 194), fill="#d4a843", outline="#1a1a1a", width=2)
-2
View File
@@ -113,5 +113,3 @@ def update_rsvp(
except Exception: except Exception:
db.rollback() db.rollback()
raise raise
+3 -2
View File
@@ -88,6 +88,7 @@ def admin_client(client: TestClient) -> TestClient:
@pytest.fixture(scope="function") @pytest.fixture(scope="function")
def guest_client(client: TestClient) -> TestClient: def guest_client(client: TestClient) -> TestClient:
login_client(client, subject="guest-001", email="guest@example.com", groups=["guests"]) login_client(
client, subject="guest-001", email="guest@example.com", groups=["guests"]
)
return client return client
+45 -9
View File
@@ -28,8 +28,18 @@ def test_remote_user_header_strictly_ignored(client: TestClient):
assert res.json() == {"detail": "Not authenticated"} assert res.json() == {"detail": "Not authenticated"}
# Also verify across other admin routes # Also verify across other admin routes
assert client.get("/birthday/api/admin/export", headers={"Remote-User": "kiskaadee"}).status_code == 401 assert (
assert client.get("/birthday/api/admin/config", headers={"Remote-User": "kiskaadee"}).status_code == 401 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 ( assert (
client.post( client.post(
"/birthday/api/admin/map-preview/generate", "/birthday/api/admin/map-preview/generate",
@@ -54,7 +64,9 @@ def test_admin_endpoints_authenticated_non_admin_forbidden(guest_client: TestCli
] ]
for method, path in endpoints: for method, path in endpoints:
res = guest_client.request(method, path) res = guest_client.request(method, path)
assert res.status_code == 403, f"{method} {path} should reject non-admin with 403" assert res.status_code == 403, (
f"{method} {path} should reject non-admin with 403"
)
assert "Forbidden" in res.json()["detail"] assert "Forbidden" in res.json()["detail"]
@@ -91,11 +103,19 @@ def test_admin_list_and_search_rsvps(admin_client: TestClient):
# Add 3 invitees # Add 3 invitees
admin_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",
},
) )
admin_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",
},
) )
admin_client.post( admin_client.post(
"/birthday/api/rsvp", "/birthday/api/rsvp",
@@ -124,7 +144,11 @@ def test_admin_list_and_search_rsvps(admin_client: TestClient):
def test_admin_export_csv(admin_client: TestClient): def test_admin_export_csv(admin_client: TestClient):
admin_client.post( admin_client.post(
"/birthday/api/rsvp", "/birthday/api/rsvp",
json={"name": "Sofia Vergara", "phone": "301 999 8877", "email": "sofia@hollywood.com"}, json={
"name": "Sofia Vergara",
"phone": "301 999 8877",
"email": "sofia@hollywood.com",
},
) )
res = admin_client.get("/birthday/api/admin/export") res = admin_client.get("/birthday/api/admin/export")
@@ -133,7 +157,11 @@ def test_admin_export_csv(admin_client: TestClient):
assert 'filename="rsvps.csv"' in res.headers["content-disposition"] assert 'filename="rsvps.csv"' in res.headers["content-disposition"]
content = res.text content = res.text
lines = content.strip().split("\r\n") if "\r\n" in content else content.strip().split("\n") lines = (
content.strip().split("\r\n")
if "\r\n" in content
else content.strip().split("\n")
)
assert lines[0] == "name,phone,email,created_at" assert 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]
@@ -153,7 +181,11 @@ def test_admin_delete_rsvp(client: TestClient):
# Create an RSVP # Create an RSVP
client.post( client.post(
"/birthday/api/rsvp", "/birthday/api/rsvp",
json={"name": "Lucas Silva", "phone": "300 444 5566", "email": "lucas@test.com"}, json={
"name": "Lucas Silva",
"phone": "300 444 5566",
"email": "lucas@test.com",
},
) )
list_res = client.get("/birthday/api/admin/rsvps") list_res = client.get("/birthday/api/admin/rsvps")
assert list_res.status_code == 200 assert list_res.status_code == 200
@@ -204,7 +236,11 @@ def test_admin_update_rsvp(client: TestClient):
# Update Person One with valid new name and phone # Update Person One with valid new name and phone
patch_res = client.patch( patch_res = client.patch(
f"/birthday/api/admin/rsvps/{id_one}", f"/birthday/api/admin/rsvps/{id_one}",
json={"name": "Person One Updated", "phone": "+57 300 999 8888", "email": "newone@test.com"}, json={
"name": "Person One Updated",
"phone": "+57 300 999 8888",
"email": "newone@test.com",
},
) )
assert patch_res.status_code == 200 assert patch_res.status_code == 200
updated_data = patch_res.json() updated_data = patch_res.json()
+3 -5
View File
@@ -1,10 +1,8 @@
from dataclasses import FrozenInstanceError from dataclasses import FrozenInstanceError
from typing import Optional
import pytest import pytest
from fastapi import Request, Response from fastapi import Request, Response
from fastapi.responses import RedirectResponse from fastapi.responses import RedirectResponse
from starlette.datastructures import Headers
from app.auth import AuthPort, Identity from app.auth import AuthPort, Identity
@@ -12,10 +10,10 @@ from app.auth import AuthPort, Identity
class MockAuthAdapter: class MockAuthAdapter:
"""Mock implementation of AuthPort for testing hexagonal boundary compliance.""" """Mock implementation of AuthPort for testing hexagonal boundary compliance."""
def __init__(self, current_user: Optional[Identity] = None): def __init__(self, current_user: Identity | None = None):
self._current_user = current_user self._current_user = current_user
def current_identity(self, request: Request) -> Optional[Identity]: def current_identity(self, request: Request) -> Identity | None:
return self._current_user return self._current_user
def login(self, request: Request) -> Response: def login(self, request: Request) -> Response:
@@ -28,7 +26,7 @@ class MockAuthAdapter:
class IncompleteAuthAdapter: class IncompleteAuthAdapter:
"""Non-conforming class missing login and logout methods.""" """Non-conforming class missing login and logout methods."""
def current_identity(self, request: Request) -> Optional[Identity]: def current_identity(self, request: Request) -> Identity | None:
return None return None
+13 -6
View File
@@ -1,6 +1,7 @@
import contextlib
import threading import threading
import time import time
from typing import Generator from collections.abc import Generator
import pytest import pytest
import uvicorn import uvicorn
@@ -31,13 +32,11 @@ def live_server() -> Generator[str, None, None]:
ready = False ready = False
for _ in range(50): for _ in range(50):
try: with contextlib.suppress(Exception):
r = httpx.get(f"{BASE_URL}/birthday/api/docs", timeout=0.5) r = httpx.get(f"{BASE_URL}/birthday/api/docs", timeout=0.5)
if r.status_code == 200: if r.status_code == 200:
ready = True ready = True
break break
except Exception:
pass
time.sleep(0.1) time.sleep(0.1)
assert ready, "Server failed to start in time" assert ready, "Server failed to start in time"
@@ -99,7 +98,9 @@ def test_browser_sso_complete_interactive_loop(
assert page.url.endswith("/birthday/admin") assert page.url.endswith("/birthday/admin")
cookies = browser_context.cookies() cookies = browser_context.cookies()
session_cookie = next((c for c in cookies if c.get("name") == "bdinvite_session"), None) 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 is not None, "bdinvite_session cookie must be set"
assert session_cookie.get("httpOnly") is True, "Session cookie must be HttpOnly" assert session_cookie.get("httpOnly") is True, "Session cookie must be HttpOnly"
@@ -118,7 +119,13 @@ def test_browser_sso_complete_interactive_loop(
assert logout_btn.is_visible() assert logout_btn.is_visible()
logout_btn.click() logout_btn.click()
# Verify navigation returns to unauthenticated state (redirect to OIDC authorize) # UI displays unauthenticated state screen
page.wait_for_selector("[data-testid='unauthenticated-state']", timeout=10000)
assert page.locator("[data-testid='unauthenticated-state']").is_visible()
assert page.locator("text=Sesión Finalizada").is_visible()
# Re-clicking login initiates fresh OIDC flow
page.locator("[data-testid='login-btn']").click()
page.wait_for_url("**/authorize**", timeout=10000) page.wait_for_url("**/authorize**", timeout=10000)
assert "authorize" in page.url assert "authorize" in page.url
+14 -8
View File
@@ -1,8 +1,8 @@
from typing import Optional from typing import Annotated
import pytest
from fastapi import Depends, FastAPI, HTTPException, Request from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
import pytest
from app.auth import ( from app.auth import (
Identity, Identity,
@@ -24,8 +24,8 @@ REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
def create_dummy_request( def create_dummy_request(
headers: Optional[dict[str, str]] = None, headers: dict[str, str] | None = None,
cookies: Optional[dict[str, str]] = None, cookies: dict[str, str] | None = None,
) -> Request: ) -> Request:
"""Construct a lightweight ASGI Request instance for unit testing dependencies.""" """Construct a lightweight ASGI Request instance for unit testing dependencies."""
raw_headers: list[tuple[bytes, bytes]] = [ raw_headers: list[tuple[bytes, bytes]] = [
@@ -73,8 +73,12 @@ def test_app() -> FastAPI:
"""Isolated FastAPI test harness registering dependency endpoints.""" """Isolated FastAPI test harness registering dependency endpoints."""
app = FastAPI(title="Dependency Test Harness") app = FastAPI(title="Dependency Test Harness")
event_planners_dep = require_group("event_planners")
@app.get("/test/identity") @app.get("/test/identity")
def route_identity(identity: Optional[Identity] = Depends(get_current_identity)): def route_identity(
identity: Annotated[Identity | None, Depends(get_current_identity)],
):
if identity is None: if identity is None:
return {"authenticated": False, "identity": None} return {"authenticated": False, "identity": None}
return { return {
@@ -85,7 +89,9 @@ def test_app() -> FastAPI:
} }
@app.get("/test/authenticated") @app.get("/test/authenticated")
def route_authenticated(identity: Identity = Depends(require_authenticated)): def route_authenticated(
identity: Annotated[Identity, Depends(require_authenticated)],
):
return { return {
"subject": identity.subject, "subject": identity.subject,
"email": identity.email, "email": identity.email,
@@ -93,7 +99,7 @@ def test_app() -> FastAPI:
} }
@app.get("/test/admin") @app.get("/test/admin")
def route_admin(admin: Identity = Depends(require_admin)): def route_admin(admin: Annotated[Identity, Depends(require_admin)]):
return { return {
"subject": admin.subject, "subject": admin.subject,
"email": admin.email, "email": admin.email,
@@ -101,7 +107,7 @@ def test_app() -> FastAPI:
} }
@app.get("/test/custom-group") @app.get("/test/custom-group")
def route_custom_group(member: Identity = Depends(require_group("event_planners"))): def route_custom_group(member: Annotated[Identity, Depends(event_planners_dep)]):
return { return {
"subject": member.subject, "subject": member.subject,
"groups": member.groups, "groups": member.groups,
+30 -17
View File
@@ -1,10 +1,7 @@
from dataclasses import FrozenInstanceError from dataclasses import FrozenInstanceError
from typing import Optional
from fastapi import Request, Response
from fastapi.responses import RedirectResponse
import httpx
import pytest import pytest
from fastapi import Request, Response
from app.auth import ( from app.auth import (
AuthPort, AuthPort,
@@ -12,8 +9,6 @@ from app.auth import (
InvalidTokenError, InvalidTokenError,
OIDCAuthAdapter, OIDCAuthAdapter,
OIDCClient, OIDCClient,
OIDCConfig,
TokenExchangeError,
) )
LIVE_ISSUER = "http://localhost:8088/default" LIVE_ISSUER = "http://localhost:8088/default"
@@ -34,8 +29,8 @@ def oidc_client() -> OIDCClient:
def create_dummy_request( def create_dummy_request(
headers: Optional[dict[str, str]] = None, headers: dict[str, str] | None = None,
cookies: Optional[dict[str, str]] = None, cookies: dict[str, str] | None = None,
) -> Request: ) -> Request:
raw_headers = [ raw_headers = [
(k.lower().encode("latin-1"), v.encode("latin-1")) (k.lower().encode("latin-1"), v.encode("latin-1"))
@@ -91,7 +86,9 @@ def test_identity_resolution_missing_email_and_name_defaults(oidc_client: OIDCCl
assert identity.groups == [] assert identity.groups == []
def test_identity_resolution_missing_subject_raises_invalid_token(oidc_client: OIDCClient): def test_identity_resolution_missing_subject_raises_invalid_token(
oidc_client: OIDCClient,
):
"""Missing or empty sub claim raises InvalidTokenError.""" """Missing or empty sub claim raises InvalidTokenError."""
with pytest.raises(InvalidTokenError, match="missing required 'sub' claim"): with pytest.raises(InvalidTokenError, match="missing required 'sub' claim"):
oidc_client.extract_identity({}) oidc_client.extract_identity({})
@@ -112,10 +109,14 @@ def test_identity_groups_extraction_clean_defaults(oidc_client: OIDCClient):
assert oidc_client.extract_identity({"sub": "u1", "groups": []}).groups == [] assert oidc_client.extract_identity({"sub": "u1", "groups": []}).groups == []
# Single string group # Single string group
assert oidc_client.extract_identity({"sub": "u1", "groups": "single_role"}).groups == ["single_role"] assert oidc_client.extract_identity(
{"sub": "u1", "groups": "single_role"}
).groups == ["single_role"]
# Tuple / Set collections # Tuple / Set collections
assert oidc_client.extract_identity({"sub": "u1", "groups": ("admin", "editor")}).groups == ["admin", "editor"] assert oidc_client.extract_identity(
{"sub": "u1", "groups": ("admin", "editor")}
).groups == ["admin", "editor"]
# Discard non-string, empty strings, and trim whitespace # Discard non-string, empty strings, and trim whitespace
claims = {"sub": "u1", "groups": [" admin ", "", " ", 123, None, "editor"]} claims = {"sub": "u1", "groups": [" admin ", "", " ", 123, None, "editor"]}
@@ -150,7 +151,9 @@ def test_identity_groups_configurable_claim_path():
assert nested_client.extract_identity(claims_nested).groups == ["app_admin", "user"] assert nested_client.extract_identity(claims_nested).groups == ["app_admin", "user"]
# Nested path missing # Nested path missing
assert nested_client.extract_identity({"sub": "u1", "realm_access": {}}).groups == [] assert (
nested_client.extract_identity({"sub": "u1", "realm_access": {}}).groups == []
)
assert nested_client.extract_identity({"sub": "u1"}).groups == [] assert nested_client.extract_identity({"sub": "u1"}).groups == []
@@ -208,7 +211,9 @@ def test_live_fixture_guest_user_authentication(oidc_client: OIDCClient):
# ============================================================================== # ==============================================================================
def test_identity_origin_integrity_rejection_of_unvalidated_request_headers(oidc_client: OIDCClient): 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.""" """Application adapter rejects constructing Identity from raw request headers or client data."""
adapter = OIDCAuthAdapter(oidc_client=oidc_client) adapter = OIDCAuthAdapter(oidc_client=oidc_client)
@@ -241,7 +246,9 @@ def test_identity_origin_integrity_rejection_of_tampered_token(oidc_client: OIDC
oidc_client.extract_identity_from_token(tampered_sig_token) oidc_client.extract_identity_from_token(tampered_sig_token)
# Case 2: Adapter with tampered token in Authorization header returns None # Case 2: Adapter with tampered token in Authorization header returns None
bad_request = create_dummy_request(headers={"Authorization": f"Bearer {tampered_sig_token}"}) bad_request = create_dummy_request(
headers={"Authorization": f"Bearer {tampered_sig_token}"}
)
adapter = OIDCAuthAdapter(oidc_client=oidc_client) adapter = OIDCAuthAdapter(oidc_client=oidc_client)
assert adapter.current_identity(bad_request) is None assert adapter.current_identity(bad_request) is None
@@ -284,7 +291,9 @@ def test_oidc_auth_adapter_current_identity_with_valid_bearer(oidc_client: OIDCC
) )
adapter = OIDCAuthAdapter(oidc_client=oidc_client) adapter = OIDCAuthAdapter(oidc_client=oidc_client)
req = create_dummy_request(headers={"Authorization": f"Bearer {token_resp.id_token}"}) req = create_dummy_request(
headers={"Authorization": f"Bearer {token_resp.id_token}"}
)
resolved = adapter.current_identity(req) resolved = adapter.current_identity(req)
assert resolved == expected_identity assert resolved == expected_identity
@@ -300,7 +309,9 @@ def test_oidc_auth_adapter_current_identity_with_valid_cookie(oidc_client: OIDCC
password="password123", password="password123",
) )
adapter = OIDCAuthAdapter(oidc_client=oidc_client, session_cookie_name="bdinvite_session") adapter = OIDCAuthAdapter(
oidc_client=oidc_client, session_cookie_name="bdinvite_session"
)
req = create_dummy_request(cookies={"bdinvite_session": token_resp.id_token}) req = create_dummy_request(cookies={"bdinvite_session": token_resp.id_token})
resolved = adapter.current_identity(req) resolved = adapter.current_identity(req)
@@ -324,7 +335,9 @@ def test_oidc_auth_adapter_login_redirect(oidc_client: OIDCClient):
def test_oidc_auth_adapter_logout_redirect_and_clears_cookie(oidc_client: OIDCClient): def test_oidc_auth_adapter_logout_redirect_and_clears_cookie(oidc_client: OIDCClient):
"""OIDCAuthAdapter logout returns 302 redirect and deletes the session cookie.""" """OIDCAuthAdapter logout returns 302 redirect and deletes the session cookie."""
adapter = OIDCAuthAdapter(oidc_client=oidc_client, session_cookie_name="bdinvite_session") adapter = OIDCAuthAdapter(
oidc_client=oidc_client, session_cookie_name="bdinvite_session"
)
req = create_dummy_request() req = create_dummy_request()
response = adapter.logout(req) response = adapter.logout(req)
+35 -12
View File
@@ -1,6 +1,7 @@
from unittest.mock import ANY, patch from unittest.mock import ANY, patch
import pytest import pytest
from app.config import settings from app.config import settings
from app.services.map_preview import ( from app.services.map_preview import (
deg2num, deg2num,
@@ -8,7 +9,6 @@ from app.services.map_preview import (
is_google_maps_host, is_google_maps_host,
validate_google_maps_url_format, validate_google_maps_url_format,
) )
from tests.conftest import login_client from tests.conftest import login_client
@@ -29,7 +29,9 @@ def test_is_google_maps_host():
def test_validate_google_maps_url_format(): def test_validate_google_maps_url_format():
validate_google_maps_url_format("https://maps.app.goo.gl/354784424357732") validate_google_maps_url_format("https://maps.app.goo.gl/354784424357732")
validate_google_maps_url_format("https://www.google.com/maps/place/Fresco/@34.1,-118.2,17z") validate_google_maps_url_format(
"https://www.google.com/maps/place/Fresco/@34.1,-118.2,17z"
)
validate_google_maps_url_format("https://maps.google.com/?q=34.1,-118.2") validate_google_maps_url_format("https://maps.google.com/?q=34.1,-118.2")
with pytest.raises(ValueError, match="no puede estar vacía"): with pytest.raises(ValueError, match="no puede estar vacía"):
@@ -44,23 +46,33 @@ def test_validate_google_maps_url_format():
def test_extract_coordinates_from_text(): def test_extract_coordinates_from_text():
# 1. @lat,lng # 1. @lat,lng
coords = extract_coordinates_from_text("https://google.com/maps/place/Venue/@34.143245,-118.255132,17z") coords = extract_coordinates_from_text(
"https://google.com/maps/place/Venue/@34.143245,-118.255132,17z"
)
assert coords == (34.143245, -118.255132) assert coords == (34.143245, -118.255132)
# 2. !3dlat!4dlng # 2. !3dlat!4dlng
coords = extract_coordinates_from_text("https://google.com/maps/data=!4m6!3m5!1s0x0!8m2!3d4.6534!4d-74.0564") coords = extract_coordinates_from_text(
"https://google.com/maps/data=!4m6!3m5!1s0x0!8m2!3d4.6534!4d-74.0564"
)
assert coords == (4.6534, -74.0564) assert coords == (4.6534, -74.0564)
# 3. Query params: q=lat,lng # 3. Query params: q=lat,lng
coords = extract_coordinates_from_text("https://maps.google.com/?q=34.1432,-118.2551") coords = extract_coordinates_from_text(
"https://maps.google.com/?q=34.1432,-118.2551"
)
assert coords == (34.1432, -118.2551) assert coords == (34.1432, -118.2551)
# 4. Query params: ll=lat,lng # 4. Query params: ll=lat,lng
coords = extract_coordinates_from_text("https://maps.google.com/maps?ll=34.1432,-118.2551&z=16") coords = extract_coordinates_from_text(
"https://maps.google.com/maps?ll=34.1432,-118.2551&z=16"
)
assert coords == (34.1432, -118.2551) assert coords == (34.1432, -118.2551)
# 5. Non-coordinate text # 5. Non-coordinate text
assert extract_coordinates_from_text("https://maps.google.com/?q=Eiffel+Tower") is None assert (
extract_coordinates_from_text("https://maps.google.com/?q=Eiffel+Tower") is None
)
def test_deg2num(): def test_deg2num():
@@ -71,12 +83,17 @@ def test_deg2num():
@patch("app.routes.admin.resolve_google_maps_coordinates") @patch("app.routes.admin.resolve_google_maps_coordinates")
@patch("app.routes.admin.generate_map_preview_image") @patch("app.routes.admin.generate_map_preview_image")
def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client, tmp_path): def test_admin_generate_map_preview_endpoint(
mock_generate, mock_resolve, client, tmp_path
):
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url") mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
mock_generate.return_value = tmp_path / "map_preview.png" mock_generate.return_value = tmp_path / "map_preview.png"
# Test without auth -> 401 # Test without auth -> 401
resp = client.post("/birthday/api/admin/map-preview/generate", json={"map_url": "https://maps.google.com/?q=34.1,-118.2"}) resp = client.post(
"/birthday/api/admin/map-preview/generate",
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
)
assert resp.status_code == 401 assert resp.status_code == 401
# Test with auth -> 200 # Test with auth -> 200
@@ -90,13 +107,17 @@ def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client
assert "/birthday/api/map-preview.png" in data["map_preview_url"] assert "/birthday/api/map-preview.png" in data["map_preview_url"]
assert data["lat"] == 34.1432 assert data["lat"] == 34.1432
assert data["lng"] == -118.2551 assert data["lng"] == -118.2551
mock_resolve.assert_called_once_with("https://maps.google.com/?q=34.1,-118.2", fallback_query=ANY) mock_resolve.assert_called_once_with(
"https://maps.google.com/?q=34.1,-118.2", fallback_query=ANY
)
mock_generate.assert_called_once_with(34.1432, -118.2551) mock_generate.assert_called_once_with(34.1432, -118.2551)
@patch("app.routes.admin.resolve_google_maps_coordinates") @patch("app.routes.admin.resolve_google_maps_coordinates")
@patch("app.routes.admin.generate_map_preview_image") @patch("app.routes.admin.generate_map_preview_image")
def test_config_update_triggers_generator_only_when_map_url_changes(mock_generate, mock_resolve, admin_client, tmp_path): def test_config_update_triggers_generator_only_when_map_url_changes(
mock_generate, mock_resolve, admin_client, tmp_path
):
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url") mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
mock_generate.return_value = tmp_path / "map_preview.png" mock_generate.return_value = tmp_path / "map_preview.png"
@@ -120,7 +141,9 @@ def test_config_update_triggers_generator_only_when_map_url_changes(mock_generat
assert resp.status_code == 200 assert resp.status_code == 200
assert resp.json()["map_url"] == "https://maps.google.com/?q=34.1432,-118.2551" assert resp.json()["map_url"] == "https://maps.google.com/?q=34.1432,-118.2551"
assert resp.json()["map_preview_url"] == "/birthday/api/map-preview.png" assert resp.json()["map_preview_url"] == "/birthday/api/map-preview.png"
mock_resolve.assert_called_once_with("https://maps.google.com/?q=34.1432,-118.2551", fallback_query=ANY) mock_resolve.assert_called_once_with(
"https://maps.google.com/?q=34.1432,-118.2551", fallback_query=ANY
)
mock_generate.assert_called_once_with(34.1432, -118.2551) mock_generate.assert_called_once_with(34.1432, -118.2551)
+25 -11
View File
@@ -2,7 +2,6 @@ import base64
import json import json
import urllib.parse import urllib.parse
from fastapi import HTTPException
import httpx import httpx
import pytest import pytest
@@ -12,7 +11,6 @@ from app.auth import (
InvalidTokenError, InvalidTokenError,
MismatchedNonceError, MismatchedNonceError,
OIDCClient, OIDCClient,
OIDCConfig,
compute_code_challenge, compute_code_challenge,
generate_code_verifier, generate_code_verifier,
generate_nonce, generate_nonce,
@@ -40,7 +38,9 @@ def test_pkce_generation_and_challenge():
verifier = generate_code_verifier(64) verifier = generate_code_verifier(64)
assert len(verifier) == 64 assert len(verifier) == 64
# RFC 7636 Section 4.1 unreserved characters # RFC 7636 Section 4.1 unreserved characters
unreserved = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") unreserved = set(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"
)
assert all(c in unreserved for c in verifier) assert all(c in unreserved for c in verifier)
# Length bounds validation # Length bounds validation
@@ -139,7 +139,9 @@ def test_rejection_of_invalid_state_400(oidc_client: OIDCClient):
assert exc_info.value.status_code == 400 assert exc_info.value.status_code == 400
def test_live_oidc_successful_code_exchange_and_id_token_validation(oidc_client: OIDCClient): 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.""" """End-to-end integration test: code exchange, ID token validation, and Identity extraction."""
# 1. Create authorization request with PKCE and transaction secrets # 1. Create authorization request with PKCE and transaction secrets
auth_req = oidc_client.create_authorization_url() auth_req = oidc_client.create_authorization_url()
@@ -150,15 +152,19 @@ def test_live_oidc_successful_code_exchange_and_id_token_validation(oidc_client:
auth_req.url, auth_req.url,
data={ data={
"username": "alice", "username": "alice",
"claims": json.dumps({ "claims": json.dumps(
{
"email": "alice@example.com", "email": "alice@example.com",
"name": "Alice In Chains", "name": "Alice In Chains",
"groups": ["family", "vip"], "groups": ["family", "vip"],
}), }
),
}, },
follow_redirects=False, follow_redirects=False,
) )
assert resp.status_code == 302, f"Expected 302 redirect from mock IdP, got {resp.status_code}" assert resp.status_code == 302, (
f"Expected 302 redirect from mock IdP, got {resp.status_code}"
)
redirect_url = resp.headers["location"] redirect_url = resp.headers["location"]
qs = urllib.parse.parse_qs(urllib.parse.urlparse(redirect_url).query) qs = urllib.parse.parse_qs(urllib.parse.urlparse(redirect_url).query)
@@ -207,7 +213,9 @@ def test_rejection_of_mismatched_nonce_401(oidc_client: OIDCClient):
# Verifying valid token against wrong nonce MUST raise MismatchedNonceError (HTTP 401) # Verifying valid token against wrong nonce MUST raise MismatchedNonceError (HTTP 401)
with pytest.raises(MismatchedNonceError) as exc_info: with pytest.raises(MismatchedNonceError) as exc_info:
oidc_client.verify_id_token(token_resp.id_token, nonce="completely_different_nonce") oidc_client.verify_id_token(
token_resp.id_token, nonce="completely_different_nonce"
)
assert exc_info.value.status_code == 401 assert exc_info.value.status_code == 401
assert "does not match expected nonce" in str(exc_info.value.detail) assert "does not match expected nonce" in str(exc_info.value.detail)
@@ -246,7 +254,9 @@ def test_rejection_of_tampered_id_token_signature_401(oidc_client: OIDCClient):
payload_raw = parts[1] + "==" payload_raw = parts[1] + "=="
payload = json.loads(base64.urlsafe_b64decode(payload_raw)) payload = json.loads(base64.urlsafe_b64decode(payload_raw))
payload["sub"] = "mallory_attacker" payload["sub"] = "mallory_attacker"
tampered_payload_b64 = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=") tampered_payload_b64 = (
base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
)
tampered_payload_token = f"{parts[0]}.{tampered_payload_b64}.{parts[2]}" tampered_payload_token = f"{parts[0]}.{tampered_payload_b64}.{parts[2]}"
with pytest.raises(InvalidTokenError) as exc_info: with pytest.raises(InvalidTokenError) as exc_info:
@@ -302,5 +312,9 @@ def test_architectural_isolation_no_domain_route_crypto_imports():
for route_file in routes_dir.glob("*.py"): for route_file in routes_dir.glob("*.py"):
content = route_file.read_text(encoding="utf-8") content = route_file.read_text(encoding="utf-8")
for term in disallowed_terms: for term in disallowed_terms:
assert f"import {term}" not in content, f"{route_file.name} violates isolation by importing {term}" assert f"import {term}" not in content, (
assert f"from {term}" not in content, f"{route_file.name} violates isolation by importing from {term}" 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}"
)
+29 -9
View File
@@ -40,7 +40,9 @@ def oidc_client() -> OIDCClient:
# ============================================================================== # ==============================================================================
def test_forged_or_invalid_csrf_state_returns_400(client: TestClient, oidc_client: OIDCClient): 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.""" """Forged, tampered, missing, or expired CSRF state returns HTTP 400 Bad Request."""
# 1. Direct unit assertion: oidc_client rejects unknown state with InvalidStateError (400) # 1. Direct unit assertion: oidc_client rejects unknown state with InvalidStateError (400)
with pytest.raises(InvalidStateError) as exc_info: with pytest.raises(InvalidStateError) as exc_info:
@@ -111,7 +113,9 @@ def test_forged_or_tampered_id_token_signature_returns_401(oidc_client: OIDCClie
claims = json.loads(payload_bytes) claims = json.loads(payload_bytes)
claims["sub"] = "hacked_admin_identity" claims["sub"] = "hacked_admin_identity"
claims["groups"] = ["bdinvite_admins", "root"] claims["groups"] = ["bdinvite_admins", "root"]
tampered_payload_b64 = base64.urlsafe_b64encode(json.dumps(claims).encode()).decode().rstrip("=") tampered_payload_b64 = (
base64.urlsafe_b64encode(json.dumps(claims).encode()).decode().rstrip("=")
)
tampered_token = f"{parts[0]}.{tampered_payload_b64}.{parts[2]}" tampered_token = f"{parts[0]}.{tampered_payload_b64}.{parts[2]}"
with pytest.raises(InvalidTokenError) as exc_info_tampered: with pytest.raises(InvalidTokenError) as exc_info_tampered:
@@ -201,7 +205,9 @@ def test_missing_or_invalid_pkce_code_verifier_returns_401(oidc_client: OIDCClie
follow_redirects=False, follow_redirects=False,
) )
assert resp.status_code == 302 assert resp.status_code == 302
code = urllib.parse.parse_qs(urllib.parse.urlparse(resp.headers["location"]).query)["code"][0] code = urllib.parse.parse_qs(
urllib.parse.urlparse(resp.headers["location"]).query
)["code"][0]
with pytest.raises(InvalidPKCEError) as exc_mismatch: with pytest.raises(InvalidPKCEError) as exc_mismatch:
oidc_client.exchange_code( oidc_client.exchange_code(
@@ -218,7 +224,9 @@ def test_missing_or_invalid_pkce_code_verifier_returns_401(oidc_client: OIDCClie
# ============================================================================== # ==============================================================================
def test_expired_id_token_returns_401(oidc_client: OIDCClient, monkeypatch: pytest.MonkeyPatch): def test_expired_id_token_returns_401(
oidc_client: OIDCClient, monkeypatch: pytest.MonkeyPatch
):
"""Expired ID token is rejected with HTTP 401 Unauthorized.""" """Expired ID token is rejected with HTTP 401 Unauthorized."""
import datetime import datetime
@@ -300,7 +308,9 @@ def test_tampered_session_cookie_signature_returns_401(client: TestClient):
# ============================================================================== # ==============================================================================
def test_authenticated_non_admin_accessing_admin_apis_returns_403(guest_client: TestClient): 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.""" """Authenticated non-admin user (guest@example.com with groups: ['guests']) receives HTTP 403."""
admin_endpoints = [ admin_endpoints = [
("GET", "/birthday/api/admin/rsvps"), ("GET", "/birthday/api/admin/rsvps"),
@@ -314,7 +324,9 @@ def test_authenticated_non_admin_accessing_admin_apis_returns_403(guest_client:
] ]
for method, path in admin_endpoints: for method, path in admin_endpoints:
res = guest_client.request(method, path) res = guest_client.request(method, path)
assert res.status_code == 403, f"{method} {path} must return 403 Forbidden for non-admin" assert res.status_code == 403, (
f"{method} {path} must return 403 Forbidden for non-admin"
)
assert "Forbidden" in res.json().get("detail", "") assert "Forbidden" in res.json().get("detail", "")
@@ -344,7 +356,9 @@ def test_legacy_remote_user_header_without_session_returns_401(client: TestClien
assert res_me.status_code == 401 assert res_me.status_code == 401
def test_legacy_remote_user_header_cannot_escalate_non_admin_session(guest_client: TestClient): 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.""" """An attacker passing Remote-User: admin with an active non-admin session cookie receives HTTP 403."""
res = guest_client.get( res = guest_client.get(
"/birthday/api/admin/rsvps", "/birthday/api/admin/rsvps",
@@ -392,7 +406,10 @@ def test_deployment_independence_multi_mode_configuration():
assert prod_settings.is_production is True assert prod_settings.is_production is True
assert prod_settings.SESSION_COOKIE_SECURE is True assert prod_settings.SESSION_COOKIE_SECURE is True
assert prod_settings.OIDC_ISSUER == "https://auth.roadtotech.me" assert prod_settings.OIDC_ISSUER == "https://auth.roadtotech.me"
assert prod_settings.OIDC_REDIRECT_URI == "https://demos.roadtotech.me/birthday/api/auth/callback" assert (
prod_settings.OIDC_REDIRECT_URI
== "https://demos.roadtotech.me/birthday/api/auth/callback"
)
# ============================================================================== # ==============================================================================
@@ -429,4 +446,7 @@ def test_static_architectural_assertion_no_runtime_remote_user():
if term in content: if term in content:
violations.append(f"{src_file}: contains '{term}'") violations.append(f"{src_file}: contains '{term}'")
assert not violations, "Architectural boundary violated by runtime Remote-User occurrences:\n" + "\n".join(violations) assert not violations, (
"Architectural boundary violated by runtime Remote-User occurrences:\n"
+ "\n".join(violations)
)
+28 -15
View File
@@ -1,8 +1,5 @@
import time
from typing import Optional
import pytest import pytest
from fastapi import Request, Response from fastapi import Request
from fastapi.responses import Response as StarletteResponse from fastapi.responses import Response as StarletteResponse
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
@@ -14,8 +11,6 @@ from app.auth import (
sign_session_cookie, sign_session_cookie,
unsign_session_cookie, unsign_session_cookie,
) )
from app.config import settings
from app.main import app
from app.routes.auth import get_auth_adapter from app.routes.auth import get_auth_adapter
LIVE_ISSUER = "http://localhost:8088/default" LIVE_ISSUER = "http://localhost:8088/default"
@@ -216,7 +211,9 @@ def test_adapter_current_identity_resolution(auth_adapter: OIDCAuthAdapter):
assert resolved == identity assert resolved == identity
# 3. Unknown / non-existent session ID -> None # 3. Unknown / non-existent session ID -> None
fake_signed = sign_session_cookie("non-existent-session-id", auth_adapter.secret_key) fake_signed = sign_session_cookie(
"non-existent-session-id", auth_adapter.secret_key
)
unknown_req = create_dummy_request(cookies={"bdinvite_session": fake_signed}) unknown_req = create_dummy_request(cookies={"bdinvite_session": fake_signed})
assert auth_adapter.current_identity(unknown_req) is None assert auth_adapter.current_identity(unknown_req) is None
@@ -230,8 +227,12 @@ def test_adapter_current_identity_resolution(auth_adapter: OIDCAuthAdapter):
assert auth_adapter.current_identity(malformed_req) is None assert auth_adapter.current_identity(malformed_req) is None
# 6. Expired session -> None # 6. Expired session -> None
expired_session = auth_adapter.session_store.create_session(identity=identity, max_age_seconds=-10) expired_session = auth_adapter.session_store.create_session(
exp_cookie = sign_session_cookie(expired_session.session_id, auth_adapter.secret_key) 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}) exp_req = create_dummy_request(cookies={"bdinvite_session": exp_cookie})
assert auth_adapter.current_identity(exp_req) is None assert auth_adapter.current_identity(exp_req) is None
@@ -332,7 +333,9 @@ def test_http_session_fixation_rotation_on_login(client: TestClient):
assert pre_auth_cookie is not None assert pre_auth_cookie is not None
# 2. Pre-auth session resolves to unauthorized # 2. Pre-auth session resolves to unauthorized
resp_anon = client.get("/birthday/api/auth/me", cookies={"bdinvite_session": pre_auth_cookie}) resp_anon = client.get(
"/birthday/api/auth/me", cookies={"bdinvite_session": pre_auth_cookie}
)
assert resp_anon.status_code == 401 assert resp_anon.status_code == 401
# 3. Authenticate while presenting pre_auth_cookie # 3. Authenticate while presenting pre_auth_cookie
@@ -349,11 +352,15 @@ def test_http_session_fixation_rotation_on_login(client: TestClient):
assert pre_auth_cookie != post_auth_cookie assert pre_auth_cookie != post_auth_cookie
# 5. Pre-auth cookie MUST NOT have been promoted # 5. Pre-auth cookie MUST NOT have been promoted
resp_old = client.get("/birthday/api/auth/me", cookies={"bdinvite_session": pre_auth_cookie}) resp_old = client.get(
"/birthday/api/auth/me", cookies={"bdinvite_session": pre_auth_cookie}
)
assert resp_old.status_code == 401 assert resp_old.status_code == 401
# 6. Post-auth cookie resolves to authenticated user # 6. Post-auth cookie resolves to authenticated user
resp_valid = client.get("/birthday/api/auth/me", cookies={"bdinvite_session": post_auth_cookie}) resp_valid = client.get(
"/birthday/api/auth/me", cookies={"bdinvite_session": post_auth_cookie}
)
assert resp_valid.status_code == 200 assert resp_valid.status_code == 200
assert resp_valid.json()["subject"] == "admin-001" assert resp_valid.json()["subject"] == "admin-001"
assert "bdinvite_admins" in resp_valid.json()["groups"] assert "bdinvite_admins" in resp_valid.json()["groups"]
@@ -398,11 +405,15 @@ def test_http_logout_invalidates_session_and_clears_cookie(client: TestClient):
assert cookie_val is not None assert cookie_val is not None
# Verify session is authenticated # Verify session is authenticated
me_resp = client.get("/birthday/api/auth/me", cookies={"bdinvite_session": cookie_val}) me_resp = client.get(
"/birthday/api/auth/me", cookies={"bdinvite_session": cookie_val}
)
assert me_resp.status_code == 200 assert me_resp.status_code == 200
# 2. Logout via POST # 2. Logout via POST
logout_resp = client.post("/birthday/api/auth/logout", cookies={"bdinvite_session": cookie_val}) logout_resp = client.post(
"/birthday/api/auth/logout", cookies={"bdinvite_session": cookie_val}
)
assert logout_resp.status_code == 200 assert logout_resp.status_code == 200
assert logout_resp.json()["status"] == "ok" assert logout_resp.json()["status"] == "ok"
@@ -412,5 +423,7 @@ def test_http_logout_invalidates_session_and_clears_cookie(client: TestClient):
assert "max-age=0" in set_cookie.lower() assert "max-age=0" in set_cookie.lower()
# 3. Subsequent request with the same cookie is rejected # 3. Subsequent request with the same cookie is rejected
me_after = client.get("/birthday/api/auth/me", cookies={"bdinvite_session": cookie_val}) me_after = client.get(
"/birthday/api/auth/me", cookies={"bdinvite_session": cookie_val}
)
assert me_after.status_code == 401 assert me_after.status_code == 401
+81 -13
View File
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react"; import { useCallback, 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 { type CurrentUser, fetchCurrentUser, logoutUser } from "../api/client";
import { Spinner } from "../components/Spinner"; import { Spinner } from "../components/Spinner";
@@ -6,8 +6,16 @@ import { Spinner } from "../components/Spinner";
export function AdminLayout() { export function AdminLayout() {
const [user, setUser] = useState<CurrentUser | null>(null); const [user, setUser] = useState<CurrentUser | null>(null);
const [loading, setLoading] = useState<boolean>(true); const [loading, setLoading] = useState<boolean>(true);
const [loggedOut, setLoggedOut] = useState<boolean>(false);
useEffect(() => { useEffect(() => {
const params = new URLSearchParams(window.location.search);
if (params.get("logged_out") === "1") {
setLoading(false);
setLoggedOut(true);
return;
}
let isMounted = true; let isMounted = true;
fetchCurrentUser() fetchCurrentUser()
.then((userData) => { .then((userData) => {
@@ -28,15 +36,16 @@ export function AdminLayout() {
}; };
}, []); }, []);
const handleLogout = async () => { const handleLogout = useCallback(async () => {
try { try {
await logoutUser(); await logoutUser();
} catch (err) { } catch (err) {
console.error("Logout failed:", err); console.error("Logout failed:", err);
} }
setUser(null); setUser(null);
window.location.href = "/birthday/api/auth/login"; setLoggedOut(true);
}; window.history.replaceState(null, "", "/birthday/admin?logged_out=1");
}, []);
if (loading) { if (loading) {
return ( return (
@@ -55,7 +64,7 @@ export function AdminLayout() {
); );
} }
if (!user) { if (loggedOut || !user) {
return ( return (
<div <div
style={{ style={{
@@ -63,23 +72,82 @@ export function AdminLayout() {
backgroundColor: "#0f0f10", backgroundColor: "#0f0f10",
color: "#f0f0f0", color: "#f0f0f0",
fontFamily: "var(--font-body)", fontFamily: "var(--font-body)",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: "1rem",
}} }}
> >
<p>No autenticado. Redirigiendo al inicio de sesión...</p> <header
style={{
borderBottom: "1px solid rgba(255, 255, 255, 0.1)",
backgroundColor: "#161618",
padding: "1rem 1.8rem",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
<div style={{ display: "flex", alignItems: "center", gap: "0.8rem" }}>
<span style={{ fontSize: "1.4rem" }}>🎂</span>
<h1
style={{
fontSize: "1.1rem",
fontWeight: 600,
letterSpacing: "0.08em",
color: "#ffffff",
textTransform: "uppercase",
}}
>
Panel de Control · Invitación
</h1>
</div>
<a <a
href="/birthday/api/auth/login" href="/birthday/api/auth/login"
data-testid="login-link"
style={{ style={{
color: "var(--color-gold-light, #e0be75)", color: "var(--color-gold-light, #e0be75)",
textDecoration: "underline", textDecoration: "none",
fontSize: "0.88rem",
fontWeight: 500,
}} }}
> >
Iniciar sesión Iniciar Sesión
</a> </a>
</header>
<div
data-testid="unauthenticated-state"
style={{
maxWidth: "480px",
margin: "4rem auto",
textAlign: "center",
padding: "2.5rem 1.5rem",
backgroundColor: "#161618",
borderRadius: "8px",
border: "1px solid rgba(255, 255, 255, 0.1)",
}}
>
<div style={{ fontSize: "2.5rem", marginBottom: "1rem" }}>🔒</div>
<h2 style={{ fontSize: "1.3rem", fontWeight: 600, color: "#fff", marginBottom: "0.6rem" }}>
Sesión Finalizada
</h2>
<p style={{ color: "rgba(255, 255, 255, 0.65)", fontSize: "0.9rem", marginBottom: "1.8rem" }}>
Has cerrado sesión correctamente. No hay sesión autenticada activa.
</p>
<a
href="/birthday/api/auth/login"
data-testid="login-btn"
style={{
display: "inline-block",
padding: "0.65rem 1.5rem",
backgroundColor: "var(--color-gold, #c5a059)",
color: "#0a0a0a",
fontWeight: 600,
borderRadius: "4px",
textDecoration: "none",
fontSize: "0.9rem",
}}
>
Iniciar Sesión
</a>
</div>
</div> </div>
); );
} }