basyx commited on
Commit
f0b0f29
·
verified ·
1 Parent(s): 96a740e

fix: return proper HTTP status for security errors

Browse files
Files changed (1) hide show
  1. main.py +32 -0
main.py CHANGED
@@ -40,6 +40,7 @@ from app.core.response import ErrorBody, ErrorResponse
40
  from app.mcp.server import create_mcp_server
41
  from app.projects import api as projects
42
  from app.security.middleware import APIKeyAuthenticationMiddleware
 
43
  from app.social.workers.scheduler import SocialSchedulerWorker
44
  from app.templates import marketplace_api
45
  from app.workers.cleanup_worker import CleanupWorker
@@ -228,6 +229,37 @@ def create_app(settings: Settings | None = None) -> FastAPI:
228
  )
229
  return DefaultJSONResponse(body.model_dump(), status_code=exc.status_code)
230
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  @application.exception_handler(Exception)
232
  async def unexpected_error_handler(request: Request, exc: Exception) -> JSONResponse:
233
  logger.exception("unhandled request error", extra={"operation": request.state.operation})
 
40
  from app.mcp.server import create_mcp_server
41
  from app.projects import api as projects
42
  from app.security.middleware import APIKeyAuthenticationMiddleware
43
+ from app.security.errors import APIKeyConflictError, APIKeyNotFoundError, ForbiddenError, RateLimitError, SecurityError, UnauthorizedError
44
  from app.social.workers.scheduler import SocialSchedulerWorker
45
  from app.templates import marketplace_api
46
  from app.workers.cleanup_worker import CleanupWorker
 
229
  )
230
  return DefaultJSONResponse(body.model_dump(), status_code=exc.status_code)
231
 
232
+ @application.exception_handler(SecurityError)
233
+ async def security_error_handler(request: Request, exc: SecurityError) -> JSONResponse:
234
+ # Security-domain errors can be raised by endpoint services as well as
235
+ # the authentication middleware. Map them explicitly so an expected
236
+ # authorization failure never leaks out as an opaque HTTP 500.
237
+ status_code = 403
238
+ message = "Security policy rejected the request."
239
+ headers: dict[str, str] = {}
240
+ if isinstance(exc, UnauthorizedError):
241
+ status_code = 401
242
+ message = "Invalid or expired API key."
243
+ headers["WWW-Authenticate"] = "Bearer"
244
+ elif isinstance(exc, ForbiddenError):
245
+ status_code = 403
246
+ message = "Missing required scope or active workspace membership."
247
+ elif isinstance(exc, RateLimitError):
248
+ status_code = 429
249
+ message = "Rate limit exceeded."
250
+ headers["Retry-After"] = str(exc.retry_after)
251
+ elif isinstance(exc, APIKeyNotFoundError):
252
+ status_code = 404
253
+ message = "API key not found."
254
+ elif isinstance(exc, APIKeyConflictError):
255
+ status_code = 409
256
+ message = str(exc) or "API key conflict."
257
+ body = ErrorResponse(
258
+ request_id=request.state.request_id,
259
+ error=ErrorBody(code=type(exc).__name__.upper(), message=message),
260
+ )
261
+ return DefaultJSONResponse(body.model_dump(), status_code=status_code, headers=headers)
262
+
263
  @application.exception_handler(Exception)
264
  async def unexpected_error_handler(request: Request, exc: Exception) -> JSONResponse:
265
  logger.exception("unhandled request error", extra={"operation": request.state.operation})