1"""FastAPI application: /api/v1 (OpenAPI at /api/v1/openapi.json, docs at /api/docs), /metrics, static console."""2from __future__ import annotations34import time5import uuid6from pathlib import Path78from fastapi import Depends, FastAPI, Request9from fastapi.exceptions import RequestValidationError10from fastapi.responses import JSONResponse, Response11from fastapi.staticfiles import StaticFiles12from findata_core.config import get_settings13from findata_core.logging import configure_logging, get_logger14from starlette.exceptions import HTTPException as StarletteHTTPException15from starlette.middleware.base import BaseHTTPMiddleware1617from findata_api import auth as A18from findata_api import metrics as M19from findata_api.ratelimit import bucket20from findata_api.routers import (21 admin,22 auth,23 catalog,24 coverage,25 exports,26 fundamentals,27 health,28 instruments,29 market,30 quality,31 query,32)3334API_PREFIX = "/api/v1"353637class Observability(BaseHTTPMiddleware):38 async def dispatch(self, request: Request, call_next):39 rid = request.headers.get("x-request-id") or uuid.uuid4().hex[:16]40 request.state.request_id = rid41 t0 = time.monotonic()42 route = request.url.path43 try:44 response = await call_next(request)45 except Exception:46 M.REQUESTS.labels(request.method, route, "500").inc()47 raise48 dt = time.monotonic() - t049 if route.startswith(API_PREFIX):50 M.REQUESTS.labels(request.method, _route_label(route), str(response.status_code)).inc()51 M.LATENCY.labels(_route_label(route)).observe(dt)52 response.headers["X-Request-ID"] = rid53 response.headers["X-Content-Type-Options"] = "nosniff"54 response.headers["X-Frame-Options"] = "DENY"55 response.headers["Referrer-Policy"] = "no-referrer"56 response.headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()"57 if get_settings().is_production:58 response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"59 if not route.startswith("/api/docs"):60 response.headers["Content-Security-Policy"] = ("default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; "61 "script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'")62 return response636465def _route_label(path: str) -> str:66 parts = path.split("/")67 return "/".join(p if not _looks_id(p) else "{id}" for p in parts[:6])686970def _looks_id(p: str) -> bool:71 return len(p) >= 16 and all(c in "0123456789abcdef-" for c in p)727374class RateLimit(BaseHTTPMiddleware):75 async def dispatch(self, request: Request, call_next):76 if request.url.path.startswith(API_PREFIX) and not request.url.path.endswith("/health"):77 auth_h = request.headers.get("authorization", "")78 key = auth_h[-24:] if auth_h else (request.cookies.get(A.SESSION_COOKIE, "")[-24:] or (request.client.host if request.client else "anon"))79 ok, remaining = bucket.allow(f"rl:{key}", get_settings().rate_limit_per_minute)80 if not ok:81 return JSONResponse({"error": {"code": "rate_limited", "message": "Too many requests", "request_id": getattr(request.state, "request_id", None)}},82 status_code=429, headers={"Retry-After": "5"})83 return await call_next(request)848586def create_app() -> FastAPI:87 s = get_settings()88 configure_logging()89 log = get_logger("api")90 app = FastAPI(title="FinData OS API", version="1.0.0", openapi_url=f"{API_PREFIX}/openapi.json", docs_url="/api/docs", redoc_url=None,91 description="Private, research-grade financial data lakehouse. All market data © FirstRate Data — no redistribution. "92 "Timestamps are UTC ISO-8601; bars are stamped at bar **open**.")93 app.add_middleware(Observability)94 app.add_middleware(RateLimit)9596 @app.exception_handler(StarletteHTTPException)97 async def http_exc(request: Request, exc: StarletteHTTPException):98 detail = exc.detail if isinstance(exc.detail, dict) else {"code": "http_error", "message": str(exc.detail)}99 detail["request_id"] = getattr(request.state, "request_id", None)100 return JSONResponse({"error": detail}, status_code=exc.status_code, headers=getattr(exc, "headers", None))101102 @app.exception_handler(RequestValidationError)103 async def val_exc(request: Request, exc: RequestValidationError):104 return JSONResponse({"error": {"code": "validation_error", "message": "Invalid request", "details": exc.errors(),105 "request_id": getattr(request.state, "request_id", None)}}, status_code=422)106107 @app.exception_handler(Exception)108 async def any_exc(request: Request, exc: Exception):109 from findata_core.redact import redact110 log.error("unhandled", error=redact(repr(exc), s.secret_values()), path=request.url.path)111 return JSONResponse({"error": {"code": "internal_error", "message": "Internal error", "request_id": getattr(request.state, "request_id", None)}}, status_code=500)112113 for r in (auth.router, catalog.router, instruments.router, market.router, fundamentals.router, query.router, exports.router,114 coverage.router, quality.router, health.router, admin.router):115 app.include_router(r, prefix=API_PREFIX)116117 @app.get("/metrics", include_in_schema=False)118 def metrics(request: Request, p: A.Principal = Depends(A.get_principal)):119 host = request.client.host if request.client else ""120 private = host in ("127.0.0.1", "::1") or host.startswith(("192.168.", "10.67.", "10.", "172.16."))121 if not private and not p.has("admin"):122 return JSONResponse({"error": {"code": "forbidden", "message": "metrics require admin or a private network"}}, status_code=403)123 from findata_api.health import evaluate124 evaluate()125 body, ctype = M.render()126 return Response(body, media_type=ctype)127128 web = s.web_dist or Path(s.root) / "apps" / "web" / "out"129 if web.exists():130 app.mount("/", StaticFiles(directory=str(web), html=True), name="web")131 log.info("web.mounted", path=str(web))132 else:133 @app.get("/", include_in_schema=False)134 def root():135 return {"service": "FinData OS", "docs": "/api/docs", "note": "web console not built"}136 return app137138139app = create_app()140