From 8ce9a731760c3199fc7fd830c7daf598f1ee8ab4 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Wed, 7 Oct 2026 06:48:32 -0500 Subject: [PATCH] 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 --- backend/app/auth/adapter.py | 70 +++++---- backend/app/auth/dependencies.py | 18 ++- backend/app/auth/identity.py | 3 +- backend/app/auth/oidc.py | 179 ++++++++++++++-------- backend/app/auth/port.py | 4 +- backend/app/auth/session.py | 29 ++-- backend/app/config.py | 1 - backend/app/main.py | 4 +- backend/app/models.py | 24 ++- backend/app/routes/admin.py | 53 +++++-- backend/app/routes/auth.py | 14 +- backend/app/schemas.py | 60 +++++--- backend/app/services/map_preview.py | 36 +++-- backend/app/services/rsvp.py | 2 - backend/tests/conftest.py | 5 +- backend/tests/test_admin.py | 54 +++++-- backend/tests/test_auth_port.py | 8 +- backend/tests/test_browser_sso.py | 21 ++- backend/tests/test_dependencies.py | 22 ++- backend/tests/test_identity_extraction.py | 47 ++++-- backend/tests/test_map_preview.py | 47 ++++-- backend/tests/test_oidc_client.py | 42 +++-- backend/tests/test_rsvp.py | 12 +- backend/tests/test_security_hardening.py | 38 +++-- backend/tests/test_session_management.py | 43 ++++-- frontend/src/admin/AdminLayout.tsx | 102 ++++++++++-- 26 files changed, 637 insertions(+), 301 deletions(-) diff --git a/backend/app/auth/adapter.py b/backend/app/auth/adapter.py index fe7c586..b5aa91c 100644 --- a/backend/app/auth/adapter.py +++ b/backend/app/auth/adapter.py @@ -1,4 +1,5 @@ -from typing import Literal, Optional +import contextlib +from typing import Literal from fastapi import Request, Response from fastapi.responses import RedirectResponse @@ -23,11 +24,11 @@ class OIDCAuthAdapter(AuthPort): self, oidc_client: OIDCClient, session_cookie_name: str = settings.SESSION_COOKIE_NAME, - session_store: Optional[SessionStore] = None, - cookie_secure: Optional[bool] = None, - cookie_samesite: Optional[Literal["lax", "strict", "none"]] = None, - session_max_age: Optional[int] = None, - secret_key: Optional[str] = None, + session_store: SessionStore | None = None, + cookie_secure: bool | None = None, + cookie_samesite: Literal["lax", "strict", "none"] | None = None, + session_max_age: int | None = None, + secret_key: str | None = None, ) -> None: self.oidc_client = oidc_client self.session_cookie_name = session_cookie_name @@ -35,21 +36,31 @@ class OIDCAuthAdapter(AuthPort): session_store if session_store is not None else InMemorySessionStore() ) self.cookie_secure: bool = ( - cookie_secure if cookie_secure is not None else settings.SESSION_COOKIE_SECURE + cookie_secure + if cookie_secure is not None + else settings.SESSION_COOKIE_SECURE ) self.cookie_samesite: Literal["lax", "strict", "none"] = ( - cookie_samesite if cookie_samesite is not None else settings.SESSION_COOKIE_SAMESITE + cookie_samesite + if cookie_samesite is not None + else settings.SESSION_COOKIE_SAMESITE ) self.session_max_age: int = ( - session_max_age if session_max_age is not None else settings.SESSION_MAX_AGE_SECONDS + session_max_age + if session_max_age is not None + else settings.SESSION_MAX_AGE_SECONDS ) self.secret_key: str = ( secret_key if secret_key is not None else settings.SESSION_SECRET_KEY ) - def parse_session_cookie(self, cookie_value: Optional[str]) -> Optional[str]: + def parse_session_cookie(self, cookie_value: str | None) -> str | None: """Extract and verify session_id from cookie, safely rejecting tampered cookies.""" - if not cookie_value or not isinstance(cookie_value, str) or not cookie_value.strip(): + if ( + not cookie_value + or not isinstance(cookie_value, str) + or not cookie_value.strip() + ): return None # 1. Attempt HMAC signature verification @@ -71,7 +82,7 @@ class OIDCAuthAdapter(AuthPort): 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. Identity Origin Integrity: @@ -83,10 +94,9 @@ class OIDCAuthAdapter(AuthPort): auth_header = request.headers.get("Authorization") if auth_header and auth_header.startswith("Bearer "): token = auth_header[7:].strip() - try: + with contextlib.suppress(Exception): return self.oidc_client.extract_identity_from_token(token) - except Exception: - return None + return None # 2. Browser session cookie raw_cookie = request.cookies.get(self.session_cookie_name) @@ -105,16 +115,15 @@ class OIDCAuthAdapter(AuthPort): return None # 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) - except Exception: - return None + return None def set_session_cookie( self, response: Response, session_id: str, - max_age: Optional[int] = None, + max_age: int | None = None, ) -> None: """Issue session cookie enforcing HttpOnly=True, SameSite, and configurable Secure flag.""" signed_val = sign_session_cookie(session_id, self.secret_key) @@ -140,11 +149,11 @@ class OIDCAuthAdapter(AuthPort): def create_session( self, - identity: Optional[Identity] = None, - request: Optional[Request] = None, - response: Optional[Response] = None, - pre_auth_session_id: Optional[str] = None, - max_age_seconds: Optional[int] = None, + identity: Identity | None = None, + request: Request | None = None, + response: Response | None = None, + pre_auth_session_id: str | None = None, + max_age_seconds: int | None = None, ) -> SessionData: """Create session with Session Fixation Protection. @@ -172,7 +181,9 @@ class OIDCAuthAdapter(AuthPort): assert session.session_id != candidate_pre_auth if response is not None: - self.set_session_cookie(response, session.session_id, max_age=effective_max_age) + self.set_session_cookie( + response, session.session_id, max_age=effective_max_age + ) return session @@ -183,8 +194,13 @@ class OIDCAuthAdapter(AuthPort): # Issue pre-authentication session if request does not already possess one raw_cookie = request.cookies.get(self.session_cookie_name) - existing_session_id = self.parse_session_cookie(raw_cookie) if raw_cookie else None - if not existing_session_id or self.session_store.get_session(existing_session_id) is None: + existing_session_id = ( + self.parse_session_cookie(raw_cookie) if raw_cookie else None + ) + if ( + not existing_session_id + or self.session_store.get_session(existing_session_id) is None + ): pre_auth = self.session_store.create_session( identity=None, max_age_seconds=self.session_max_age, diff --git a/backend/app/auth/dependencies.py b/backend/app/auth/dependencies.py index d000763..b7f1ab7 100644 --- a/backend/app/auth/dependencies.py +++ b/backend/app/auth/dependencies.py @@ -1,5 +1,5 @@ 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.params import Depends as DependsClass @@ -10,7 +10,7 @@ from .identity import Identity from .oidc import OIDCClient from .session import InMemorySessionStore -_auth_adapter_instance: Optional[OIDCAuthAdapter] = None +_auth_adapter_instance: OIDCAuthAdapter | None = None def get_auth_adapter() -> OIDCAuthAdapter: @@ -38,17 +38,19 @@ def get_auth_adapter() -> OIDCAuthAdapter: def get_current_identity( request: Request, - adapter: OIDCAuthAdapter = Depends(get_auth_adapter), -) -> Optional[Identity]: + adapter: Annotated[OIDCAuthAdapter | None, Depends(get_auth_adapter)] = None, +) -> Identity | None: """Resolves the active Identity from the session/adapter, or None if unauthenticated.""" resolved_adapter: OIDCAuthAdapter = ( - get_auth_adapter() if 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) def require_authenticated( - identity: Optional[Identity] = Depends(get_current_identity), + identity: Annotated[Identity | None, Depends(get_current_identity)] = None, ) -> Identity: """Enforces authentication, raising HTTP 401 Unauthorized if anonymous.""" if isinstance(cast(object, identity), DependsClass) or identity is None: @@ -67,7 +69,7 @@ def require_group(group_name: str) -> Callable[..., Identity]: """ def _group_dependency( - identity: Identity = Depends(require_authenticated), + identity: Annotated[Identity | None, Depends(require_authenticated)] = None, ) -> Identity: if isinstance(cast(object, identity), DependsClass) or identity is None: raise HTTPException( @@ -90,7 +92,7 @@ def require_group(group_name: str) -> Callable[..., Identity]: 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)] AdminDep = Annotated[Identity, Depends(require_admin)] diff --git a/backend/app/auth/identity.py b/backend/app/auth/identity.py index 261404c..6b2cf94 100644 --- a/backend/app/auth/identity.py +++ b/backend/app/auth/identity.py @@ -1,5 +1,4 @@ from dataclasses import dataclass, field -from typing import Optional @dataclass(frozen=True) @@ -14,7 +13,7 @@ class Identity: subject: str email: str - name: Optional[str] = None + name: str | None = None groups: list[str] = field(default_factory=list) def __post_init__(self) -> None: diff --git a/backend/app/auth/oidc.py b/backend/app/auth/oidc.py index 8aee84a..6975c92 100644 --- a/backend/app/auth/oidc.py +++ b/backend/app/auth/oidc.py @@ -1,15 +1,16 @@ import base64 +import contextlib import hashlib import secrets import string import time import urllib.parse from dataclasses import dataclass, field -from typing import Any, Optional +from typing import Any -from fastapi import HTTPException, status import httpx import jwt +from fastapi import HTTPException, status from .identity import Identity @@ -38,14 +39,18 @@ class OIDCError(HTTPException): class InvalidStateError(OIDCError): """Raised when the state parameter is missing, invalid, or expired (CSRF protection).""" - def __init__(self, detail: str = "Invalid, missing, or expired state parameter") -> None: + def __init__( + self, detail: str = "Invalid, missing, or expired state parameter" + ) -> None: super().__init__(status_code=status.HTTP_400_BAD_REQUEST, detail=detail) class MismatchedNonceError(OIDCError): """Raised when the nonce in the ID token does not match the request nonce (Replay protection).""" - def __init__(self, detail: str = "Mismatched or missing nonce claim in ID token") -> None: + def __init__( + self, detail: str = "Mismatched or missing nonce claim in ID token" + ) -> None: super().__init__(status_code=status.HTTP_401_UNAUTHORIZED, detail=detail) @@ -59,14 +64,18 @@ class InvalidTokenError(OIDCError): class DiscoveryError(OIDCError): """Raised when dynamic OIDC discovery configuration cannot be retrieved or parsed.""" - def __init__(self, detail: str = "Failed to fetch or parse OIDC discovery document") -> None: + def __init__( + self, detail: str = "Failed to fetch or parse OIDC discovery document" + ) -> None: super().__init__(status_code=status.HTTP_502_BAD_GATEWAY, detail=detail) class TokenExchangeError(OIDCError): """Raised when the token endpoint returns an error during authorization code exchange.""" - def __init__(self, detail: str = "Failed to exchange authorization code for tokens") -> None: + def __init__( + self, detail: str = "Failed to exchange authorization code for tokens" + ) -> None: super().__init__(status_code=status.HTTP_400_BAD_REQUEST, detail=detail) @@ -83,7 +92,7 @@ class OIDCConfig: issuer: str client_id: str - client_secret: Optional[str] = None + client_secret: str | None = None redirect_uri: str = "http://localhost:8000/birthday/api/auth/callback" scopes: list[str] = field(default_factory=lambda: list(DEFAULT_SCOPES)) groups_claim: str = "groups" @@ -136,10 +145,10 @@ class TokenResponse: """Result of token endpoint exchange and cryptographic validation.""" id_token: str - access_token: Optional[str] = None - refresh_token: Optional[str] = None - token_type: Optional[str] = None - expires_in: Optional[int] = None + access_token: str | None = None + refresh_token: str | None = None + token_type: str | None = None + expires_in: int | None = None raw: dict[str, Any] = field(default_factory=dict) claims: dict[str, Any] = field(default_factory=dict) @@ -147,14 +156,18 @@ class TokenResponse: def generate_code_verifier(length: int = 64) -> str: """Generate cryptographically secure PKCE code_verifier (RFC 7636 Section 4.1).""" if not (43 <= length <= 128): - raise ValueError("PKCE code_verifier length must be between 43 and 128 characters") + raise ValueError( + "PKCE code_verifier length must be between 43 and 128 characters" + ) return "".join(secrets.choice(PKCE_CHARSET) for _ in range(length)) def compute_code_challenge(code_verifier: str) -> str: """Derive PKCE code_challenge using SHA-256 (RFC 7636 Section 4.2).""" if not (43 <= len(code_verifier) <= 128): - raise ValueError("PKCE code_verifier length must be between 43 and 128 characters") + raise ValueError( + "PKCE code_verifier length must be between 43 and 128 characters" + ) digest = hashlib.sha256(code_verifier.encode("ascii")).digest() return base64.urlsafe_b64encode(digest).decode("ascii").rstrip("=") @@ -174,15 +187,15 @@ class OIDCClient: def __init__( self, - config: Optional[OIDCConfig] = None, + config: OIDCConfig | None = None, *, - issuer: Optional[str] = None, - client_id: Optional[str] = None, - client_secret: Optional[str] = None, - redirect_uri: Optional[str] = None, - scopes: Optional[list[str]] = None, - groups_claim: Optional[str] = None, - discovery_doc: Optional[dict[str, Any]] = None, + issuer: str | None = None, + client_id: str | None = None, + client_secret: str | None = None, + redirect_uri: str | None = None, + scopes: list[str] | None = None, + groups_claim: str | None = None, + discovery_doc: dict[str, Any] | None = None, timeout: float = 10.0, max_state_age_seconds: float = 600.0, ) -> None: @@ -190,20 +203,23 @@ class OIDCClient: self.config = config else: if not issuer or not client_id: - raise ValueError("Both 'issuer' and 'client_id' are required if 'config' is not supplied") + raise ValueError( + "Both 'issuer' and 'client_id' are required if 'config' is not supplied" + ) self.config = OIDCConfig( issuer=issuer, client_id=client_id, client_secret=client_secret, - redirect_uri=redirect_uri or "http://localhost:8000/birthday/api/auth/callback", + redirect_uri=redirect_uri + or "http://localhost:8000/birthday/api/auth/callback", scopes=scopes if scopes is not None else list(DEFAULT_SCOPES), groups_claim=groups_claim or "groups", ) self.timeout = timeout self.max_state_age_seconds = max_state_age_seconds - self._discovery_doc: Optional[dict[str, Any]] = discovery_doc - self._jwks_client: Optional[jwt.PyJWKClient] = None + self._discovery_doc: dict[str, Any] | None = discovery_doc + self._jwks_client: jwt.PyJWKClient | None = None self._transactions: dict[str, OIDCTransaction] = {} def get_discovery_document(self, refresh: bool = False) -> dict[str, Any]: @@ -221,19 +237,25 @@ class OIDCClient: ) data = response.json() 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 return data except DiscoveryError: raise 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: doc = self.get_discovery_document() val = doc.get(field_name) if not val or not isinstance(val, str): - raise DiscoveryError(f"Discovery document missing required field: {field_name}") + raise DiscoveryError( + f"Discovery document missing required field: {field_name}" + ) return val @property @@ -249,13 +271,13 @@ class OIDCClient: return self._get_discovery_field("jwks_uri") @property - def userinfo_endpoint(self) -> Optional[str]: + def userinfo_endpoint(self) -> str | None: doc = self.get_discovery_document() val = doc.get("userinfo_endpoint") return str(val) if val else None @property - def end_session_endpoint(self) -> Optional[str]: + def end_session_endpoint(self) -> str | None: doc = self.get_discovery_document() val = doc.get("end_session_endpoint") return str(val) if val else None @@ -276,7 +298,9 @@ class OIDCClient: def get_jwks_client(self, refresh: bool = False) -> jwt.PyJWKClient: """Obtain or cache PyJWKClient for signing key resolution.""" if self._jwks_client is None or refresh: - self._jwks_client = jwt.PyJWKClient(self.jwks_uri, cache_jwk_set=True, lifespan=3600) + self._jwks_client = jwt.PyJWKClient( + self.jwks_uri, cache_jwk_set=True, lifespan=3600 + ) return self._jwks_client def save_transaction(self, transaction: OIDCTransaction) -> None: @@ -287,13 +311,14 @@ class OIDCClient: def _prune_expired_transactions(self) -> None: now = time.time() 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 ] for s in expired: 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.""" self._prune_expired_transactions() if not state or not isinstance(state, str) or not state.strip(): @@ -307,16 +332,18 @@ class OIDCClient: def create_authorization_url( self, - state: Optional[str] = None, - nonce: Optional[str] = None, - code_verifier: Optional[str] = None, - scopes: Optional[list[str]] = None, - extra_params: Optional[dict[str, str]] = None, + state: str | None = None, + nonce: str | None = None, + code_verifier: str | None = None, + scopes: list[str] | None = None, + extra_params: dict[str, str] | None = None, ) -> AuthorizationRequest: """Generate authorization URL with PKCE (S256), cryptographic state, and nonce.""" actual_state = state if state is not None else generate_state() actual_nonce = nonce if nonce is not None else generate_nonce() - actual_verifier = code_verifier if code_verifier is not None else generate_code_verifier() + actual_verifier = ( + code_verifier if code_verifier is not None else generate_code_verifier() + ) code_challenge = compute_code_challenge(actual_verifier) @@ -357,22 +384,24 @@ class OIDCClient: try: return jwks_client.get_signing_key_from_jwt(token) except jwt.PyJWKClientError as e: - try: + with contextlib.suppress(Exception): jwk_set = jwks_client.get_jwk_set() if jwk_set and len(jwk_set.keys) == 1: return jwk_set.keys[0] - except Exception: - pass raise InvalidTokenError(f"Signing key not found in JWKS: {e}") from e except jwt.DecodeError as e: - raise InvalidTokenError(f"ID token signature is invalid or tampered: {e}") from e + raise InvalidTokenError( + f"ID token signature is invalid or tampered: {e}" + ) from e except Exception as e: - raise InvalidTokenError(f"Error resolving signing key from JWKS: {e}") from e + raise InvalidTokenError( + f"Error resolving signing key from JWKS: {e}" + ) from e def verify_id_token( self, id_token: str, - nonce: Optional[str] = None, + nonce: str | None = None, leeway: float = 60.0, ) -> dict[str, Any]: """Cryptographically validate returned ID token. @@ -408,7 +437,9 @@ class OIDCClient: except jwt.ExpiredSignatureError as e: raise InvalidTokenError(f"ID token has expired: {e}") from e except (jwt.InvalidSignatureError, jwt.DecodeError) as e: - raise InvalidTokenError(f"ID token signature is invalid or tampered: {e}") from e + raise InvalidTokenError( + f"ID token signature is invalid or tampered: {e}" + ) from e except (jwt.InvalidAudienceError, jwt.InvalidIssuerError) as e: raise InvalidTokenError(f"ID token claims validation failed: {e}") from e except jwt.PyJWTError as e: @@ -427,10 +458,10 @@ class OIDCClient: def exchange_code( self, code: str, - state: Optional[str] = None, - code_verifier: Optional[str] = None, - nonce: Optional[str] = None, - extra_token_params: Optional[dict[str, str]] = None, + state: str | None = None, + code_verifier: str | None = None, + nonce: str | None = None, + extra_token_params: dict[str, str] | None = None, ) -> TokenResponse: """Exchange authorization code for tokens using PKCE code_verifier and cryptographically verify ID token.""" if not code or not isinstance(code, str) or not code.strip(): @@ -455,11 +486,17 @@ class OIDCClient: elif resolved_verifier is None: raise InvalidPKCEError("Missing PKCE code_verifier") - if resolved_verifier is None or not isinstance(resolved_verifier, str) or not resolved_verifier.strip(): + if ( + resolved_verifier is None + or not isinstance(resolved_verifier, str) + or not resolved_verifier.strip() + ): raise InvalidPKCEError("Missing or invalid PKCE code_verifier") # Validate code_verifier length and character set per RFC 7636 - if not (43 <= len(resolved_verifier) <= 128) or not all(c in PKCE_CHARSET for c in resolved_verifier): + if not (43 <= len(resolved_verifier) <= 128) or not all( + c in PKCE_CHARSET for c in resolved_verifier + ): raise InvalidPKCEError( "Invalid PKCE code_verifier: length must be between 43 and 128 unreserved characters" ) @@ -473,7 +510,7 @@ class OIDCClient: if extra_token_params: data.update(extra_token_params) - auth: Optional[httpx.BasicAuth] = None + auth: httpx.BasicAuth | None = None if self.config.client_secret: auth = httpx.BasicAuth(self.config.client_id, self.config.client_secret) data["client_id"] = self.config.client_id @@ -497,19 +534,23 @@ class OIDCClient: headers={"Accept": "application/json"}, ) 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: error_data: dict[str, Any] = {} - try: + with contextlib.suppress(Exception): parsed = response.json() if isinstance(parsed, dict): error_data = parsed - except Exception: - pass err_desc = str(error_data.get("error_description", "")).lower() err_code = str(error_data.get("error", "")).lower() - if "pkce" in err_desc or "code_verifier" in err_desc or "invalid_grant" in err_code: + if ( + "pkce" in err_desc + or "code_verifier" in err_desc + or "invalid_grant" in err_code + ): raise InvalidPKCEError( f"PKCE verification failed: {error_data.get('error_description') or error_data.get('error') or response.text}" ) @@ -564,13 +605,21 @@ class OIDCClient: email = f"{subject}@{self.config.client_id}.local" name_val = claims.get("name") - name = str(name_val).strip() if name_val and isinstance(name_val, str) and name_val.strip() else None + name = ( + str(name_val).strip() + if name_val and isinstance(name_val, str) and name_val.strip() + else None + ) raw_groups = _extract_claim_path(claims, self.config.groups_claim) if isinstance(raw_groups, str): groups = [raw_groups.strip()] if raw_groups.strip() else [] elif isinstance(raw_groups, (list, tuple, set)): - groups = [str(g).strip() for g in raw_groups if isinstance(g, str) and str(g).strip()] + groups = [ + str(g).strip() + for g in raw_groups + if isinstance(g, str) and str(g).strip() + ] else: groups = [] @@ -587,7 +636,7 @@ class OIDCClient: def extract_identity_from_token( self, id_token: str, - nonce: Optional[str] = None, + nonce: str | None = None, leeway: float = 60.0, ) -> Identity: """Cryptographically verify ID token and extract domain Identity with origin integrity.""" @@ -598,7 +647,7 @@ class OIDCClient: self, username: str, password: str, - scopes: Optional[list[str]] = None, + scopes: list[str] | None = None, ) -> tuple[TokenResponse, Identity]: """Authenticate using resource owner password credentials against IdP and extract Identity. @@ -618,7 +667,7 @@ class OIDCClient: "scope": " ".join(query_scopes), } - auth: Optional[httpx.BasicAuth] = None + auth: httpx.BasicAuth | None = None if self.config.client_secret: auth = httpx.BasicAuth(self.config.client_id, self.config.client_secret) data["client_secret"] = self.config.client_secret @@ -639,7 +688,9 @@ class OIDCClient: headers={"Accept": "application/json"}, ) 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: raise TokenExchangeError( diff --git a/backend/app/auth/port.py b/backend/app/auth/port.py index 3d2f28e..79e309a 100644 --- a/backend/app/auth/port.py +++ b/backend/app/auth/port.py @@ -1,4 +1,4 @@ -from typing import Optional, Protocol, runtime_checkable +from typing import Protocol, runtime_checkable from fastapi import Request, Response @@ -13,7 +13,7 @@ class AuthPort(Protocol): 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. Returns None if the request is unauthenticated or credentials/session are invalid. diff --git a/backend/app/auth/session.py b/backend/app/auth/session.py index d29f547..e6296df 100644 --- a/backend/app/auth/session.py +++ b/backend/app/auth/session.py @@ -4,7 +4,7 @@ import secrets import threading import time from dataclasses import dataclass, field -from typing import Any, Optional, Protocol, runtime_checkable +from typing import Any, Protocol, runtime_checkable from .identity import Identity @@ -14,7 +14,7 @@ class SessionData: """Represents an application-level browser session.""" session_id: str - identity: Optional[Identity] = None + identity: Identity | None = None created_at: float = field(default_factory=time.time) expires_at: float = 0.0 metadata: dict[str, Any] = field(default_factory=dict) @@ -24,7 +24,7 @@ class SessionData: """Return True if session has a verified identity.""" 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.""" now = current_time if current_time is not None else time.time() return now >= self.expires_at @@ -36,15 +36,15 @@ class SessionStore(Protocol): def create_session( self, - identity: Optional[Identity] = None, + identity: Identity | None = None, max_age_seconds: int = 86400, - pre_auth_session_id: Optional[str] = None, - metadata: Optional[dict[str, Any]] = None, + pre_auth_session_id: str | None = None, + metadata: dict[str, Any] | None = None, ) -> SessionData: """Create a fresh session. If pre_auth_session_id is provided, invalidate it (Session Fixation Protection).""" ... - def get_session(self, session_id: str) -> Optional[SessionData]: + def get_session(self, session_id: str) -> SessionData | None: """Retrieve a session by its identifier. Returns None if absent or expired.""" ... @@ -70,10 +70,10 @@ class InMemorySessionStore: def create_session( self, - identity: Optional[Identity] = None, + identity: Identity | None = None, max_age_seconds: int = 86400, - pre_auth_session_id: Optional[str] = None, - metadata: Optional[dict[str, Any]] = None, + pre_auth_session_id: str | None = None, + metadata: dict[str, Any] | None = None, ) -> SessionData: """Create a brand new session, enforcing the Session Fixation Barrier.""" with self._lock: @@ -87,7 +87,10 @@ class InMemorySessionStore: # Generate fresh, unguessable cryptographic token while True: new_session_id = secrets.token_urlsafe(32) - if new_session_id != pre_auth_session_id and new_session_id not in self._sessions: + if ( + new_session_id != pre_auth_session_id + and new_session_id not in self._sessions + ): break session = SessionData( @@ -100,7 +103,7 @@ class InMemorySessionStore: self._sessions[new_session_id] = 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.""" if not session_id or not isinstance(session_id, str): return None @@ -149,7 +152,7 @@ def sign_session_cookie(session_id: str, secret_key: str) -> str: 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.""" if not cookie_val or not isinstance(cookie_val, str) or not cookie_val.strip(): return None diff --git a/backend/app/config.py b/backend/app/config.py index 4f2da34..de9bbd4 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -67,4 +67,3 @@ class Settings(BaseSettings): settings = Settings() - diff --git a/backend/app/main.py b/backend/app/main.py index cc10b09..7a5a1ad 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -129,7 +129,9 @@ if os.path.isdir(ASSETS_DIR): @app.get("/birthday", include_in_schema=False) async def redirect_birthday_slash(): - return RedirectResponse(url="/birthday/", status_code=status.HTTP_307_TEMPORARY_REDIRECT) + return RedirectResponse( + url="/birthday/", status_code=status.HTTP_307_TEMPORARY_REDIRECT + ) @app.get("/birthday/", include_in_schema=False) diff --git a/backend/app/models.py b/backend/app/models.py index a639446..6877161 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -15,7 +15,9 @@ class RSVP(Base): id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) name: Mapped[str] = mapped_column(String(100), nullable=False) - phone: Mapped[str] = mapped_column(String(20), nullable=False, unique=True, index=True) + phone: Mapped[str] = mapped_column( + String(20), nullable=False, unique=True, index=True + ) email: Mapped[str | None] = mapped_column(String(255), nullable=True) created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), nullable=False, default=utc_now @@ -26,14 +28,20 @@ class InvitationConfig(Base): __tablename__ = "invitation_config" id: Mapped[int] = mapped_column(Integer, primary_key=True, default=1) - title: Mapped[str] = mapped_column(String(200), nullable=False, default="Birthday Party") + title: Mapped[str] = mapped_column( + String(200), nullable=False, default="Birthday Party" + ) invitation_text: Mapped[str] = mapped_column( String(500), nullable=False, default="You're invited to the birthday party honoring", ) - honoree_name: Mapped[str] = mapped_column(String(200), nullable=False, default="Isabelle Snow") - event_date: Mapped[str] = mapped_column(String(20), nullable=False, default="2026-10-28") + honoree_name: Mapped[str] = mapped_column( + String(200), nullable=False, default="Isabelle Snow" + ) + event_date: Mapped[str] = mapped_column( + String(20), nullable=False, default="2026-10-28" + ) event_time: Mapped[str] = mapped_column(String(10), nullable=False, default="19:00") event_timezone: Mapped[str] = mapped_column( String(50), nullable=False, default="America/Bogota" @@ -56,11 +64,15 @@ class InvitationConfig(Base): nullable=False, default="https://maps.google.com/?q=Fresco+Ristorante+Glendale+CA", ) - rsvp_heading: Mapped[str] = mapped_column(String(100), nullable=False, default="¿Nos vemos?") + rsvp_heading: Mapped[str] = mapped_column( + String(100), nullable=False, default="¿Nos vemos?" + ) rsvp_cta: Mapped[str] = mapped_column( String(100), nullable=False, default="CONFIRMA TU ASISTENCIA" ) - submit_label: Mapped[str] = mapped_column(String(100), nullable=False, default="TE VEO AHÍ") + submit_label: Mapped[str] = mapped_column( + String(100), nullable=False, default="TE VEO AHÍ" + ) msg_success: Mapped[str] = mapped_column( String(300), nullable=False, diff --git a/backend/app/routes/admin.py b/backend/app/routes/admin.py index a8be019..0e10af6 100644 --- a/backend/app/routes/admin.py +++ b/backend/app/routes/admin.py @@ -25,19 +25,20 @@ from ..services.map_preview import ( ) 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)] DbDep = Annotated[Session, Depends(get_db)] ADMIN_RESPONSES = { 401: {"description": "No autenticado. Se requiere sesión activa de usuario."}, - 403: {"description": "Acceso denegado. Se requiere pertenecer al grupo 'bdinvite_admins'."}, + 403: { + "description": "Acceso denegado. Se requiere pertenecer al grupo 'bdinvite_admins'." + }, } ADMIN_401 = ADMIN_RESPONSES - @router.get( "/rsvps", response_model=RSVPListResponse, @@ -47,7 +48,10 @@ ADMIN_401 = ADMIN_RESPONSES "Permite filtrado por coincidencia parcial (`?search=`) sobre nombre, teléfono o correo." ), responses={ - 200: {"model": RSVPListResponse, "description": "Lista de confirmaciones obtenida."}, + 200: { + "model": RSVPListResponse, + "description": "Lista de confirmaciones obtenida.", + }, **ADMIN_RESPONSES, }, ) @@ -100,10 +104,15 @@ def delete_rsvp_endpoint( summary="Editar una confirmación de asistencia", description="Actualiza el nombre, teléfono o correo de un asistente confirmado.", responses={ - 200: {"model": RSVPAdminItem, "description": "Registro actualizado exitosamente."}, + 200: { + "model": RSVPAdminItem, + "description": "Registro actualizado exitosamente.", + }, 400: {"description": "Error de validación en los campos proporcionados."}, 404: {"description": "Registro no encontrado."}, - 409: {"description": "El número de teléfono ya está registrado por otro asistente."}, + 409: { + "description": "El número de teléfono ya está registrado por otro asistente." + }, **ADMIN_RESPONSES, }, ) @@ -129,7 +138,6 @@ def update_rsvp_endpoint( return updated - @router.get( "/export", summary="Exportar confirmaciones en formato CSV", @@ -158,7 +166,11 @@ def export_rsvps_csv( for item in rsvps: created_iso = "" if item.created_at: - dt = item.created_at if item.created_at.tzinfo else item.created_at.replace(tzinfo=UTC) + dt = ( + item.created_at + if item.created_at.tzinfo + else item.created_at.replace(tzinfo=UTC) + ) created_iso = dt.isoformat() writer.writerow([item.name, item.phone, item.email or "", created_iso]) @@ -176,7 +188,10 @@ def export_rsvps_csv( summary="Obtener configuración editable", description="Retorna el objeto completo de configuración para poblar el formulario de administración.", responses={ - 200: {"model": InvitationConfigResponse, "description": "Configuración obtenida correctamente."}, + 200: { + "model": InvitationConfigResponse, + "description": "Configuración obtenida correctamente.", + }, **ADMIN_RESPONSES, }, ) @@ -201,7 +216,10 @@ def get_admin_config( "Los cambios toman efecto de inmediato sin requerir recarga del contenedor." ), responses={ - 200: {"model": InvitationConfigResponse, "description": "Configuración actualizada con éxito."}, + 200: { + "model": InvitationConfigResponse, + "description": "Configuración actualizada con éxito.", + }, **ADMIN_RESPONSES, }, ) @@ -216,7 +234,10 @@ def get_admin_config( "Los cambios toman efecto de inmediato sin requerir recarga del contenedor." ), responses={ - 200: {"model": InvitationConfigResponse, "description": "Configuración actualizada con éxito."}, + 200: { + "model": InvitationConfigResponse, + "description": "Configuración actualizada con éxito.", + }, **ADMIN_RESPONSES, }, ) @@ -262,7 +283,10 @@ async def update_admin_config( "sin realizar escrituras innecesarias a la base de datos." ), responses={ - 200: {"model": GenerateMapPreviewResponse, "description": "Vista previa generada exitosamente."}, + 200: { + "model": GenerateMapPreviewResponse, + "description": "Vista previa generada exitosamente.", + }, **ADMIN_RESPONSES, }, ) @@ -282,7 +306,9 @@ async def regenerate_map_preview_endpoint( target_url = current.map_url try: - fallback = f"{current.address_lines}\n{current.address_name}" if current else None + fallback = ( + f"{current.address_lines}\n{current.address_name}" if current else None + ) lat, lng, _ = await resolve_google_maps_coordinates( target_url, fallback_query=fallback ) @@ -305,4 +331,3 @@ async def regenerate_map_preview_endpoint( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Error al generar la vista previa del mapa: {err}", ) from err - diff --git a/backend/app/routes/auth.py b/backend/app/routes/auth.py index fc88ed7..a2adfe9 100644 --- a/backend/app/routes/auth.py +++ b/backend/app/routes/auth.py @@ -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.responses import JSONResponse, RedirectResponse +from fastapi.responses import RedirectResponse from ..auth import Identity, OIDCAuthAdapter from ..auth.dependencies import get_auth_adapter @@ -71,13 +71,17 @@ def direct_login_endpoint( def callback_endpoint( request: Request, 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")], ): token_response = adapter.oidc_client.exchange_code(code=code, state=state) identity = adapter.oidc_client.extract_identity(token_response.claims) - redirect_response = RedirectResponse(url="/birthday/admin", status_code=status.HTTP_302_FOUND) + redirect_response = RedirectResponse( + url="/birthday/admin", status_code=status.HTTP_302_FOUND + ) adapter.create_session( identity=identity, request=request, @@ -96,7 +100,7 @@ def me_endpoint( request: Request, adapter: AuthAdapterDep, ): - identity: Optional[Identity] = adapter.current_identity(request) + identity: Identity | None = adapter.current_identity(request) if identity is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, diff --git a/backend/app/schemas.py b/backend/app/schemas.py index 691e3d3..84b0c77 100644 --- a/backend/app/schemas.py +++ b/backend/app/schemas.py @@ -6,7 +6,6 @@ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator - def normalize_phone(raw: str) -> str: """Normalize Colombian mobile numbers. @@ -127,8 +126,6 @@ class RSVPUpdate(BaseModel): return cleaned.lower() - - class RSVPSuccessResponse(BaseModel): result: Literal["SUCCESS"] = Field( default="SUCCESS", @@ -168,11 +165,27 @@ class RSVPErrorResponse(BaseModel): class RSVPAdminItem(BaseModel): - id: int = Field(..., description="Identificador único del registro en base de datos", examples=[1]) - name: str = Field(..., description="Nombre completo del asistente", examples=["Ana García"]) - phone: str = Field(..., description="Número telefónico normalizado a 10 dígitos", examples=["3001234567"]) - email: str | None = Field(default=None, description="Correo electrónico registrado", examples=["ana@example.com"]) - created_at: datetime = Field(..., description="Marca de tiempo UTC de la confirmación") + id: int = Field( + ..., + description="Identificador único del registro en base de datos", + examples=[1], + ) + name: str = Field( + ..., description="Nombre completo del asistente", examples=["Ana García"] + ) + phone: str = Field( + ..., + description="Número telefónico normalizado a 10 dígitos", + examples=["3001234567"], + ) + email: str | None = Field( + default=None, + description="Correo electrónico registrado", + examples=["ana@example.com"], + ) + created_at: datetime = Field( + ..., description="Marca de tiempo UTC de la confirmación" + ) model_config = ConfigDict(from_attributes=True) @@ -183,10 +196,13 @@ class RSVPAdminItem(BaseModel): return dt.isoformat() - class RSVPListResponse(BaseModel): - count: int = Field(..., description="Cantidad total de confirmaciones encontradas", examples=[37]) - rsvps: list[RSVPAdminItem] = Field(..., description="Lista de asistentes confirmados") + count: int = Field( + ..., description="Cantidad total de confirmaciones encontradas", examples=[37] + ) + rsvps: list[RSVPAdminItem] = Field( + ..., description="Lista de asistentes confirmados" + ) class InvitationConfigBase(BaseModel): @@ -376,8 +392,12 @@ class InvitationConfigUpdate(InvitationConfigBase): class InvitationConfigResponse(InvitationConfigBase): - id: int = Field(default=1, description="Identificador único del registro singleton (siempre 1)") - updated_at: datetime | None = Field(default=None, description="Última modificación en UTC") + id: int = Field( + default=1, description="Identificador único del registro singleton (siempre 1)" + ) + updated_at: datetime | None = Field( + default=None, description="Última modificación en UTC" + ) model_config = ConfigDict(from_attributes=True) @@ -390,7 +410,6 @@ class InvitationConfigResponse(InvitationConfigBase): return dt.isoformat() - class GenerateMapPreviewRequest(BaseModel): map_url: str | None = Field( default=None, @@ -400,14 +419,18 @@ class GenerateMapPreviewRequest(BaseModel): class GenerateMapPreviewResponse(BaseModel): - map_preview_url: str = Field(description="URL para acceder a la imagen de vista previa generada") + map_preview_url: str = Field( + description="URL para acceder a la imagen de vista previa generada" + ) lat: float = Field(description="Latitud resuelta") lng: float = Field(description="Longitud resuelta") message: str = Field(default="Vista previa generada con éxito") class LoginRequest(BaseModel): - username: str = Field(..., description="Nombre de usuario o correo para autenticación OIDC") + username: str = Field( + ..., description="Nombre de usuario o correo para autenticación OIDC" + ) password: str = Field(..., description="Contraseña de usuario") @@ -415,5 +438,6 @@ class UserResponse(BaseModel): subject: str = Field(..., description="Identificador único del usuario (sub)") email: str = Field(..., description="Correo electrónico del usuario") name: str | None = Field(default=None, description="Nombre visible del usuario") - groups: list[str] = Field(default_factory=list, description="Grupos o roles asignados al usuario") - + groups: list[str] = Field( + default_factory=list, description="Grupos o roles asignados al usuario" + ) diff --git a/backend/app/services/map_preview.py b/backend/app/services/map_preview.py index 7350cad..d21174f 100644 --- a/backend/app/services/map_preview.py +++ b/backend/app/services/map_preview.py @@ -1,3 +1,4 @@ +import contextlib import io import math import re @@ -27,12 +28,10 @@ def is_google_maps_host(host: str) -> bool: return True if clean_host.startswith("maps.google."): return True - if clean_host == "google.com" or clean_host.endswith(".google.com") or clean_host.endswith(".google"): + if clean_host == "google.com" or clean_host.endswith((".google.com", ".google")): return True # Regional domains like google.es, google.co, google.com.co - if re.match(r"^(?:www\.)?google\.[a-z.]+$", clean_host): - return True - return False + return bool(re.match(r"^(?:www\.)?google\.[a-z.]+$", clean_host)) def validate_google_maps_url_format(url: str) -> None: @@ -74,7 +73,7 @@ def extract_coordinates_from_text(text: str) -> tuple[float, float] | None: if parsed.query: qs = parse_qs(parsed.query) for param in ("q", "ll", "destination"): - if param in qs and qs[param]: + if qs.get(param): val = qs[param][0].strip() m = re.match(r"^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$", val) if m: @@ -118,7 +117,9 @@ async def resolve_google_maps_coordinates( if hop_coords: return hop_coords[0], hop_coords[1], resolved_url except httpx.RequestError as exc: - raise ValueError(f"No se pudo resolver el enlace de Google Maps: {exc}") from exc + raise ValueError( + f"No se pudo resolver el enlace de Google Maps: {exc}" + ) from exc # Try extraction on the final resolved destination URL final_coords = extract_coordinates_from_text(resolved_url) @@ -129,7 +130,7 @@ async def resolve_google_maps_coordinates( parsed = urlparse(resolved_url) qs = parse_qs(parsed.query) query_text = None - if "q" in qs and qs["q"]: + if qs.get("q"): query_text = qs["q"][0] elif "/place/" in parsed.path: # e.g. /maps/place/Fresco+Ristorante/... @@ -153,9 +154,11 @@ async def resolve_google_maps_coordinates( candidates.append(query_text) if candidates: - async with httpx.AsyncClient(timeout=8.0, headers={"User-Agent": USER_AGENT}) as client: + async with httpx.AsyncClient( + timeout=8.0, headers={"User-Agent": USER_AGENT} + ) as client: for candidate in candidates: - try: + with contextlib.suppress(Exception): nom_res = await client.get( "https://nominatim.openstreetmap.org/search", params={"q": candidate, "format": "json", "limit": 1}, @@ -167,8 +170,6 @@ async def resolve_google_maps_coordinates( lng = float(results[0]["lon"]) if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0: return lat, lng, resolved_url - except Exception: - pass raise ValueError( "No se pudieron extraer las coordenadas de la URL de Google Maps. " @@ -207,18 +208,17 @@ async def generate_map_preview_image( # Canvas of 3x3 tiles = 768x768 pixels canvas = Image.new("RGB", (768, 768), color=(229, 227, 223)) - async with httpx.AsyncClient(timeout=10.0, headers={"User-Agent": USER_AGENT}) as client: + async with httpx.AsyncClient( + timeout=10.0, headers={"User-Agent": USER_AGENT} + ) as client: for r_idx, y in enumerate(range(y_int - 1, y_int + 2)): for c_idx, x in enumerate(range(x_int - 1, x_int + 2)): tile_url = f"https://tile.openstreetmap.org/{zoom}/{x}/{y}.png" - try: + with contextlib.suppress(Exception): res = await client.get(tile_url) if res.status_code == 200: tile = Image.open(io.BytesIO(res.content)).convert("RGB") canvas.paste(tile, (c_idx * 256, r_idx * 256)) - except Exception: - # Keep neutral background tile if individual tile fails - pass # Exact target location within the 768x768 canvas cx = 256 + int(dx * 256) @@ -236,7 +236,9 @@ async def generate_map_preview_image( draw.ellipse((192, 198, 208, 204), fill=(40, 40, 40, 140)) # Golden pin pointer (inverted triangle) - draw.polygon([(188, 184), (212, 184), (200, 200)], fill="#d4a843", outline="#1a1a1a") + draw.polygon( + [(188, 184), (212, 184), (200, 200)], fill="#d4a843", outline="#1a1a1a" + ) # Golden pin circular head draw.ellipse((188, 170, 212, 194), fill="#d4a843", outline="#1a1a1a", width=2) diff --git a/backend/app/services/rsvp.py b/backend/app/services/rsvp.py index bd4915f..4bbf0c7 100644 --- a/backend/app/services/rsvp.py +++ b/backend/app/services/rsvp.py @@ -113,5 +113,3 @@ def update_rsvp( except Exception: db.rollback() raise - - diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 57bd1a7..568e1b0 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -88,6 +88,7 @@ def admin_client(client: TestClient) -> TestClient: @pytest.fixture(scope="function") 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 - diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index f1c9871..ded256e 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -28,8 +28,18 @@ def test_remote_user_header_strictly_ignored(client: TestClient): assert res.json() == {"detail": "Not authenticated"} # Also verify across other admin routes - assert client.get("/birthday/api/admin/export", headers={"Remote-User": "kiskaadee"}).status_code == 401 - assert client.get("/birthday/api/admin/config", headers={"Remote-User": "kiskaadee"}).status_code == 401 + assert ( + client.get( + "/birthday/api/admin/export", headers={"Remote-User": "kiskaadee"} + ).status_code + == 401 + ) + assert ( + client.get( + "/birthday/api/admin/config", headers={"Remote-User": "kiskaadee"} + ).status_code + == 401 + ) assert ( client.post( "/birthday/api/admin/map-preview/generate", @@ -54,7 +64,9 @@ def test_admin_endpoints_authenticated_non_admin_forbidden(guest_client: TestCli ] for method, path in endpoints: res = guest_client.request(method, path) - assert res.status_code == 403, f"{method} {path} should reject non-admin with 403" + assert res.status_code == 403, ( + f"{method} {path} should reject non-admin with 403" + ) assert "Forbidden" in res.json()["detail"] @@ -91,11 +103,19 @@ def test_admin_list_and_search_rsvps(admin_client: TestClient): # Add 3 invitees admin_client.post( "/birthday/api/rsvp", - json={"name": "Carlos Gomez", "phone": "300 111 2233", "email": "carlos@test.com"}, + json={ + "name": "Carlos Gomez", + "phone": "300 111 2233", + "email": "carlos@test.com", + }, ) admin_client.post( "/birthday/api/rsvp", - json={"name": "Maria Perez", "phone": "315 222 3344", "email": "maria@test.com"}, + json={ + "name": "Maria Perez", + "phone": "315 222 3344", + "email": "maria@test.com", + }, ) admin_client.post( "/birthday/api/rsvp", @@ -124,7 +144,11 @@ def test_admin_list_and_search_rsvps(admin_client: TestClient): def test_admin_export_csv(admin_client: TestClient): admin_client.post( "/birthday/api/rsvp", - json={"name": "Sofia Vergara", "phone": "301 999 8877", "email": "sofia@hollywood.com"}, + json={ + "name": "Sofia Vergara", + "phone": "301 999 8877", + "email": "sofia@hollywood.com", + }, ) 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"] content = res.text - lines = content.strip().split("\r\n") if "\r\n" in content else content.strip().split("\n") + lines = ( + content.strip().split("\r\n") + if "\r\n" in content + else content.strip().split("\n") + ) assert lines[0] == "name,phone,email,created_at" assert "Sofia Vergara,3019998877,sofia@hollywood.com" in lines[1] @@ -153,7 +181,11 @@ def test_admin_delete_rsvp(client: TestClient): # Create an RSVP client.post( "/birthday/api/rsvp", - json={"name": "Lucas Silva", "phone": "300 444 5566", "email": "lucas@test.com"}, + json={ + "name": "Lucas Silva", + "phone": "300 444 5566", + "email": "lucas@test.com", + }, ) list_res = client.get("/birthday/api/admin/rsvps") 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 patch_res = client.patch( f"/birthday/api/admin/rsvps/{id_one}", - json={"name": "Person One Updated", "phone": "+57 300 999 8888", "email": "newone@test.com"}, + json={ + "name": "Person One Updated", + "phone": "+57 300 999 8888", + "email": "newone@test.com", + }, ) assert patch_res.status_code == 200 updated_data = patch_res.json() diff --git a/backend/tests/test_auth_port.py b/backend/tests/test_auth_port.py index 27dd548..a52bb92 100644 --- a/backend/tests/test_auth_port.py +++ b/backend/tests/test_auth_port.py @@ -1,10 +1,8 @@ from dataclasses import FrozenInstanceError -from typing import Optional import pytest from fastapi import Request, Response from fastapi.responses import RedirectResponse -from starlette.datastructures import Headers from app.auth import AuthPort, Identity @@ -12,10 +10,10 @@ from app.auth import AuthPort, Identity class MockAuthAdapter: """Mock implementation of AuthPort for testing hexagonal boundary compliance.""" - def __init__(self, current_user: Optional[Identity] = None): + def __init__(self, current_user: Identity | None = None): 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 def login(self, request: Request) -> Response: @@ -28,7 +26,7 @@ class MockAuthAdapter: class IncompleteAuthAdapter: """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 diff --git a/backend/tests/test_browser_sso.py b/backend/tests/test_browser_sso.py index 95f80de..6a88c80 100644 --- a/backend/tests/test_browser_sso.py +++ b/backend/tests/test_browser_sso.py @@ -1,6 +1,7 @@ +import contextlib import threading import time -from typing import Generator +from collections.abc import Generator import pytest import uvicorn @@ -31,13 +32,11 @@ def live_server() -> Generator[str, None, None]: ready = False for _ in range(50): - try: + with contextlib.suppress(Exception): r = httpx.get(f"{BASE_URL}/birthday/api/docs", timeout=0.5) if r.status_code == 200: ready = True break - except Exception: - pass time.sleep(0.1) assert ready, "Server failed to start in time" @@ -74,7 +73,7 @@ def test_browser_sso_complete_interactive_loop( page: Page, ): """Complete browser SSO acceptance test (CP7). - + Verifies: 1. Browser navigates to /birthday/admin -> redirected to OIDC login form. 2. Form submitted with admin@example.com / password123. @@ -99,7 +98,9 @@ def test_browser_sso_complete_interactive_loop( assert page.url.endswith("/birthday/admin") cookies = browser_context.cookies() - session_cookie = next((c for c in cookies if c.get("name") == "bdinvite_session"), None) + session_cookie = next( + (c for c in cookies if c.get("name") == "bdinvite_session"), None + ) assert session_cookie is not None, "bdinvite_session cookie must be set" assert session_cookie.get("httpOnly") is True, "Session cookie must be HttpOnly" @@ -118,7 +119,13 @@ def test_browser_sso_complete_interactive_loop( assert logout_btn.is_visible() 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) assert "authorize" in page.url diff --git a/backend/tests/test_dependencies.py b/backend/tests/test_dependencies.py index 0e2bb08..31ee0d5 100644 --- a/backend/tests/test_dependencies.py +++ b/backend/tests/test_dependencies.py @@ -1,8 +1,8 @@ -from typing import Optional +from typing import Annotated +import pytest from fastapi import Depends, FastAPI, HTTPException, Request from fastapi.testclient import TestClient -import pytest from app.auth import ( Identity, @@ -24,8 +24,8 @@ REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback" def create_dummy_request( - headers: Optional[dict[str, str]] = None, - cookies: Optional[dict[str, str]] = None, + headers: dict[str, str] | None = None, + cookies: dict[str, str] | None = None, ) -> Request: """Construct a lightweight ASGI Request instance for unit testing dependencies.""" raw_headers: list[tuple[bytes, bytes]] = [ @@ -73,8 +73,12 @@ def test_app() -> FastAPI: """Isolated FastAPI test harness registering dependency endpoints.""" app = FastAPI(title="Dependency Test Harness") + event_planners_dep = require_group("event_planners") + @app.get("/test/identity") - def route_identity(identity: Optional[Identity] = Depends(get_current_identity)): + def route_identity( + identity: Annotated[Identity | None, Depends(get_current_identity)], + ): if identity is None: return {"authenticated": False, "identity": None} return { @@ -85,7 +89,9 @@ def test_app() -> FastAPI: } @app.get("/test/authenticated") - def route_authenticated(identity: Identity = Depends(require_authenticated)): + def route_authenticated( + identity: Annotated[Identity, Depends(require_authenticated)], + ): return { "subject": identity.subject, "email": identity.email, @@ -93,7 +99,7 @@ def test_app() -> FastAPI: } @app.get("/test/admin") - def route_admin(admin: Identity = Depends(require_admin)): + def route_admin(admin: Annotated[Identity, Depends(require_admin)]): return { "subject": admin.subject, "email": admin.email, @@ -101,7 +107,7 @@ def test_app() -> FastAPI: } @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 { "subject": member.subject, "groups": member.groups, diff --git a/backend/tests/test_identity_extraction.py b/backend/tests/test_identity_extraction.py index c6b66e5..5661fad 100644 --- a/backend/tests/test_identity_extraction.py +++ b/backend/tests/test_identity_extraction.py @@ -1,10 +1,7 @@ from dataclasses import FrozenInstanceError -from typing import Optional -from fastapi import Request, Response -from fastapi.responses import RedirectResponse -import httpx import pytest +from fastapi import Request, Response from app.auth import ( AuthPort, @@ -12,8 +9,6 @@ from app.auth import ( InvalidTokenError, OIDCAuthAdapter, OIDCClient, - OIDCConfig, - TokenExchangeError, ) LIVE_ISSUER = "http://localhost:8088/default" @@ -34,8 +29,8 @@ def oidc_client() -> OIDCClient: def create_dummy_request( - headers: Optional[dict[str, str]] = None, - cookies: Optional[dict[str, str]] = None, + headers: dict[str, str] | None = None, + cookies: dict[str, str] | None = None, ) -> Request: raw_headers = [ (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 == [] -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.""" with pytest.raises(InvalidTokenError, match="missing required 'sub' claim"): 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 == [] # 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 - 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 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"] # 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 == [] @@ -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.""" 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) # 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) 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) - 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) assert resolved == expected_identity @@ -300,7 +309,9 @@ def test_oidc_auth_adapter_current_identity_with_valid_cookie(oidc_client: OIDCC 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}) 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): """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() response = adapter.logout(req) diff --git a/backend/tests/test_map_preview.py b/backend/tests/test_map_preview.py index 08ce0a4..01157e9 100644 --- a/backend/tests/test_map_preview.py +++ b/backend/tests/test_map_preview.py @@ -1,6 +1,7 @@ from unittest.mock import ANY, patch import pytest + from app.config import settings from app.services.map_preview import ( deg2num, @@ -8,7 +9,6 @@ from app.services.map_preview import ( is_google_maps_host, validate_google_maps_url_format, ) - from tests.conftest import login_client @@ -29,7 +29,9 @@ def test_is_google_maps_host(): def test_validate_google_maps_url_format(): validate_google_maps_url_format("https://maps.app.goo.gl/354784424357732") - validate_google_maps_url_format("https://www.google.com/maps/place/Fresco/@34.1,-118.2,17z") + validate_google_maps_url_format( + "https://www.google.com/maps/place/Fresco/@34.1,-118.2,17z" + ) validate_google_maps_url_format("https://maps.google.com/?q=34.1,-118.2") with pytest.raises(ValueError, match="no puede estar vacía"): @@ -44,23 +46,33 @@ def test_validate_google_maps_url_format(): def test_extract_coordinates_from_text(): # 1. @lat,lng - coords = extract_coordinates_from_text("https://google.com/maps/place/Venue/@34.143245,-118.255132,17z") + coords = extract_coordinates_from_text( + "https://google.com/maps/place/Venue/@34.143245,-118.255132,17z" + ) assert coords == (34.143245, -118.255132) # 2. !3dlat!4dlng - coords = extract_coordinates_from_text("https://google.com/maps/data=!4m6!3m5!1s0x0!8m2!3d4.6534!4d-74.0564") + coords = extract_coordinates_from_text( + "https://google.com/maps/data=!4m6!3m5!1s0x0!8m2!3d4.6534!4d-74.0564" + ) assert coords == (4.6534, -74.0564) # 3. Query params: q=lat,lng - coords = extract_coordinates_from_text("https://maps.google.com/?q=34.1432,-118.2551") + coords = extract_coordinates_from_text( + "https://maps.google.com/?q=34.1432,-118.2551" + ) assert coords == (34.1432, -118.2551) # 4. Query params: ll=lat,lng - coords = extract_coordinates_from_text("https://maps.google.com/maps?ll=34.1432,-118.2551&z=16") + coords = extract_coordinates_from_text( + "https://maps.google.com/maps?ll=34.1432,-118.2551&z=16" + ) assert coords == (34.1432, -118.2551) # 5. Non-coordinate text - assert extract_coordinates_from_text("https://maps.google.com/?q=Eiffel+Tower") is None + assert ( + extract_coordinates_from_text("https://maps.google.com/?q=Eiffel+Tower") is None + ) def test_deg2num(): @@ -71,12 +83,17 @@ def test_deg2num(): @patch("app.routes.admin.resolve_google_maps_coordinates") @patch("app.routes.admin.generate_map_preview_image") -def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client, tmp_path): +def test_admin_generate_map_preview_endpoint( + mock_generate, mock_resolve, client, tmp_path +): mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url") mock_generate.return_value = tmp_path / "map_preview.png" # Test without auth -> 401 - resp = client.post("/birthday/api/admin/map-preview/generate", json={"map_url": "https://maps.google.com/?q=34.1,-118.2"}) + resp = client.post( + "/birthday/api/admin/map-preview/generate", + json={"map_url": "https://maps.google.com/?q=34.1,-118.2"}, + ) assert resp.status_code == 401 # Test with auth -> 200 @@ -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 data["lat"] == 34.1432 assert data["lng"] == -118.2551 - mock_resolve.assert_called_once_with("https://maps.google.com/?q=34.1,-118.2", fallback_query=ANY) + mock_resolve.assert_called_once_with( + "https://maps.google.com/?q=34.1,-118.2", fallback_query=ANY + ) mock_generate.assert_called_once_with(34.1432, -118.2551) @patch("app.routes.admin.resolve_google_maps_coordinates") @patch("app.routes.admin.generate_map_preview_image") -def test_config_update_triggers_generator_only_when_map_url_changes(mock_generate, mock_resolve, admin_client, tmp_path): +def test_config_update_triggers_generator_only_when_map_url_changes( + mock_generate, mock_resolve, admin_client, tmp_path +): mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url") mock_generate.return_value = tmp_path / "map_preview.png" @@ -120,7 +141,9 @@ def test_config_update_triggers_generator_only_when_map_url_changes(mock_generat assert resp.status_code == 200 assert resp.json()["map_url"] == "https://maps.google.com/?q=34.1432,-118.2551" assert resp.json()["map_preview_url"] == "/birthday/api/map-preview.png" - mock_resolve.assert_called_once_with("https://maps.google.com/?q=34.1432,-118.2551", fallback_query=ANY) + mock_resolve.assert_called_once_with( + "https://maps.google.com/?q=34.1432,-118.2551", fallback_query=ANY + ) mock_generate.assert_called_once_with(34.1432, -118.2551) diff --git a/backend/tests/test_oidc_client.py b/backend/tests/test_oidc_client.py index b24fa46..1a26fe7 100644 --- a/backend/tests/test_oidc_client.py +++ b/backend/tests/test_oidc_client.py @@ -2,7 +2,6 @@ import base64 import json import urllib.parse -from fastapi import HTTPException import httpx import pytest @@ -12,7 +11,6 @@ from app.auth import ( InvalidTokenError, MismatchedNonceError, OIDCClient, - OIDCConfig, compute_code_challenge, generate_code_verifier, generate_nonce, @@ -40,7 +38,9 @@ def test_pkce_generation_and_challenge(): verifier = generate_code_verifier(64) assert len(verifier) == 64 # RFC 7636 Section 4.1 unreserved characters - unreserved = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") + unreserved = set( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~" + ) assert all(c in unreserved for c in verifier) # Length bounds validation @@ -139,7 +139,9 @@ def test_rejection_of_invalid_state_400(oidc_client: OIDCClient): 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.""" # 1. Create authorization request with PKCE and transaction secrets 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, data={ "username": "alice", - "claims": json.dumps({ - "email": "alice@example.com", - "name": "Alice In Chains", - "groups": ["family", "vip"], - }), + "claims": json.dumps( + { + "email": "alice@example.com", + "name": "Alice In Chains", + "groups": ["family", "vip"], + } + ), }, follow_redirects=False, ) - assert resp.status_code == 302, f"Expected 302 redirect from mock IdP, got {resp.status_code}" + assert resp.status_code == 302, ( + f"Expected 302 redirect from mock IdP, got {resp.status_code}" + ) redirect_url = resp.headers["location"] qs = urllib.parse.parse_qs(urllib.parse.urlparse(redirect_url).query) @@ -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) 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 "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 = json.loads(base64.urlsafe_b64decode(payload_raw)) payload["sub"] = "mallory_attacker" - tampered_payload_b64 = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=") + tampered_payload_b64 = ( + base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=") + ) tampered_payload_token = f"{parts[0]}.{tampered_payload_b64}.{parts[2]}" with pytest.raises(InvalidTokenError) as exc_info: @@ -302,5 +312,9 @@ def test_architectural_isolation_no_domain_route_crypto_imports(): for route_file in routes_dir.glob("*.py"): content = route_file.read_text(encoding="utf-8") for term in disallowed_terms: - assert f"import {term}" not in content, f"{route_file.name} violates isolation by importing {term}" - assert f"from {term}" not in content, f"{route_file.name} violates isolation by importing from {term}" + assert f"import {term}" not in content, ( + f"{route_file.name} violates isolation by importing {term}" + ) + assert f"from {term}" not in content, ( + f"{route_file.name} violates isolation by importing from {term}" + ) diff --git a/backend/tests/test_rsvp.py b/backend/tests/test_rsvp.py index 97f7247..cc64663 100644 --- a/backend/tests/test_rsvp.py +++ b/backend/tests/test_rsvp.py @@ -19,12 +19,12 @@ def test_normalize_phone_valid_cases(): def test_normalize_phone_invalid_cases(): invalid_cases = [ - "123456", # Too short - "1234567890", # Doesn't start with 3 - "+1 555 123 4567", # US format - "30012345678", # Too long - "", # Empty - "abcdefghij", # Non-digits + "123456", # Too short + "1234567890", # Doesn't start with 3 + "+1 555 123 4567", # US format + "30012345678", # Too long + "", # Empty + "abcdefghij", # Non-digits ] for raw in invalid_cases: with pytest.raises(ValueError, match="Formato de teléfono inválido"): diff --git a/backend/tests/test_security_hardening.py b/backend/tests/test_security_hardening.py index ce6b763..2b6bd29 100644 --- a/backend/tests/test_security_hardening.py +++ b/backend/tests/test_security_hardening.py @@ -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.""" # 1. Direct unit assertion: oidc_client rejects unknown state with InvalidStateError (400) 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["sub"] = "hacked_admin_identity" 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]}" 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, ) 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: 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.""" 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.""" admin_endpoints = [ ("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: 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", "") @@ -344,7 +356,9 @@ def test_legacy_remote_user_header_without_session_returns_401(client: TestClien 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.""" res = guest_client.get( "/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.SESSION_COOKIE_SECURE is True assert prod_settings.OIDC_ISSUER == "https://auth.roadtotech.me" - assert prod_settings.OIDC_REDIRECT_URI == "https://demos.roadtotech.me/birthday/api/auth/callback" + 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: 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) + ) diff --git a/backend/tests/test_session_management.py b/backend/tests/test_session_management.py index 37fdafe..423f8d9 100644 --- a/backend/tests/test_session_management.py +++ b/backend/tests/test_session_management.py @@ -1,8 +1,5 @@ -import time -from typing import Optional - import pytest -from fastapi import Request, Response +from fastapi import Request from fastapi.responses import Response as StarletteResponse from fastapi.testclient import TestClient @@ -14,8 +11,6 @@ from app.auth import ( sign_session_cookie, unsign_session_cookie, ) -from app.config import settings -from app.main import app from app.routes.auth import get_auth_adapter LIVE_ISSUER = "http://localhost:8088/default" @@ -216,7 +211,9 @@ def test_adapter_current_identity_resolution(auth_adapter: OIDCAuthAdapter): assert resolved == identity # 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}) 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 # 6. Expired session -> None - expired_session = auth_adapter.session_store.create_session(identity=identity, max_age_seconds=-10) - exp_cookie = sign_session_cookie(expired_session.session_id, auth_adapter.secret_key) + expired_session = auth_adapter.session_store.create_session( + identity=identity, max_age_seconds=-10 + ) + exp_cookie = sign_session_cookie( + expired_session.session_id, auth_adapter.secret_key + ) exp_req = create_dummy_request(cookies={"bdinvite_session": exp_cookie}) assert auth_adapter.current_identity(exp_req) is None @@ -332,7 +333,9 @@ def test_http_session_fixation_rotation_on_login(client: TestClient): assert pre_auth_cookie is not None # 2. Pre-auth session resolves to unauthorized - resp_anon = client.get("/birthday/api/auth/me", cookies={"bdinvite_session": pre_auth_cookie}) + resp_anon = client.get( + "/birthday/api/auth/me", cookies={"bdinvite_session": pre_auth_cookie} + ) assert resp_anon.status_code == 401 # 3. Authenticate while presenting pre_auth_cookie @@ -349,11 +352,15 @@ def test_http_session_fixation_rotation_on_login(client: TestClient): assert pre_auth_cookie != post_auth_cookie # 5. Pre-auth cookie MUST NOT have been promoted - resp_old = client.get("/birthday/api/auth/me", cookies={"bdinvite_session": pre_auth_cookie}) + resp_old = client.get( + "/birthday/api/auth/me", cookies={"bdinvite_session": pre_auth_cookie} + ) assert resp_old.status_code == 401 # 6. Post-auth cookie resolves to authenticated user - resp_valid = client.get("/birthday/api/auth/me", cookies={"bdinvite_session": post_auth_cookie}) + resp_valid = client.get( + "/birthday/api/auth/me", cookies={"bdinvite_session": post_auth_cookie} + ) assert resp_valid.status_code == 200 assert resp_valid.json()["subject"] == "admin-001" assert "bdinvite_admins" in resp_valid.json()["groups"] @@ -398,11 +405,15 @@ def test_http_logout_invalidates_session_and_clears_cookie(client: TestClient): assert cookie_val is not None # 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 # 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.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() # 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 diff --git a/frontend/src/admin/AdminLayout.tsx b/frontend/src/admin/AdminLayout.tsx index 286b242..6222815 100644 --- a/frontend/src/admin/AdminLayout.tsx +++ b/frontend/src/admin/AdminLayout.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useCallback, useEffect, useState } from "react"; import { Link, NavLink, Outlet } from "react-router-dom"; import { type CurrentUser, fetchCurrentUser, logoutUser } from "../api/client"; import { Spinner } from "../components/Spinner"; @@ -6,8 +6,16 @@ import { Spinner } from "../components/Spinner"; export function AdminLayout() { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); + const [loggedOut, setLoggedOut] = useState(false); useEffect(() => { + const params = new URLSearchParams(window.location.search); + if (params.get("logged_out") === "1") { + setLoading(false); + setLoggedOut(true); + return; + } + let isMounted = true; fetchCurrentUser() .then((userData) => { @@ -28,15 +36,16 @@ export function AdminLayout() { }; }, []); - const handleLogout = async () => { + const handleLogout = useCallback(async () => { try { await logoutUser(); } catch (err) { console.error("Logout failed:", err); } setUser(null); - window.location.href = "/birthday/api/auth/login"; - }; + setLoggedOut(true); + window.history.replaceState(null, "", "/birthday/admin?logged_out=1"); + }, []); if (loading) { return ( @@ -55,7 +64,7 @@ export function AdminLayout() { ); } - if (!user) { + if (loggedOut || !user) { return (
-

No autenticado. Redirigiendo al inicio de sesión...

- - Iniciar sesión - +
+ 🎂 +

+ Panel de Control · Invitación +

+
+ + Iniciar Sesión + + + +
+
🔒
+

+ Sesión Finalizada +

+

+ Has cerrado sesión correctamente. No hay sesión autenticada activa. +

+ + Iniciar Sesión + +
); }