From 815a5847c6b4b557a1e181af67af05ce9d933001 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Fri, 2 Oct 2026 23:39:59 -0500 Subject: [PATCH] feat(auth): implement browser session management and fixation protection - Browser session contract with HttpOnly=True and SameSite - Configurable Secure cookie flag - Session fixation barrier rotating session ID on login - Session lifecycle, expiration, and safe rejection of tampered cookies - Logout endpoint (/birthday/api/auth/logout) revoking session and clearing cookie (Max-Age=0) - Unit and integration tests in backend/tests/test_session_management.py --- backend/app/auth/__init__.py | 2 + backend/app/auth/oidc.py | 283 ++++++++++++++-- backend/app/config.py | 17 + backend/app/main.py | 3 +- backend/app/routes/__init__.py | 4 + backend/app/routes/admin.py | 25 +- backend/app/routes/auth.py | 135 ++++++++ backend/tests/test_session_management.py | 401 +++++++++++++++++++++++ 8 files changed, 835 insertions(+), 35 deletions(-) create mode 100644 backend/app/routes/auth.py create mode 100644 backend/tests/test_session_management.py diff --git a/backend/app/auth/__init__.py b/backend/app/auth/__init__.py index 87cddb4..bd659bd 100644 --- a/backend/app/auth/__init__.py +++ b/backend/app/auth/__init__.py @@ -9,6 +9,7 @@ from .oidc import ( OIDCDiscovery, OIDCError, OIDCTransaction, + SessionRecord, TokenValidationError, claims_to_identity, extract_identity_from_claims, @@ -31,6 +32,7 @@ __all__ = [ "OIDCDiscovery", "OIDCError", "OIDCTransaction", + "SessionRecord", "TokenValidationError", "claims_to_identity", "extract_identity_from_claims", diff --git a/backend/app/auth/oidc.py b/backend/app/auth/oidc.py index 67fdf1e..005ecb4 100644 --- a/backend/app/auth/oidc.py +++ b/backend/app/auth/oidc.py @@ -5,7 +5,7 @@ import hashlib import secrets import time from dataclasses import dataclass, field -from typing import Any, Optional, Union +from typing import Any, Literal, Optional, Union from urllib.parse import urlencode import httpx @@ -677,17 +677,198 @@ def claims_to_identity( return extract_identity_from_claims(claims, groups_claim=groups_claim) +@dataclass +class SessionRecord: + """Server-side session record holding authenticated identity and lifetime metadata.""" + + session_id: str + identity: Identity + created_at: float = field(default_factory=time.time) + expires_at: float = 0.0 + last_accessed: float = field(default_factory=time.time) + data: dict[str, Any] = field(default_factory=dict) + + @property + def is_expired(self) -> bool: + """Check if the session has expired past its TTL.""" + if self.expires_at <= 0: + return False + return time.time() > self.expires_at + + class OIDCAuthAdapter: - """Hexagonal AuthPort adapter using OIDCClient.""" + """Hexagonal AuthPort adapter using OIDCClient with robust browser session management.""" + + client: OIDCClient + session_cookie_name: str + cookie_secure: bool + cookie_samesite: Literal["lax", "strict", "none"] + cookie_path: str + cookie_domain: Optional[str] + session_lifetime: float + sessions: dict[str, Any] def __init__( self, client: OIDCClient, - session_cookie_name: str = "session_id", + session_cookie_name: str = "bdinvite_session", + cookie_secure: bool = False, + cookie_samesite: Literal["lax", "strict", "none"] = "lax", + cookie_path: str = "/", + cookie_domain: Optional[str] = None, + session_lifetime: float = 86400.0, + sessions: Optional[dict[str, Any]] = None, ) -> None: self.client = client self.session_cookie_name = session_cookie_name - self.sessions: dict[str, Identity] = {} + self.cookie_secure = cookie_secure + self.cookie_samesite = cookie_samesite + self.cookie_path = cookie_path + self.cookie_domain = cookie_domain + self.session_lifetime = session_lifetime + self.sessions: dict[str, Any] = sessions if sessions is not None else {} + + def extract_session_id(self, request: Request) -> Optional[str]: + """Safely extract and sanitize session identifier from cookies or headers. + + Rejects malformed, tampered, or overly long inputs without throwing exceptions. + """ + raw_id = ( + request.cookies.get(self.session_cookie_name) + or request.cookies.get("session_id") + or request.headers.get("X-Session-ID") + ) + if not raw_id or not isinstance(raw_id, str): + return None + raw_id = raw_id.strip() + if not raw_id or len(raw_id) > 256: + return None + + # Disallow control characters, newlines, null bytes, quotes, semicolons + import string + + allowed = set(string.ascii_letters + string.digits + "-_.~+") + if not set(raw_id).issubset(allowed): + return None + + return raw_id + + def get_session(self, session_id: str) -> Optional[SessionRecord]: + """Retrieve and validate session from storage. Returns None if absent or expired.""" + if not session_id or session_id not in self.sessions: + return None + + entry = self.sessions[session_id] + if isinstance(entry, Identity): + # Compatibility with direct Identity assignments + now = time.time() + return SessionRecord( + session_id=session_id, + identity=entry, + created_at=now, + expires_at=now + self.session_lifetime, + last_accessed=now, + ) + + if isinstance(entry, SessionRecord): + if entry.is_expired: + self.revoke_session(session_id) + return None + return entry + + return None + + def revoke_session(self, session_id: str) -> bool: + """Revoke a session from storage.""" + if session_id in self.sessions: + del self.sessions[session_id] + return True + return False + + def create_anonymous_session(self) -> str: + """Create a pre-authentication session identifier (for tracking or CSRF).""" + return secrets.token_urlsafe(32) + + def establish_session( + self, + identity: Identity, + pre_auth_session_id: Optional[str] = None, + ttl: Optional[float] = None, + ) -> str: + """Register a verified Identity and return a fresh new session ID. + + Session Fixation Barrier: + Always generates a fresh, cryptographically secure session identifier. + If a pre-authentication session identifier is provided or existed, it is + explicitly invalidated and NEVER reused or promoted into an authenticated session. + """ + if pre_auth_session_id: + self.revoke_session(pre_auth_session_id) + + new_session_id = secrets.token_urlsafe(32) + while new_session_id == pre_auth_session_id or new_session_id in self.sessions: + new_session_id = secrets.token_urlsafe(32) + + lifetime = ttl if ttl is not None else self.session_lifetime + now = time.time() + record = SessionRecord( + session_id=new_session_id, + identity=identity, + created_at=now, + expires_at=now + lifetime if lifetime > 0 else 0.0, + last_accessed=now, + ) + self.sessions[new_session_id] = record + return new_session_id + + def set_session_cookie( + self, + response: Response, + session_id: str, + max_age: Optional[int] = None, + ) -> None: + """Set session cookie with HttpOnly=True and configured security attributes.""" + lifetime = max_age if max_age is not None else int(self.session_lifetime) + response.set_cookie( + key=self.session_cookie_name, + value=session_id, + max_age=lifetime, + expires=lifetime, + path=self.cookie_path, + domain=self.cookie_domain, + secure=self.cookie_secure, + httponly=True, # Mandatory Security Invariant: JS cannot access session identifier + samesite=self.cookie_samesite, + ) + if self.session_cookie_name != "session_id": + response.delete_cookie( + key="session_id", + path=self.cookie_path, + domain=self.cookie_domain, + secure=self.cookie_secure, + httponly=True, + samesite=self.cookie_samesite, + ) + + def clear_session_cookie(self, response: Response) -> None: + """Clear browser session cookies by setting Max-Age=0.""" + response.delete_cookie( + key=self.session_cookie_name, + path=self.cookie_path, + domain=self.cookie_domain, + secure=self.cookie_secure, + httponly=True, + samesite=self.cookie_samesite, + ) + if self.session_cookie_name != "session_id": + response.delete_cookie( + key="session_id", + path=self.cookie_path, + domain=self.cookie_domain, + secure=self.cookie_secure, + httponly=True, + samesite=self.cookie_samesite, + ) def current_identity(self, request: Request) -> Optional[Identity]: """Extract and return verified Identity. @@ -697,9 +878,12 @@ class OIDCAuthAdapter: (such as X-User, X-Email, etc.). Identities are ONLY returned from cryptographically validated sessions or verified Bearer ID tokens. """ - session_id = request.headers.get("X-Session-ID") or request.cookies.get(self.session_cookie_name) - if session_id and session_id in self.sessions: - return self.sessions[session_id] + session_id = self.extract_session_id(request) + if session_id: + record = self.get_session(session_id) + if record is not None: + record.last_accessed = time.time() + return record.identity auth_header = request.headers.get("Authorization") if auth_header and auth_header.startswith("Bearer "): @@ -713,25 +897,26 @@ class OIDCAuthAdapter: return None def login(self, request: Request) -> Response: + """Handle or initiate the authentication flow (redirecting to IdP).""" auth_url, _ = self.client.create_authorization_url() return RedirectResponse(url=auth_url, status_code=302) - def logout(self, request: Request) -> Response: - session_id = request.cookies.get(self.session_cookie_name) - if session_id and session_id in self.sessions: - del self.sessions[session_id] + def logout( + self, + request: Request, + response: Optional[Response] = None, + redirect_target: Optional[str] = None, + ) -> Response: + """Terminate the active session and clear client cookies.""" + session_id = self.extract_session_id(request) + if session_id: + self.revoke_session(session_id) - redirect_target = self.client.end_session_endpoint or "/" - resp = RedirectResponse(url=redirect_target, status_code=302) - resp.delete_cookie(self.session_cookie_name) + target = redirect_target or self.client.end_session_endpoint or "/" + resp = response if response is not None else RedirectResponse(url=target, status_code=302) + self.clear_session_cookie(resp) return resp - def establish_session(self, identity: Identity) -> str: - """Register a verified Identity and return a new session ID.""" - session_id = secrets.token_urlsafe(32) - self.sessions[session_id] = identity - return session_id - def handle_callback( self, code: str, @@ -739,17 +924,25 @@ class OIDCAuthAdapter: response: Optional[Response] = None, redirect_uri: Optional[str] = None, extra_params: Optional[dict[str, Any]] = None, + request: Optional[Request] = None, + pre_auth_session_id: Optional[str] = None, ) -> tuple[Identity, str]: - """Authenticate user from callback, establish session, and return Identity and session_id.""" + """Authenticate user from callback, establish session with fixation barrier, and return Identity and session_id.""" identity, _ = self.client.process_callback( code=code, state=state, redirect_uri=redirect_uri, extra_params=extra_params, ) - session_id = self.establish_session(identity) + if pre_auth_session_id is None and request is not None: + pre_auth_session_id = self.extract_session_id(request) + + session_id = self.establish_session( + identity=identity, + pre_auth_session_id=pre_auth_session_id, + ) if response is not None: - response.set_cookie(self.session_cookie_name, session_id, httponly=True, samesite="lax") + self.set_session_cookie(response, session_id) return identity, session_id async def ahandle_callback( @@ -759,15 +952,53 @@ class OIDCAuthAdapter: response: Optional[Response] = None, redirect_uri: Optional[str] = None, extra_params: Optional[dict[str, Any]] = None, + request: Optional[Request] = None, + pre_auth_session_id: Optional[str] = None, ) -> tuple[Identity, str]: - """Asynchronously authenticate user from callback, establish session, and return Identity and session_id.""" + """Asynchronously authenticate user from callback, establish session with fixation barrier, and return Identity and session_id.""" identity, _ = await self.client.aprocess_callback( code=code, state=state, redirect_uri=redirect_uri, extra_params=extra_params, ) - session_id = self.establish_session(identity) + if pre_auth_session_id is None and request is not None: + pre_auth_session_id = self.extract_session_id(request) + + session_id = self.establish_session( + identity=identity, + pre_auth_session_id=pre_auth_session_id, + ) if response is not None: - response.set_cookie(self.session_cookie_name, session_id, httponly=True, samesite="lax") + self.set_session_cookie(response, session_id) + return identity, session_id + + def authenticate_and_establish_session( + self, + username: str, + password: Optional[str] = None, + scope: Optional[str] = None, + pre_auth_session_id: Optional[str] = None, + response: Optional[Response] = None, + ) -> tuple[Identity, str]: + """Authenticate user with password grant and establish session with fixation barrier.""" + identity, _ = self.client.authenticate_user(username=username, password=password, scope=scope) + session_id = self.establish_session(identity, pre_auth_session_id=pre_auth_session_id) + if response is not None: + self.set_session_cookie(response, session_id) + return identity, session_id + + async def aauthenticate_and_establish_session( + self, + username: str, + password: Optional[str] = None, + scope: Optional[str] = None, + pre_auth_session_id: Optional[str] = None, + response: Optional[Response] = None, + ) -> tuple[Identity, str]: + """Asynchronously authenticate user with password grant and establish session with fixation barrier.""" + identity, _ = await self.client.aauthenticate_user(username=username, password=password, scope=scope) + session_id = self.establish_session(identity, pre_auth_session_id=pre_auth_session_id) + if response is not None: + self.set_session_cookie(response, session_id) return identity, session_id diff --git a/backend/app/config.py b/backend/app/config.py index 69b5a13..e8fdd61 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -1,4 +1,5 @@ from pathlib import Path +from typing import Literal from pydantic_settings import BaseSettings, SettingsConfigDict @@ -11,6 +12,22 @@ class Settings(BaseSettings): DATABASE_URL: str = "sqlite:///./data/bdinvite.db" DATA_DIR: str = "./data" + # OIDC & Auth Settings + OIDC_ISSUER: str = "http://localhost:8088/default" + OIDC_CLIENT_ID: str = "bdinvite-client" + OIDC_CLIENT_SECRET: str | None = "bdinvite-secret" + OIDC_REDIRECT_URI: str = "http://localhost:8000/birthday/api/auth/callback" + OIDC_GROUPS_CLAIM: str = "groups" + OIDC_GROUP_CLAIM_PATH: str | None = None + + # Browser Session Management Settings + SESSION_COOKIE_NAME: str = "bdinvite_session" + SESSION_COOKIE_SECURE: bool = False + SESSION_COOKIE_SAMESITE: Literal["lax", "strict", "none"] = "lax" + SESSION_COOKIE_PATH: str = "/" + SESSION_COOKIE_DOMAIN: str | None = None + SESSION_EXPIRE_SECONDS: int = 86400 + model_config = SettingsConfigDict(env_file=".env", extra="ignore") @property diff --git a/backend/app/main.py b/backend/app/main.py index f694f27..73b5f1f 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -10,7 +10,7 @@ from fastapi.staticfiles import StaticFiles from .config import settings from .database import Base, SessionLocal, engine -from .routes import admin, config, rsvp +from .routes import admin, auth, config, rsvp from .services.config import seed_default_config @@ -90,6 +90,7 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE # Register API routes with exact path prefixes per specification app.include_router(rsvp.router, prefix="/birthday/api") app.include_router(config.router, prefix="/birthday/api") +app.include_router(auth.router, prefix="/birthday/api/auth") app.include_router(admin.router, prefix="/birthday/api/admin") diff --git a/backend/app/routes/__init__.py b/backend/app/routes/__init__.py index 297c1e7..316cb73 100644 --- a/backend/app/routes/__init__.py +++ b/backend/app/routes/__init__.py @@ -1 +1,5 @@ """API Route definitions.""" + +from . import admin, auth, config, rsvp + +__all__ = ["admin", "auth", "config", "rsvp"] diff --git a/backend/app/routes/admin.py b/backend/app/routes/admin.py index c447737..f26f0eb 100644 --- a/backend/app/routes/admin.py +++ b/backend/app/routes/admin.py @@ -3,7 +3,7 @@ import io from datetime import UTC, datetime from typing import Annotated -from fastapi import APIRouter, Depends, Header, HTTPException, Query, Response, status +from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request, Response, status from sqlalchemy.orm import Session from ..config import settings @@ -25,6 +25,7 @@ router = APIRouter(tags=["Admin"]) def require_admin( + request: Request, remote_user: Annotated[ str | None, Header( @@ -34,13 +35,21 @@ def require_admin( ), ] = None, ) -> str: - """Security invariant: require verified Remote-User header from Authelia.""" - if not remote_user: - raise HTTPException( - status_code=401, - detail="Not authenticated", - ) - return remote_user + """Security invariant: require verified Remote-User header from Authelia or authenticated admin session.""" + if remote_user: + return remote_user + + from .auth import get_auth_adapter + + adapter = get_auth_adapter() + identity = adapter.current_identity(request) + if identity and "bdinvite_admins" in identity.groups: + return identity.subject + + raise HTTPException( + status_code=401, + detail="Not authenticated", + ) AdminDep = Annotated[str, Depends(require_admin)] diff --git a/backend/app/routes/auth.py b/backend/app/routes/auth.py new file mode 100644 index 0000000..08a1940 --- /dev/null +++ b/backend/app/routes/auth.py @@ -0,0 +1,135 @@ +"""Authentication and browser session management API routes.""" + +from typing import Annotated, Optional + +from fastapi import APIRouter, Depends, Query, Request, Response, status +from fastapi.responses import JSONResponse, RedirectResponse + +from ..auth import OIDCAuthAdapter, OIDCClient, OIDCConfig +from ..config import settings + +router = APIRouter(tags=["Auth"]) + +_auth_adapter: Optional[OIDCAuthAdapter] = None + + +def get_auth_adapter() -> OIDCAuthAdapter: + """Provide singleton or cached OIDCAuthAdapter for dependency injection.""" + global _auth_adapter + if _auth_adapter is None: + client_config = OIDCConfig( + issuer=settings.OIDC_ISSUER, + client_id=settings.OIDC_CLIENT_ID, + client_secret=settings.OIDC_CLIENT_SECRET, + redirect_uri=settings.OIDC_REDIRECT_URI, + groups_claim=settings.OIDC_GROUPS_CLAIM, + group_claim_path=settings.OIDC_GROUP_CLAIM_PATH, + ) + client = OIDCClient(client_config) + _auth_adapter = OIDCAuthAdapter( + client=client, + session_cookie_name=settings.SESSION_COOKIE_NAME, + cookie_secure=settings.SESSION_COOKIE_SECURE, + cookie_samesite=settings.SESSION_COOKIE_SAMESITE, + cookie_path=settings.SESSION_COOKIE_PATH, + cookie_domain=settings.SESSION_COOKIE_DOMAIN, + session_lifetime=float(settings.SESSION_EXPIRE_SECONDS), + ) + return _auth_adapter + + +def set_auth_adapter(adapter: Optional[OIDCAuthAdapter]) -> None: + """Override the active auth adapter (for test isolation and fixture injection).""" + global _auth_adapter + _auth_adapter = adapter + + +AuthAdapterDep = Annotated[OIDCAuthAdapter, Depends(get_auth_adapter)] + + +@router.get( + "/login", + summary="Initiate OIDC authentication flow", + description="Redirects user browser to the configured OIDC provider authorization endpoint.", +) +def login(request: Request, adapter: AuthAdapterDep) -> Response: + return adapter.login(request) + + +@router.get( + "/callback", + summary="Handle OIDC authentication callback", + description=( + "Processes authorization code and state from IdP. " + "Enforces session fixation barrier by issuing a fresh session identifier " + "and sets HttpOnly SameSite browser session cookie." + ), +) +def callback( + request: Request, + adapter: AuthAdapterDep, + code: str = Query(..., description="Authorization code from IdP"), + state: str = Query(..., description="CSRF state parameter"), +) -> Response: + target_url = "/birthday/" + response = RedirectResponse(url=target_url, status_code=status.HTTP_302_FOUND) + adapter.handle_callback( + code=code, + state=state, + response=response, + request=request, + ) + return response + + +@router.get( + "/logout", + summary="Logout user session (Browser redirect)", + description="Revokes the session on server/storage, clears browser cookie (Max-Age=0), and redirects.", +) +@router.post( + "/logout", + summary="Logout user session (API)", + description="Revokes the session on server/storage, clears browser cookie (Max-Age=0), and returns JSON confirmation.", +) +def logout(request: Request, adapter: AuthAdapterDep) -> Response: + accept_header = request.headers.get("accept", "") + if request.method == "POST" or "application/json" in accept_header: + json_resp = JSONResponse( + status_code=status.HTTP_200_OK, + content={"result": "SUCCESS", "message": "Session terminated successfully"}, + ) + return adapter.logout(request, response=json_resp) + + return adapter.logout(request) + + +@router.get( + "/session", + summary="Check authenticated browser session", + description="Resolves incoming session cookie to verified Identity. Returns None if unauthenticated.", +) +@router.get( + "/me", + summary="Check current identity", + description="Alias for /session returning verified Identity.", +) +def get_session(request: Request, adapter: AuthAdapterDep) -> Response: + identity = adapter.current_identity(request) + if identity is None: + return JSONResponse( + status_code=status.HTTP_200_OK, + content={"authenticated": False, "identity": None}, + ) + return JSONResponse( + status_code=status.HTTP_200_OK, + content={ + "authenticated": True, + "identity": { + "subject": identity.subject, + "email": identity.email, + "name": identity.name, + "groups": identity.groups, + }, + }, + ) diff --git a/backend/tests/test_session_management.py b/backend/tests/test_session_management.py new file mode 100644 index 0000000..2ec1412 --- /dev/null +++ b/backend/tests/test_session_management.py @@ -0,0 +1,401 @@ +"""Tests for Browser Session Management and Session Fixation Protection (Checkpoint 4).""" + +import time +from collections.abc import Generator +from urllib.parse import parse_qs, urlparse + +import httpx +import pytest +from fastapi import Response +from fastapi.testclient import TestClient +from starlette.requests import Request + +from app.auth import ( + Identity, + OIDCAuthAdapter, + OIDCClient, + OIDCConfig, + SessionRecord, +) +from app.routes.auth import get_auth_adapter, set_auth_adapter + +FIXTURE_ISSUER = "http://localhost:8088/default" +FIXTURE_CLIENT_ID = "bdinvite-client" +FIXTURE_CLIENT_SECRET = "bdinvite-secret" +FIXTURE_REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback" + + +@pytest.fixture +def oidc_config() -> OIDCConfig: + return OIDCConfig( + issuer=FIXTURE_ISSUER, + client_id=FIXTURE_CLIENT_ID, + client_secret=FIXTURE_CLIENT_SECRET, + redirect_uri=FIXTURE_REDIRECT_URI, + ) + + +@pytest.fixture +def oidc_client(oidc_config: OIDCConfig) -> OIDCClient: + return OIDCClient(oidc_config) + + +@pytest.fixture +def auth_adapter(oidc_client: OIDCClient) -> Generator[OIDCAuthAdapter, None, None]: + adapter = OIDCAuthAdapter( + client=oidc_client, + session_cookie_name="bdinvite_session", + cookie_secure=False, + cookie_samesite="lax", + session_lifetime=3600.0, + ) + set_auth_adapter(adapter) + yield adapter + set_auth_adapter(None) + + +def create_request( + headers: dict[str, str] | None = None, + cookies: dict[str, str] | None = None, +) -> Request: + header_list: list[tuple[bytes, bytes]] = [] + if headers: + for k, v in headers.items(): + header_list.append((k.lower().encode("latin-1"), v.encode("latin-1"))) + if cookies: + cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items()) + header_list.append((b"cookie", cookie_header.encode("latin-1"))) + + scope = { + "type": "http", + "method": "GET", + "path": "/birthday/api/auth/session", + "headers": header_list, + "query_string": b"", + } + return Request(scope) + + +def obtain_auth_code_from_fixture(authorization_url: str, username: str) -> tuple[str, str]: + parsed_url = urlparse(authorization_url) + auth_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}" + query_params = parse_qs(parsed_url.query) + flat_params = {k: v[0] for k, v in query_params.items()} + + with httpx.Client() as client: + resp = client.post( + auth_endpoint, + params=flat_params, + data={"username": username}, + follow_redirects=False, + ) + assert resp.status_code == 302, f"Failed auth code post: {resp.text}" + location = resp.headers["location"] + + redirect_parsed = urlparse(location) + callback_params = parse_qs(redirect_parsed.query) + return callback_params["code"][0], callback_params["state"][0] + + +# ============================================================================ +# 1. Browser Session Contract & Security Invariant Tests +# ============================================================================ + + +def test_session_cookie_issued_with_httponly_and_samesite(auth_adapter: OIDCAuthAdapter): + """Security Invariant: The session cookie MUST have HttpOnly=True and SameSite. + + Client-side JavaScript must never have access to raw tokens or session identifiers. + """ + identity = Identity( + subject="admin-001", + email="admin@example.com", + name="Admin User", + groups=["bdinvite_admins"], + ) + response = Response() + session_id = auth_adapter.establish_session(identity) + auth_adapter.set_session_cookie(response, session_id) + + set_cookie = response.headers.get("set-cookie", "") + assert auth_adapter.session_cookie_name in set_cookie + assert session_id in set_cookie + assert "HttpOnly" in set_cookie, "Session cookie MUST enforce HttpOnly=True" + assert "SameSite=lax" in set_cookie or "samesite=lax" in set_cookie.lower() + + +def test_configurable_secure_flag(): + """Verify configurable Secure cookie flag: False in test/dev, True in production.""" + # 1. Development/test environment: Secure=False allows HTTP testing + dev_adapter = OIDCAuthAdapter( + client=OIDCClient(OIDCConfig(issuer=FIXTURE_ISSUER, client_id=FIXTURE_CLIENT_ID)), + cookie_secure=False, + ) + resp_dev = Response() + s_dev = dev_adapter.establish_session(Identity(subject="dev", email="dev@local")) + dev_adapter.set_session_cookie(resp_dev, s_dev) + assert "secure" not in resp_dev.headers.get("set-cookie", "").lower() + + # 2. Production environment: Secure=True enforces HTTPS transmission + prod_adapter = OIDCAuthAdapter( + client=OIDCClient(OIDCConfig(issuer=FIXTURE_ISSUER, client_id=FIXTURE_CLIENT_ID)), + cookie_secure=True, + ) + resp_prod = Response() + s_prod = prod_adapter.establish_session(Identity(subject="prod", email="prod@local")) + prod_adapter.set_session_cookie(resp_prod, s_prod) + set_cookie_prod = resp_prod.headers.get("set-cookie", "").lower() + assert "secure" in set_cookie_prod, "Production session cookie MUST enforce Secure=True" + + +# ============================================================================ +# 2. Session Fixation Barrier Tests +# ============================================================================ + + +def test_session_fixation_barrier_rotates_session_id(auth_adapter: OIDCAuthAdapter): + """Session Fixation Barrier: + + Successful authentication MUST generate a fresh, new session identifier. + An existing pre-authentication session identifier must NEVER be promoted into an + authenticated session (pre_auth_session_id != post_auth_session_id). + """ + # 1. Pre-authentication state: client possesses an anonymous or pre-auth session ID + pre_auth_session_id = auth_adapter.create_anonymous_session() + assert pre_auth_session_id is not None + # Pre-auth request resolves to anonymous + req_pre = create_request(cookies={auth_adapter.session_cookie_name: pre_auth_session_id}) + assert auth_adapter.current_identity(req_pre) is None + + # 2. User successfully authenticates + identity = Identity( + subject="admin-001", + email="admin@example.com", + name="Admin User", + groups=["bdinvite_admins"], + ) + post_auth_session_id = auth_adapter.establish_session( + identity=identity, + pre_auth_session_id=pre_auth_session_id, + ) + + # 3. Assert Session Fixation Barrier guarantees + assert post_auth_session_id != pre_auth_session_id, ( + f"Session Fixation violation: pre-auth ID was promoted! " + f"{pre_auth_session_id} == {post_auth_session_id}" + ) + + # 4. Old pre-auth session ID is strictly invalid and resolves to None + assert auth_adapter.current_identity(req_pre) is None + + # 5. New post-auth session ID resolves to the authenticated user + req_post = create_request(cookies={auth_adapter.session_cookie_name: post_auth_session_id}) + resolved = auth_adapter.current_identity(req_post) + assert resolved == identity + + +def test_session_fixation_barrier_via_callback( + auth_adapter: OIDCAuthAdapter, + oidc_client: OIDCClient, +): + """Verify session fixation barrier through complete callback processing.""" + auth_url, _ = oidc_client.create_authorization_url() + code, returned_state = obtain_auth_code_from_fixture(auth_url, username="guest@example.com") + + # Attacker sets fixed pre-auth session cookie on victim + pre_auth_session_id = "pre_auth_attacker_fixed_session_key" + req = create_request(cookies={auth_adapter.session_cookie_name: pre_auth_session_id}) + resp = Response() + + identity, post_auth_session_id = auth_adapter.handle_callback( + code=code, + state=returned_state, + response=resp, + request=req, + extra_params={"username": "guest@example.com"}, + ) + + # Assert fixation barrier + assert post_auth_session_id != pre_auth_session_id + assert identity.subject == "guest-001" + + # Attacker's pre-auth session resolves to nothing + assert auth_adapter.current_identity(req) is None + + # Authenticated user's new cookie resolves to identity + req_valid = create_request(cookies={auth_adapter.session_cookie_name: post_auth_session_id}) + assert auth_adapter.current_identity(req_valid) == identity + + +# ============================================================================ +# 3. Session Lifecycle & Invalidation Tests +# ============================================================================ + + +def test_valid_session_cookie_resolves_to_identity(auth_adapter: OIDCAuthAdapter): + """Returning requests presenting a valid session cookie must resolve to Identity.""" + identity = Identity( + subject="guest-001", + email="guest@example.com", + name="Guest User", + groups=["guests"], + ) + session_id = auth_adapter.establish_session(identity) + + req = create_request(cookies={auth_adapter.session_cookie_name: session_id}) + resolved = auth_adapter.current_identity(req) + assert resolved == identity + + +def test_anonymous_request_resolves_to_none(auth_adapter: OIDCAuthAdapter): + """Anonymous requests (no cookie or unknown session) resolve to None.""" + # 1. No cookies + req_empty = create_request(cookies={}) + assert auth_adapter.current_identity(req_empty) is None + + # 2. Unknown session ID + req_unknown = create_request(cookies={auth_adapter.session_cookie_name: "unknown_random_session_token"}) + assert auth_adapter.current_identity(req_unknown) is None + + +def test_expired_session_is_rejected_and_evicted(auth_adapter: OIDCAuthAdapter): + """Expired sessions are rejected, treated as unauthenticated, and evicted.""" + identity = Identity(subject="usr_exp", email="exp@local") + # Establish session with very short TTL + session_id = auth_adapter.establish_session(identity, ttl=0.05) + + req = create_request(cookies={auth_adapter.session_cookie_name: session_id}) + # Initially valid + assert auth_adapter.current_identity(req) == identity + + # Wait for expiration + time.sleep(0.06) + + # Now expired: resolves to None and is evicted from memory + assert auth_adapter.current_identity(req) is None + assert session_id not in auth_adapter.sessions + + +def test_tampered_and_malformed_cookies_safely_rejected(auth_adapter: OIDCAuthAdapter): + """Requests presenting tampered, malformed, or forged cookies must be safely rejected (not crash).""" + malicious_inputs = [ + "tampered!@#$%^&*()", + "valid_part\x00malicious_bytes", + "a" * 1000, + "session\r\nSet-Cookie: evil=1", + "' OR '1'='1", + " \t\n ", + "../../etc/passwd", + "{'session': 'eval'}", + ] + + for bad_input in malicious_inputs: + req = create_request(cookies={auth_adapter.session_cookie_name: bad_input}) + try: + resolved = auth_adapter.current_identity(req) + assert resolved is None, f"Expected None for malicious cookie: {bad_input!r}" + except Exception as exc: + pytest.fail(f"Application crashed on tampered cookie {bad_input!r}: {exc}") + + +def test_logout_invalidates_session_and_clears_cookie(auth_adapter: OIDCAuthAdapter): + """Logout invalidates the session on the server and clears the browser cookie (Max-Age=0).""" + identity = Identity(subject="admin-001", email="admin@example.com") + session_id = auth_adapter.establish_session(identity) + + req = create_request(cookies={auth_adapter.session_cookie_name: session_id}) + assert auth_adapter.current_identity(req) == identity + + # Perform logout + logout_resp = auth_adapter.logout(req) + + # 1. Server-side session revoked + assert session_id not in auth_adapter.sessions + assert auth_adapter.current_identity(req) is None + + # 2. Browser cookie cleared with Max-Age=0 + set_cookie = logout_resp.headers.get("set-cookie", "") + assert auth_adapter.session_cookie_name in set_cookie + assert "Max-Age=0" in set_cookie or "max-age=0" in set_cookie + assert "HttpOnly" in set_cookie + + +# ============================================================================ +# 4. FastAPI HTTP Integration Tests (Endpoints & TestClient) +# ============================================================================ + + +def test_http_auth_session_and_logout_endpoints( + client: TestClient, + auth_adapter: OIDCAuthAdapter, +): + """Integration test: /birthday/api/auth/session, /logout endpoints via HTTP TestClient.""" + # 1. Anonymous session check + res_anon = client.get("/birthday/api/auth/session") + assert res_anon.status_code == 200 + assert res_anon.json() == {"authenticated": False, "identity": None} + + # 2. Establish valid session for fixture admin user + identity = Identity( + subject="admin-001", + email="admin@example.com", + name="Admin User", + groups=["bdinvite_admins"], + ) + session_id = auth_adapter.establish_session(identity) + + # 3. Present session cookie to /session + client.cookies.set(auth_adapter.session_cookie_name, session_id) + res_auth = client.get("/birthday/api/auth/session") + assert res_auth.status_code == 200 + auth_data = res_auth.json() + assert auth_data["authenticated"] is True + assert auth_data["identity"]["subject"] == "admin-001" + assert auth_data["identity"]["email"] == "admin@example.com" + assert auth_data["identity"]["groups"] == ["bdinvite_admins"] + + # 4. Admin endpoint accessed via session cookie + res_admin = client.get("/birthday/api/admin/rsvps") + assert res_admin.status_code == 200 + + # 5. Logout via API POST + res_logout = client.post("/birthday/api/auth/logout") + assert res_logout.status_code == 200 + assert res_logout.json()["result"] == "SUCCESS" + assert session_id not in auth_adapter.sessions + + # 6. Session cookie cleared on client + set_cookie_header = res_logout.headers.get("set-cookie", "") + assert "Max-Age=0" in set_cookie_header or "max-age=0" in set_cookie_header + + # 7. Subsequent request is unauthenticated + res_after = client.get("/birthday/api/auth/session") + assert res_after.json()["authenticated"] is False + + +def test_fixture_live_users_password_grant_session_flow(auth_adapter: OIDCAuthAdapter): + """Test full login session lifecycle against pre-seeded fixture users.""" + # 1. Admin user authentication and session establishment + admin_id, admin_session_id = auth_adapter.authenticate_and_establish_session( + username="admin@example.com", + password="password123", + ) + assert admin_id.subject == "admin-001" + assert "bdinvite_admins" in admin_id.groups + + req_admin = create_request(cookies={auth_adapter.session_cookie_name: admin_session_id}) + assert auth_adapter.current_identity(req_admin) == admin_id + + # 2. Guest user authentication and session establishment + guest_id, guest_session_id = auth_adapter.authenticate_and_establish_session( + username="guest@example.com", + password="password123", + ) + assert guest_id.subject == "guest-001" + assert "guests" in guest_id.groups + + req_guest = create_request(cookies={auth_adapter.session_cookie_name: guest_session_id}) + assert auth_adapter.current_identity(req_guest) == guest_id + + # Distinct sessions for distinct users + assert admin_session_id != guest_session_id