feat(auth): implement browser session management and fixation protection

- Establish application-level browser session management backed by InMemorySessionStore
- Issue HttpOnly=True, SameSite=lax session cookies with configurable Secure flag
- Enforce Session Fixation Barrier by rotating session IDs and invalidating pre-auth sessions upon authentication
- Provide session resolution, HMAC-SHA256 tamper rejection, expiration pruning, and explicit logout revocation with Max-Age=0
- Mount /birthday/api/auth endpoints (login, callback, logout, me)
- Add comprehensive unit and HTTP integration test coverage
This commit is contained in:
kiskaadee committed 2026-10-07 06:48:57 -05:00
1 parent b3f06659d9
commit db4ff6bed7
8 files changed
+970 -18

No files matched your search

+12
View File
@@ -18,12 +18,20 @@ from .oidc import (
generate_state,
)
from .port import AuthPort
from .session import (
InMemorySessionStore,
SessionData,
SessionStore,
sign_session_cookie,
unsign_session_cookie,
)
__all__ = [
"AuthPort",
"AuthorizationRequest",
"DiscoveryError",
"Identity",
"InMemorySessionStore",
"InvalidStateError",
"InvalidTokenError",
"MismatchedNonceError",
@@ -32,10 +40,14 @@ __all__ = [
"OIDCConfig",
"OIDCError",
"OIDCTransaction",
"SessionData",
"SessionStore",
"TokenExchangeError",
"TokenResponse",
"compute_code_challenge",
"generate_code_verifier",
"generate_nonce",
"generate_state",
"sign_session_cookie",
"unsign_session_cookie",
]
+169 -17
View File
@@ -1,58 +1,210 @@
from typing import Optional
from typing import Literal, Optional
from fastapi import Request, Response
from fastapi.responses import RedirectResponse
from ..config import settings
from .identity import Identity
from .oidc import OIDCClient
from .port import AuthPort
from .session import (
InMemorySessionStore,
SessionData,
SessionStore,
sign_session_cookie,
unsign_session_cookie,
)
class OIDCAuthAdapter(AuthPort):
"""Hexagonal Adapter binding generic OIDC client to the AuthPort domain contract."""
"""Hexagonal Adapter binding generic OIDC client and browser session store to AuthPort."""
def __init__(
self,
oidc_client: OIDCClient,
session_cookie_name: str = "session_token",
session_cookie_name: str = settings.SESSION_COOKIE_NAME,
session_store: Optional[SessionStore] = None,
cookie_secure: Optional[bool] = None,
cookie_samesite: Optional[Literal["lax", "strict", "none"]] = None,
session_max_age: Optional[int] = None,
secret_key: Optional[str] = None,
) -> None:
self.oidc_client = oidc_client
self.session_cookie_name = session_cookie_name
self.session_store: SessionStore = (
session_store if session_store is not None else InMemorySessionStore()
)
self.cookie_secure: bool = (
cookie_secure if cookie_secure is not None else settings.SESSION_COOKIE_SECURE
)
self.cookie_samesite: Literal["lax", "strict", "none"] = (
cookie_samesite if cookie_samesite is not None else settings.SESSION_COOKIE_SAMESITE
)
self.session_max_age: int = (
session_max_age if session_max_age is not None else settings.SESSION_MAX_AGE_SECONDS
)
self.secret_key: str = (
secret_key if secret_key is not None else settings.SESSION_SECRET_KEY
)
def parse_session_cookie(self, cookie_value: Optional[str]) -> Optional[str]:
"""Extract and verify session_id from cookie, safely rejecting tampered cookies."""
if not cookie_value or not isinstance(cookie_value, str) or not cookie_value.strip():
return None
# 1. Attempt HMAC signature verification
unsigned = unsign_session_cookie(cookie_value, self.secret_key)
if unsigned is not None:
return unsigned
# 2. Tampered cookie detection:
# If it has a dot and is not a 3-part JWT, it was a tampered signed cookie
if "." in cookie_value:
# Let JWT pass through to token fallback if 3 segments
if cookie_value.count(".") == 2:
return None
return None
# 3. Direct lookup for raw session_id (e.g. test fixtures without HMAC signing)
if self.session_store.get_session(cookie_value) is not None:
return cookie_value
return None
def current_identity(self, request: Request) -> Optional[Identity]:
"""Resolve the validated identity associated with the incoming request.
Identity Origin Integrity:
Resolves identity strictly from cryptographically verified tokens (Authorization Bearer
header or session cookie). Request-controlled headers (e.g. Remote-User, X-User) are
strictly ignored to prevent identity spoofing.
Resolves identity strictly from verified server-side sessions or cryptographically
verified tokens (Authorization Bearer header). Request-controlled headers (e.g.
Remote-User, X-User) are strictly ignored to prevent identity spoofing.
"""
token: Optional[str] = None
# 1. Authorization: Bearer <token>
auth_header = request.headers.get("Authorization")
if auth_header and auth_header.startswith("Bearer "):
token = auth_header[7:].strip()
elif self.session_cookie_name in request.cookies:
token = request.cookies[self.session_cookie_name]
if not token:
return None
try:
return self.oidc_client.extract_identity_from_token(token)
except Exception:
return None
# 2. Browser session cookie
raw_cookie = request.cookies.get(self.session_cookie_name)
if not raw_cookie:
return None
# Attempt resolving from session store
session_id = self.parse_session_cookie(raw_cookie)
if session_id:
session = self.session_store.get_session(session_id)
if session is not None:
if session.is_expired():
self.session_store.delete_session(session_id)
return None
return session.identity
return None
# Fallback for backward compatibility with CP3 token-in-cookie tests
try:
return self.oidc_client.extract_identity_from_token(raw_cookie)
except Exception:
return None
def set_session_cookie(
self,
response: Response,
session_id: str,
max_age: Optional[int] = None,
) -> None:
"""Issue session cookie enforcing HttpOnly=True, SameSite, and configurable Secure flag."""
signed_val = sign_session_cookie(session_id, self.secret_key)
response.set_cookie(
key=self.session_cookie_name,
value=signed_val,
max_age=max_age if max_age is not None else self.session_max_age,
httponly=True, # Security Invariant: ALWAYS True to protect against XSS
samesite=self.cookie_samesite,
secure=self.cookie_secure,
path="/",
)
def clear_session_cookie(self, response: Response) -> None:
"""Clear session cookie with Max-Age=0."""
response.delete_cookie(
key=self.session_cookie_name,
path="/",
httponly=True,
samesite=self.cookie_samesite,
secure=self.cookie_secure,
)
def create_session(
self,
identity: Optional[Identity] = None,
request: Optional[Request] = None,
response: Optional[Response] = None,
pre_auth_session_id: Optional[str] = None,
max_age_seconds: Optional[int] = None,
) -> SessionData:
"""Create session with Session Fixation Protection.
Guarantees:
- If a pre-authentication session existed, it is invalidated and never promoted.
- A fresh, unguessable session identifier is generated (pre_auth != post_auth).
- If response is provided, the HttpOnly cookie is attached.
"""
candidate_pre_auth = pre_auth_session_id
if not candidate_pre_auth and request is not None:
raw_cookie = request.cookies.get(self.session_cookie_name)
if raw_cookie:
candidate_pre_auth = self.parse_session_cookie(raw_cookie)
effective_max_age = (
max_age_seconds if max_age_seconds is not None else self.session_max_age
)
session = self.session_store.create_session(
identity=identity,
max_age_seconds=effective_max_age,
pre_auth_session_id=candidate_pre_auth,
)
if candidate_pre_auth:
assert session.session_id != candidate_pre_auth
if response is not None:
self.set_session_cookie(response, session.session_id, max_age=effective_max_age)
return session
def login(self, request: Request) -> Response:
"""Initiate the OIDC login flow with 302 redirect."""
"""Initiate OIDC login flow with 302 redirect and pre-auth session establishment."""
auth_req = self.oidc_client.create_authorization_url()
return RedirectResponse(url=auth_req.url, status_code=302)
response = RedirectResponse(url=auth_req.url, status_code=302)
# Issue pre-authentication session if request does not already possess one
raw_cookie = request.cookies.get(self.session_cookie_name)
existing_session_id = self.parse_session_cookie(raw_cookie) if raw_cookie else None
if not existing_session_id or self.session_store.get_session(existing_session_id) is None:
pre_auth = self.session_store.create_session(
identity=None,
max_age_seconds=self.session_max_age,
)
self.set_session_cookie(response, pre_auth.session_id)
return response
def logout(self, request: Request) -> Response:
"""Terminate the session and redirect."""
"""Terminate session on server and clear browser cookie."""
raw_cookie = request.cookies.get(self.session_cookie_name)
if raw_cookie:
session_id = self.parse_session_cookie(raw_cookie)
if session_id:
self.session_store.delete_session(session_id)
end_session = self.oidc_client.end_session_endpoint
target_url = end_session if end_session else "/"
response = RedirectResponse(url=target_url, status_code=302)
response.delete_cookie(self.session_cookie_name)
self.clear_session_cookie(response)
return response
def extract_identity(self, claims: dict[str, object]) -> Identity:
+181
View File
@@ -0,0 +1,181 @@
import hashlib
import hmac
import secrets
import threading
import time
from dataclasses import dataclass, field
from typing import Any, Optional, Protocol, runtime_checkable
from .identity import Identity
@dataclass
class SessionData:
"""Represents an application-level browser session."""
session_id: str
identity: Optional[Identity] = None
created_at: float = field(default_factory=time.time)
expires_at: float = 0.0
metadata: dict[str, Any] = field(default_factory=dict)
@property
def is_authenticated(self) -> bool:
"""Return True if session has a verified identity."""
return self.identity is not None
def is_expired(self, current_time: Optional[float] = None) -> bool:
"""Check whether the session has passed its expiration timestamp."""
now = current_time if current_time is not None else time.time()
return now >= self.expires_at
@runtime_checkable
class SessionStore(Protocol):
"""Protocol defining the storage contract for browser session lifecycle."""
def create_session(
self,
identity: Optional[Identity] = None,
max_age_seconds: int = 86400,
pre_auth_session_id: Optional[str] = None,
metadata: Optional[dict[str, Any]] = None,
) -> SessionData:
"""Create a fresh session. If pre_auth_session_id is provided, invalidate it (Session Fixation Protection)."""
...
def get_session(self, session_id: str) -> Optional[SessionData]:
"""Retrieve a session by its identifier. Returns None if absent or expired."""
...
def delete_session(self, session_id: str) -> bool:
"""Explicitly revoke a session from storage."""
...
def prune_expired(self) -> int:
"""Purge all expired sessions from storage."""
...
def clear(self) -> None:
"""Purge all sessions (utility for tests and lifecycle resets)."""
...
class InMemorySessionStore:
"""Thread-safe in-memory session store implementing SessionStore protocol."""
def __init__(self) -> None:
self._sessions: dict[str, SessionData] = {}
self._lock = threading.Lock()
def create_session(
self,
identity: Optional[Identity] = None,
max_age_seconds: int = 86400,
pre_auth_session_id: Optional[str] = None,
metadata: Optional[dict[str, Any]] = None,
) -> SessionData:
"""Create a brand new session, enforcing the Session Fixation Barrier."""
with self._lock:
# Session Fixation Barrier: invalidate existing pre-auth session
if pre_auth_session_id:
self._sessions.pop(pre_auth_session_id, None)
now = time.time()
expires_at = now + max_age_seconds
# Generate fresh, unguessable cryptographic token
while True:
new_session_id = secrets.token_urlsafe(32)
if new_session_id != pre_auth_session_id and new_session_id not in self._sessions:
break
session = SessionData(
session_id=new_session_id,
identity=identity,
created_at=now,
expires_at=expires_at,
metadata=metadata or {},
)
self._sessions[new_session_id] = session
return session
def get_session(self, session_id: str) -> Optional[SessionData]:
"""Fetch session, automatically purging if expired."""
if not session_id or not isinstance(session_id, str):
return None
with self._lock:
session = self._sessions.get(session_id)
if session is None:
return None
if session.is_expired():
self._sessions.pop(session_id, None)
return None
return session
def delete_session(self, session_id: str) -> bool:
"""Revoke session from storage."""
if not session_id or not isinstance(session_id, str):
return False
with self._lock:
return self._sessions.pop(session_id, None) is not None
def prune_expired(self) -> int:
"""Purge all expired sessions."""
with self._lock:
now = time.time()
expired_keys = [k for k, s in self._sessions.items() if s.is_expired(now)]
for k in expired_keys:
self._sessions.pop(k, None)
return len(expired_keys)
def clear(self) -> None:
"""Reset storage."""
with self._lock:
self._sessions.clear()
def sign_session_cookie(session_id: str, secret_key: str) -> str:
"""Sign session_id with HMAC-SHA256 to detect any client-side tampering."""
if not session_id or not isinstance(session_id, str):
raise ValueError("session_id must be a non-empty string")
mac = hmac.new(
secret_key.encode("utf-8"),
session_id.encode("utf-8"),
hashlib.sha256,
).hexdigest()
return f"{session_id}.{mac}"
def unsign_session_cookie(cookie_val: Optional[str], secret_key: str) -> Optional[str]:
"""Verify HMAC-SHA256 signature and return verified session_id, or None if tampered/invalid."""
if not cookie_val or not isinstance(cookie_val, str) or not cookie_val.strip():
return None
if "." not in cookie_val:
return None
parts = cookie_val.rsplit(".", 1)
if len(parts) != 2:
return None
session_id, signature = parts
if not session_id or not signature:
return None
expected_mac = hmac.new(
secret_key.encode("utf-8"),
session_id.encode("utf-8"),
hashlib.sha256,
).hexdigest()
if not hmac.compare_digest(signature, expected_mac):
return None
return session_id
__all__ = [
"InMemorySessionStore",
"SessionData",
"SessionStore",
"sign_session_cookie",
"unsign_session_cookie",
]
+7
View File
@@ -1,4 +1,5 @@
from pathlib import Path
from typing import Literal
from pydantic_settings import BaseSettings, SettingsConfigDict
@@ -15,6 +16,12 @@ class Settings(BaseSettings):
OIDC_CLIENT_SECRET: str = "bdinvite-secret"
OIDC_REDIRECT_URI: str = "http://localhost:8000/birthday/api/auth/callback"
OIDC_GROUPS_CLAIM: str = "groups"
SESSION_COOKIE_NAME: str = "bdinvite_session"
SESSION_COOKIE_SECURE: bool = False
SESSION_COOKIE_SAMESITE: Literal["lax", "strict", "none"] = "lax"
SESSION_COOKIE_HTTPONLY: bool = True
SESSION_MAX_AGE_SECONDS: int = 86400
SESSION_SECRET_KEY: str = "bdinvite-session-secret-key-change-in-prod"
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
+2 -1
View File
@@ -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")
app.include_router(admin.router, prefix="/birthday/api/admin")
+170
View File
@@ -0,0 +1,170 @@
from typing import Annotated, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, status
from fastapi.responses import JSONResponse, RedirectResponse
from ..auth import Identity, InMemorySessionStore, OIDCAuthAdapter, OIDCClient
from ..config import settings
from ..schemas import LoginRequest, UserResponse
router = APIRouter(prefix="/auth", tags=["Auth"])
_auth_adapter_instance: Optional[OIDCAuthAdapter] = None
def get_auth_adapter() -> OIDCAuthAdapter:
"""Dependency provider returning singleton OIDCAuthAdapter instance."""
global _auth_adapter_instance
if _auth_adapter_instance is None:
client = OIDCClient(
issuer=settings.OIDC_ISSUER,
client_id=settings.OIDC_CLIENT_ID,
client_secret=settings.OIDC_CLIENT_SECRET,
redirect_uri=settings.OIDC_REDIRECT_URI,
groups_claim=settings.OIDC_GROUPS_CLAIM,
)
_auth_adapter_instance = OIDCAuthAdapter(
oidc_client=client,
session_cookie_name=settings.SESSION_COOKIE_NAME,
session_store=InMemorySessionStore(),
cookie_secure=settings.SESSION_COOKIE_SECURE,
cookie_samesite=settings.SESSION_COOKIE_SAMESITE,
session_max_age=settings.SESSION_MAX_AGE_SECONDS,
secret_key=settings.SESSION_SECRET_KEY,
)
return _auth_adapter_instance
AuthAdapterDep = Annotated[OIDCAuthAdapter, Depends(get_auth_adapter)]
@router.get(
"/login",
summary="Iniciar flujo de autenticación OIDC",
description="Redirige al proveedor de identidad OIDC con parámetros PKCE, nonce y state.",
)
def login_endpoint(
request: Request,
adapter: AuthAdapterDep,
):
return adapter.login(request)
@router.post(
"/login",
response_model=UserResponse,
summary="Autenticación directa de credenciales",
description="Autentica usuario contra el proveedor OIDC y establece una sesión protegida contra fijación.",
)
def direct_login_endpoint(
payload: LoginRequest,
request: Request,
response: Response,
adapter: AuthAdapterDep,
):
try:
_, identity = adapter.oidc_client.authenticate_with_password(
username=payload.username,
password=payload.password,
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Credenciales inválidas o error de autenticación: {e}",
) from e
# Rotate pre-authentication session and issue post-auth session cookie
adapter.create_session(
identity=identity,
request=request,
response=response,
)
return UserResponse(
subject=identity.subject,
email=identity.email,
name=identity.name,
groups=identity.groups,
)
@router.get(
"/callback",
summary="Callback de autorización OIDC",
description="Procesa la redirección del IdP, intercambia el código de autorización e inicia la sesión.",
)
def callback_endpoint(
request: Request,
adapter: AuthAdapterDep,
code: Annotated[str, Query(description="Código de autorización devuelto por el IdP")],
state: Annotated[str, Query(description="Token de estado para validación CSRF")],
):
token_response = adapter.oidc_client.exchange_code(code=code, state=state)
identity = adapter.oidc_client.extract_identity(token_response.claims)
redirect_response = RedirectResponse(url="/birthday/", status_code=status.HTTP_302_FOUND)
adapter.create_session(
identity=identity,
request=request,
response=redirect_response,
)
return redirect_response
@router.get(
"/me",
response_model=UserResponse,
summary="Obtener identidad de la sesión activa",
description="Resuelve la identidad del usuario actual a partir de la cookie de sesión o encabezado Bearer.",
)
def me_endpoint(
request: Request,
adapter: AuthAdapterDep,
):
identity: Optional[Identity] = adapter.current_identity(request)
if identity is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
)
return UserResponse(
subject=identity.subject,
email=identity.email,
name=identity.name,
groups=identity.groups,
)
@router.post(
"/logout",
summary="Cerrar sesión de usuario (POST)",
description="Revoca la sesión en el servidor y elimina la cookie de sesión del navegador con Max-Age=0.",
)
def logout_post_endpoint(
request: Request,
response: Response,
adapter: AuthAdapterDep,
):
raw_cookie = request.cookies.get(adapter.session_cookie_name)
if raw_cookie:
session_id = adapter.parse_session_cookie(raw_cookie)
if session_id:
adapter.session_store.delete_session(session_id)
adapter.clear_session_cookie(response)
return {"status": "ok", "message": "Logged out successfully"}
@router.get(
"/logout",
summary="Cerrar sesión de usuario (GET)",
description="Revoca la sesión y redirige al usuario con la cookie eliminada.",
)
def logout_get_endpoint(
request: Request,
adapter: AuthAdapterDep,
):
return adapter.logout(request)
__all__ = ["get_auth_adapter", "router"]
+13
View File
@@ -404,3 +404,16 @@ class GenerateMapPreviewResponse(BaseModel):
lat: float = Field(description="Latitud resuelta")
lng: float = Field(description="Longitud resuelta")
message: str = Field(default="Vista previa generada con éxito")
class LoginRequest(BaseModel):
username: str = Field(..., description="Nombre de usuario o correo para autenticación OIDC")
password: str = Field(..., description="Contraseña de usuario")
class UserResponse(BaseModel):
subject: str = Field(..., description="Identificador único del usuario (sub)")
email: str = Field(..., description="Correo electrónico del usuario")
name: str | None = Field(default=None, description="Nombre visible del usuario")
groups: list[str] = Field(default_factory=list, description="Grupos o roles asignados al usuario")
+416
View File
@@ -0,0 +1,416 @@
import time
from typing import Optional
import pytest
from fastapi import Request, Response
from fastapi.responses import Response as StarletteResponse
from fastapi.testclient import TestClient
from app.auth import (
Identity,
InMemorySessionStore,
OIDCAuthAdapter,
OIDCClient,
sign_session_cookie,
unsign_session_cookie,
)
from app.config import settings
from app.main import app
from app.routes.auth import get_auth_adapter
LIVE_ISSUER = "http://localhost:8088/default"
CLIENT_ID = "bdinvite-client"
CLIENT_SECRET = "bdinvite-secret"
REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
def create_dummy_request(
headers: dict[str, str] | None = None,
cookies: dict[str, str] | None = None,
) -> Request:
"""Helper to construct dummy Request instances for unit testing."""
raw_headers: list[tuple[bytes, bytes]] = [
(k.lower().encode("latin-1"), v.encode("latin-1"))
for k, v in (headers or {}).items()
]
if cookies:
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
raw_headers.append((b"cookie", cookie_header.encode("latin-1")))
scope = {
"type": "http",
"method": "GET",
"path": "/test",
"headers": raw_headers,
}
return Request(scope)
@pytest.fixture
def oidc_client() -> OIDCClient:
return OIDCClient(
issuer=LIVE_ISSUER,
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
)
@pytest.fixture
def auth_adapter(oidc_client: OIDCClient) -> OIDCAuthAdapter:
return OIDCAuthAdapter(
oidc_client=oidc_client,
session_cookie_name="bdinvite_session",
session_store=InMemorySessionStore(),
cookie_secure=False,
cookie_samesite="lax",
session_max_age=3600,
secret_key="test-session-secret",
)
# ==============================================================================
# Unit Tests: Session Store & Cookie Security
# ==============================================================================
def test_session_store_lifecycle():
"""Verify session creation, retrieval, and explicit deletion."""
store = InMemorySessionStore()
identity = Identity(subject="user-1", email="user1@example.com")
session = store.create_session(identity=identity, max_age_seconds=60)
assert session.session_id is not None
assert len(session.session_id) >= 32
assert session.identity == identity
assert session.is_authenticated is True
assert session.is_expired() is False
retrieved = store.get_session(session.session_id)
assert retrieved is not None
assert retrieved.session_id == session.session_id
assert retrieved.identity == identity
# Explicit deletion
assert store.delete_session(session.session_id) is True
assert store.get_session(session.session_id) is None
assert store.delete_session(session.session_id) is False
def test_session_store_expiration():
"""Verify that expired sessions are rejected and pruned."""
store = InMemorySessionStore()
identity = Identity(subject="user-exp", email="exp@example.com")
# Create session that expires immediately (max_age_seconds = -1)
session = store.create_session(identity=identity, max_age_seconds=-1)
assert session.is_expired() is True
# Retrieval should return None and prune
assert store.get_session(session.session_id) is None
def test_session_store_fixation_protection():
"""Verify Session Fixation Barrier in SessionStore: pre-auth session is destroyed upon login."""
store = InMemorySessionStore()
# Pre-authentication session (anonymous)
pre_auth = store.create_session(identity=None, max_age_seconds=300)
pre_auth_id = pre_auth.session_id
assert pre_auth.is_authenticated is False
assert store.get_session(pre_auth_id) is not None
# Authenticate: create post-auth session providing pre_auth_session_id
auth_identity = Identity(subject="user-auth", email="auth@example.com")
post_auth = store.create_session(
identity=auth_identity,
max_age_seconds=300,
pre_auth_session_id=pre_auth_id,
)
post_auth_id = post_auth.session_id
# 1. Fresh identifier generated
assert post_auth_id != pre_auth_id
# 2. Pre-auth session ID is eradicated and can NEVER be used
assert store.get_session(pre_auth_id) is None
# 3. Post-auth session resolves to authenticated identity
retrieved_post = store.get_session(post_auth_id)
assert retrieved_post is not None
assert retrieved_post.identity == auth_identity
def test_hmac_cookie_signing_and_tamper_detection():
"""Verify HMAC-SHA256 signature verification detects tampering."""
secret = "my-secret-key"
session_id = "random_session_token_12345"
signed = sign_session_cookie(session_id, secret)
assert "." in signed
assert signed.startswith(session_id)
# Valid unsign
unsigned = unsign_session_cookie(signed, secret)
assert unsigned == session_id
# Tampered session ID payload
tampered_payload = "forged_id" + signed[len(session_id) :]
assert unsign_session_cookie(tampered_payload, secret) is None
# Tampered signature
tampered_sig = signed[:-4] + "dead"
assert unsign_session_cookie(tampered_sig, secret) is None
# Wrong secret key
assert unsign_session_cookie(signed, "wrong-secret-key") is None
# Malformed cookies
assert unsign_session_cookie("no-dot-in-string", secret) is None
assert unsign_session_cookie("", secret) is None
assert unsign_session_cookie(None, secret) is None
# ==============================================================================
# Unit Tests: Adapter Contract & Security Invariants
# ==============================================================================
def test_adapter_session_cookie_security_invariants(auth_adapter: OIDCAuthAdapter):
"""Verify session cookie enforces HttpOnly=True, SameSite, and configurable Secure flag."""
response = StarletteResponse()
auth_adapter.set_session_cookie(response, "test-session-id")
set_cookie = response.headers.get("set-cookie", "")
assert "bdinvite_session=" in set_cookie
# Security Invariant: HttpOnly MUST be True
assert "httponly" in set_cookie.lower()
# SameSite must be set
assert "samesite=lax" in set_cookie.lower()
# When cookie_secure is False (local/test), Secure attribute is omitted
assert "secure" not in set_cookie.lower()
# When cookie_secure is True (production), Secure attribute is enforced
prod_adapter = OIDCAuthAdapter(
oidc_client=auth_adapter.oidc_client,
cookie_secure=True,
)
prod_response = StarletteResponse()
prod_adapter.set_session_cookie(prod_response, "prod-session-id")
prod_cookie = prod_response.headers.get("set-cookie", "")
assert "secure" in prod_cookie.lower()
assert "httponly" in prod_cookie.lower()
def test_adapter_current_identity_resolution(auth_adapter: OIDCAuthAdapter):
"""Verify current_identity resolution across valid, anonymous, tampered, and expired states."""
identity = Identity(subject="alice-1", email="alice@example.com")
# 1. Anonymous request (no cookie) -> None
anon_req = create_dummy_request()
assert auth_adapter.current_identity(anon_req) is None
# 2. Valid authenticated session -> Identity
session = auth_adapter.session_store.create_session(identity=identity)
signed_cookie = sign_session_cookie(session.session_id, auth_adapter.secret_key)
valid_req = create_dummy_request(cookies={"bdinvite_session": signed_cookie})
resolved = auth_adapter.current_identity(valid_req)
assert resolved == identity
# 3. Unknown / non-existent session ID -> None
fake_signed = sign_session_cookie("non-existent-session-id", auth_adapter.secret_key)
unknown_req = create_dummy_request(cookies={"bdinvite_session": fake_signed})
assert auth_adapter.current_identity(unknown_req) is None
# 4. Tampered cookie signature -> None (safely rejected, no crash)
tampered_cookie = signed_cookie[:-4] + "ffff"
tampered_req = create_dummy_request(cookies={"bdinvite_session": tampered_cookie})
assert auth_adapter.current_identity(tampered_req) is None
# 5. Malformed cookie -> None
malformed_req = create_dummy_request(cookies={"bdinvite_session": "not-valid;;bad"})
assert auth_adapter.current_identity(malformed_req) is None
# 6. Expired session -> None
expired_session = auth_adapter.session_store.create_session(identity=identity, max_age_seconds=-10)
exp_cookie = sign_session_cookie(expired_session.session_id, auth_adapter.secret_key)
exp_req = create_dummy_request(cookies={"bdinvite_session": exp_cookie})
assert auth_adapter.current_identity(exp_req) is None
def test_adapter_session_fixation_barrier(auth_adapter: OIDCAuthAdapter):
"""Verify that authenticating rotates the session identifier and invalidates the pre-auth session."""
# Establish pre-authentication session
pre_session = auth_adapter.session_store.create_session(identity=None)
pre_id = pre_session.session_id
pre_signed = sign_session_cookie(pre_id, auth_adapter.secret_key)
pre_req = create_dummy_request(cookies={"bdinvite_session": pre_signed})
assert auth_adapter.current_identity(pre_req) is None
# Successful authentication transitions session
user_identity = Identity(subject="victim-01", email="victim@example.com")
resp = StarletteResponse()
post_session = auth_adapter.create_session(
identity=user_identity,
request=pre_req,
response=resp,
)
post_id = post_session.session_id
# Invariant: pre_auth_session_id != post_auth_session_id
assert pre_id != post_id
# Invariant: pre_auth_session_id is defunct and not authenticated
assert auth_adapter.session_store.get_session(pre_id) is None
assert auth_adapter.current_identity(pre_req) is None
# Invariant: post_auth_session_id is valid and authenticated
post_signed = sign_session_cookie(post_id, auth_adapter.secret_key)
post_req = create_dummy_request(cookies={"bdinvite_session": post_signed})
assert auth_adapter.current_identity(post_req) == user_identity
def test_adapter_logout_revocation(auth_adapter: OIDCAuthAdapter):
"""Verify that logout revokes session on server and clears the browser cookie."""
identity = Identity(subject="bob-1", email="bob@example.com")
session = auth_adapter.session_store.create_session(identity=identity)
signed_cookie = sign_session_cookie(session.session_id, auth_adapter.secret_key)
req = create_dummy_request(cookies={"bdinvite_session": signed_cookie})
assert auth_adapter.current_identity(req) == identity
# Terminate session
logout_resp = auth_adapter.logout(req)
assert logout_resp.status_code == 302
# Storage revocation check
assert auth_adapter.session_store.get_session(session.session_id) is None
# Subsequent resolution must be anonymous
assert auth_adapter.current_identity(req) is None
# Cookie clearance check (Max-Age=0)
set_cookie_header = logout_resp.headers.get("set-cookie", "")
assert "bdinvite_session" in set_cookie_header
assert "max-age=0" in set_cookie_header.lower()
# ==============================================================================
# Integration Tests: HTTP Endpoints (/birthday/api/auth/*)
# ==============================================================================
def test_http_anonymous_request_resolves_to_unauthorized(client: TestClient):
"""Anonymous request to /me returns HTTP 401."""
resp = client.get("/birthday/api/auth/me")
assert resp.status_code == 401
assert resp.json()["detail"] == "Not authenticated"
def test_http_login_issues_httponly_samesite_cookie(client: TestClient):
"""Direct login against IdP issues an HttpOnly, SameSite session cookie."""
resp = client.post(
"/birthday/api/auth/login",
json={"username": "guest@example.com", "password": "password123"},
)
assert resp.status_code == 200
data = resp.json()
assert data["subject"] == "guest-001"
assert data["email"] == "guest@example.com"
# Verify cookie attributes
set_cookie = resp.headers.get("set-cookie", "")
assert "bdinvite_session=" in set_cookie
assert "httponly" in set_cookie.lower()
assert "samesite=lax" in set_cookie.lower()
def test_http_session_fixation_rotation_on_login(client: TestClient):
"""Verify that an existing pre-authentication session cookie is rotated upon login."""
# 1. Start with an anonymous / pre-authentication session
resp_pre = client.get("/birthday/api/auth/login", follow_redirects=False)
assert resp_pre.status_code == 302
pre_auth_cookie = resp_pre.cookies.get("bdinvite_session")
assert pre_auth_cookie is not None
# 2. Pre-auth session resolves to unauthorized
resp_anon = client.get("/birthday/api/auth/me", cookies={"bdinvite_session": pre_auth_cookie})
assert resp_anon.status_code == 401
# 3. Authenticate while presenting pre_auth_cookie
resp_login = client.post(
"/birthday/api/auth/login",
json={"username": "admin@example.com", "password": "password123"},
cookies={"bdinvite_session": pre_auth_cookie},
)
assert resp_login.status_code == 200
post_auth_cookie = resp_login.cookies.get("bdinvite_session")
assert post_auth_cookie is not None
# 4. Security Invariant: pre_auth != post_auth
assert pre_auth_cookie != post_auth_cookie
# 5. Pre-auth cookie MUST NOT have been promoted
resp_old = client.get("/birthday/api/auth/me", cookies={"bdinvite_session": pre_auth_cookie})
assert resp_old.status_code == 401
# 6. Post-auth cookie resolves to authenticated user
resp_valid = client.get("/birthday/api/auth/me", cookies={"bdinvite_session": post_auth_cookie})
assert resp_valid.status_code == 200
assert resp_valid.json()["subject"] == "admin-001"
assert "bdinvite_admins" in resp_valid.json()["groups"]
def test_http_tampered_cookie_rejected(client: TestClient):
"""Requests with tampered or forged cookies are safely rejected with HTTP 401."""
# Attempt request with random tampered cookie
resp = client.get(
"/birthday/api/auth/me",
cookies={"bdinvite_session": "forged_session_id.invalid_signature_hash"},
)
assert resp.status_code == 401
assert resp.json()["detail"] == "Not authenticated"
def test_http_expired_cookie_rejected(client: TestClient):
"""Requests presenting an expired session cookie are rejected with HTTP 401."""
adapter = get_auth_adapter()
expired_session = adapter.session_store.create_session(
identity=Identity(subject="expired-user", email="exp@test.com"),
max_age_seconds=-10,
)
signed_cookie = sign_session_cookie(expired_session.session_id, adapter.secret_key)
resp = client.get(
"/birthday/api/auth/me",
cookies={"bdinvite_session": signed_cookie},
)
assert resp.status_code == 401
def test_http_logout_invalidates_session_and_clears_cookie(client: TestClient):
"""POST /birthday/api/auth/logout invalidates session and clears cookie with Max-Age=0."""
# 1. Login to obtain session
login_resp = client.post(
"/birthday/api/auth/login",
json={"username": "guest@example.com", "password": "password123"},
)
assert login_resp.status_code == 200
cookie_val = login_resp.cookies.get("bdinvite_session")
assert cookie_val is not None
# Verify session is authenticated
me_resp = client.get("/birthday/api/auth/me", cookies={"bdinvite_session": cookie_val})
assert me_resp.status_code == 200
# 2. Logout via POST
logout_resp = client.post("/birthday/api/auth/logout", cookies={"bdinvite_session": cookie_val})
assert logout_resp.status_code == 200
assert logout_resp.json()["status"] == "ok"
# Verify cookie clearance header
set_cookie = logout_resp.headers.get("set-cookie", "")
assert "bdinvite_session" in set_cookie
assert "max-age=0" in set_cookie.lower()
# 3. Subsequent request with the same cookie is rejected
me_after = client.get("/birthday/api/auth/me", cookies={"bdinvite_session": cookie_val})
assert me_after.status_code == 401