Skip to content

ccproxy.api.middleware

ccproxy.api.middleware

API middleware for CCProxy API Server.

get_cors_config

get_cors_config(settings)

Get CORS configuration dictionary.

Parameters:

Name Type Description Default
settings Settings

Application settings containing CORS configuration

required

Returns:

Type Description
dict[str, Any]

Dictionary containing CORS configuration

Source code in ccproxy/api/middleware/cors.py
def get_cors_config(settings: Settings) -> dict[str, Any]:
    """Get CORS configuration dictionary.

    Args:
        settings: Application settings containing CORS configuration

    Returns:
        Dictionary containing CORS configuration
    """
    return {
        "allow_origins": settings.cors.origins,
        "allow_credentials": settings.cors.credentials,
        "allow_methods": settings.cors.methods,
        "allow_headers": settings.cors.headers,
        "allow_origin_regex": settings.cors.origin_regex,
        "expose_headers": settings.cors.expose_headers,
        "max_age": settings.cors.max_age,
    }

setup_cors_middleware

setup_cors_middleware(app, settings)

Setup CORS middleware for the FastAPI application.

Parameters:

Name Type Description Default
app FastAPI

FastAPI application instance

required
settings Settings

Application settings containing CORS configuration

required
Source code in ccproxy/api/middleware/cors.py
def setup_cors_middleware(app: FastAPI, settings: Settings) -> None:
    """Setup CORS middleware for the FastAPI application.

    Args:
        app: FastAPI application instance
        settings: Application settings containing CORS configuration
    """

    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.cors.origins,
        allow_credentials=settings.cors.credentials,
        allow_methods=settings.cors.methods,
        allow_headers=settings.cors.headers,
        allow_origin_regex=settings.cors.origin_regex,
        expose_headers=settings.cors.expose_headers,
        max_age=settings.cors.max_age,
    )

    logger.debug(
        "cors_middleware_configured",
        origins=settings.cors.origins,
        category="middleware",
    )

setup_error_handlers

setup_error_handlers(app)

Setup error handlers for the FastAPI application.

Parameters:

Name Type Description Default
app FastAPI

FastAPI application instance

