File size: 13,138 Bytes
56c063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Security middleware for FastAPI applications.

Integrates rate limiting, input validation, and security monitoring.

"""

import time
import json
from typing import Callable, Optional
from fastapi import Request, Response, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse
import logging

from .security import (
    rate_limiter, sql_prevention, audit_logger, 
    SecurityEvent, SQLInjectionPrevention
)
from .auth import get_current_user
from datetime import datetime

logger = logging.getLogger(__name__)

class SecurityMiddleware(BaseHTTPMiddleware):
    """

    Comprehensive security middleware that handles:

    - Rate limiting and DDoS protection

    - Input validation and SQL injection prevention

    - Security event logging

    - Request/response monitoring

    """
    
    def __init__(self, app, excluded_paths: Optional[list] = None):
        super().__init__(app)
        self.excluded_paths = excluded_paths or ['/health', '/docs', '/openapi.json']
    
    async def dispatch(self, request: Request, call_next: Callable) -> Response:
        """Process request through security checks."""
        start_time = time.time()
        
        # Skip security checks for excluded paths
        if request.url.path in self.excluded_paths:
            return await call_next(request)
        
        # Get client IP
        client_ip = self._get_client_ip(request)
        
        # Rate limiting check
        is_allowed, block_reason = rate_limiter.is_allowed(client_ip, request.url.path)
        if not is_allowed:
            audit_logger.log_rate_limit_violation(client_ip, request.url.path, block_reason)
            return JSONResponse(
                status_code=429,
                content={
                    "error": "Rate limit exceeded",
                    "message": block_reason,
                    "retry_after": 60
                }
            )
        
        # Input validation for POST/PUT requests
        if request.method in ['POST', 'PUT', 'PATCH']:
            validation_result = await self._validate_request_input(request, client_ip)
            if not validation_result['is_valid']:
                return JSONResponse(
                    status_code=400,
                    content={
                        "error": "Invalid input detected",
                        "details": validation_result['threats']
                    }
                )
        
        # Process request
        try:
            response = await call_next(request)
            
            # Log successful request
            processing_time = time.time() - start_time
            await self._log_request(request, response, client_ip, processing_time)
            
            return response
            
        except Exception as e:
            # Log error
            audit_logger.log_event(SecurityEvent(
                timestamp=datetime.utcnow(),
                event_type='request_error',
                user_id=await self._get_user_id(request),
                ip_address=client_ip,
                severity='MEDIUM',
                details={
                    'path': request.url.path,
                    'method': request.method,
                    'error': str(e)
                }
            ))
            raise
    
    def _get_client_ip(self, request: Request) -> str:
        """Extract client IP address from request."""
        # Check for forwarded headers (behind proxy/load balancer)
        forwarded_for = request.headers.get('X-Forwarded-For')
        if forwarded_for:
            return forwarded_for.split(',')[0].strip()
        
        real_ip = request.headers.get('X-Real-IP')
        if real_ip:
            return real_ip
        
        # Fallback to direct connection
        return request.client.host if request.client else 'unknown'
    
    async def _validate_request_input(self, request: Request, client_ip: str) -> dict:
        """Validate request input for security threats."""
        threats = []
        
        try:
            # Get request body
            body = await request.body()
            
            if body:
                # Parse JSON if content-type is JSON
                content_type = request.headers.get('content-type', '')
                
                if 'application/json' in content_type:
                    try:
                        json_data = json.loads(body)
                        threats.extend(self._validate_json_data(json_data))
                    except json.JSONDecodeError:
                        threats.append("Invalid JSON format")
                
                elif 'application/x-www-form-urlencoded' in content_type:
                    # Validate form data
                    form_data = body.decode('utf-8', errors='ignore')
                    is_safe, form_threats = sql_prevention.validate_input(form_data, 'form_data')
                    if not is_safe:
                        threats.extend(form_threats)
            
            # Validate query parameters
            for param_name, param_value in request.query_params.items():
                is_safe, param_threats = sql_prevention.validate_input(param_value, f'query_param_{param_name}')
                if not is_safe:
                    threats.extend(param_threats)
            
            # Log threats if found
            if threats:
                user_id = await self._get_user_id(request)
                audit_logger.log_sql_injection_attempt(user_id, client_ip, 'request_input', threats)
        
        except Exception as e:
            logger.error(f"Error validating request input: {e}")
            threats.append("Input validation error")
        
        return {
            'is_valid': len(threats) == 0,
            'threats': threats
        }
    
    def _validate_json_data(self, data, path: str = 'root') -> list:
        """Recursively validate JSON data for security threats."""
        threats = []
        
        if isinstance(data, dict):
            for key, value in data.items():
                # Validate key
                is_safe, key_threats = sql_prevention.validate_input(str(key), f'{path}.{key}')
                if not is_safe:
                    threats.extend(key_threats)
                
                # Recursively validate value
                threats.extend(self._validate_json_data(value, f'{path}.{key}'))
        
        elif isinstance(data, list):
            for i, item in enumerate(data):
                threats.extend(self._validate_json_data(item, f'{path}[{i}]'))
        
        elif isinstance(data, str):
            is_safe, str_threats = sql_prevention.validate_input(data, path)
            if not is_safe:
                threats.extend(str_threats)
        
        return threats
    
    async def _get_user_id(self, request: Request) -> str:
        """Extract user ID from request if available."""
        try:
            # Try to get from authorization header
            auth_header = request.headers.get('authorization')
            if auth_header and auth_header.startswith('Bearer '):
                token = auth_header.split(' ')[1]
                user = await get_current_user(token)
                return user.id if user else 'unknown'
        except:
            pass
        
        return 'unknown'
    
    async def _log_request(self, request: Request, response: Response, 

                          client_ip: str, processing_time: float):
        """Log request details for monitoring."""
        user_id = await self._get_user_id(request)
        
        # Determine severity based on response status
        severity = 'LOW'
        if response.status_code >= 500:
            severity = 'HIGH'
        elif response.status_code >= 400:
            severity = 'MEDIUM'
        
        audit_logger.log_event(SecurityEvent(
            timestamp=datetime.utcnow(),
            event_type='api_request',
            user_id=user_id,
            ip_address=client_ip,
            severity=severity,
            details={
                'method': request.method,
                'path': request.url.path,
                'status_code': response.status_code,
                'processing_time_ms': round(processing_time * 1000, 2),
                'user_agent': request.headers.get('user-agent', 'unknown')
            }
        ))

class FileUploadSecurityMiddleware:
    """Specialized middleware for file upload security."""
    
    @staticmethod
    async def validate_file_upload(request: Request) -> dict:
        """Validate file upload requests."""
        from .security import file_validator
        
        client_ip = SecurityMiddleware._get_client_ip(None, request)
        user_id = await SecurityMiddleware._get_user_id(None, request)
        
        # Check if request contains file upload
        content_type = request.headers.get('content-type', '')
        
        if not content_type.startswith('multipart/form-data'):
            return {'is_valid': True, 'message': 'Not a file upload'}
        
        try:
            # This would be handled by FastAPI's file upload handling
            # The actual validation happens in the endpoint
            return {'is_valid': True, 'message': 'File upload validation pending'}
            
        except Exception as e:
            audit_logger.log_event(SecurityEvent(
                timestamp=datetime.utcnow(),
                event_type='file_upload_error',
                user_id=user_id,
                ip_address=client_ip,
                severity='MEDIUM',
                details={'error': str(e)}
            ))
            
            return {
                'is_valid': False,
                'message': f'File upload validation error: {str(e)}'
            }

class CSRFProtectionMiddleware(BaseHTTPMiddleware):
    """CSRF protection middleware."""
    
    def __init__(self, app, secret_key: str):
        super().__init__(app)
        self.secret_key = secret_key
    
    async def dispatch(self, request: Request, call_next: Callable) -> Response:
        """Check CSRF token for state-changing requests."""
        
        # Skip CSRF for safe methods
        if request.method in ['GET', 'HEAD', 'OPTIONS']:
            return await call_next(request)
        
        # Skip for API endpoints with proper authentication
        if request.url.path.startswith('/api/'):
            auth_header = request.headers.get('authorization')
            if auth_header and auth_header.startswith('Bearer '):
                return await call_next(request)
        
        # Check CSRF token
        csrf_token = request.headers.get('X-CSRF-Token')
        if not csrf_token:
            return JSONResponse(
                status_code=403,
                content={'error': 'CSRF token missing'}
            )
        
        # Validate CSRF token (simplified - in production use proper CSRF library)
        if not self._validate_csrf_token(csrf_token):
            return JSONResponse(
                status_code=403,
                content={'error': 'Invalid CSRF token'}
            )
        
        return await call_next(request)
    
    def _validate_csrf_token(self, token: str) -> bool:
        """Validate CSRF token (simplified implementation)."""
        # In production, use a proper CSRF library like django-csrf or similar
        # This is a simplified example
        return len(token) >= 32 and token.isalnum()

class SecurityHeadersMiddleware(BaseHTTPMiddleware):
    """Add security headers to responses."""
    
    async def dispatch(self, request: Request, call_next: Callable) -> Response:
        """Add security headers to response."""
        response = await call_next(request)
        
        # Security headers
        response.headers['X-Content-Type-Options'] = 'nosniff'
        response.headers['X-Frame-Options'] = 'DENY'
        response.headers['X-XSS-Protection'] = '1; mode=block'
        response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
        response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
        response.headers['Permissions-Policy'] = 'geolocation=(), microphone=(), camera=()'
        
        # Content Security Policy
        csp = (
            "default-src 'self'; "
            "script-src 'self' 'unsafe-inline' 'unsafe-eval'; "
            "style-src 'self' 'unsafe-inline'; "
            "img-src 'self' data: https:; "
            "font-src 'self'; "
            "connect-src 'self'; "
            "frame-ancestors 'none';"
        )
        response.headers['Content-Security-Policy'] = csp
        
        return response