Coverage for /Users/les/Projects/crackerjack/crackerjack/services/validation_rate_limiter.py: 0%

124 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1""" 

2Rate limiting for input validation to prevent abuse and DoS attacks. 

3 

4This module provides rate limiting functionality to: 

5- Prevent excessive validation failures 

6- Protect against DoS attacks via malformed input 

7- Track validation patterns for security monitoring 

8""" 

9 

10import time 

11import typing as t 

12from collections import defaultdict, deque 

13from threading import Lock 

14 

15from .security_logger import SecurityEventLevel, get_security_logger 

16 

17 

18class ValidationRateLimit: 

19 """Rate limiting configuration for different validation types.""" 

20 

21 def __init__( 

22 self, 

23 max_failures: int = 10, 

24 window_seconds: int = 60, 

25 block_duration: int = 300, # 5 minutes 

26 ): 

27 self.max_failures = max_failures 

28 self.window_seconds = window_seconds 

29 self.block_duration = block_duration 

30 

31 

32class ValidationRateLimiter: 

33 """ 

34 Rate limiter for validation failures to prevent abuse. 

35 

36 Tracks validation failures by client/source and blocks excessive failures. 

37 Uses sliding window approach for accurate rate limiting. 

38 """ 

39 

40 def __init__(self): 

41 self._failure_windows: dict[str, deque] = defaultdict(deque) 

42 self._blocked_until: dict[str, float] = {} 

43 self._lock = Lock() 

44 self._logger = get_security_logger() 

45 

46 # Default rate limits by validation type 

47 self._limits = { 

48 "default": ValidationRateLimit(max_failures=10, window_seconds=60), 

49 "command_injection": ValidationRateLimit( 

50 max_failures=3, window_seconds=60, block_duration=600 

51 ), 

52 "path_traversal": ValidationRateLimit( 

53 max_failures=3, window_seconds=60, block_duration=600 

54 ), 

55 "sql_injection": ValidationRateLimit( 

56 max_failures=2, window_seconds=60, block_duration=900 

57 ), 

58 "code_injection": ValidationRateLimit( 

59 max_failures=2, window_seconds=60, block_duration=900 

60 ), 

61 "json_payload": ValidationRateLimit(max_failures=20, window_seconds=60), 

62 "job_id": ValidationRateLimit(max_failures=15, window_seconds=60), 

63 "project_name": ValidationRateLimit(max_failures=15, window_seconds=60), 

64 } 

65 

66 def is_blocked(self, client_id: str) -> bool: 

67 """Check if a client is currently blocked.""" 

68 with self._lock: 

69 if client_id in self._blocked_until: 

70 if time.time() < self._blocked_until[client_id]: 

71 return True 

72 else: 

73 # Block expired, remove it 

74 del self._blocked_until[client_id] 

75 return False 

76 

77 def record_failure( 

78 self, 

79 client_id: str, 

80 validation_type: str, 

81 severity: SecurityEventLevel = SecurityEventLevel.MEDIUM, 

82 ) -> bool: 

83 """ 

84 Record a validation failure and check if client should be blocked. 

85 

86 Returns True if the client should be blocked, False otherwise. 

87 """ 

88 with self._lock: 

89 current_time = time.time() 

90 

91 # Get rate limit for this validation type 

92 limit = self._limits.get(validation_type, self._limits["default"]) 

93 

94 # Initialize failure window if needed 

95 if client_id not in self._failure_windows: 

96 self._failure_windows[client_id] = deque() 

97 

98 # Clean old failures outside the window 

99 window = self._failure_windows[client_id] 

100 while window and current_time - window[0] > limit.window_seconds: 

101 window.popleft() 

102 

103 # Record this failure 

104 window.append(current_time) 

105 

106 # Check if limit exceeded 

107 if len(window) >= limit.max_failures: 

108 # Block this client 

109 self._blocked_until[client_id] = current_time + limit.block_duration 

110 

111 # Log the rate limit exceeded event 

