"""FastAPI backend for AI Tester Platform.""" import json import mimetypes import os import sys import warnings from contextlib import asynccontextmanager from pathlib import Path from urllib.error import HTTPError, URLError from urllib.parse import urlparse # NOTE: ``urllib.request.Request`` must be imported under an alias to avoid # clashing with ``fastapi.Request`` (see ``_load_desktop_release_feed``). from urllib.request import Request as UrlRequest, urlopen from dotenv import load_dotenv from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.gzip import GZipMiddleware from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates # Suppress noisy third-party warnings that do not affect runtime behavior. try: from urllib3.exceptions import NotOpenSSLWarning warnings.filterwarnings("ignore", category=NotOpenSSLWarning) except Exception: pass warnings.filterwarnings( "ignore", message=r".*PydanticDeprecatedSince.*", category=DeprecationWarning, module=r"pyiceberg\..*", ) warnings.filterwarnings( "ignore", message=r".*enablePackrat.*|.*escChar.*|.*unquoteResults.*", category=DeprecationWarning, module=r"pyiceberg\..*", ) # Ensure browsers render `.webp` screenshots served from `/output`. mimetypes.add_type("image/webp", ".webp") # Load env vars from project root env_path = Path(__file__).parent.parent.parent / ".env" load_dotenv(dotenv_path=env_path) # Add src to path sys.path.insert(0, str(Path(__file__).parent.parent)) from src.api.routes import ( admin_llm_keys, admin_settings, ai_proxy, bots, bug_tickets, evaluations, integrations as integrations_routes, knowledge_sources, openproject as openproject_routes, personas, report_records, reports, scenarios, sessions, workspaces, ) from src.api.routes import ( auth as auth_routes, ) from src.db import init_db from src.utils.env import env_bool, env_int, env_str from src.utils.logging import configure_logging, get_logger from src.web.reports_dashboard import router as reports_dashboard_router # Configure logging once, before any module starts emitting records. configure_logging() logger = get_logger(__name__) def _is_production() -> bool: """Production mode is opt-in via ``ENV=production`` (canonical) or ``DEBUG=false`` paired with a non-empty ``DATABASE_URL`` pointing to Postgres. Default is dev-friendly (returns False).""" env = env_str("ENV", "").strip().lower() if env in {"production", "prod"}: return True if env in {"development", "dev", "local", "test", "staging"}: return False # Fallback: assume prod only if explicitly using Postgres + DEBUG=false. db_url = env_str("DATABASE_URL", "") return ("postgresql" in db_url or "postgres://" in db_url) and not env_bool("DEBUG", False) def _validate_production_env() -> None: """Fail-fast on missing critical env vars in production.""" missing: list[str] = [] if not env_str("DATABASE_URL", "").strip(): missing.append("DATABASE_URL") # Encryption key for stored LLM keys — required when admin LLM keys are used. if not env_str("APP_SECRETS_MASTER_KEY", "").strip(): missing.append("APP_SECRETS_MASTER_KEY") # If auth is enforced, we need at least Supabase URL + anon key configured. if env_bool("ENFORCE_AUTH", False): for var in ("SUPABASE_URL", "SUPABASE_ANON_KEY"): if not env_str(var, "").strip(): missing.append(var) if missing: raise RuntimeError( "Production startup aborted — missing required env vars: " + ", ".join(missing) ) def _parse_allowed_origins() -> list[str]: """Read ALLOWED_ORIGINS as comma-separated list. Empty in prod by default.""" raw = env_str("ALLOWED_ORIGINS", "") parts = [p.strip() for p in raw.split(",") if p.strip()] if parts: return parts # Permissive default only in non-production dev. if not _is_production(): return ["*"] return [] @asynccontextmanager async def lifespan(app: FastAPI): """Lifespan context manager for startup/shutdown events.""" # Validate environment first so the app refuses to come up half-broken. if _is_production(): _validate_production_env() logger.info("startup: production env validated") init_db() try: from src.core.knowledge_memory import knowledge_memory_service recovered = knowledge_memory_service.recover_orphan_runs() if recovered: logger.info( "startup: knowledge-memory recovered orphan crawl runs", extra={"recovered": recovered}, ) except Exception: logger.exception("startup: knowledge-memory recovery failed") try: # Test sessions left RUNNING in DB by a previous process die when # the process dies (daemon thread). Without this, those rows stay # in `running` forever. session_runner.recover_orphan_sessions() # finalizes them as FAILED with `error_message=process_restart_*` # so the UI shows them as interrotte invece di pendenti. from src.api.session_runner import session_runner recovered_sessions = session_runner.recover_orphan_sessions() if recovered_sessions: logger.info( "startup: test-session recovery finalized orphan sessions", extra={"recovered": recovered_sessions}, ) except Exception: logger.exception("startup: test-session recovery failed (non-fatal)") # Stesso problema dei test session orphans, applicato al post-session AIS # judge: il BackgroundTask di `_run_session_judge_sync` muore quando il # container HF si riavvia (deploy / OOM / scaling). Il record DB resta # `judge_status='running'` per sempre. Qui finalizziamo tutto come # `failed` con un messaggio chiaro, così l'utente può rilanciare via # "Rivaluta tutti" invece di aspettare un job morto. try: from datetime import datetime, timedelta from src.db import get_db as _get_db from src.db.models import TestSessionModel db = _get_db() # 1800s = 30min default — copre rebuild lenti del container HF e # sessioni con molti turni (judge GPT-4.5 ~15-30s/turn × 60 turn). stale_after_seconds = int(os.getenv("JUDGE_STALE_AFTER_SECONDS", "1800")) now = datetime.utcnow() cutoff = now - timedelta(seconds=stale_after_seconds) with db.get_session() as s: stale = ( s.query(TestSessionModel) .filter(TestSessionModel.judge_status.in_(["running", "pending"])) .all() ) recovered_judge = 0 for row in stale: started_at = row.judge_started_at # Check heartbeat: se il judge_progress ha last_heartbeat_at # recente (< stale_after_seconds), il job era vivo poco fa → # presumibilmente è morto col restart MA può ripartire # rapidamente se il restart è stato breve. Decisione: comunque # marchiamo failed perché il BG task non sopravvive comunque # al restart; se l'admin clicca "Rivaluta tutti" riparte. # Manteniamo il running solo se started_at è recentissimo # (< stale_after_seconds): caso edge in cui l'app si è appena # avviata mentre un altro worker stava già scrivendo. if started_at is not None and started_at > cutoff: continue # job fresco — lascia stare row.judge_status = "failed" row.judge_completed_at = now age_str = "" if started_at is not None: age_min = int((now - started_at).total_seconds() / 60) age_str = f" Job started {age_min} min ago." prev_err = (row.judge_error or "")[:200] row.judge_error = ( "Stale: worker terminated before completion (likely container " "restart o crash)." + age_str + " Reset automatico all'avvio. " "Clicca 'Rivaluta tutti' per ripartire." + (f" Previous error: {prev_err}" if prev_err else "") ) recovered_judge += 1 if recovered_judge: s.commit() logger.info( "startup: judge recovery finalized stale runs", extra={"recovered": recovered_judge, "cutoff_sec": stale_after_seconds}, ) except Exception: logger.exception("startup: judge stale recovery failed (non-fatal)") # OpenProject retry loop (best-effort: never blocks startup). openproject_retry_task = None try: import asyncio as _asyncio from src.integrations.openproject.config import OpenProjectConfig from src.integrations.openproject.retry_loop import run_retry_loop _op_cfg = OpenProjectConfig.from_env() if _op_cfg is not None and _op_cfg.retry_loop_enabled: openproject_retry_task = _asyncio.create_task(run_retry_loop()) logger.info("startup: openproject retry loop scheduled") except Exception: logger.exception("startup: openproject retry loop bootstrap failed") # Screenshot purge loop (best-effort): ogni 24h scansiona le sessioni più # vecchie di SCREENSHOT_RETENTION_DAYS (default 45) e cancella i file # `.webp` dal bucket Supabase Storage + ripulisce i riferimenti nel DB. # Non blocca lo startup; in caso di errori in singoli batch continua. # Disabilita via SCREENSHOT_PURGE_ENABLED=false se serve troubleshooting. purge_task = None try: import asyncio as _asyncio if env_bool("SCREENSHOT_PURGE_ENABLED", True): retention_days = env_int("SCREENSHOT_RETENTION_DAYS", 45) interval_seconds = env_int("SCREENSHOT_PURGE_INTERVAL_SECONDS", 86400) async def _purge_loop() -> None: # Aspetta 5min al boot per non concorrere con altre init. await _asyncio.sleep(300) while True: try: from src.db import get_db as _get_db from src.db.repositories import SessionRepository _db = _get_db() with _db.get_session() as _s: repo = SessionRepository(_s) stats = repo.purge_old_screenshots( older_than_days=retention_days ) _s.commit() if stats.get("sessions_processed"): logger.info( "purge: screenshot retention sweep completed", extra=stats, ) except Exception: logger.exception( "purge: screenshot retention sweep failed (non-fatal)" ) await _asyncio.sleep(interval_seconds) purge_task = _asyncio.create_task(_purge_loop()) logger.info( "startup: screenshot purge loop scheduled " f"(retention={retention_days}d, interval={interval_seconds}s)" ) except Exception: logger.exception("startup: screenshot purge loop bootstrap failed") yield # Shutdown — swallow CancelledError too (it's a BaseException in 3.9+, # so a bare `except Exception` lets it bubble up and breaks shutdown). if openproject_retry_task is not None: openproject_retry_task.cancel() try: await openproject_retry_task except BaseException: pass if purge_task is not None: purge_task.cancel() try: await purge_task except BaseException: pass _PRODUCTION = _is_production() app = FastAPI( title="AI Tester Platform API", description="API for testing conversational AI chatbots", version="1.0.0", lifespan=lifespan, # Disable interactive docs in production to avoid leaking the schema. docs_url=None if _PRODUCTION else "/docs", redoc_url=None if _PRODUCTION else "/redoc", openapi_url=None if _PRODUCTION else "/openapi.json", ) # ---- Middleware (order matters: GZip after CORS so CORS headers gzip too) ---- _allowed_origins = _parse_allowed_origins() app.add_middleware( CORSMiddleware, allow_origins=_allowed_origins, allow_origin_regex=env_str("ALLOWED_ORIGIN_REGEX", "") or None, allow_credentials=True, allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], allow_headers=["*"], expose_headers=["X-Request-ID"], ) app.add_middleware(GZipMiddleware, minimum_size=1024) logger.info( "cors: configured", extra={"allowed_origins": _allowed_origins, "production": _PRODUCTION}, ) # RBAC: viewer-mutation guard middleware # ---------------------------------------------------------------------------- # Il ruolo `viewer` è read-only (vedi src/api/auth.py). Per evitare di # annotare 80+ endpoint con `Depends(require_not_viewer)`, lo blocco a # livello middleware su tutti i metodi mutanti di /api/* — esclusi gli # endpoint di auth (signin/signout/me) che devono restare accessibili. # # Costo per request mutante: 1 chiamata a `get_current_user` (cache della # decodifica JWT). I metodi safe (GET/HEAD/OPTIONS) bypassano subito. @app.middleware("http") async def viewer_mutation_guard(request: Request, call_next): from src.utils.env import env_bool as _env_bool_mw if not _env_bool_mw("ENFORCE_AUTH", False): return await call_next(request) method = request.method.upper() if method not in {"POST", "PUT", "DELETE", "PATCH"}: return await call_next(request) path = request.url.path if not path.startswith("/api/"): return await call_next(request) # Whitelist endpoint auth: signin/signout/me devono restare invocabili # da chiunque (anche viewer fa logout, refresh, ecc.). if path.startswith("/api/auth/signin") \ or path.startswith("/api/auth/signout") \ or path == "/api/auth/me" \ or path.startswith("/api/auth/refresh"): return await call_next(request) # Decodifica auth header senza rompere se assente: l'auth dep # dell'endpoint farà comunque 401 a valle. auth_header = request.headers.get("authorization", "") if not auth_header.lower().startswith("bearer "): return await call_next(request) bearer = auth_header[7:].strip() if not bearer: return await call_next(request) try: from fastapi.security import HTTPAuthorizationCredentials from src.api.auth import get_current_user credentials = HTTPAuthorizationCredentials(scheme="Bearer", credentials=bearer) user = await get_current_user(credentials) except Exception: # Token invalido / Supabase down: lascia che la dep dell'endpoint # decida (probabilmente 401). Non bloccare qui. return await call_next(request) if user.is_viewer: return JSONResponse( status_code=403, content={"detail": "Viewer role: action not allowed (read-only access)"}, ) # Cache user su request.state così le dep `require_auth_if_enabled` # downstream lo riusano (no doppio fetch Supabase). request.state.user = user return await call_next(request) # Global exception handlers @app.exception_handler(ValueError) async def value_error_handler(request: Request, exc: ValueError): # ValueError messages are usually safe (validation/parse errors) but we # still avoid leaking the raw repr in production. detail = str(exc) if not _PRODUCTION else "Invalid input" logger.warning("value_error", extra={"path": request.url.path, "error": str(exc)}) return JSONResponse(status_code=422, content={"detail": detail}) @app.exception_handler(Exception) async def generic_exception_handler(request: Request, exc: Exception): logger.exception("unhandled_exception", extra={"path": request.url.path}) return JSONResponse(status_code=500, content={"detail": "Internal server error"}) # Include API routes app.include_router(auth_routes.router, prefix="/api/auth", tags=["auth"]) app.include_router(bots.router, prefix="/api/bots", tags=["bots"]) app.include_router(personas.router, prefix="/api/personas", tags=["personas"]) app.include_router(scenarios.router, prefix="/api/scenarios", tags=["scenarios"]) app.include_router(sessions.router, prefix="/api/sessions", tags=["sessions"]) app.include_router(sessions.ws_router, prefix="/api/sessions", tags=["sessions"]) app.include_router(reports.router, prefix="/api/reports", tags=["reports"]) app.include_router(ai_proxy.router, prefix="/api/ai", tags=["ai"]) app.include_router(workspaces.router, prefix="/api/workspaces", tags=["workspaces"]) app.include_router(admin_llm_keys.router, prefix="/api/admin/llm", tags=["admin-llm"]) app.include_router(admin_settings.router, prefix="/api/admin", tags=["admin-settings"]) app.include_router( knowledge_sources.router, prefix="/api/knowledge-sources", tags=["knowledge-sources"] ) app.include_router(evaluations.router, prefix="/api/evaluations", tags=["evaluations"]) app.include_router(bug_tickets.router, prefix="/api/bug-tickets", tags=["bug-tickets"]) app.include_router( openproject_routes.router, prefix="/api/openproject", tags=["openproject"] ) app.include_router( integrations_routes.router, prefix="/api/integrations", tags=["integrations"] ) app.include_router(report_records.router, prefix="/api/report-records", tags=["report-records"]) app.include_router(reports_dashboard_router) # Static files — wrapped to set a sensible Cache-Control header. We use # ``no-cache`` rather than a long TTL because the bundle filenames are stable # (no content-hash) and the platform pushes CSS/JS updates often: long TTLs # would strand users on stale assets after a deploy. ``no-cache`` still # benefits from ETag/If-None-Match revalidation. class _CachedStaticFiles(StaticFiles): def __init__(self, *args, cache_control: str = "no-cache", **kwargs): super().__init__(*args, **kwargs) self._cache_control = cache_control async def get_response(self, path, scope): response = await super().get_response(path, scope) # 4 tier di caching: # 1) vendor/* (Chart.min, Alpine.min, ecc.) — bundle frozen, # cache lunghissima + immutable. # 2) URL con cache-buster `?v=` (es. app.js?v=abc123) — il # fingerprint viene rigenerato ad ogni deploy via `_compute_asset_version` # dei file critici, quindi possiamo cachare aggressivamente # immutable. Risparmia 10-15 round-trip 304 per page nav. # 3) Asset binari (img, font, ico) — content immutabile di natura, # cache lunga ma senza `immutable` (può cambiare al refresh del brand). # 4) JS/CSS principali serviti SENZA query string (es. bookmark/legacy) # — fallback no-cache così l'utente è sempre freschissimo. path_lower = path.lower() has_version_buster = b"v=" in (scope.get("query_string", b"") or b"") if path.startswith("vendor/"): response.headers["Cache-Control"] = "public, max-age=31536000, immutable" elif has_version_buster and path_lower.endswith((".js", ".css", ".mjs")): # URL con fingerprint => content è "immutabile" per definizione # (deploy successivo => fingerprint diverso => URL nuovo). response.headers["Cache-Control"] = "public, max-age=31536000, immutable" elif path_lower.endswith(( ".png", ".jpg", ".jpeg", ".svg", ".ico", ".gif", ".webp", ".woff", ".woff2", ".ttf", ".otf", ".eot", )): response.headers["Cache-Control"] = "public, max-age=2592000" else: response.headers["Cache-Control"] = self._cache_control return response def _compute_asset_version(static_dir: Path) -> str: """Fingerprint SHA1 (10 char) dei file static critici per cache-busting. Combina app.css + ui-busy.css + tutti i js/ui/*.js + app.js. Cambia ad ogni modifica del bundle → invalida cache browser solo quando serve. Tollerante a file mancanti (best-effort). """ import hashlib targets = [ # Bundle globali (caricati in base.html su ogni pagina) static_dir / "app.css", static_dir / "css" / "ui-busy.css", static_dir / "js" / "ui" / "theme.js", static_dir / "js" / "ui" / "focus-trap.js", static_dir / "js" / "ui" / "toast.js", static_dir / "js" / "ui" / "dialog.js", static_dir / "js" / "ui" / "dropdown.js", static_dir / "js" / "ui" / "tabs.js", static_dir / "js" / "ui" / "ais-grade.js", static_dir / "js" / "app.js", # Per-page bundle (estratti dagli inline