fix: rate-limit and audit by real client address
uvicorn does not trust forwarded headers from a peer outside forwarded_allow_ips, so request.client.host was the web gateway for every request. The auth-source bucket therefore counted all customers together: 60 failed logins from one attacker locked out everyone. Security events recorded the gateway address, which made the audit trail useless for attribution. The gateway now overwrites X-Forwarded-For with the peer address it observed instead of appending to whatever the client sent, so the header carries one value the client cannot choose, and client_ip() resolves it with a fallback to the connection peer. The guest-session limiter was keyed on the environment name, making it one global bucket of 120 per 15 minutes: roughly eight new visitors a minute for the whole site before legitimate traffic started receiving 429. It is now per source, and the ceiling is deliberately generous because offices and mobile carriers put many real customers behind a single address. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -10,6 +10,20 @@ from .db import connect
|
||||
|
||||
COOKIE_SECURE = os.environ.get('COOKIE_SECURE', 'false').lower() == 'true'
|
||||
|
||||
def client_ip(request: Request):
|
||||
"""The requester's address, for rate-limit buckets and security events.
|
||||
|
||||
The API is only reachable through the web gateway, which replaces
|
||||
X-Forwarded-For with the peer address it observed, so the header carries
|
||||
exactly one value the client could not choose. Without this every request
|
||||
looks like the gateway, which collapses per-source limits into one global
|
||||
bucket and strips the address from the audit trail.
|
||||
"""
|
||||
forwarded = request.headers.get('x-forwarded-for', '').split(',')[0].strip()
|
||||
if forwarded:
|
||||
return forwarded[:64]
|
||||
return request.client.host if request.client else 'unknown'
|
||||
|
||||
def password_hash(password, salt=None):
|
||||
salt = salt or secrets.token_hex(16)
|
||||
digest = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt), n=16384, r=8, p=5).hex()
|
||||
@@ -82,7 +96,7 @@ def rate_limit(scope, identity, limit, seconds=900):
|
||||
|
||||
def throttle(email, request):
|
||||
# Independent account and source buckets prevent bypass by rotating emails.
|
||||
rate_limit('auth-source', request.client.host if request.client else 'local', 60)
|
||||
rate_limit('auth-source', client_ip(request), 60)
|
||||
rate_limit('auth-account', email, 10)
|
||||
|
||||
def operator(request: Request):
|
||||
|
||||
Reference in New Issue
Block a user