required
Source code in ccproxy/api/middleware/errors.py
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
def setup_error_handlers(app: FastAPI) -> None:
    """Setup error handlers for the FastAPI application.

    Args:
        app: FastAPI application instance
    """
    logger.debug("error_handlers_setup_start", category="lifecycle")

    # Metrics are now handled by the metrics plugin via hooks
    metrics = None

    # Define error type mappings with status codes and error types
    ERROR_MAPPINGS: dict[type[Exception], tuple[int | None, str]] = {
        ClaudeProxyError: (None, "claude_proxy_error"),  # Uses exc.status_code
        ValidationError: (400, "validation_error"),
        AuthenticationError: (401, "authentication_error"),
        ProxyAuthenticationError: (401, "proxy_authentication_error"),
        PermissionError: (403, "permission_error"),
        NotFoundError: (404, "not_found_error"),
        ModelNotFoundError: (404, "model_not_found_error"),
        TimeoutError: (408, "timeout_error"),
        RateLimitError: (429, "rate_limit_error"),
        ProxyError: (500, "proxy_error"),
        TransformationError: (500, "transformation_error"),
        MiddlewareError: (500, "middleware_error"),
        DockerError: (500, "docker_error"),
        ProxyConnectionError: (502, "proxy_connection_error"),
        ServiceUnavailableError: (503, "service_unavailable_error"),
        ProxyTimeoutError: (504, "proxy_timeout_error"),
    }

    async def unified_error_handler(
        request: Request,
        exc: Exception,
        status_code: int | None = None,
        error_type: str | None = None,
        include_client_info: bool = False,
    ) -> JSONResponse:
        """Unified error handler for all exception types.

        Args:
            request: The incoming request
            exc: The exception that was raised
            status_code: HTTP status code to return
            error_type: Type of error for logging and response
            include_client_info: Whether to include client IP in logs
        """
        # Get status code from exception if it has one
        if status_code is None:
            status_code = getattr(exc, "status_code", 500)

        # Determine error type if not provided
        if error_type is None:
            error_type = getattr(exc, "error_type", "unknown_error")

        # Get request ID from request state or headers
        request_id = getattr(request.state, "request_id", None) or request.headers.get(
            "x-request-id"
        )

        # Store status code in request state for access logging
        if hasattr(request.state, "context") and hasattr(
            request.state.context, "metadata"
        ):
            request.state.context.metadata["status_code"] = status_code

        # Build log kwargs
        log_kwargs = {
            "error_type": error_type,
            "error_message": str(exc),
            "status_code": status_code,
            "request_method": request.method,
            "request_url": str(request.url.path),
        }

        # Add client info if needed (for auth errors)
        if include_client_info and request.client:
            log_kwargs["client_ip"] = request.client.host
            if error_type in ("authentication_error", "proxy_authentication_error"):
                log_kwargs["user_agent"] = request.headers.get("user-agent", "unknown")

        # Log the error
        logger.error(
            f"{error_type.replace('_', ' ').title()}",
            **log_kwargs,
            category="middleware",
        )

        # Record error in metrics
        if metrics:
            metrics.record_error(
                error_type=error_type,
                endpoint=str(request.url.path),
                model=None,
                service_type="middleware",
            )

        # Prepare headers with x-request-id if available
        headers = {}
        if request_id:
            headers["x-request-id"] = request_id

        # Detect format from request context for format-aware error responses
        base_format = None
        try:
            if hasattr(request.state, "context") and hasattr(
                request.state.context, "format_chain"
            ):
                format_chain = request.state.context.format_chain
                if format_chain and len(format_chain) > 0:
                    base_format = format_chain[
                        0
                    ]  # First format is the client's expected format
                    logger.debug(
                        "format_aware_error_detected",
                        base_format=base_format,
                        format_chain=format_chain,
                        category="middleware",
                    )
        except Exception as e:
            logger.debug("format_detection_failed", error=str(e), category="middleware")

        # Get format-aware error content
        error_content = _get_format_aware_error_content(
            error_type=error_type,
            message=str(exc),
            status_code=status_code,
            base_format=base_format,
        )

        # Return JSON response with format-aware content
        return JSONResponse(
            status_code=status_code,
            content=error_content,
            headers=headers,
        )

    # Register specific error handlers using the unified handler
    for exc_class, (status, err_type) in ERROR_MAPPINGS.items():
        # Determine if this error type should include client info
        include_client = err_type in (
            "authentication_error",
            "proxy_authentication_error",
            "permission_error",
            "rate_limit_error",
        )

        # Create a closure to capture the specific error configuration
        def make_handler(
            status_code: int | None, error_type: str, include_client_info: bool
        ) -> Callable[[Request, Exception], Awaitable[JSONResponse]]:
            async def handler(request: Request, exc: Exception) -> JSONResponse:
                return await unified_error_handler(
                    request, exc, status_code, error_type, include_client_info
                )

            return handler

        # Register the handler
        app.exception_handler(exc_class)(make_handler(status, err_type, include_client))

    # FastAPI validation errors
    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(
        request: Request, exc: RequestValidationError
    ) -> JSONResponse:
        """Handle FastAPI request validation errors with format awareness."""
        # Get request ID from request state or headers
        request_id = getattr(request.state, "request_id", None) or request.headers.get(
            "x-request-id"
        )

        # Try to get format from request context (set by middleware)
        base_format = None
        try:
            if hasattr(request.state, "context") and hasattr(
                request.state.context, "format_chain"
            ):
                format_chain = request.state.context.format_chain
                if format_chain and len(format_chain) > 0:
                    base_format = format_chain[0]
        except Exception:
            pass  # Fallback to path detection if needed

        # Fallback: detect format from path if context isn't available
        if base_format is None:
            base_format = _detect_format_from_path(str(request.url.path))

        # Create a readable error message from validation errors
        error_details = []
        for error in exc.errors():
            loc = " -> ".join(str(x) for x in error["loc"])
            error_details.append(f"{loc}: {error['msg']}")

        error_message = "; ".join(error_details)

        # Log the validation error
        logger.warning(
            "Request validation error",
            error_type="validation_error",
            error_message=error_message,
            status_code=422,
            request_method=request.method,
            request_url=str(request.url.path),
            base_format=base_format,
            category="middleware",
        )

        # Prepare headers with x-request-id if available
        headers = {}
        if request_id:
            headers["x-request-id"] = request_id

        # Get format-aware error content
        error_content = _get_format_aware_error_content(
            error_type="validation_error",
            message=error_message,
            status_code=422,
            base_format=base_format,
        )

        return JSONResponse(
            status_code=422,
            content=error_content,
            headers=headers,
        )

    # Standard HTTP exceptions
    @app.exception_handler(HTTPException)
    async def http_exception_handler(
        request: Request, exc: HTTPException
    ) -> JSONResponse:
        """Handle HTTP exceptions."""
        # Get request ID from request state or headers
        request_id = getattr(request.state, "request_id", None) or request.headers.get(
            "x-request-id"
        )

        # Store status code in request state for access logging
        if hasattr(request.state, "context") and hasattr(
            request.state.context, "metadata"
        ):
            request.state.context.metadata["status_code"] = exc.status_code

        # Don't log stack trace for expected errors (404, 401)
        if exc.status_code in (404, 401):
            log_func = logger.debug if exc.status_code == 404 else logger.warning

            log_func(
                f"HTTP {exc.status_code} error",
                error_type=f"http_{exc.status_code}",
                error_message=exc.detail,
                status_code=exc.status_code,
                request_method=request.method,
                request_url=str(request.url.path),
                category="middleware",
            )
        else:
            # Log with basic stack trace (no local variables)
            stack_trace = traceback.format_exc(limit=5)  # Limit to 5 frames

            logger.error(
                "HTTP exception",
                error_type="http_error",
                error_message=exc.detail,
                status_code=exc.status_code,
                request_method=request.method,
                request_url=str(request.url.path),
                stack_trace=stack_trace,
                category="middleware",
            )

        # Record error in metrics
        if metrics:
            if exc.status_code == 404:
                error_type = "http_404"
            elif exc.status_code == 401:
                error_type = "http_401"
            else:
                error_type = "http_error"
            metrics.record_error(
                error_type=error_type,
                endpoint=str(request.url.path),
                model=None,
                service_type="middleware",
            )

        # Prepare headers with x-request-id if available
        headers = {}
        if request_id:
            headers["x-request-id"] = request_id

        # Detect format from request context for format-aware error responses
        base_format = None
        try:
            if hasattr(request.state, "context") and hasattr(
                request.state.context, "format_chain"
            ):
                format_chain = request.state.context.format_chain
                if format_chain and len(format_chain) > 0:
                    base_format = format_chain[0]
        except Exception:
            pass  # Ignore format detection errors

        # Determine error type for format-aware response
        if exc.status_code == 404:
            error_type = "not_found"
        elif exc.status_code == 401:
            error_type = "authentication_error"
        else:
            error_type = "http_error"

        # Get format-aware error content
        error_content = _get_format_aware_error_content(
            error_type=error_type,
            message=exc.detail,
            status_code=exc.status_code,
            base_format=base_format,
        )

        return JSONResponse(
            status_code=exc.status_code,
            content=error_content,
            headers=headers,
        )

    @app.exception_handler(StarletteHTTPException)
    async def starlette_http_exception_handler(
        request: Request, exc: StarletteHTTPException
    ) -> JSONResponse:
        """Handle Starlette HTTP exceptions."""
        # Get request ID from request state or headers
        request_id = getattr(request.state, "request_id", None) or request.headers.get(
            "x-request-id"
        )

        # Don't log stack trace for 404 errors as they're expected
        if exc.status_code == 404:
            logger.debug(
                "Starlette HTTP 404 error",
                error_type="starlette_http_404",
                error_message=exc.detail,
                status_code=404,
                request_method=request.method,
                request_url=str(request.url.path),
                category="middleware",
            )
        else:
            logger.error(
                "Starlette HTTP exception",
                error_type="starlette_http_error",
                error_message=exc.detail,
                status_code=exc.status_code,
                request_method=request.method,
                request_url=str(request.url.path),
                category="middleware",
            )

        # Record error in metrics
        if metrics:
            error_type = (
                "starlette_http_404"
                if exc.status_code == 404
                else "starlette_http_error"
            )
            metrics.record_error(
                error_type=error_type,
                endpoint=str(request.url.path),
                model=None,
                service_type="middleware",
            )

        # Prepare headers with x-request-id if available
        headers = {}
        if request_id:
            headers["x-request-id"] = request_id

        # Detect format from request context for format-aware error responses
        base_format = None
        try:
            if hasattr(request.state, "context") and hasattr(
                request.state.context, "format_chain"
            ):
                format_chain = request.state.context.format_chain
                if format_chain and len(format_chain) > 0:
                    base_format = format_chain[0]
        except Exception:
            pass  # Ignore format detection errors

        # Determine error type for format-aware response
        if exc.status_code == 404:
            error_type = "not_found"
        else:
            error_type = "http_error"

        # Get format-aware error content
        error_content = _get_format_aware_error_content(
            error_type=error_type,
            message=exc.detail,
            status_code=exc.status_code,
            base_format=base_format,
        )

        return JSONResponse(
            status_code=exc.status_code,
            content=error_content,
            headers=headers,
        )

    # Global exception handler
    @app.exception_handler(Exception)
    async def global_exception_handler(
        request: Request, exc: Exception
    ) -> JSONResponse:
        """Handle all other unhandled exceptions."""
        # Get request ID from request state or headers
        request_id = getattr(request.state, "request_id", None) or request.headers.get(
            "x-request-id"
        )

        # Store status code in request state for access logging
        if hasattr(request.state, "context") and hasattr(
            request.state.context, "metadata"
        ):
            request.state.context.metadata["status_code"] = 500

        logger.error(
            "Unhandled exception",
            error_type="unhandled_exception",
            error_message=str(exc),
            status_code=500,
            request_method=request.method,
            request_url=str(request.url.path),
            exc_info=True,
            category="middleware",
        )

        # Record error in metrics
        if metrics:
            metrics.record_error(
                error_type="unhandled_exception",
                endpoint=str(request.url.path),
                model=None,
                service_type="middleware",
            )

        # Prepare headers with x-request-id if available
        headers = {}
        if request_id:
            headers["x-request-id"] = request_id

        # Detect format from request context for format-aware error responses
        base_format = None
        try:
            if hasattr(request.state, "context") and hasattr(
                request.state.context, "format_chain"
            ):
                format_chain = request.state.context.format_chain
                if format_chain and len(format_chain) > 0:
                    base_format = format_chain[0]
        except Exception:
            pass  # Ignore format detection errors

        # Get format-aware error content for internal server error
        error_content = _get_format_aware_error_content(
            error_type="internal_server_error",
            message="An internal server error occurred",
            status_code=500,
            base_format=base_format,
        )

        return JSONResponse(
            status_code=500,
            content=error_content,
            headers=headers,
        )

    logger.debug("error_handlers_setup_completed", category="lifecycle")