112 self._logger.log_rate_limit_exceeded( 

113 limit_type=validation_type, 

114 current_count=len(window), 

115 max_allowed=limit.max_failures, 

116 client_id=client_id, 

117 block_duration=limit.block_duration, 

118 ) 

119 

120 # Clear the failure window since client is now blocked 

121 self._failure_windows[client_id].clear() 

122 

123 return True 

124 

125 return False 

126 

127 def get_remaining_attempts(self, client_id: str, validation_type: str) -> int: 

128 """Get remaining validation attempts before rate limit.""" 

129 with self._lock: 

130 if self.is_blocked(client_id): 

131 return 0 

132 

133 limit = self._limits.get(validation_type, self._limits["default"]) 

134 current_failures = len(self._failure_windows.get(client_id, [])) 

135 return max(0, limit.max_failures - current_failures) 

136 

137 def get_block_time_remaining(self, client_id: str) -> int: 

138 """Get seconds remaining until client is unblocked.""" 

139 with self._lock: 

140 if client_id in self._blocked_until: 

141 remaining = max(0, int(self._blocked_until[client_id] - time.time())) 

142 return remaining 

143 return 0 

144 

145 def get_client_stats(self, client_id: str) -> dict[str, t.Any]: 

146 """Get rate limiting statistics for a client.""" 

147 with self._lock: 

148 current_time = time.time() 

149 

150 stats = { 

151 "client_id": client_id, 

152 "is_blocked": self.is_blocked(client_id), 

153 "block_time_remaining": self.get_block_time_remaining(client_id), 

154 "recent_failures": 0, 

155 "total_failures": 0, 

156 } 

157 

158 if client_id in self._failure_windows: 

159 window = self._failure_windows[client_id] 

160 stats["total_failures"] = len(window) 

161 

162 # Count recent failures (last 5 minutes) 

163 recent_count = sum( 

164 1 for failure_time in window if current_time - failure_time <= 300 

165 ) 

166 stats["recent_failures"] = recent_count 

167 

168 return stats 

169 

170 def cleanup_expired_data(self) -> int: 

171 """Clean up expired data and return number of items removed.""" 

172 with self._lock: 

173 current_time = time.time() 

174 removed_count = 0 

175 

176 # Clean expired blocks 

177 expired_blocks = [ 

178 client_id 

179 for client_id, block_until in self._blocked_until.items() 

180 if current_time >= block_until 

181 ] 

182 

183 for client_id in expired_blocks: 

184 del self._blocked_until[client_id] 

185 removed_count += 1 

186 

187 # Clean old failure windows (keep only last 24 hours) 

188 for client_id, window in list(self._failure_windows.items()): 

189 # Remove failures older than 24 hours 

190 while window and current_time - window[0] > 86400: # 24 hours 

191 window.popleft() 

192 removed_count += 1 

193 

194 # Remove empty windows 

195 if not window: 

196 del self._failure_windows[client_id] 

197 

198 return removed_count 

199 

200 def update_rate_limits( 

201 self, 

202 validation_type: str, 

203 max_failures: int, 

204 window_seconds: int, 

205 block_duration: int, 

206 ) -> None: 

207 """Update rate limits for a specific validation type.""" 

208 with self._lock: 

209 self._limits[validation_type] = ValidationRateLimit( 

210 max_failures=max_failures, 

211 window_seconds=window_seconds, 

212 block_duration=block_duration, 

213 ) 

214 

215 def get_all_stats(self) -> dict[str, t.Any]: 

216 """Get comprehensive rate limiting statistics.""" 

217 with self._lock: 

218 current_time = time.time() 

219 

220 stats = { 

221 "total_clients_tracked": len(self._failure_windows), 

222 "currently_blocked": len(self._blocked_until), 

223 "rate_limits": { 

224 vtype: { 

225 "max_failures": limit.max_failures, 

226 "window_seconds": limit.window_seconds, 

227 "block_duration": limit.block_duration, 

228 } 

229 for vtype, limit in self._limits.items() 

230 }, 

231 "blocked_clients": [], 

232 "active_clients": [], 

233 } 

234 

235 # Get blocked client info 

