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 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
"""
Error Response Enforcement Middleware

This middleware ensures that all errors thrown by the application
are properly formatted using the standardized ErrorResponse structure.
"""

import traceback
from typing import Dict

from fastapi import HTTPException, Request, Response
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.middleware.base import BaseHTTPMiddleware

from core.api_models import create_error_response
from core.logging import log_error


class ErrorResponseMiddleware(BaseHTTPMiddleware):
    """
    Middleware to enforce consistent error response format across the application.

    This middleware catches all exceptions and ensures they return a standardized
    error response format, regardless of where they originate in the application.
    """

    def __init__(self, app, debug: bool = False):
        super().__init__(app)
        self.debug = debug

    async def dispatch(self, request: Request, call_next):
        try:
            response = await call_next(request)

            # Check if response is already a standardized error response
            if self._is_standard_error_response(response):
                return response

            return response

        except HTTPException as exc:
            return self._handle_http_exception(request, exc)

        except StarletteHTTPException as exc:
            return self._handle_starlette_exception(request, exc)

        except Exception as exc:
            return self._handle_unexpected_exception(request, exc)

    def _is_standard_error_response(self, response: Response) -> bool:
        """Check if response is already in standard error format"""
        if not isinstance(response, JSONResponse):
            return False

        try:
            content = response.body.decode() if hasattr(response, "body") else {}
            if isinstance(content, str):
                import json

                content = json.loads(content)

            return (
                isinstance(content, dict)
                and "error" in content
                and isinstance(content["error"], dict)
                and "type" in content["error"]
                and "status_code" in content["error"]
                and "detail" in content["error"]
            )
        except (json.JSONDecodeError, AttributeError, KeyError):
            return False

    def _handle_http_exception(
        self, request: Request, exc: HTTPException
    ) -> JSONResponse:
        """Handle HTTPException with standardized response"""
        # Determine error type based on status code
        error_type = self._get_error_type_from_status(exc.status_code)

        # Log the error
        log_error(
            "http_exception",
            f"HTTP {exc.status_code}: {exc.detail}",
            {
                "status_code": exc.status_code,
                "path": str(request.url.path),
                "method": request.method,
                "client_ip": request.client.host if request.client else None,
                "error_type": error_type,
            },
        )

        # Create standardized error response
        error_response = create_error_response(
            status_code=exc.status_code,
            detail=exc.detail,
            error_type=error_type,
            request=request,
        )

        return JSONResponse(
            status_code=exc.status_code,
            content=error_response,
            headers=self._get_security_headers(),
        )

    def _handle_starlette_exception(
        self, request: Request, exc: StarletteHTTPException
    ) -> JSONResponse:
        """Handle Starlette HTTPException with standardized response"""
        error_type = self._get_error_type_from_status(exc.status_code)

        # Log the error
        log_error(
            "starlette_exception",
            f"Starlette HTTP {exc.status_code}: {exc.detail}",
            {
                "status_code": exc.status_code,
                "path": str(request.url.path),
                "method": request.method,
                "client_ip": request.client.host if request.client else None,
                "error_type": error_type,
            },
        )

        # Create standardized error response
        error_response = create_error_response(
            status_code=exc.status_code,
            detail=exc.detail,
            error_type=error_type,
            request=request,
        )

        return JSONResponse(
            status_code=exc.status_code,
            content=error_response,
            headers=self._get_security_headers(),
        )

    def _handle_unexpected_exception(
        self, request: Request, exc: Exception
    ) -> JSONResponse:
        """Handle unexpected exceptions with standardized response"""
        # Log the full error
        error_details = {
            "type": type(exc).__name__,
            "message": str(exc),
            "traceback": traceback.format_exc(),
            "path": str(request.url.path),
            "method": request.method,
            "client_ip": request.client.host if request.client else None,
        }

        log_error("unexpected_error", f"Unexpected error: {exc!s}", error_details)

        # Determine error response based on debug mode
        if self.debug:
            # Show full details in development
            detail = f"Internal server error: {exc!s}"
            error_response = create_error_response(
                status_code=500,
                detail=detail,
                error_type="unexpected_error",
                request=request,
            )

            # Add debug information
            if isinstance(error_response, dict) and "error" in error_response:
                error_response["error"]["debug"] = {
                    "exception_type": type(exc).__name__,
                    "traceback": traceback.format_exc(),
                }
        else:
            # Hide internal details in production
            error_response = create_error_response(
                status_code=500,
                detail="Internal server error",
                error_type="internal_server_error",
                request=request,
            )

        return JSONResponse(
            status_code=500,
            content=error_response,
            headers=self._get_security_headers(),
        )

    def _get_error_type_from_status(self, status_code: int) -> str:
        """Map HTTP status codes to error types"""
        error_mapping = {
            400: "bad_request",
            401: "unauthorized",
            403: "forbidden",
            404: "not_found",
            405: "method_not_allowed",
            409: "conflict",
            422: "validation_error",
            429: "rate_limit_exceeded",
            500: "internal_server_error",
            502: "bad_gateway",
            503: "service_unavailable",
            504: "gateway_timeout",
        }
        return error_mapping.get(status_code, "http_error")

    def _get_security_headers(self) -> Dict[str, str]:
        """Get security headers for error responses"""
        return {
            "X-Content-Type-Options": "nosniff",
            "X-Frame-Options": "DENY",
            "X-XSS-Protection": "1; mode=block",
            "Cache-Control": "no-store, no-cache, must-revalidate",
            "Pragma": "no-cache",
        }


