Files
wireguard_webadmin/containers/auth-gateway/auth_gateway/limiter.py
T

41 lines
1.2 KiB
Python
Raw Normal View History

2026-11-21 12:26:28 -03:00
import ipaddress
from fastapi import Request
from slowapi import Limiter
AUTH_RATE_LIMIT = "5/minute"
2026-11-21 12:26:28 -03:00
def _is_trusted_proxy(peer: str) -> bool:
"""Caddy reaches the gateway over a Docker network, so only private and loopback peers can forward the client."""
try:
address = ipaddress.ip_address(peer)
except ValueError:
return False
return address.is_private or address.is_loopback
def get_real_client_ip(request: Request) -> str:
2026-11-21 12:26:28 -03:00
peer = request.client.host if request.client else ""
forwarded_for = request.headers.get("x-forwarded-for", "")
2026-11-21 12:26:28 -03:00
if forwarded_for and _is_trusted_proxy(peer):
return forwarded_for.split(",")[0].strip()
2026-11-21 12:26:28 -03:00
return peer or "unknown"
2026-11-21 12:26:28 -03:00
def get_rate_limit_key(request: Request) -> str:
"""Client address used by the rate limit. IPv6 clients usually own a whole /64, so it counts as one address."""
client = get_real_client_ip(request)
try:
address = ipaddress.ip_address(client)
except ValueError:
return client
if address.version == 6:
if address.ipv4_mapped:
return str(address.ipv4_mapped)
return str(ipaddress.ip_network(f"{address}/64", strict=False))
return str(address)
limiter = Limiter(key_func=get_rate_limit_key)