- Added `auth.py` for mock login and JWT issuance. - Introduced `chat.py` for handling chat requests with role-based access control. - Enhanced `main.py` to include new routers and middleware for tracing. - Implemented input validation in `input_guard.py` to prevent SQL injection. - Created repositories for managing agent sessions and audit logs. - Added exception handling for authorization errors. - Updated settings to include JWT configuration. - Introduced tests for authentication and input validation.
46 lines
1.7 KiB
Python
46 lines
1.7 KiB
Python
"""FastAPI 入口:挂载路由、中间件(JWT/RBAC)、生命周期。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from app.api.auth import router as auth_router
|
|
from app.api.chat import router as chat_router
|
|
from app.config.settings import settings
|
|
from app.middleware.trace import TraceMiddleware
|
|
from app.repository.audit_repository import AuditRepository
|
|
from app.utils.exceptions import AppError
|
|
from app.utils.response import fail
|
|
|
|
app = FastAPI(title="JinRong Agent Platform", version="0.1.0")
|
|
app.add_middleware(TraceMiddleware)
|
|
app.include_router(auth_router)
|
|
app.include_router(chat_router)
|
|
|
|
|
|
@app.get("/health")
|
|
def health(request: Request):
|
|
trace_id = getattr(request.state, "trace_id", "unknown")
|
|
return {"status": "ok", "env": settings.app_env, "trace_id": trace_id}
|
|
|
|
|
|
@app.exception_handler(AppError)
|
|
async def app_error_handler(request: Request, exc: AppError):
|
|
trace_id = getattr(request.state, "trace_id", "unknown")
|
|
if exc.audit_event:
|
|
agent_type = request.headers.get("X-Agent-Type", "platform")
|
|
try:
|
|
AuditRepository().insert(
|
|
trace_id=trace_id,
|
|
event_type=exc.audit_event,
|
|
agent_type=agent_type if agent_type in ("customer", "advisor", "analyst", "risk") else "platform",
|
|
actor_id="anonymous",
|
|
decision=exc.error_code,
|
|
input_summary={"message": exc.message},
|
|
)
|
|
except Exception:
|
|
pass
|
|
body = fail(exc.code, exc.message, trace_id, data={"error_code": exc.error_code})
|
|
return JSONResponse(status_code=exc.http_status, content=body.model_dump())
|