236 for client_id, block_until in self._blocked_until.items(): 

237 remaining = max(0, int(block_until - current_time)) 

238 stats["blocked_clients"].append( 

239 { 

240 "client_id": client_id, 

241 "blocked_until": block_until, 

242 "time_remaining": remaining, 

243 } 

244 ) 

245 

246 # Get active client info (with recent failures) 

247 for client_id, window in self._failure_windows.items(): 

248 if client_id not in self._blocked_until and window: 

249 recent_failures = sum( 

250 1 

251 for failure_time in window 

252 if current_time - failure_time <= 300 # Last 5 minutes 

253 ) 

254 if recent_failures > 0: 

255 stats["active_clients"].append( 

256 { 

257 "client_id": client_id, 

258 "recent_failures": recent_failures, 

259 "total_failures": len(window), 

260 } 

261 ) 

262 

263 return stats 

264 

265 

266# Global rate limiter instance 

267_rate_limiter: ValidationRateLimiter | None = None 

268 

269 

270def get_validation_rate_limiter() -> ValidationRateLimiter: 

271 """Get the global validation rate limiter instance.""" 

272 global _rate_limiter 

273 if _rate_limiter is None: 

274 _rate_limiter = ValidationRateLimiter() 

275 return _rate_limiter 

276 

277 

278def reset_validation_rate_limiter() -> None: 

279 """Reset the global rate limiter (mainly for testing).""" 

280 global _rate_limiter 

281 _rate_limiter = ValidationRateLimiter() 

282 

283 

284def cleanup_rate_limiter_data() -> int: 

285 """Clean up expired rate limiter data.""" 

286 limiter = get_validation_rate_limiter() 

287 return limiter.cleanup_expired_data() 

288 

289 

290class RateLimitedValidator: 

291 """Wrapper for input validation with rate limiting.""" 

292 

293 def __init__(self, base_validator, client_id_func: t.Callable[[], str] = None): 

294 self.base_validator = base_validator 

295 self.rate_limiter = get_validation_rate_limiter() 

296 self.client_id_func = client_id_func or (lambda: "default") 

297 

298 def validate_with_rate_limit( 

299 self, validation_func: t.Callable, validation_type: str, *args, **kwargs 

300 ): 

301 """Execute validation with rate limiting.""" 

302 client_id = self.client_id_func() 

303 

304 # Check if client is blocked 

305 if self.rate_limiter.is_blocked(client_id): 

306 remaining_time = self.rate_limiter.get_block_time_remaining(client_id) 

307 from ..errors import ErrorCode, ExecutionError 

308 

309 raise ExecutionError( 

310 message=f"Rate limit exceeded. Try again in {remaining_time} seconds.", 

311 error_code=ErrorCode.RATE_LIMIT_EXCEEDED, 

312 ) 

313 

314 # Perform validation 

315 result = validation_func(*args, **kwargs) 

316 

317 # If validation failed, record the failure 

318 if hasattr(result, "valid") and not result.valid: 

319 # Map security levels to rate limiting severity 

320 severity_mapping = { 

321 "shell_injection": SecurityEventLevel.CRITICAL, 

322 "command_injection": SecurityEventLevel.CRITICAL, 

323 "sql_injection": SecurityEventLevel.CRITICAL, 

324 "code_injection": SecurityEventLevel.CRITICAL, 

325 "path_traversal": SecurityEventLevel.CRITICAL, 

326 "directory_escape": SecurityEventLevel.CRITICAL, 

327 } 

328 

329 severity = severity_mapping.get( 

330 result.validation_type, SecurityEventLevel.MEDIUM 

331 ) 

332 

333 # Record failure and check if client should be blocked 

334 should_block = self.rate_limiter.record_failure( 

335 client_id, validation_type, severity 

336 ) 

337 

338 if should_block: 

339 from ..errors import ErrorCode, ExecutionError 

340 

341 raise ExecutionError( 

342 message="Too many validation failures. Client blocked.", 

343 error_code=ErrorCode.RATE_LIMIT_EXCEEDED, 

344 ) 

345 

346 return result