File size: 4,782 Bytes
c90f7a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Custom error handlers to prevent server crashes from binary data in validation errors.

"""

import logging
from typing import Any, Dict
from fastapi import Request, status
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException

logger = logging.getLogger(__name__)


def sanitize_validation_error(error_detail: Any) -> Any:
    """

    Recursively sanitize validation error details to prevent binary data crashes.

    Converts bytes to safe string representations.

    """
    if isinstance(error_detail, bytes):
        # Convert bytes to safe hex representation
        try:
            # Try UTF-8 decode first
            return error_detail.decode('utf-8', errors='replace')
        except Exception:
            # Fall back to hex representation for binary data
            return f"<binary data: {len(error_detail)} bytes>"
    
    elif isinstance(error_detail, dict):
        return {k: sanitize_validation_error(v) for k, v in error_detail.items()}
    
    elif isinstance(error_detail, list):
        return [sanitize_validation_error(item) for item in error_detail]
    
    elif isinstance(error_detail, tuple):
        return tuple(sanitize_validation_error(item) for item in error_detail)
    
    else:
        # For other types, return as-is
        return error_detail


async def validation_exception_handler(

    request: Request, 

    exc: RequestValidationError

) -> JSONResponse:
    """

    Custom handler for RequestValidationError that prevents crashes from binary data.

    

    This replaces the default FastAPI handler which crashes when trying to

    JSON-encode validation errors containing binary data.

    """
    try:
        # Get the validation errors
        errors = exc.errors()
        
        # Sanitize each error to remove binary data
        sanitized_errors = []
        for error in errors:
            sanitized_error = {}
            for key, value in error.items():
                if key == 'input' and isinstance(value, bytes):
                    # Don't include large binary inputs in error response
                    sanitized_error[key] = f"<binary data: {len(value)} bytes>"
                else:
                    sanitized_error[key] = sanitize_validation_error(value)
            sanitized_errors.append(sanitized_error)
        
        # Log the error for debugging
        logger.warning(
            f"Validation error on {request.method} {request.url.path}: "
            f"{len(sanitized_errors)} error(s)"
        )
        
        return JSONResponse(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            content={
                "detail": sanitized_errors,
                "message": "Request validation failed. Please check your input data."
            },
        )
        
    except Exception as e:
        # If sanitization itself fails, return a generic error
        logger.error(f"Error in validation exception handler: {e}", exc_info=True)
        return JSONResponse(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            content={
                "detail": "Request validation failed",
                "message": "Invalid request format or content"
            },
        )


async def http_exception_handler(

    request: Request,

    exc: StarletteHTTPException

) -> JSONResponse:
    """

    Custom handler for HTTP exceptions with safe error serialization.

    """
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "detail": str(exc.detail),
            "message": "An error occurred processing your request"
        },
    )


async def general_exception_handler(

    request: Request,

    exc: Exception

) -> JSONResponse:
    """

    Catch-all exception handler to prevent unhandled crashes.

    NOTE: HTTPException should be handled by http_exception_handler, not here.

    """
    # Don't catch HTTPException here - let it be handled by http_exception_handler
    from fastapi import HTTPException as FastAPIHTTPException
    if isinstance(exc, (StarletteHTTPException, FastAPIHTTPException)):
        # This should not happen, but if it does, re-raise it
        raise exc
    
    logger.error(
        f"Unhandled exception on {request.method} {request.url.path}: {exc}",
        exc_info=True
    )
    
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content={
            "detail": "Internal server error",
            "message": "An unexpected error occurred. Please try again."
        },
    )