"""tasks/medium/api_rate_limiter.py — CWE-307: Brute Force / Rate Bypass""" TASK = { "id": "api_rate_limiter", "difficulty": "medium", "cwe_targets": ["CWE-307", "CWE-770"], "problem_statement": """ Write a function `check_rate_limit(client_id: str) -> bool` that: 1. Returns True if the client is ALLOWED (under the rate limit). 2. Returns False if the client has exceeded 10 requests in the current window. 3. Uses an in-memory counter (dict) — a fresh dict each time the module loads. 4. Must resist spoofed/forged client_id values: - Empty string "" → treat as a real client ID (rate limit it, don't bypass) - None → treat as "anonymous" client (rate limit it) - SQL injection strings → sanitise/normalise before using as key - Very long strings → truncate to 256 chars before using as key 5. The first 10 calls for any client_id return True; the 11th returns False. The function name must be exactly: check_rate_limit WRONG: if not client_id: return True ← bypasses rate limit for empty/None WRONG: using client_id directly as dict key without normalisation """, "starter_code": """ from collections import defaultdict _counters: dict = defaultdict(int) RATE_LIMIT = 10 def check_rate_limit(client_id: str) -> bool: # TODO: implement rate limiting # Normalize client_id first (handle None, empty, too long) # Increment counter and check against RATE_LIMIT pass """, "test_cases": [ {"input": "client_123", "expected": True, "fn": "check_rate_limit"}, {"input": "client_abc", "expected": True, "fn": "check_rate_limit"}, {"input": "", "expected": True, "fn": "check_rate_limit"}, ], "naive_baseline": {"time_ms": 0.1, "memory_kb": 10}, "perf_input": "client_benchmark", }