|
| 1 | +"""Rate limiting configuration for CodeFRAME API. |
| 2 | +
|
| 3 | +This module provides configuration for API rate limiting using slowapi. |
| 4 | +It delegates to GlobalConfig in core/config.py as the single source of truth |
| 5 | +for environment variable handling. |
| 6 | +
|
| 7 | +Environment Variables (via GlobalConfig): |
| 8 | + RATE_LIMIT_ENABLED: Enable/disable rate limiting (default: true) |
| 9 | + RATE_LIMIT_AUTH: Rate limit for authentication endpoints (default: 10/minute) |
| 10 | + RATE_LIMIT_STANDARD: Rate limit for standard API endpoints (default: 100/minute) |
| 11 | + RATE_LIMIT_AI: Rate limit for AI/expensive operations (default: 20/minute) |
| 12 | + RATE_LIMIT_WEBSOCKET: Rate limit for WebSocket connections (default: 30/minute) |
| 13 | + RATE_LIMIT_STORAGE: Storage backend - memory or redis (default: memory) |
| 14 | + RATE_LIMIT_TRUSTED_PROXIES: Comma-separated trusted proxy IPs/CIDRs |
| 15 | + REDIS_URL: Redis connection URL for distributed rate limiting (optional) |
| 16 | +""" |
| 17 | + |
| 18 | +import ipaddress |
| 19 | +import logging |
| 20 | +from dataclasses import dataclass, field |
| 21 | +from functools import lru_cache |
| 22 | +from typing import Optional |
| 23 | + |
| 24 | +logger = logging.getLogger(__name__) |
| 25 | + |
| 26 | + |
| 27 | +@dataclass |
| 28 | +class RateLimitConfig: |
| 29 | + """Configuration for API rate limiting. |
| 30 | +
|
| 31 | + Attributes: |
| 32 | + auth_limit: Rate limit for authentication endpoints |
| 33 | + standard_limit: Rate limit for standard API endpoints |
| 34 | + ai_limit: Rate limit for AI/expensive operations |
| 35 | + websocket_limit: Rate limit for WebSocket connections |
| 36 | + enabled: Whether rate limiting is enabled |
| 37 | + storage: Storage backend ('memory' or 'redis') |
| 38 | + redis_url: Redis connection URL for distributed rate limiting |
| 39 | + trusted_proxies: List of trusted proxy IP addresses/networks |
| 40 | + """ |
| 41 | + |
| 42 | + auth_limit: str = "10/minute" |
| 43 | + standard_limit: str = "100/minute" |
| 44 | + ai_limit: str = "20/minute" |
| 45 | + websocket_limit: str = "30/minute" |
| 46 | + enabled: bool = True |
| 47 | + storage: str = "memory" |
| 48 | + redis_url: Optional[str] = None |
| 49 | + trusted_proxies: list = field(default_factory=list) |
| 50 | + |
| 51 | + def is_trusted_proxy(self, ip: str) -> bool: |
| 52 | + """Check if an IP address is from a trusted proxy. |
| 53 | +
|
| 54 | + Args: |
| 55 | + ip: IP address to check |
| 56 | +
|
| 57 | + Returns: |
| 58 | + True if IP is in trusted_proxies list or matches a trusted network |
| 59 | + """ |
| 60 | + if not self.trusted_proxies: |
| 61 | + return False |
| 62 | + |
| 63 | + try: |
| 64 | + client_ip = ipaddress.ip_address(ip) |
| 65 | + for proxy in self.trusted_proxies: |
| 66 | + try: |
| 67 | + # Check if it's a network (CIDR notation) |
| 68 | + if "/" in proxy: |
| 69 | + network = ipaddress.ip_network(proxy, strict=False) |
| 70 | + if client_ip in network: |
| 71 | + return True |
| 72 | + else: |
| 73 | + # Check exact IP match |
| 74 | + if client_ip == ipaddress.ip_address(proxy): |
| 75 | + return True |
| 76 | + except ValueError: |
| 77 | + # Invalid proxy entry, skip it |
| 78 | + continue |
| 79 | + return False |
| 80 | + except ValueError: |
| 81 | + # Invalid IP address |
| 82 | + return False |
| 83 | + |
| 84 | + @classmethod |
| 85 | + def from_global_config(cls) -> "RateLimitConfig": |
| 86 | + """Create RateLimitConfig from GlobalConfig. |
| 87 | +
|
| 88 | + Uses core/config.py as the single source of truth for |
| 89 | + environment variable handling. |
| 90 | +
|
| 91 | + Returns: |
| 92 | + RateLimitConfig instance with values from GlobalConfig |
| 93 | + """ |
| 94 | + # Import here to avoid circular imports |
| 95 | + from codeframe.core.config import get_global_config |
| 96 | + |
| 97 | + global_config = get_global_config() |
| 98 | + |
| 99 | + enabled = global_config.rate_limit_enabled |
| 100 | + storage = global_config.rate_limit_storage |
| 101 | + redis_url = global_config.redis_url |
| 102 | + |
| 103 | + # Parse trusted proxies from comma-separated string |
| 104 | + trusted_proxies_str = global_config.rate_limit_trusted_proxies.strip() |
| 105 | + trusted_proxies = [] |
| 106 | + if trusted_proxies_str: |
| 107 | + trusted_proxies = [ |
| 108 | + p.strip() for p in trusted_proxies_str.split(",") if p.strip() |
| 109 | + ] |
| 110 | + |
| 111 | + # Validate storage type (already validated by Pydantic, but double-check) |
| 112 | + if storage not in ("memory", "redis"): |
| 113 | + logger.warning( |
| 114 | + f"Invalid RATE_LIMIT_STORAGE: {storage}. " |
| 115 | + f"Must be 'memory' or 'redis'. Defaulting to 'memory'." |
| 116 | + ) |
| 117 | + storage = "memory" |
| 118 | + |
| 119 | + # Warn if redis storage is requested but no URL provided |
| 120 | + if storage == "redis" and not redis_url: |
| 121 | + logger.warning( |
| 122 | + "RATE_LIMIT_STORAGE is 'redis' but REDIS_URL is not set. " |
| 123 | + "Falling back to in-memory storage." |
| 124 | + ) |
| 125 | + storage = "memory" |
| 126 | + |
| 127 | + return cls( |
| 128 | + auth_limit=global_config.rate_limit_auth, |
| 129 | + standard_limit=global_config.rate_limit_standard, |
| 130 | + ai_limit=global_config.rate_limit_ai, |
| 131 | + websocket_limit=global_config.rate_limit_websocket, |
| 132 | + enabled=enabled, |
| 133 | + storage=storage, |
| 134 | + redis_url=redis_url, |
| 135 | + trusted_proxies=trusted_proxies, |
| 136 | + ) |
| 137 | + |
| 138 | + |
| 139 | +@lru_cache(maxsize=1) |
| 140 | +def get_rate_limit_config() -> RateLimitConfig: |
| 141 | + """Get the global rate limit configuration. |
| 142 | +
|
| 143 | + Loads from GlobalConfig on first call, cached thereafter. |
| 144 | + Thread-safe via lru_cache. |
| 145 | +
|
| 146 | + Returns: |
| 147 | + RateLimitConfig instance |
| 148 | + """ |
| 149 | + config = RateLimitConfig.from_global_config() |
| 150 | + logger.info( |
| 151 | + f"Rate limit config initialized: " |
| 152 | + f"enabled={config.enabled}, " |
| 153 | + f"storage={config.storage}, " |
| 154 | + f"standard={config.standard_limit}, " |
| 155 | + f"trusted_proxies={len(config.trusted_proxies)} configured" |
| 156 | + ) |
| 157 | + return config |
| 158 | + |
| 159 | + |
| 160 | +def _reset_rate_limit_config() -> None: |
| 161 | + """Reset the global rate limit configuration. |
| 162 | +
|
| 163 | + Useful for testing to ensure clean state between tests. |
| 164 | + """ |
| 165 | + get_rate_limit_config.cache_clear() |
0 commit comments