Refactor backend configuration and authentication
- Add comprehensive documentation for backend development - Improve client IP detection with utility functions and tests - Update auth router with better error handling - Refactor config module with environment-based settings Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -4,6 +4,7 @@ Follows pydantic-settings patterns: all values are prefixed with BANGUI_
|
||||
and validated at startup via the Settings singleton.
|
||||
"""
|
||||
|
||||
import ipaddress
|
||||
import shlex
|
||||
from typing import Literal
|
||||
|
||||
@@ -180,6 +181,62 @@ class Settings(BaseSettings):
|
||||
"In production, leave unset (defaults to false) to avoid exposing API schema."
|
||||
),
|
||||
)
|
||||
trusted_proxies: str | list[str] = Field(
|
||||
default_factory=list,
|
||||
description=(
|
||||
"Comma-separated list of trusted reverse proxy IP addresses or CIDR ranges. "
|
||||
"Only requests from these IPs/ranges are allowed to set X-Forwarded-For and X-Real-IP headers. "
|
||||
"Examples: '192.168.1.1' or '10.0.0.0/8' or '192.168.1.1,10.0.0.0/8'. "
|
||||
"Leave empty to disable proxy header forwarding (default). "
|
||||
"This is critical for correct client IP extraction behind reverse proxies like nginx."
|
||||
),
|
||||
)
|
||||
|
||||
@field_validator("trusted_proxies", mode="before")
|
||||
@classmethod
|
||||
def _normalize_trusted_proxies(cls, value: str | list[str] | None) -> list[str]:
|
||||
"""Normalize trusted_proxies from comma-separated string to list.
|
||||
|
||||
Args:
|
||||
value: A comma-separated string or list of trusted proxy IPs/CIDRs.
|
||||
|
||||
Returns:
|
||||
A list of normalized proxy IP/CIDR strings.
|
||||
"""
|
||||
if value is None:
|
||||
return []
|
||||
if isinstance(value, str):
|
||||
return [proxy.strip() for proxy in value.split(",") if proxy.strip()]
|
||||
return value
|
||||
|
||||
@field_validator("trusted_proxies", mode="after")
|
||||
@classmethod
|
||||
def _validate_trusted_proxies(cls, value: list[str]) -> list[str]:
|
||||
"""Validate trusted_proxies as valid IPs or CIDR ranges.
|
||||
|
||||
Args:
|
||||
value: A list of proxy IP addresses or CIDR ranges.
|
||||
|
||||
Returns:
|
||||
The validated list.
|
||||
|
||||
Raises:
|
||||
ValueError: If any item is not a valid IP address or CIDR range.
|
||||
"""
|
||||
for proxy in value:
|
||||
try:
|
||||
# Try to parse as a CIDR network first
|
||||
ipaddress.ip_network(proxy, strict=False)
|
||||
except ValueError:
|
||||
try:
|
||||
# Fall back to parsing as a single IP address
|
||||
ipaddress.ip_address(proxy)
|
||||
except ValueError as exc:
|
||||
raise ValueError(
|
||||
f"Invalid IP address or CIDR range: {proxy!r}. "
|
||||
f"Expected format: '192.168.1.1' or '10.0.0.0/8'"
|
||||
) from exc
|
||||
return value
|
||||
|
||||
@field_validator("fail2ban_start_command", mode="after")
|
||||
@classmethod
|
||||
@@ -222,4 +279,4 @@ def get_settings() -> Settings:
|
||||
A validated :class:`Settings` object. Raises :class:`pydantic.ValidationError`
|
||||
if required keys are absent or values fail validation.
|
||||
"""
|
||||
return Settings() # pydantic-settings populates required fields from env vars
|
||||
return Settings() # type: ignore[call-arg] # pydantic-settings populates required fields from env vars
|
||||
|
||||
@@ -41,10 +41,6 @@ log: structlog.stdlib.BoundLogger = structlog.get_logger()
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
|
||||
# Trusted proxy IPs that can set X-Forwarded-For header.
|
||||
# By default, none are trusted. In production behind nginx, add the nginx container IP.
|
||||
_TRUSTED_PROXIES: list[str] = []
|
||||
|
||||
|
||||
@router.post(
|
||||
"/login",
|
||||
@@ -73,7 +69,7 @@ async def login(
|
||||
response: FastAPI response object used to set the cookie.
|
||||
request: The incoming HTTP request (used to extract client IP).
|
||||
session_ctx: Session service context containing db and repository.
|
||||
settings: Application settings (used for session duration).
|
||||
settings: Application settings (used for session duration and trusted proxies).
|
||||
rate_limiter: The login rate limiter (per IP).
|
||||
|
||||
Returns:
|
||||
@@ -83,7 +79,7 @@ async def login(
|
||||
AuthenticationError: if the password is incorrect.
|
||||
RateLimitError: if the rate limit is exceeded.
|
||||
"""
|
||||
client_ip = get_client_ip(request, trusted_proxies=_TRUSTED_PROXIES)
|
||||
client_ip = get_client_ip(request, trusted_proxies=settings.trusted_proxies)
|
||||
|
||||
if not rate_limiter.is_allowed(client_ip):
|
||||
log.warning("login_rate_limit_exceeded", client_ip=client_ip)
|
||||
|
||||
@@ -6,13 +6,16 @@ Only trusts these headers when the request comes from a known trusted proxy.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from fastapi import Request
|
||||
|
||||
|
||||
def get_client_ip(request: Request, trusted_proxies: list[str] | None = None) -> str:
|
||||
def get_client_ip(
|
||||
request: Request, trusted_proxies: str | list[str] | None = None
|
||||
) -> str:
|
||||
"""Extract the client IP address from a request.
|
||||
|
||||
When the request comes from a trusted proxy, reads the real IP from
|
||||
@@ -20,12 +23,12 @@ def get_client_ip(request: Request, trusted_proxies: list[str] | None = None) ->
|
||||
connection source (request.client.host).
|
||||
|
||||
X-Forwarded-For can be spoofed by the client, so we only trust it if
|
||||
the request comes from a known proxy IP.
|
||||
the request comes from a known proxy IP or CIDR range.
|
||||
|
||||
Args:
|
||||
request: The incoming FastAPI request.
|
||||
trusted_proxies: Optional list of trusted proxy IP addresses. If None,
|
||||
only uses request.client.host.
|
||||
trusted_proxies: Optional list of trusted proxy IP addresses or CIDR ranges,
|
||||
or a comma-separated string. If None, only uses request.client.host.
|
||||
|
||||
Returns:
|
||||
The best-guess client IP address suitable for rate limiting.
|
||||
@@ -34,10 +37,23 @@ def get_client_ip(request: Request, trusted_proxies: list[str] | None = None) ->
|
||||
return "0.0.0.0"
|
||||
|
||||
immediate_ip = request.client.host
|
||||
trusted_proxies = trusted_proxies or []
|
||||
|
||||
# If the immediate connection is not from a trusted proxy, use it directly.
|
||||
if immediate_ip not in trusted_proxies:
|
||||
# Normalize trusted_proxies to a list
|
||||
if isinstance(trusted_proxies, str):
|
||||
trusted_proxies = [
|
||||
proxy.strip()
|
||||
for proxy in trusted_proxies.split(",")
|
||||
if proxy.strip()
|
||||
]
|
||||
elif trusted_proxies is None:
|
||||
trusted_proxies = []
|
||||
|
||||
# If no trusted proxies are configured, use immediate IP directly
|
||||
if not trusted_proxies:
|
||||
return immediate_ip
|
||||
|
||||
# Check if the immediate connection is from a trusted proxy
|
||||
if not _is_trusted_proxy(immediate_ip, trusted_proxies):
|
||||
return immediate_ip
|
||||
|
||||
# Proxy is trusted, check for forwarded headers.
|
||||
@@ -57,3 +73,41 @@ def get_client_ip(request: Request, trusted_proxies: list[str] | None = None) ->
|
||||
|
||||
# No forwarded headers found, use immediate connection
|
||||
return immediate_ip
|
||||
|
||||
|
||||
def _is_trusted_proxy(ip: str, trusted_proxies: list[str]) -> bool:
|
||||
"""Check if an IP is in the list of trusted proxies.
|
||||
|
||||
Supports both single IP addresses and CIDR ranges.
|
||||
|
||||
Args:
|
||||
ip: The IP address to check.
|
||||
trusted_proxies: List of trusted proxy IP addresses or CIDR ranges.
|
||||
|
||||
Returns:
|
||||
True if the IP is trusted, False otherwise.
|
||||
"""
|
||||
try:
|
||||
ip_obj = ipaddress.ip_address(ip)
|
||||
except ValueError:
|
||||
# Invalid IP format
|
||||
return False
|
||||
|
||||
for proxy in trusted_proxies:
|
||||
try:
|
||||
# Try to parse as a CIDR network
|
||||
network = ipaddress.ip_network(proxy, strict=False)
|
||||
if ip_obj in network:
|
||||
return True
|
||||
except ValueError:
|
||||
try:
|
||||
# Fall back to single IP address
|
||||
proxy_ip = ipaddress.ip_address(proxy)
|
||||
if ip_obj == proxy_ip:
|
||||
return True
|
||||
except ValueError:
|
||||
# Invalid proxy format, skip it
|
||||
continue
|
||||
|
||||
return False
|
||||
|
||||
|
||||
Reference in New Issue
Block a user