gabriel / musehub public
failure_limiter.py python
91 lines 3.0 KB
Raw
sha256:0032d6cfa33bc3c8367436ad768e7dd0e339b4332153160247da8266cb5fa352 Merge branch 'task/version-tags-phase3-server' into dev Human 18 days ago
1 """Per-IP auth failure tracking with exponential backoff.
2
3 Tracks consecutive verify failures per IP in memory. After successive
4 failures the IP is blocked for an increasing cooldown period.
5
6 Thresholds (consecutive failures → cooldown):
7 5 → 30 seconds
8 10 → 5 minutes
9 20 → 15 minutes
10
11 The counter resets on the first successful verify from that IP.
12 Stale entries (no activity for 1 hour) are garbage-collected lazily.
13
14 This is in-memory and process-local. For multi-worker deployments move
15 the state to a shared cache (Redis). For single-worker (UVICORN_WORKERS=1)
16 this is sufficient and has zero external dependencies.
17
18 Why this matters even with Ed25519:
19 - Prevents automated stuffing of the verify endpoint with fabricated
20 challenge tokens and random signatures.
21 - Makes enumeration of valid handles via timing measurably slower.
22 - Adds a layer of defence that complements the global 20/min rate limit.
23 """
24
25 import time
26 from fastapi import HTTPException, status
27
28 type _FailureEntry = tuple[int, float, float]
29 type _FailureMap = dict[str, _FailureEntry]
30
31 # (failure_count, first_failure_ts, last_failure_ts)
32 _failures: _FailureMap = {}
33
34 # Cooldown thresholds: (min_failures, cooldown_seconds)
35 _THRESHOLDS: list[tuple[int, int]] = [
36 (20, 900), # 20+ failures → 15 min
37 (10, 300), # 10+ failures → 5 min
38 (5, 30), # 5+ failures → 30 sec
39 ]
40
41 _GC_AFTER_SECONDS = 3600 # drop entries inactive for 1 hour
42
43 def _cooldown_for(count: int) -> int:
44 for min_failures, seconds in _THRESHOLDS:
45 if count >= min_failures:
46 return seconds
47 return 0
48
49 def _gc() -> None:
50 """Remove entries that have been quiet for GC_AFTER_SECONDS."""
51 now = time.monotonic()
52 stale = [ip for ip, (_, _, last) in _failures.items() if now - last > _GC_AFTER_SECONDS]
53 for ip in stale:
54 del _failures[ip]
55
56 def check_failure_limit(ip: str) -> None:
57 """Raise 429 if this IP is currently in a cooldown window.
58
59 Call this at the top of the verify endpoint, before any DB work.
60 """
61 entry = _failures.get(ip)
62 if entry is None:
63 return
64
65 count, _, last_failure_ts = entry
66 cooldown = _cooldown_for(count)
67 if cooldown == 0:
68 return
69
70 elapsed = time.monotonic() - last_failure_ts
71 remaining = cooldown - elapsed
72 if remaining > 0:
73 raise HTTPException(
74 status_code=status.HTTP_429_TOO_MANY_REQUESTS,
75 detail=f"Too many failed auth attempts. Try again in {int(remaining) + 1}s.",
76 headers={"Retry-After": str(int(remaining) + 1)},
77 )
78
79 def record_failure(ip: str) -> None:
80 """Increment the failure counter for this IP after a failed verify."""
81 _gc()
82 now = time.monotonic()
83 if ip in _failures:
84 count, first_ts, _ = _failures[ip]
85 _failures[ip] = (count + 1, first_ts, now)
86 else:
87 _failures[ip] = (1, now, now)
88
89 def record_success(ip: str) -> None:
90 """Reset the failure counter for this IP after a successful verify."""
91 _failures.pop(ip, None)
File History 10 commits
sha256:0032d6cfa33bc3c8367436ad768e7dd0e339b4332153160247da8266cb5fa352 Merge branch 'task/version-tags-phase3-server' into dev Human 18 days ago
sha256:4669620efda9ff41c55bdefd1f7bfe1c239d468428744c84ead9957e5a003a53 merge: rescue snapshot-recovery hardening (c00aa21d) into d… Opus 4.8 minor 31 days ago
sha256:a59da49c4611b970fc4b6ae48678ce4943261c213a07ddbd73ce9201df869b4a fix: remove false-positive proposal_comments index drop fro… Sonnet 4.6 patch 35 days ago
sha256:0a240d6dbff234f07d98a28a4a9a68db702f3f9ff9260196f24219bdb1c0b6f3 feat: render markdown mists as HTML with heading anchor links Sonnet 4.6 patch 36 days ago
sha256:24a7d47486ebc4ebd1832830580e177ec6f877b48dced8c000e198cdec4ce9d6 Merge 'task/bump-version-rc12' into 'dev' — proposal: Bump … Human 37 days ago
sha256:b9ff931d147e0114a1f17060f415b89ed551c170a91ff226c70437aa5c85f9ee Merge 'task/bump-version-rc12' into 'dev' — proposal: Bump … Human 37 days ago
sha256:d1122d21e73471879b460037b22c0b50fded7c423444a176f248428f75dac39c Merge 'task/fix-issue-pagination-cursor' into 'dev' — propo… Human 37 days ago
sha256:01e18975e73d2b3cd5b6db7929c895bef9aa6e0d4391dc5b2adfc548b41318dd Merge 'feat/adding-debug-logs-to-staging' into 'dev' — prop… Human 37 days ago
sha256:6b1949fc2797ca4c1936a637a4cbfec828ef56cf52398a2e74ca3c4f494e728f fix: use wire_bytes not mpack_bytes_raw in compute_object_b… Sonnet 4.6 patch 49 days ago
sha256:b99f2455dc346966d040133f5203297e6e3ef5803a93728a2c30568d0a0f7583 rename: delta_add → delta_upsert across wire format, models… Sonnet 4.6 patch 52 days ago