File size: 5,773 Bytes
4c4c8a0
3c8d218
1e24842
 
ef865f2
4c4c8a0
 
 
 
 
 
 
 
 
6817100
1e24842
518a750
1e24842
098f3ea
3c8d218
ef865f2
3c8d218
ef865f2
c6f3411
ef865f2
3c8d218
ef865f2
098f3ea
ef865f2
 
c6f3411
ef865f2
3f78860
1e24842
6270070
ef865f2
3c8d218
1e24842
 
 
 
 
 
 
 
 
 
 
 
 
 
ef865f2
 
 
3c8d218
ef865f2
 
1e24842
 
 
 
 
 
4c4c8a0
 
 
 
 
 
 
 
 
 
1e24842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef865f2
 
3c8d218
ef865f2
1e24842
 
 
 
 
 
 
 
 
 
 
 
 
 
3c8d218
 
ef865f2
3c8d218
c6f3411
 
3c8d218
 
1e24842
 
 
3c8d218
ef865f2
 
 
 
6270070
 
1e24842
 
098f3ea
1e24842
098f3ea
 
 
1e24842
 
 
 
 
 
 
 
6270070
 
ef865f2
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import logging
import os
import time
from pathlib import Path

# Force logging config AFTER uvicorn sets up its own β€” this runs at import time
# which is after uvicorn's dictConfig, so it takes precedence.
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    datefmt="%H:%M:%S",
    force=True,  # overrides any existing root-logger handlers
)


import jwt as _pyjwt

from cryptography.fernet import Fernet
from fastapi import Depends, FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded

from backend import database
from backend.core.auth import verify_token
from backend.core.config import settings
from backend.core.errors import AppError, app_error_handler
from backend.core.limiter import limiter
from backend.core.logging import get_logger
from backend.app.api.routes import specs, assets, sessions, history, chat, execution, auth, usage
import backend.app.api.routes.settings as llm_settings_router

logger = get_logger(__name__)

# Validate ENCRYPTION_KEY at startup β€” fail fast rather than silently storing plaintext
if not settings.ENCRYPTION_KEY:
    raise RuntimeError(
        "ENCRYPTION_KEY must be set in .env before starting the server. "
        "Generate one with: python -c \"from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())\""
    )
try:
    Fernet(settings.ENCRYPTION_KEY.encode())
except Exception:
    raise RuntimeError(
        "ENCRYPTION_KEY is invalid. "
        "Generate a valid one with: python -c \"from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())\""
    )

# Ensure upload directories exist
for category in ["audio", "video", "documents", "images", "specs"]:
    os.makedirs(os.path.join(settings.UPLOAD_DIR, category), exist_ok=True)

app = FastAPI(title="AI API Testing Assistant")
app.state.limiter = limiter


@app.middleware("http")
async def request_logger(request: Request, call_next):
    start = time.perf_counter()
    qs = f"?{request.url.query}" if request.url.query else ""
    logger.info("β†’ %s %s%s", request.method, request.url.path, qs)
    try:
        response = await call_next(request)
        ms = (time.perf_counter() - start) * 1000
        logger.info("← %s %s%s  %d  (%.0fms)", request.method, request.url.path, qs, response.status_code, ms)
        return response
    except Exception as exc:
        ms = (time.perf_counter() - start) * 1000
        logger.error("βœ— %s %s%s  ERROR  (%.0fms): %s", request.method, request.url.path, qs, ms, exc)
        raise


@app.middleware("http")
async def extract_user_state(request: Request, call_next):
    """Extract the JWT subject and store it in request.state.user so route handlers
    can read the current user without duplicating the verify_token dependency."""
    request.state.user = None
    auth_header = request.headers.get("Authorization", "")
    if auth_header.startswith("Bearer "):
        try:
            token = auth_header[7:]
            payload = _pyjwt.decode(token, settings.JWT_SECRET, algorithms=["HS256"])
            request.state.user = payload.get("sub")
        except Exception:
            pass
    return await call_next(request)


app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_exception_handler(AppError, app_error_handler)


@app.exception_handler(Exception)
async def unhandled_exception_handler(request: Request, exc: Exception):
    """Catch-all: log the traceback and return a CORS-safe 500 so the browser
    shows the real error instead of a misleading CORS-blocked message."""
    logger.exception("Unhandled 500 on %s %s", request.method, request.url.path)
    origin = request.headers.get("origin", "")
    cors_headers = (
        {"Access-Control-Allow-Origin": origin, "Access-Control-Allow-Credentials": "true"}
        if origin in settings.allowed_origins_list
        else {}
    )
    return JSONResponse(status_code=500, content={"detail": str(exc)}, headers=cors_headers)

# CORS β€” must be added after the custom HTTP middleware so it wraps all requests
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.allowed_origins_list,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
    allow_headers=["Content-Type", "Authorization"],
)

# Static file serving for uploads
app.mount("/uploads", StaticFiles(directory=settings.UPLOAD_DIR), name="uploads")


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    logger.warning("Validation error: %s", exc.errors())
    return JSONResponse(status_code=422, content={"detail": exc.errors()})


_V1 = "/api/v1"

# Public routes (no auth required)
app.include_router(auth.router, prefix=_V1)

# Protected routes β€” all require a valid JWT
_auth = [Depends(verify_token)]
app.include_router(specs.router,     prefix=_V1, dependencies=_auth)
app.include_router(assets.router,    prefix=_V1, dependencies=_auth)
app.include_router(sessions.router,  prefix=_V1, dependencies=_auth)
app.include_router(history.router,   prefix=_V1, dependencies=_auth)
app.include_router(chat.router,      prefix=_V1, dependencies=_auth)
app.include_router(execution.router, prefix=_V1, dependencies=_auth)
app.include_router(usage.router,     prefix=_V1, dependencies=_auth)
app.include_router(llm_settings_router.router, prefix=_V1, dependencies=_auth)


@app.get("/")
def health_check():
    return {"status": "ok", "message": "AI API Testing Tool Backend running."}