from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from contextlib import asynccontextmanager from app.core.config import settings from app.db.session import engine from app.models.models import Base @asynccontextmanager async def lifespan(app: FastAPI): # Create tables on startup (dev only — use Alembic in production) async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) yield await engine.dispose() app = FastAPI( title=settings.PROJECT_NAME, version=settings.VERSION, lifespan=lifespan, ) # The app is normally served same-origin (nginx proxies /api to the backend), # so CORS is not exercised in the primary flow. This allowlist exists for direct # browser access to :8000 during development and for any explicitly configured # origins. Extra origins can be added via the CORS_ORIGINS env var (comma-separated). _extra_origins = [o.strip() for o in (settings.CORS_ORIGINS or "").split(",") if o.strip()] app.add_middleware( CORSMiddleware, allow_origins=["http://localhost:3000", "http://frontend:3000", *_extra_origins], # Also allow localhost and private-network hosts on any port (dev convenience). allow_origin_regex=r"^https?://(localhost|127\.0\.0\.1|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+)(:\d+)?$", allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # ─── Routes ─────────────────────────────────────────────────────────────────── from app.api.routes import auth, dashboard, findings, reports, attack_paths, footprint, ai as ai_routes, scanning app.include_router(auth.router, prefix=settings.API_V1_STR) app.include_router(dashboard.router, prefix=settings.API_V1_STR) app.include_router(findings.router, prefix=settings.API_V1_STR) app.include_router(reports.router, prefix=settings.API_V1_STR) app.include_router(attack_paths.router, prefix=settings.API_V1_STR) app.include_router(footprint.router, prefix=settings.API_V1_STR) app.include_router(ai_routes.router, prefix=settings.API_V1_STR) app.include_router(scanning.router, prefix=settings.API_V1_STR) @app.get("/health") async def health(): return {"status": "ok", "service": settings.PROJECT_NAME, "version": settings.VERSION}