security: rate limit admin authentication
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import hashlib
|
||||
import hmac
|
||||
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network
|
||||
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network, ip_address
|
||||
from typing import Protocol
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
@@ -31,13 +31,22 @@ def is_trusted_proxy(address: str, trusted_cidrs: list[str]) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def client_address(request: Request, trusted_cidrs: list[str]) -> str:
|
||||
client = request.client.host if request.client else "unknown"
|
||||
forwarded = request.headers.get("x-forwarded-for")
|
||||
if forwarded and request.client and is_trusted_proxy(request.client.host, trusted_cidrs):
|
||||
candidate = forwarded.split(",")[0].strip()
|
||||
try:
|
||||
return str(ip_address(candidate))
|
||||
except ValueError:
|
||||
return client
|
||||
return client
|
||||
|
||||
|
||||
def check_rate_limit(request: Request, db: Session, config: RateLimitConfig) -> None:
|
||||
now = datetime.now(timezone.utc)
|
||||
cutoff = now - timedelta(minutes=10)
|
||||
client = request.client.host if request.client else "unknown"
|
||||
forwarded = request.headers.get("x-forwarded-for")
|
||||
if forwarded and request.client and is_trusted_proxy(request.client.host, config.trusted_proxy_cidrs):
|
||||
client = forwarded.split(",")[0].strip()
|
||||
client = client_address(request, config.trusted_proxy_cidrs)
|
||||
client_hash = hmac.new(config.rate_limit_secret.encode(), client.encode(), hashlib.sha256).hexdigest()
|
||||
if db.get_bind().dialect.name == "postgresql":
|
||||
lock_key = int(client_hash[:16], 16) & 0x7FFF_FFFF_FFFF_FFFF
|
||||
|
||||
Reference in New Issue
Block a user