""" 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