"""
Module: api.middleware.security
Description: Advanced security middleware for comprehensive protection
Author: Anderson H. Silva
Date: 2025-01-15
License: Proprietary - All rights reserved
"""
import time
import re
import ipaddress
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Set, Tuple
from collections import defaultdict, deque
import hashlib
import hmac
import secrets
from fastapi import Request, HTTPException, status
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.types import ASGIApp
from src.core import get_logger, settings
from src.core.audit import audit_logger, AuditEventType, AuditSeverity, AuditContext
from src.services.rate_limit_service import get_rate_limiter
class SecurityConfig:
"""Security middleware configuration."""
# Rate limiting
RATE_LIMIT_REQUESTS_PER_MINUTE = 60
RATE_LIMIT_REQUESTS_PER_HOUR = 1000
RATE_LIMIT_BURST_SIZE = 10
# IP blocking
MAX_FAILED_ATTEMPTS = 5
BLOCK_DURATION_MINUTES = 30
SUSPICIOUS_ACTIVITY_THRESHOLD = 20
# Request validation
MAX_REQUEST_SIZE = 10 * 1024 * 1024 # 10MB
MAX_HEADER_SIZE = 8192 # 8KB
MAX_URL_LENGTH = 2048
# Content security
ALLOWED_CONTENT_TYPES = {
"application/json",
"application/x-www-form-urlencoded",
"multipart/form-data",
"text/plain"
}
# Security headers
SECURITY_HEADERS = {
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"X-XSS-Protection": "1; mode=block",
"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Permissions-Policy": "camera=(), microphone=(), geolocation=()"
}
# Suspicious patterns
SUSPICIOUS_PATTERNS = [
# XSS patterns
r"", # XSS script tags
r"javascript:", # XSS javascript protocol
r"on\w+\s*=", # Event handlers
r"