Coverage for main.py: 61%
300 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"""
2Core App BFF - Backend for Frontend API Proxy Service
3"""
5from fastapi import (
6 FastAPI,
7 Request,
8 HTTPException,
9 Response,
10 WebSocket,
11 WebSocketDisconnect,
12)
13from fastapi.responses import JSONResponse
14from fastapi.middleware.trustedhost import TrustedHostMiddleware
15from contextlib import asynccontextmanager
16import asyncio
17import httpx
18import redis.asyncio as redis
19import json
20import logging
21import websockets
22from typing import Optional, Dict, Any
23from datetime import datetime
24from itsdangerous import URLSafeTimedSerializer, BadSignature
26from app.cache_control import DefaultCacheControlMiddleware
27from app.config import settings
28from app.cors import CORSMiddleware, cors_middleware_args
29from app.internal_auth import mint_internal_token
31# Configure logging: the format svc-core and svc-ai write (``ts | LEVEL |
32# name | message``), which Promtail reads a line's level from and starts a
33# record at (monitoring/promtail/promtail-config.yml). Python's warnings go
34# through it too, rather than to stderr bare.
35logging.basicConfig(
36 level=logging.INFO,
37 format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
38 datefmt="%Y-%m-%d %H:%M:%S",
39)
40logging.captureWarnings(True)
41logger = logging.getLogger(__name__)
44# Application state
45class AppState:
46 redis_client: Optional[redis.Redis] = None
49app_state = AppState()
52def create_redis_client() -> redis.Redis:
53 """Create the shared Redis client.
55 Uses a BlockingConnectionPool: when the pool is saturated, callers wait up
56 to `timeout` seconds for a free connection instead of failing with
57 "Too many connections" (the default ConnectionPool raises immediately).
58 """
59 pool = redis.BlockingConnectionPool.from_url(
60 settings.REDIS_URL,
61 password=settings.REDIS_PASSWORD,
62 decode_responses=True,
63 encoding="utf-8",
64 max_connections=50,
65 timeout=5,
66 )
67 return redis.Redis(connection_pool=pool)
70# Lifespan context manager
71@asynccontextmanager
72async def lifespan(app: FastAPI):
73 """
74 Lifespan context manager for startup and shutdown events.
76 Startup:
77 - Initialize Redis connection
78 - Test connectivity
80 Shutdown:
81 - Close Redis connection gracefully
82 """
83 # Startup
84 logger.info("Starting up Core App BFF...")
85 try:
86 app_state.redis_client = create_redis_client()
87 # Test connection
88 await app_state.redis_client.ping()
89 logger.info("Redis connection established successfully")
90 except Exception as e:
91 logger.error(f"Failed to connect to Redis: {e}")
92 raise
94 yield # Application runs here
96 # Shutdown
97 logger.info("Shutting down Core App BFF...")
98 if app_state.redis_client:
99 await app_state.redis_client.close()
100 logger.info("Redis connection closed")
103# Initialize FastAPI app with lifespan
104app = FastAPI(
105 title="Core App BFF",
106 description="API Proxy Backend for Frontend service",
107 version="1.0.0",
108 docs_url="/docs" if settings.ENVIRONMENT == "development" else None,
109 redoc_url="/redoc" if settings.ENVIRONMENT == "development" else None,
110 lifespan=lifespan,
111)
113# Session serializer
114serializer = URLSafeTimedSerializer(settings.SESSION_SECRET)
117def _proxy_timeout_for(path: str) -> int:
118 """Timeout for a proxied backend call, by route class.
120 LLM-backed routes (agent config generation, synchronous prompt calls)
121 legitimately run for minutes and get PROXY_TIMEOUT_LONG, as does the
122 user's data export, which svc-core builds in full before answering;
123 everything else keeps the tight default so a hung backend can't pile up
124 connections.
125 """
126 normalized = path.rstrip("/")
127 if normalized.startswith("app/agents/generate") or normalized.endswith("/prompt"):
128 return settings.PROXY_TIMEOUT_LONG
129 if normalized == "app/dashboards/generate":
130 # One structured call designs the whole board, and one more corrects
131 # the tiles that failed their validators.
132 return settings.PROXY_TIMEOUT_LONG
133 if normalized == "app/users/me/export":
134 return settings.PROXY_TIMEOUT_LONG
135 if normalized.startswith("app/scenario-runs/") and normalized.endswith("/export"):
136 # A run's export holds every turn's trace and decision record.
137 return settings.PROXY_TIMEOUT_LONG
138 return settings.PROXY_TIMEOUT
141# CORS Middleware — strict, env-derived allowlist (see app/cors.py).
142app.add_middleware(CORSMiddleware, **cors_middleware_args)
144# Every response is one user's data: never let a shared cache (Cloudflare)
145# keep a copy unless the route says otherwise (see app/cache_control.py).
146app.add_middleware(DefaultCacheControlMiddleware)
149# Trusted Host Middleware. Allow the cookie domain and its subdomains so it
150# tracks the deployment (8000 / 80 / behind Cloudflare) without hardcoding ports.
151# Starlette strips the port before comparing.
152#
153# localhost/127.0.0.1 must also be allowed: the container healthcheck probes
154# /health over loopback, and a Host of "localhost" can only originate from
155# inside the container — without it every probe gets 400 and the healthcheck
156# silently stops verifying anything.
157def trusted_hosts(cookie_domain: str) -> list[str]:
158 domain = cookie_domain.lstrip(".")
159 return [domain, f"*.{domain}", "localhost", "127.0.0.1"]
162if settings.ENVIRONMENT == "production" and settings.COOKIE_DOMAIN:
163 app.add_middleware(
164 TrustedHostMiddleware,
165 allowed_hosts=trusted_hosts(settings.COOKIE_DOMAIN),
166 )
169# Helper Functions
170def get_session_id(request: Request) -> Optional[str]:
171 """Extract and verify session ID from signed cookie."""
172 cookie = request.cookies.get(settings.SESSION_COOKIE_NAME)
173 if not cookie:
174 return None
176 try:
177 session_id = serializer.loads(cookie, max_age=settings.SESSION_MAX_AGE)
178 return session_id
179 except BadSignature:
180 logger.warning("Invalid session cookie signature")
181 return None
182 except Exception as e:
183 logger.error(f"Error decoding session cookie: {e}")
184 return None
187async def get_access_token(session_id: str) -> Optional[str]:
188 """Retrieve access token from Redis.
190 Returns None only when the session has no token (→ 401). Redis errors
191 propagate so callers can surface a retryable failure instead of treating
192 an infrastructure hiccup as an expired session.
193 """
194 token_key = f"tokens:{session_id}"
195 tokens_json = await app_state.redis_client.get(token_key)
196 if not tokens_json:
197 return None
199 try:
200 tokens = json.loads(tokens_json)
201 except json.JSONDecodeError as e:
202 logger.error(f"Corrupt token payload for session {session_id}: {e}")
203 return None
204 return tokens.get("access_token")
207async def get_session_data(session_id: str) -> Optional[Dict[str, Any]]:
208 """Retrieve full session data from Redis.
210 Returns None when the session is missing or corrupt; Redis errors
211 propagate (see get_access_token).
212 """
213 session_key = f"session:{session_id}"
214 session_json = await app_state.redis_client.get(session_key)
215 if not session_json:
216 return None
217 try:
218 return json.loads(session_json)
219 except json.JSONDecodeError as e:
220 logger.error(f"Corrupt session payload for session {session_id}: {e}")
221 return None
224#: The only svc-core surface the browser may reach. svc-core also serves
225#: ``/monitoring`` (unauthenticated, for Prometheus and the healthcheck) and,
226#: in local/dev, ``/dev`` (which can truncate every table); neither is the
227#: browser's business, and fe-core only ever calls ``/app``.
228ALLOWED_BACKEND_PREFIX = "app"
231def backend_path_allowed(path: str) -> bool:
232 """Whether a proxied path may be forwarded to svc-core.
234 Dot segments are refused outright rather than normalised: ``app/../dev``
235 passes a prefix check and resolves outside it.
236 """
237 segments = path.split("/")
238 if any(segment in (".", "..") for segment in segments):
239 return False
240 return segments[0] == ALLOWED_BACKEND_PREFIX
243def session_roles(session_data: dict) -> Optional[list[str]]:
244 """The platform roles svc-auth kept on the session (svc-auth
245 ``app/roles.py``), or None when Auth0 sent none — which svc-core reads as
246 "not said", leaving the user's roles alone. Anything that is not a list of
247 names is not said either."""
248 roles = session_data.get("roles")
249 if not isinstance(roles, list) or not all(isinstance(r, str) for r in roles):
250 return None
251 # A comma would split one name into two in the legacy header.
252 return [r for r in roles if "," not in r]
255def should_forward_header(header_name: str) -> bool:
256 """Determine if header should be forwarded to backend.
258 Hop-by-hop headers (RFC 9110 §7.6.1) must never be forwarded — they are
259 meaningful only for the immediate connection and are re-set by the proxy
260 transport layer (httpx) when it sends the re-assembled request.
261 Forwarding transfer-encoding or content-length alongside pre-read bytes
262 causes receivers (FastAPI multipart parser) to reject the body with 422.
263 """
264 header_lower = header_name.lower()
266 excluded_headers = {
267 # Auth / session — injected server-side instead
268 "host",
269 "connection",
270 "cookie",
271 "authorization",
272 "x-forwarded-host",
273 "x-forwarded-server",
274 # Identity — minted/derived server-side; never trust client-supplied
275 # values, otherwise a caller could spoof another user.
276 "x-internal-token",
277 "x-user-id",
278 "x-user-email",
279 "x-user-name",
280 "x-user-roles",
281 # Hop-by-hop — httpx sets these correctly for the outbound request
282 "transfer-encoding",
283 "content-length",
284 "te",
285 "trailers",
286 "upgrade",
287 "keep-alive",
288 "proxy-connection",
289 }
291 return header_lower not in excluded_headers
294def clean_response_headers(headers: Dict[str, str]) -> Dict[str, str]:
295 """Clean response headers from backend.
297 ``server`` and ``date`` are svc-core's uvicorn's; svc-bff's own uvicorn
298 adds its pair without looking, so forwarding them sent each twice and
299 nginx logged a "duplicate header line" warning on every proxied request.
300 """
301 excluded = {
302 "transfer-encoding",
303 "connection",
304 "keep-alive",
305 "proxy-authenticate",
306 "proxy-authorization",
307 "te",
308 "trailers",
309 "upgrade",
310 "server",
311 "date",
312 }
314 return {k: v for k, v in headers.items() if k.lower() not in excluded}
317# Helper to extract session ID from a cookie dict (works for both HTTP requests and WebSocket)
318def get_session_id_from_cookies(cookies: dict) -> Optional[str]:
319 cookie = cookies.get(settings.SESSION_COOKIE_NAME)
320 if not cookie:
321 return None
322 try:
323 return serializer.loads(cookie, max_age=settings.SESSION_MAX_AGE)
324 except BadSignature:
325 logger.warning("Invalid session cookie signature (WS)")
326 return None
327 except Exception as e:
328 logger.error(f"Error decoding session cookie (WS): {e}")
329 return None
332# API Endpoints
335@app.get("/health")
336async def health_check():
337 """Health check endpoint."""
338 try:
339 await app_state.redis_client.ping()
340 redis_status = "connected"
341 except Exception as e:
342 logger.error(f"Redis health check failed: {e}")
343 redis_status = "disconnected"
345 # Check backend connectivity
346 try:
347 async with httpx.AsyncClient() as client:
348 response = await client.get(
349 f"{settings.BACKEND_API_URL}/monitoring/health", timeout=5.0
350 )
351 backend_status = "connected" if response.status_code == 200 else "error"
352 except Exception as e:
353 logger.error(f"Backend health check failed: {e}")
354 backend_status = "disconnected"
356 return {
357 "status": "healthy"
358 if redis_status == "connected" and backend_status == "connected"
359 else "degraded",
360 "service": "svc-bff",
361 "redis": redis_status,
362 "backend": backend_status,
363 "timestamp": datetime.utcnow().isoformat(),
364 }
367@app.websocket("/ws/{path:path}")
368async def websocket_proxy(websocket: WebSocket, path: str):
369 """
370 Proxy WebSocket connections from the frontend through to svc-core.
372 Auth flow: validates session cookie → fetches access token + user data from Redis
373 → accepts the frontend WS → opens a backend WS to svc-core with injected headers
374 → bidirectionally forwards messages until either side closes.
375 """
376 if not backend_path_allowed(path):
377 logger.warning(f"WS proxy: refused path {path!r}")
378 await websocket.close(code=4004)
379 return
381 session_id = get_session_id_from_cookies(dict(websocket.cookies))
382 if not session_id:
383 logger.warning("WS proxy: no valid session cookie")
384 await websocket.close(code=4001)
385 return
387 try:
388 access_token = await get_access_token(session_id)
389 session_data = await get_session_data(session_id) or {}
390 except redis.RedisError as e:
391 logger.error(f"WS proxy: session store unavailable: {e}")
392 # 1013 = try again later: the session may be valid, Redis just failed
393 await websocket.close(code=1013)
394 return
396 if not access_token:
397 logger.warning(f"WS proxy: no access token for session {session_id}")
398 await websocket.close(code=4001)
399 return
401 user_id = session_data.get("user_id", "")
402 user_email = session_data.get("email", "")
403 user_name = session_data.get("name", "")
405 await websocket.accept()
407 backend_ws_url = (
408 settings.BACKEND_API_URL.replace("https://", "wss://", 1).replace(
409 "http://", "ws://", 1
410 )
411 + f"/{path}"
412 )
414 additional_headers = [
415 ("Authorization", f"Bearer {access_token}"),
416 ("X-User-Id", user_id),
417 ("X-User-Email", user_email),
418 ("X-User-Name", user_name),
419 ("X-Forwarded-For", websocket.client.host if websocket.client else ""),
420 ("X-Forwarded-Proto", "ws"),
421 ]
422 roles = session_roles(session_data)
423 if roles is not None:
424 additional_headers.append(("X-User-Roles", ",".join(roles)))
426 internal_token = mint_internal_token(
427 sub=user_id, email=user_email, name=user_name, roles=roles
428 )
429 if internal_token:
430 additional_headers.append(("X-Internal-Token", internal_token))
432 logger.info(f"WS proxy: {path} for user {user_id}")
434 try:
435 async with websockets.connect(
436 backend_ws_url, additional_headers=additional_headers
437 ) as backend_ws:
439 async def forward_to_backend():
440 try:
441 while True:
442 data = await websocket.receive_text()
443 await backend_ws.send(data)
444 except (WebSocketDisconnect, Exception):
445 pass
447 async def forward_to_frontend():
448 try:
449 async for message in backend_ws:
450 if isinstance(message, bytes):
451 await websocket.send_bytes(message)
452 else:
453 await websocket.send_text(message)
454 except Exception:
455 pass
457 task_fwd = asyncio.create_task(forward_to_backend())
458 task_recv = asyncio.create_task(forward_to_frontend())
460 done, pending = await asyncio.wait(
461 [task_fwd, task_recv],
462 return_when=asyncio.FIRST_COMPLETED,
463 )
464 for task in pending:
465 task.cancel()
466 try:
467 await task
468 except asyncio.CancelledError:
469 pass
471 except Exception as e:
472 logger.error(f"WS proxy error for {path}: {e}")
473 try:
474 await websocket.send_text(
475 json.dumps({"type": "error", "message": "Proxy connection failed"})
476 )
477 except Exception:
478 pass
479 finally:
480 try:
481 await websocket.close()
482 except Exception:
483 pass
486@app.api_route(
487 "/proxy/{path:path}",
488 methods=["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"],
489)
490async def proxy_to_backend(request: Request, path: str):
491 """Proxy all /api/* requests to backend with injected access token."""
492 if not backend_path_allowed(path):
493 raise HTTPException(status_code=404, detail="Not found")
495 # Get and validate session
496 session_id = get_session_id(request)
497 if not session_id:
498 logger.warning("API request without valid session")
499 raise HTTPException(status_code=401, detail="Not authenticated")
501 # Get access token + session data from Redis (server-side only). A Redis
502 # failure is a retryable 503, not a 401 — otherwise a transient outage
503 # kicks users with valid sessions back to login.
504 try:
505 access_token = await get_access_token(session_id)
506 session_data = await get_session_data(session_id) or {}
507 except redis.RedisError as e:
508 logger.error(f"Session store unavailable: {e}")
509 raise HTTPException(status_code=503, detail="Session store unavailable")
511 if not access_token:
512 logger.warning(f"No access token found for session {session_id}")
513 raise HTTPException(status_code=401, detail="No access token")
514 user_id = session_data.get("user_id", "")
516 # Build backend URL
517 backend_url = f"{settings.BACKEND_API_URL}/{path}"
518 if request.url.query:
519 backend_url += f"?{request.url.query}"
521 # Base headers — auth + proxy context, no hop-by-hop headers
522 base_headers = {
523 k: v for k, v in request.headers.items() if should_forward_header(k)
524 }
525 base_headers["Authorization"] = f"Bearer {access_token}"
526 base_headers["X-Forwarded-For"] = request.client.host
527 base_headers["X-Forwarded-Proto"] = request.url.scheme
528 base_headers["X-User-Id"] = user_id
529 base_headers["X-User-Email"] = session_data.get("email") or ""
530 base_headers["X-User-Name"] = session_data.get("name") or ""
531 roles = session_roles(session_data)
532 if roles is not None:
533 base_headers["X-User-Roles"] = ",".join(roles)
535 # Mint a short-lived, audience-bound internal token so svc-core can verify
536 # this request genuinely came from svc-bff (defence-in-depth beyond the
537 # forwarded identity headers above).
538 internal_token = mint_internal_token(
539 sub=user_id,
540 email=session_data.get("email") or "",
541 name=session_data.get("name") or "",
542 roles=roles,
543 )
544 if internal_token:
545 base_headers["X-Internal-Token"] = internal_token
547 async with httpx.AsyncClient() as client:
548 try:
549 logger.info(f"Proxying {request.method} {path} for user {user_id}")
551 content_type = request.headers.get("content-type", "")
552 is_multipart = "multipart/form-data" in content_type
554 if is_multipart:
555 # ── Multipart / file-upload path ──────────────────────────────
556 # Re-parse the form at Starlette and re-construct it via httpx's
557 # native files= API. httpx then owns the Content-Type boundary
558 # which guarantees the boundary in the header matches the body —
559 # forwarding the raw bytes + boundary header is unreliable.
560 form = await request.form()
562 httpx_files: list = []
563 httpx_data: dict = {}
564 for field_name, field_value in form.multi_items():
565 if hasattr(field_value, "read"):
566 file_bytes = await field_value.read()
567 httpx_files.append(
568 (
569 field_name,
570 (
571 field_value.filename or field_name,
572 file_bytes,
573 field_value.content_type
574 or "application/octet-stream",
575 ),
576 )
577 )
578 else:
579 httpx_data[field_name] = field_value
581 # Do NOT include content-type — httpx sets it with the correct boundary
582 upload_headers = {
583 k: v for k, v in base_headers.items() if k.lower() != "content-type"
584 }
586 response = await client.request(
587 method=request.method,
588 url=backend_url,
589 headers=upload_headers,
590 files=httpx_files or None,
591 data=httpx_data or None,
592 timeout=_proxy_timeout_for(path),
593 follow_redirects=False,
594 )
596 else:
597 # ── Regular JSON / binary path ────────────────────────────────
598 body = None
599 if request.method in ["POST", "PUT", "PATCH"]:
600 body = await request.body()
602 content_length = int(request.headers.get("content-length", 0))
603 if content_length > settings.MAX_UPLOAD_SIZE:
604 raise HTTPException(
605 status_code=413,
606 detail=f"Payload too large. Maximum size: {settings.MAX_UPLOAD_SIZE} bytes",
607 )
609 response = await client.request(
610 method=request.method,
611 url=backend_url,
612 headers=base_headers,
613 content=body,
614 timeout=_proxy_timeout_for(path),
615 follow_redirects=False,
616 )
618 # Clean response headers
619 response_headers = clean_response_headers(dict(response.headers))
621 return Response(
622 content=response.content,
623 status_code=response.status_code,
624 headers=response_headers,
625 media_type=response.headers.get("content-type"),
626 )
628 except httpx.TimeoutException:
629 logger.error(f"Backend timeout for {request.method} {path}")
630 raise HTTPException(status_code=504, detail="Backend request timeout")
631 except httpx.RequestError as e:
632 logger.error(f"Backend request error for {request.method} {path}: {e}")
633 raise HTTPException(status_code=502, detail="Backend unavailable")
634 except Exception as e:
635 logger.error(f"Unexpected error proxying request: {e}", exc_info=True)
636 raise HTTPException(status_code=500, detail="Internal proxy error")
639@app.get("/debug/session")
640async def debug_session(request: Request):
641 """Debug endpoint to check session status."""
642 if settings.ENVIRONMENT != "development":
643 raise HTTPException(status_code=404, detail="Not found")
645 session_id = get_session_id(request)
646 if not session_id:
647 return {"authenticated": False, "session_id": None}
649 access_token = await get_access_token(session_id)
650 session_data = await get_session_data(session_id) or {}
652 return {
653 "authenticated": True,
654 "session_id": session_id,
655 "has_access_token": access_token is not None,
656 "user_id": session_data.get("user_id"),
657 "email": session_data.get("email"),
658 "name": session_data.get("name"),
659 }
662# Exception handlers
663@app.exception_handler(HTTPException)
664async def http_exception_handler(request: Request, exc: HTTPException):
665 """Custom HTTP exception handler."""
666 return JSONResponse(
667 status_code=exc.status_code,
668 content={"error": exc.detail, "status_code": exc.status_code},
669 )
672@app.exception_handler(Exception)
673async def general_exception_handler(request: Request, exc: Exception):
674 """Catch-all exception handler."""
675 logger.error(f"Unhandled exception: {exc}", exc_info=True)
676 return JSONResponse(
677 status_code=500, content={"error": "Internal server error", "status_code": 500}
678 )
681if __name__ == "__main__":
682 import uvicorn
684 # nosec B104 — binds all interfaces by design: runs inside a container with
685 # no host ports published, reachable only via nginx on the internal network.
686 uvicorn.run(app, host="0.0.0.0", port=4000, log_level="info") # nosec B104