Coverage for main.py: 73%
414 statements
« prev ^ index » next coverage.py v7.14.1, created at 2026-10-31 11:18 +0000
« prev ^ index » next coverage.py v7.14.1, created at 2026-10-31 11:18 +0000
1# svc-auth/main.py
2"""
3Core Auth BFF - Backend for Frontend Authentication Service
5This service handles:
6- OAuth2 flow with Auth0
7- Session management
8- Token storage and refresh
9- User authentication verification
11Security features:
12- Tokens stored server-side only (never exposed to browser)
13- Signed session cookies
14- Automatic token refresh
15- State/nonce validation
16- Rate limiting ready (handled by nginx)
17"""
19from fastapi import FastAPI, Request, Response, HTTPException, status
20from fastapi.responses import RedirectResponse, JSONResponse
21from fastapi.middleware.trustedhost import TrustedHostMiddleware
22import asyncio
23import httpx
24import redis.asyncio as redis
25import secrets
26import json
27import time
28import logging
29from typing import Optional, Dict, Any
30from datetime import datetime
31from itsdangerous import URLSafeTimedSerializer, BadSignature
32import base64
33from contextlib import asynccontextmanager
34from urllib.parse import urlencode
35import uuid as uuidlib
37from app.config import settings
38from app.redirects import safe_return_to
39from app.roles import roles_from
40from app.cors import CORSMiddleware, cors_middleware_args
41from app.db.models import SessionEndReason
42from app.services import sessions as sessions_service
43from app.util.geoip import lookup as geoip_lookup
44from app.util.request_meta import get_client_ip, parse_device
46# Configure logging: the format svc-core and svc-ai write (``ts | LEVEL |
47# name | message``), which Promtail reads a line's level from and starts a
48# record at (monitoring/promtail/promtail-config.yml). Python's warnings go
49# through it too, rather than to stderr bare.
50logging.basicConfig(
51 level=logging.INFO,
52 format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
53 datefmt="%Y-%m-%d %H:%M:%S",
54)
55logging.captureWarnings(True)
56logger = logging.getLogger(__name__)
59# Application state
60class AppState:
61 redis_client: Optional[redis.Redis] = None
64app_state = AppState()
67def create_redis_client() -> redis.Redis:
68 """Create the shared Redis client.
70 Uses a BlockingConnectionPool: when the pool is saturated, callers wait up
71 to `timeout` seconds for a free connection instead of failing with
72 "Too many connections" (the default ConnectionPool raises immediately).
73 """
74 pool = redis.BlockingConnectionPool.from_url(
75 settings.REDIS_URL,
76 password=settings.REDIS_PASSWORD,
77 decode_responses=True,
78 encoding="utf-8",
79 max_connections=50,
80 timeout=5,
81 )
82 return redis.Redis(connection_pool=pool)
85# Lifespan context manager
88async def _session_retention_loop():
89 """Periodically purge ended sessions past the retention window.
91 Best-effort housekeeping: runs once at startup, then every
92 ``SESSION_PURGE_INTERVAL`` seconds. The DELETE is idempotent, so it is safe
93 for multiple replicas to run it. The blocking DB call is offloaded to a
94 thread so it never stalls the event loop, and errors are swallowed by the
95 service layer so a transient failure never kills the loop.
96 """
97 if settings.SESSION_RETENTION_DAYS <= 0:
98 logger.info("Session retention purge disabled (SESSION_RETENTION_DAYS<=0)")
99 return
100 while True:
101 try:
102 deleted = await asyncio.to_thread(
103 sessions_service.purge_old_sessions,
104 retention_days=settings.SESSION_RETENTION_DAYS,
105 )
106 if deleted:
107 logger.info(
108 "Purged %d session(s) older than %d days",
109 deleted,
110 settings.SESSION_RETENTION_DAYS,
111 )
112 except Exception as e:
113 logger.error("Session retention purge cycle failed: %s", e)
114 await asyncio.sleep(settings.SESSION_PURGE_INTERVAL)
117@asynccontextmanager
118async def lifespan(app: FastAPI):
119 """
120 Lifespan context manager for startup and shutdown events.
122 Startup:
123 - Initialize Redis connection
124 - Test connectivity
125 - Start the session-retention purge task
127 Shutdown:
128 - Cancel the retention task
129 - Close Redis connection gracefully
130 """
131 # Startup
132 logger.info("Starting up Core Auth BFF...")
133 try:
134 app_state.redis_client = create_redis_client()
135 # Test connection
136 await app_state.redis_client.ping()
137 logger.info("Redis connection established successfully")
138 except Exception as e:
139 logger.error(f"Failed to connect to Redis: {e}")
140 raise
142 # Run database migrations for the durable session store. Best-effort: a
143 # Postgres hiccup must not take down authentication (Redis is the fast path),
144 # so a failure here is logged but does not abort startup.
145 if settings.RUN_MIGRATIONS:
146 try:
147 from app.migrations import run_migrations
149 run_migrations()
150 except Exception as e:
151 logger.error(f"Session-store migrations failed (continuing): {e}")
153 # Background retention purge for the durable session history.
154 purge_task = asyncio.create_task(_session_retention_loop())
156 yield # Application runs here
158 # Shutdown
159 logger.info("Shutting down Core Auth BFF...")
160 purge_task.cancel()
161 try:
162 await purge_task
163 except asyncio.CancelledError:
164 pass
165 if app_state.redis_client:
166 await app_state.redis_client.close()
167 logger.info("Redis connection closed")
170# Initialize FastAPI app
171app = FastAPI(
172 title="Core Auth BFF",
173 description="Authentication Backend for Frontend service",
174 version="1.0.0",
175 docs_url="/docs" if settings.ENVIRONMENT == "development" else None,
176 redoc_url="/redoc" if settings.ENVIRONMENT == "development" else None,
177 lifespan=lifespan,
178)
180# Session serializer for signing cookies
181serializer = URLSafeTimedSerializer(settings.SESSION_SECRET)
184# CORS Middleware — strict, env-derived allowlist (see app/cors.py).
185app.add_middleware(CORSMiddleware, **cors_middleware_args)
188# Trusted Host Middleware (prevent host header attacks). Allow the cookie domain
189# and its subdomains so it tracks the deployment (8000 / 80 / behind Cloudflare)
190# without hardcoding ports. Starlette strips the port before comparing.
191#
192# localhost/127.0.0.1 must also be allowed: the container healthcheck probes
193# /health over loopback, and a Host of "localhost" can only originate from
194# inside the container — without it every probe gets 400 and the healthcheck
195# silently stops verifying anything.
196def trusted_hosts(cookie_domain: str) -> list[str]:
197 domain = cookie_domain.lstrip(".")
198 return [domain, f"*.{domain}", "localhost", "127.0.0.1"]
201if settings.ENVIRONMENT == "production" and settings.COOKIE_DOMAIN:
202 app.add_middleware(
203 TrustedHostMiddleware,
204 allowed_hosts=trusted_hosts(settings.COOKIE_DOMAIN),
205 )
208# Helper Functions
209def get_session_id(request: Request) -> Optional[str]:
210 """
211 Extract and verify session ID from signed cookie.
213 Returns:
214 Session ID if valid, None otherwise
215 """
216 cookie = request.cookies.get(settings.SESSION_COOKIE_NAME)
217 if not cookie:
218 return None
220 try:
221 session_id = serializer.loads(cookie, max_age=settings.SESSION_MAX_AGE)
222 return session_id
223 except BadSignature:
224 logger.warning("Invalid session cookie signature")
225 return None
226 except Exception as e:
227 logger.error(f"Error decoding session cookie: {e}")
228 return None
231def create_session_cookie(session_id: str) -> str:
232 """Create signed session cookie value."""
233 return serializer.dumps(session_id)
236async def get_tokens(session_id: str) -> Optional[Dict[str, Any]]:
237 """
238 Retrieve tokens from Redis.
240 Args:
241 session_id: Session identifier
243 Returns:
244 Dictionary containing tokens or None if not found
245 """
246 try:
247 token_key = f"tokens:{session_id}"
248 tokens_json = await app_state.redis_client.get(token_key)
249 if not tokens_json:
250 return None
251 return json.loads(tokens_json)
252 except Exception as e:
253 logger.error(f"Error retrieving tokens: {e}")
254 return None
257async def store_tokens(
258 session_id: str, tokens: Dict[str, Any], ttl: int = None
259) -> bool:
260 """
261 Store tokens in Redis with TTL.
263 Args:
264 session_id: Session identifier
265 tokens: Token data to store
266 ttl: Time to live in seconds
268 Returns:
269 True if successful, False otherwise
270 """
271 try:
272 token_key = f"tokens:{session_id}"
273 ttl = ttl or settings.SESSION_MAX_AGE
274 await app_state.redis_client.setex(token_key, ttl, json.dumps(tokens))
275 return True
276 except Exception as e:
277 logger.error(f"Error storing tokens: {e}")
278 return False
281async def get_session_data(session_id: str) -> Optional[Dict[str, Any]]:
282 """Retrieve session metadata from Redis."""
283 try:
284 session_key = f"session:{session_id}"
285 session_json = await app_state.redis_client.get(session_key)
286 if not session_json:
287 return None
288 return json.loads(session_json)
289 except Exception as e:
290 logger.error(f"Error retrieving session: {e}")
291 return None
294async def store_session_data(
295 session_id: str, data: Dict[str, Any], ttl: int = None
296) -> bool:
297 """Store session metadata in Redis."""
298 try:
299 session_key = f"session:{session_id}"
300 ttl = ttl or settings.SESSION_MAX_AGE
301 await app_state.redis_client.setex(session_key, ttl, json.dumps(data))
302 return True
303 except Exception as e:
304 logger.error(f"Error storing session: {e}")
305 return False
308async def delete_session(session_id: str) -> bool:
309 """Delete session and tokens from Redis."""
310 try:
311 await app_state.redis_client.delete(f"session:{session_id}")
312 await app_state.redis_client.delete(f"tokens:{session_id}")
313 return True
314 except Exception as e:
315 logger.error(f"Error deleting session: {e}")
316 return False
319async def refresh_access_token(refresh_token: str) -> Optional[Dict[str, Any]]:
320 """
321 Refresh access token using refresh token.
323 Args:
324 refresh_token: OAuth refresh token
326 Returns:
327 New token response or None if failed
328 """
329 async with httpx.AsyncClient() as client:
330 try:
331 response = await client.post(
332 f"https://{settings.AUTH0_DOMAIN}/oauth/token",
333 json={
334 "grant_type": "refresh_token",
335 "client_id": settings.AUTH0_CLIENT_ID,
336 "client_secret": settings.AUTH0_CLIENT_SECRET,
337 "refresh_token": refresh_token,
338 },
339 headers={"Content-Type": "application/json"},
340 timeout=10.0,
341 )
342 response.raise_for_status()
343 return response.json()
344 except httpx.HTTPStatusError as e:
345 logger.error(
346 f"Token refresh HTTP error: {e.response.status_code} - {e.response.text}"
347 )
348 return None
349 except httpx.RequestError as e:
350 logger.error(f"Token refresh request error: {e}")
351 return None
352 except Exception as e:
353 logger.error(f"Unexpected error during token refresh: {e}")
354 return None
357def decode_jwt_payload(token: str) -> Dict[str, Any]:
358 """
359 Decode JWT payload without verification (for user info extraction).
361 Args:
362 token: JWT token
364 Returns:
365 Decoded payload dictionary
367 Raises:
368 ValueError: If token format is invalid
369 """
370 parts = token.split(".")
371 if len(parts) != 3:
372 raise ValueError("Invalid token format")
374 payload = parts[1]
375 # Add padding if needed
376 padding = 4 - len(payload) % 4
377 if padding != 4:
378 payload += "=" * padding
380 try:
381 decoded = base64.urlsafe_b64decode(payload)
382 return json.loads(decoded)
383 except Exception as e:
384 logger.error(f"Error decoding JWT payload: {e}")
385 raise ValueError("Failed to decode token")
388def build_auth_url(state: str, nonce: str) -> str:
389 """Build Auth0 authorization URL."""
390 params = {
391 "response_type": "code",
392 "client_id": settings.AUTH0_CLIENT_ID,
393 "redirect_uri": settings.AUTH_CALLBACK_URL,
394 "scope": "openid profile email offline_access",
395 "audience": settings.AUTH0_AUDIENCE,
396 "state": state,
397 "nonce": nonce,
398 }
399 return f"https://{settings.AUTH0_DOMAIN}/authorize?{urlencode(params)}"
402def build_logout_url(return_to: str = None) -> str:
403 """Build Auth0 logout URL."""
404 params = {
405 "client_id": settings.AUTH0_CLIENT_ID,
406 "returnTo": return_to or settings.PUBLIC_URL,
407 }
408 return f"https://{settings.AUTH0_DOMAIN}/v2/logout?{urlencode(params)}"
411# API Endpoints
414@app.get("/health")
415async def health_check():
416 """
417 Health check endpoint.
419 Returns service health and Redis connectivity status.
420 """
421 try:
422 await app_state.redis_client.ping()
423 redis_status = "connected"
424 except Exception as e:
425 logger.error(f"Redis health check failed: {e}")
426 redis_status = "disconnected"
428 return {
429 "status": "healthy" if redis_status == "connected" else "degraded",
430 "service": "svc-auth",
431 "redis": redis_status,
432 "timestamp": datetime.utcnow().isoformat(),
433 }
436@app.get("/login")
437async def login(return_to: Optional[str] = None):
438 """
439 Initiate OAuth login flow.
441 Query Parameters:
442 return_to: URL to redirect to after successful authentication
444 Flow:
445 1. Generate state and nonce for CSRF protection
446 2. Store OAuth state in temporary Redis session
447 3. Redirect to Auth0 authorization endpoint
448 """
449 # Generate cryptographically secure state and nonce
450 state = secrets.token_urlsafe(32)
451 nonce = secrets.token_urlsafe(32)
453 # Create temporary session for OAuth state
454 temp_session_id = secrets.token_urlsafe(32)
455 oauth_state = {
456 "state": state,
457 "nonce": nonce,
458 "return_to": safe_return_to(return_to),
459 "created_at": int(time.time()),
460 }
462 try:
463 # Store OAuth state in Redis with short TTL
464 await app_state.redis_client.setex(
465 f"oauth_state:{temp_session_id}",
466 settings.OAUTH_STATE_TTL,
467 json.dumps(oauth_state),
468 )
469 except Exception as e:
470 logger.error(f"Failed to store OAuth state: {e}")
471 raise HTTPException(
472 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
473 detail="Authentication initialization failed",
474 )
476 # Build Auth0 authorization URL
477 auth_url = build_auth_url(state, nonce)
479 # Redirect to Auth0 with temp session cookie
480 response = RedirectResponse(url=auth_url, status_code=302)
481 response.set_cookie(
482 key="oauth_temp",
483 value=temp_session_id,
484 httponly=True,
485 secure=settings.COOKIE_SECURE,
486 samesite=settings.COOKIE_SAMESITE,
487 max_age=settings.OAUTH_STATE_TTL,
488 # ".localhost" if settings.ENVIRONMENT == "development" else None
489 domain=settings.COOKIE_DOMAIN,
490 )
492 logger.info(f"Login initiated for session {temp_session_id}")
493 return response
496@app.get("/callback")
497async def callback(
498 request: Request,
499 code: Optional[str] = None,
500 state: Optional[str] = None,
501 error: Optional[str] = None,
502):
503 """
504 Handle OAuth callback from Auth0.
506 Query Parameters:
507 code: Authorization code from Auth0
508 state: State parameter for CSRF validation
509 error: Error code if authentication failed
511 Flow:
512 1. Validate state parameter against stored value
513 2. Exchange authorization code for tokens
514 3. Extract user info from ID token
515 4. Create session and store tokens server-side
516 5. Redirect to application with session cookie
517 """
518 # Check for OAuth errors
519 if error:
520 logger.warning(f"OAuth error: {error}")
521 return RedirectResponse(
522 url=f"{settings.PUBLIC_URL}?error=auth_failed", status_code=302
523 )
525 if not code or not state:
526 logger.warning("Missing code or state in callback")
527 raise HTTPException(
528 status_code=status.HTTP_400_BAD_REQUEST,
529 detail="Missing code or state parameter",
530 )
532 # Get OAuth state from temporary session
533 temp_session_id = request.cookies.get("oauth_temp")
534 if not temp_session_id:
535 logger.warning("Missing OAuth temporary session")
536 raise HTTPException(
537 status_code=status.HTTP_400_BAD_REQUEST, detail="Missing OAuth session"
538 )
540 try:
541 oauth_state_json = await app_state.redis_client.get(
542 f"oauth_state:{temp_session_id}"
543 )
544 if not oauth_state_json:
545 logger.warning(f"Invalid OAuth session: {temp_session_id}")
546 raise HTTPException(
547 status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid OAuth session"
548 )
550 oauth_state = json.loads(oauth_state_json)
551 except Exception as e:
552 logger.error(f"Error retrieving OAuth state: {e}")
553 raise HTTPException(
554 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
555 detail="Session retrieval failed",
556 )
558 # Validate state parameter (CSRF protection)
559 if state != oauth_state["state"]:
560 logger.warning(f"State mismatch: expected {oauth_state['state']}, got {state}")
561 raise HTTPException(
562 status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid state parameter"
563 )
565 # Exchange authorization code for tokens
566 async with httpx.AsyncClient() as client:
567 try:
568 token_response = await client.post(
569 f"https://{settings.AUTH0_DOMAIN}/oauth/token",
570 json={
571 "grant_type": "authorization_code",
572 "client_id": settings.AUTH0_CLIENT_ID,
573 "client_secret": settings.AUTH0_CLIENT_SECRET,
574 "code": code,
575 "redirect_uri": settings.AUTH_CALLBACK_URL,
576 },
577 headers={"Content-Type": "application/json"},
578 timeout=10.0,
579 )
580 token_response.raise_for_status()
581 tokens = token_response.json()
582 except httpx.HTTPStatusError as e:
583 logger.error(
584 f"Token exchange HTTP error: {e.response.status_code} - {e.response.text}"
585 )
586 raise HTTPException(
587 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
588 detail="Token exchange failed",
589 )
590 except httpx.RequestError as e:
591 logger.error(f"Token exchange request error: {e}")
592 raise HTTPException(
593 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
594 detail="Token exchange failed",
595 )
597 # Extract user info from ID token
598 try:
599 id_token_payload = decode_jwt_payload(tokens["id_token"])
600 user_id = id_token_payload.get("sub")
602 if not user_id:
603 raise ValueError("Missing user ID in token")
605 # Validate nonce (replay attack protection)
606 if id_token_payload.get("nonce") != oauth_state["nonce"]:
607 logger.warning("Nonce mismatch in ID token")
608 raise HTTPException(
609 status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid token nonce"
610 )
612 except HTTPException:
613 # Deliberate validation rejections (e.g. nonce mismatch) keep their
614 # intended status code instead of being masked as a 500.
615 raise
616 except Exception as e:
617 logger.error(f"ID token validation error: {e}")
618 raise HTTPException(
619 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Invalid ID token"
620 )
622 # Create new session
623 session_id = secrets.token_urlsafe(32)
624 current_time = int(time.time())
626 # Prepare token data for storage
627 tokens_data = {
628 "access_token": tokens["access_token"],
629 "refresh_token": tokens.get("refresh_token"),
630 "id_token": tokens["id_token"],
631 "expires_at": current_time + tokens.get("expires_in", 3600),
632 "user_id": user_id,
633 "token_type": tokens.get("token_type", "Bearer"),
634 }
636 # Store tokens server-side only
637 if not await store_tokens(session_id, tokens_data):
638 raise HTTPException(
639 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
640 detail="Failed to store session",
641 )
643 # Store session metadata
644 session_data = {
645 "user_id": user_id,
646 "authenticated": True,
647 "created_at": current_time,
648 "last_activity": current_time,
649 "email": id_token_payload.get("email"),
650 "name": id_token_payload.get("name"),
651 }
652 # The platform roles assigned in Auth0, when its Action sent them
653 # (app/roles.py). Absent means "not said", and svc-core leaves the
654 # user's roles as they are.
655 roles = roles_from(id_token_payload)
656 if roles is not None:
657 session_data["roles"] = roles
659 if not await store_session_data(session_id, session_data):
660 await delete_session(session_id) # Cleanup
661 raise HTTPException(
662 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
663 detail="Failed to create session",
664 )
666 # Record the session in the durable store for the account "sessions" view.
667 # Capture identifying detail (device/IP/geo) from this callback request —
668 # it carries the real browser's User-Agent and forwarded client IP.
669 client_ip = get_client_ip(request)
670 sessions_service.create_session(
671 sid=session_id,
672 user_id=user_id,
673 ip=client_ip,
674 device=parse_device(request.headers.get("user-agent")),
675 geo=geoip_lookup(client_ip),
676 )
678 # Clean up temporary OAuth state
679 try:
680 await app_state.redis_client.delete(f"oauth_state:{temp_session_id}")
681 except Exception as e:
682 logger.warning(f"Failed to cleanup OAuth state: {e}")
684 # Redirect to application
685 # Re-checked here too: state written before the check existed is still
686 # live in Redis for OAUTH_STATE_TTL.
687 return_to = safe_return_to(oauth_state.get("return_to"))
688 response = RedirectResponse(url=return_to, status_code=302)
690 # Set secure session cookie
691 signed_cookie = create_session_cookie(session_id)
692 response.set_cookie(
693 key=settings.SESSION_COOKIE_NAME,
694 value=signed_cookie,
695 httponly=True,
696 secure=settings.COOKIE_SECURE,
697 samesite=settings.COOKIE_SAMESITE,
698 max_age=settings.SESSION_MAX_AGE,
699 domain=settings.COOKIE_DOMAIN,
700 path="/",
701 )
703 # Delete temporary OAuth cookie
704 response.delete_cookie(
705 key="oauth_temp",
706 domain=".localhost" if settings.ENVIRONMENT == "development" else None,
707 )
709 logger.info(f"Authentication successful for user {user_id}")
710 return response
713@app.get("/verify")
714async def verify_session(request: Request):
715 """
716 Verify session and return user info.
718 Used by nginx auth_request directive to protect routes.
720 Headers:
721 X-User-Id: User identifier
722 X-Session-Id: Session identifier
724 Returns:
725 200: Session valid
726 401: Session invalid or expired
727 """
728 session_id = get_session_id(request)
730 if not session_id:
731 raise HTTPException(
732 status_code=status.HTTP_401_UNAUTHORIZED, detail="No session"
733 )
735 # Get session data
736 session_data = await get_session_data(session_id)
737 if not session_data:
738 raise HTTPException(
739 status_code=status.HTTP_401_UNAUTHORIZED, detail="Session expired"
740 )
742 # Get tokens
743 tokens = await get_tokens(session_id)
744 if not tokens:
745 await delete_session(session_id)
746 sessions_service.end_session_by_sid(
747 sid=session_id, reason=SessionEndReason.EXPIRED
748 )
749 raise HTTPException(
750 status_code=status.HTTP_401_UNAUTHORIZED, detail="No tokens found"
751 )
753 # Check if token needs refresh
754 expires_at = tokens.get("expires_at", 0)
755 current_time = int(time.time())
757 if current_time > expires_at - settings.TOKEN_REFRESH_THRESHOLD:
758 refresh_token = tokens.get("refresh_token")
760 if refresh_token:
761 # Attempt token refresh
762 new_tokens = await refresh_access_token(refresh_token)
764 if new_tokens:
765 # Update stored tokens
766 tokens_data = {
767 "access_token": new_tokens["access_token"],
768 "refresh_token": new_tokens.get("refresh_token", refresh_token),
769 "id_token": new_tokens.get("id_token", tokens["id_token"]),
770 "expires_at": current_time + new_tokens.get("expires_in", 3600),
771 "user_id": tokens["user_id"],
772 "token_type": new_tokens.get("token_type", "Bearer"),
773 }
775 await store_tokens(session_id, tokens_data)
776 logger.info(f"Token refreshed for session {session_id}")
777 # A refreshed ID token carries the roles as they are in Auth0
778 # now, so a role granted or taken away there reaches the
779 # session without a new sign-in.
780 if new_tokens.get("id_token"):
781 try:
782 refreshed = roles_from(
783 decode_jwt_payload(new_tokens["id_token"])
784 )
785 except ValueError:
786 refreshed = None
787 if refreshed is not None:
788 session_data["roles"] = refreshed
789 else:
790 # Refresh failed - invalidate session
791 await delete_session(session_id)
792 sessions_service.end_session_by_sid(
793 sid=session_id, reason=SessionEndReason.REFRESH_FAILED
794 )
795 logger.warning(f"Token refresh failed for session {session_id}")
796 raise HTTPException(
797 status_code=status.HTTP_401_UNAUTHORIZED,
798 detail="Token refresh failed",
799 )
800 else:
801 # No refresh token and access token expired
802 await delete_session(session_id)
803 sessions_service.end_session_by_sid(
804 sid=session_id, reason=SessionEndReason.EXPIRED
805 )
806 raise HTTPException(
807 status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired"
808 )
810 # Update last activity
811 session_data["last_activity"] = current_time
812 await store_session_data(session_id, session_data)
814 # Keep the durable session record's last-seen fresh (throttled internally).
815 sessions_service.touch_session(
816 sid=session_id, interval_seconds=settings.SESSION_TOUCH_INTERVAL
817 )
819 # Return success with user info headers
820 return Response(
821 status_code=status.HTTP_200_OK,
822 headers={
823 "X-User-Id": session_data["user_id"],
824 "X-Session-Id": session_id,
825 },
826 )
829@app.api_route("/logout", methods=["GET", "POST"])
830async def logout(request: Request):
831 """
832 Logout user and clear session.
834 Flow:
835 1. Delete session and tokens from Redis
836 2. Clear session cookie
837 3. Redirect to Auth0 logout endpoint
838 """
839 session_id = get_session_id(request)
841 if session_id:
842 # Delete session and tokens
843 deleted = await delete_session(session_id)
844 sessions_service.end_session_by_sid(
845 sid=session_id, reason=SessionEndReason.LOGOUT
846 )
847 if deleted:
848 logger.info(f"Session {session_id} logged out")
849 else:
850 logger.warning(f"Failed to delete session {session_id}")
852 # Build Auth0 logout URL
853 logout_url = build_logout_url()
855 # Redirect with cleared cookie
856 response = RedirectResponse(url=logout_url, status_code=302)
857 response.delete_cookie(
858 key=settings.SESSION_COOKIE_NAME, domain=settings.COOKIE_DOMAIN, path="/"
859 )
861 return response
864@app.get("/me")
865async def get_user_info(request: Request):
866 """
867 Get current authenticated user information.
869 Returns:
870 User profile data from ID token
872 Raises:
873 401: Not authenticated
874 """
875 session_id = get_session_id(request)
877 if not session_id:
878 raise HTTPException(
879 status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated"
880 )
882 session_data = await get_session_data(session_id)
883 if not session_data:
884 raise HTTPException(
885 status_code=status.HTTP_401_UNAUTHORIZED, detail="Session expired"
886 )
888 tokens = await get_tokens(session_id)
889 if not tokens:
890 raise HTTPException(
891 status_code=status.HTTP_401_UNAUTHORIZED, detail="No tokens found"
892 )
894 try:
895 id_token_payload = decode_jwt_payload(tokens["id_token"])
897 return {
898 "user_id": session_data["user_id"],
899 "email": id_token_payload.get("email"),
900 "email_verified": id_token_payload.get("email_verified"),
901 "name": id_token_payload.get("name"),
902 "nickname": id_token_payload.get("nickname"),
903 "picture": id_token_payload.get("picture"),
904 "updated_at": id_token_payload.get("updated_at"),
905 "sub": id_token_payload.get("sub"),
906 # As the session holds them (app/roles.py): null when Auth0 sent
907 # none.
908 "roles": session_data.get("roles"),
909 }
910 except Exception as e:
911 logger.error(f"Failed to decode user info: {e}")
912 raise HTTPException(
913 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
914 detail="Failed to retrieve user information",
915 )
918async def _require_authenticated(request: Request) -> tuple[str, str]:
919 """Resolve the caller's (session_id, user_id) or raise 401.
921 Shared guard for the session-management endpoints — same cookie-based check
922 used by /me, returning the user_id so handlers can scope to the owner.
923 """
924 session_id = get_session_id(request)
925 if not session_id:
926 raise HTTPException(
927 status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated"
928 )
930 session_data = await get_session_data(session_id)
931 if not session_data:
932 raise HTTPException(
933 status_code=status.HTTP_401_UNAUTHORIZED, detail="Session expired"
934 )
936 return session_id, session_data["user_id"]
939@app.get("/sessions")
940async def list_sessions(request: Request):
941 """List the caller's currently-active sessions for the account UI.
943 Reconciles state on read: any session still marked active whose Redis key
944 has vanished (idle TTL lapse) is flagged expired and dropped from the
945 response — it surfaces under ``/sessions/history`` instead. The opaque
946 session token is never included; sessions are addressed by their UUID.
947 """
948 current_sid, user_id = await _require_authenticated(request)
950 views = sessions_service.get_active_sessions(user_id=user_id)
952 # Reconcile: active rows whose Redis session no longer exists are expired.
953 alive_views = []
954 expired_ids = []
955 for view in views:
956 if await app_state.redis_client.get(f"session:{view.sid}"):
957 alive_views.append(view)
958 else:
959 expired_ids.append(view.id)
961 if expired_ids:
962 sessions_service.mark_expired(session_ids=expired_ids)
964 return {
965 "sessions": [
966 view.to_public_dict(current=(view.sid == current_sid))
967 for view in alive_views
968 ]
969 }
972@app.get("/sessions/history")
973async def list_session_history(request: Request, limit: int = 20, offset: int = 0):
974 """Return a page of the caller's ended sessions, most-recently-ended first.
976 Covers logged-out, revoked, and expired sessions. ``limit`` is clamped to
977 [1, 100] and ``offset`` to >= 0 to bound the query. The response carries the
978 total ended count so the UI can drive "load more" / pagination.
979 """
980 _, user_id = await _require_authenticated(request)
982 limit = max(1, min(limit, 100))
983 offset = max(0, offset)
985 views, total = sessions_service.get_session_history(
986 user_id=user_id, limit=limit, offset=offset
987 )
989 return {
990 "sessions": [view.to_public_dict(current=False) for view in views],
991 "total": total,
992 "limit": limit,
993 "offset": offset,
994 }
997@app.post("/sessions/{session_id}/revoke")
998@app.delete("/sessions/{session_id}")
999async def revoke_session(session_id: str, request: Request):
1000 """Revoke one of the caller's sessions by its UUID.
1002 Ends the durable record and deletes the matching Redis session/tokens so the
1003 next /verify on that session fails. Only the owner may revoke.
1005 Exposed as both ``POST /sessions/{id}/revoke`` and ``DELETE /sessions/{id}``.
1006 The browser uses POST: edge proxies / WAFs (Cloudflare) in front of the
1007 deployment frequently block the DELETE method outright (returning 403), so
1008 the safe-everywhere mutation verb is POST. DELETE is retained for API
1009 clients / backward compatibility.
1010 """
1011 _, user_id = await _require_authenticated(request)
1013 try:
1014 session_uuid = uuidlib.UUID(session_id)
1015 except ValueError:
1016 raise HTTPException(
1017 status_code=status.HTTP_404_NOT_FOUND, detail="Session not found"
1018 )
1020 sid = sessions_service.end_session_by_id(
1021 session_id=session_uuid, user_id=user_id, reason=SessionEndReason.REVOKED
1022 )
1023 if sid is None:
1024 raise HTTPException(
1025 status_code=status.HTTP_404_NOT_FOUND, detail="Session not found"
1026 )
1028 # Purge the Redis session + tokens so the access is killed immediately.
1029 await delete_session(sid)
1031 return {"revoked": True, "id": session_id}
1034@app.post("/sessions/revoke-others")
1035async def revoke_other_sessions(request: Request):
1036 """Sign out everywhere except the caller's current session."""
1037 current_sid, user_id = await _require_authenticated(request)
1039 sids = sessions_service.end_other_sessions(
1040 user_id=user_id,
1041 keep_sid=current_sid,
1042 reason=SessionEndReason.REVOKED_OTHERS,
1043 )
1045 for sid in sids:
1046 await delete_session(sid)
1048 return {"revoked_count": len(sids)}
1051@app.get("/session/info")
1052async def get_session_info(request: Request):
1053 """
1054 Get session information (for debugging in development).
1056 Only available in development mode.
1057 """
1058 if settings.ENVIRONMENT != "development":
1059 raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
1061 session_id = get_session_id(request)
1062 if not session_id:
1063 return {"authenticated": False}
1065 session_data = await get_session_data(session_id)
1066 tokens = await get_tokens(session_id)
1068 return {
1069 "authenticated": session_data is not None,
1070 "session_id": session_id,
1071 "session_data": session_data,
1072 "has_tokens": tokens is not None,
1073 "token_expires_at": tokens.get("expires_at") if tokens else None,
1074 }
1077# Exception handlers
1078@app.exception_handler(HTTPException)
1079async def http_exception_handler(request: Request, exc: HTTPException):
1080 """Custom HTTP exception handler."""
1081 return JSONResponse(
1082 status_code=exc.status_code,
1083 content={"error": exc.detail, "status_code": exc.status_code},
1084 )
1087@app.exception_handler(Exception)
1088async def general_exception_handler(request: Request, exc: Exception):
1089 """Catch-all exception handler."""
1090 logger.error(f"Unhandled exception: {exc}", exc_info=True)
1091 return JSONResponse(
1092 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
1093 content={"error": "Internal server error", "status_code": 500},
1094 )
1097if __name__ == "__main__":
1098 import uvicorn
1100 # nosec B104 — binds all interfaces by design: runs inside a container with
1101 # no host ports published, reachable only via nginx on the internal network.
1102 uvicorn.run(app, host="0.0.0.0", port=3000, log_level="info") # nosec B104