class ValidationErrorMiddleware(BaseHTTPMiddleware):
    """
    Specialized middleware for handling validation errors from Pydantic models.
    Ensures consistent error format for request validation failures.
    """

    async def dispatch(self, request: Request, call_next):
        try:
            response = await call_next(request)
            return response
        except Exception as exc:
            # Check if this is a validation error
            if self._is_validation_error(exc):
                return self._handle_validation_error(request, exc)
            # Let other errors be handled by the main error middleware
            raise

    def _is_validation_error(self, exc: Exception) -> bool:
        """Check if exception is a validation error"""
        from fastapi.exceptions import RequestValidationError
        from pydantic import ValidationError

        return isinstance(exc, (ValidationError, RequestValidationError))

    def _handle_validation_error(
        self, request: Request, exc: Exception
    ) -> JSONResponse:
        """Handle validation errors with detailed response"""
        from fastapi.exceptions import RequestValidationError
        from pydantic import ValidationError

        # Extract validation details
        if isinstance(exc, ValidationError):
            validation_details = [
                {
                    "field": ".".join(str(x) for x in loc),
                    "message": msg,
                    "type": error_type,
                }
                for loc, msg, error_type in exc.errors()
            ]
        elif isinstance(exc, RequestValidationError):
            validation_details = [
                {
                    "field": ".".join(str(x) for x in loc),
                    "message": msg,
                    "type": error_type,
                }
                for loc, msg, error_type in exc.errors()
            ]
        else:
            validation_details = [
                {
                    "field": "unknown",
                    "message": str(exc),
                    "type": "validation_error",
                }
            ]

        # Log validation error
        log_error(
            "validation_error",
            f"Request validation failed: {exc!s}",
            {
                "path": str(request.url.path),
                "method": request.method,
                "validation_errors": validation_details,
                "client_ip": request.client.host if request.client else None,
            },
        )

        # Create standardized error response
        error_response = create_error_response(
            status_code=422,
            detail="Request validation failed",
            error_type="validation_error",
            request=request,
            details=validation_details,
        )

        return JSONResponse(
            status_code=422,
            content=error_response,
            headers=self._get_security_headers(),
        )

    def _get_security_headers(self) -> Dict[str, str]:
        """Get security headers for validation error responses"""
        return {
            "X-Content-Type-Options": "nosniff",
            "X-Frame-Options": "DENY",
            "X-XSS-Protection": "1; mode=block",
        }


class BusinessErrorMiddleware(BaseHTTPMiddleware):
    """
    Middleware for handling business logic errors with proper HTTP mapping.

    This middleware catches custom business exceptions and maps them to
    appropriate HTTP responses with standardized error format.
    """

    def __init__(self, app):
        super().__init__(app)
        self._business_error_mapping = {
            "UserNotFoundError": (404, "user_not_found", "User not found"),
            "InvalidCredentialsError": (
                401,
                "invalid_credentials",
                "Invalid credentials",
            ),
            "AccountLockedError": (423, "account_locked", "Account is locked"),
            "InsufficientPermissionsError": (
                403,
                "insufficient_permissions",
                "Insufficient permissions",
            ),
            "ResourceNotFoundError": (404, "resource_not_found", "Resource not found"),
            "ResourceConflictError": (409, "resource_conflict", "Resource conflict"),
            "BusinessRuleViolationError": (
                422,
                "business_rule_violation",
                "Business rule violation",
            ),
            "RateLimitExceededError": (
                429,
                "rate_limit_exceeded",
                "Rate limit exceeded",
            ),
            "ServiceUnavailableError": (
                503,
                "service_unavailable",
                "Service temporarily unavailable",
            ),
        }

    async def dispatch(self, request: Request, call_next):
        try:
            response = await call_next(request)
            return response
        except Exception as exc:
            # Check if this is a known business error
            error_name = type(exc).__name__
            if error_name in self._business_error_mapping:
                return self._handle_business_error(request, exc, error_name)
            # Let other errors be handled by other middleware
            raise

    def _handle_business_error(
        self, request: Request, exc: Exception, error_name: str
    ) -> JSONResponse:
        """Handle known business errors with standardized response"""
        status_code, error_type, default_message = self._business_error_mapping[
            error_name
        ]

        # Use exception message if available, otherwise use default
        detail = str(exc) if str(exc) else default_message

        # Log business error
        log_error(
            "business_error",
            f"Business error: {error_name} - {detail}",
            {
                "error_name": error_name,
                "status_code": status_code,
                "path": str(request.url.path),
                "method": request.method,
                "client_ip": request.client.host if request.client else None,
            },
        )

        # Create standardized error response
        error_response = create_error_response(
            status_code=status_code,
            detail=detail,
            error_type=error_type,
            request=request,
        )

        return JSONResponse(
            status_code=status_code,
            content=error_response,
            headers=self._get_security_headers(),
        )

    def _get_security_headers(self) -> Dict[str, str]:
        """Get security headers for business error responses"""
        return {
            "X-Content-Type-Options": "nosniff",
            "X-Frame-Options": "DENY",
            "X-XSS-Protection": "1; mode=block",
        }


def setup_error_enforcement_middleware(app, debug: bool = False):
    """
    Setup all error enforcement middleware in the correct order.

    The middleware should be applied in this order:
    1. BusinessErrorMiddleware (first, for specific business errors)
    2. ValidationErrorMiddleware (for validation errors)
    3. ErrorResponseMiddleware (last, catch-all for all other errors)
    """
    from app.exceptions import setup_exception_handlers

    # First, setup the existing exception handlers
    setup_exception_handlers(app)

    # Then add our enforcement middleware
    app.add_middleware(BusinessErrorMiddleware)
    app.add_middleware(ValidationErrorMiddleware)
    app.add_middleware(ErrorResponseMiddleware, debug=debug)


# Export middleware classes
__all__ = [
    "ErrorResponseMiddleware",
    "ValidationErrorMiddleware",
    "BusinessErrorMiddleware",
    "setup_error_enforcement_middleware",
]