feat(ratelimit): env-tunable per-IP auth limiter budgets

Add RATELIMIT_OTC_REQUEST_MAX / RATELIMIT_VERIFY_MAX / RATELIMIT_CHECK_MAX
(default to the existing secure values; non-positive/unparseable → default).
Lets a test/PPE stack that drives the auth endpoints repeatedly from one IP
lift the budget; production leaves them unset. Mirrors the existing
OTC_REQUEST_COOLDOWN_SECONDS knob.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ben Stull
2026-06-07 22:28:57 -07:00
parent cbaba76345
commit 9e1b7ce34f
2 changed files with 66 additions and 3 deletions
+22 -3
View File
@@ -19,11 +19,27 @@ lockouts). Both layers run together.
"""
from __future__ import annotations
import os
import threading
import time
from collections import defaultdict, deque
def _max_events(env_name: str, default: int) -> int:
"""Per-limiter budget, overridable via env (e.g. a test/PPE stack that
drives the auth endpoints repeatedly from one IP). Production leaves these
unset and gets the secure defaults below. A non-positive / unparseable
value falls back to the default."""
raw = os.environ.get(env_name, "").strip()
if not raw:
return default
try:
n = int(raw)
except ValueError:
return default
return n if n > 0 else default
class SlidingWindowLimiter:
"""Allow at most `max_events` per `window_seconds` per key.
@@ -66,12 +82,15 @@ class SlidingWindowLimiter:
# * verify: 10 attempts / 5 min / IP across the auth verify surfaces.
# * otc request: 5 sends / 5 min / IP (Turnstile is the primary gate;
# this is defense in depth against a solved-challenge replay loop).
verify_limiter = SlidingWindowLimiter(max_events=10, window_seconds=300)
otc_request_limiter = SlidingWindowLimiter(max_events=5, window_seconds=300)
verify_limiter = SlidingWindowLimiter(
max_events=_max_events("RATELIMIT_VERIFY_MAX", 10), window_seconds=300)
otc_request_limiter = SlidingWindowLimiter(
max_events=_max_events("RATELIMIT_OTC_REQUEST_MAX", 5), window_seconds=300)
# /auth/passcode/check is an anonymous has-passcode oracle (audit 0026 L3).
# It's a legitimate Login-flow affordance, so the budget is generous —
# enough for a human typing emails, tight enough to stop bulk scraping.
check_limiter = SlidingWindowLimiter(max_events=30, window_seconds=300)
check_limiter = SlidingWindowLimiter(
max_events=_max_events("RATELIMIT_CHECK_MAX", 30), window_seconds=300)
def _reset_all_for_tests() -> None: