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:
2026-04-29 19:39:55 +02:00
parent dd14ed7e7e
commit 6bc440dce4
7 changed files with 632 additions and 33 deletions

View File

@@ -1748,6 +1748,106 @@ BANGUI_FAIL2BAN_START_COMMAND='"/opt/my tools/fail2ban" start' # Quoted path
**Common Pitfall:**
Using `.split()` instead of `shlex.split()` would break commands with spaces in paths. Always use quoted strings for paths that contain whitespace.
### Trusted Proxy Configuration (Reverse Proxy Deployments)
When BanGUI is deployed behind a reverse proxy (nginx, HAProxy, etc.), the proxy forwards the original client IP via HTTP headers (`X-Forwarded-For`, `X-Real-IP`). To extract the correct client IP for rate limiting and logging, you must configure which proxies are trusted.
**Why This Is Needed:**
Rate limiting (`POST /api/auth/login`) relies on accurate client IP detection to prevent brute-force attacks. Without proper proxy configuration:
- Rate limits are applied per **proxy IP** (always the same) instead of per **client IP** — attackers can bypass limits by making many requests from the same proxy.
- Logging shows proxy IPs instead of actual attacker IPs.
**Trusted Proxies Configuration:**
```bash
BANGUI_TRUSTED_PROXIES="10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"
```
Accepted formats:
- **Single IP:** `BANGUI_TRUSTED_PROXIES="192.168.1.1"`
- **CIDR range:** `BANGUI_TRUSTED_PROXIES="10.0.0.0/8"` (matches any IP in 10.0.0.0 to 10.255.255.255)
- **Multiple entries (comma-separated):** `BANGUI_TRUSTED_PROXIES="192.168.1.1,10.0.0.0/8"`
- **Whitespace is stripped:** `BANGUI_TRUSTED_PROXIES="192.168.1.1 , 10.0.0.0/8"` is valid
- **IPv6 supported:** `BANGUI_TRUSTED_PROXIES="2001:db8::/32"`
**Default:** Empty list (no proxies trusted). Proxy headers are ignored, and only the direct connection IP is used.
**Validation:**
The application validates all entries at startup:
- Each entry must be a valid IP address or CIDR range.
- Invalid entries (e.g., `"not-an-ip"`, `"10.0.0.0/33"`) will cause a `ValidationError` at startup.
- The application will not start if any entry is invalid.
**How It Works:**
1. When a request arrives, the middleware checks the immediate connection source (e.g., `client.host`).
2. If the immediate connection is **not** in the `trusted_proxies` list, it is used directly as the client IP (proxy headers are ignored).
3. If the immediate connection **is** trusted, the middleware extracts the original client IP from headers in this order:
- `X-Forwarded-For` (leftmost IP in the chain, if present)
- `X-Real-IP` (fallback)
- Immediate connection IP (if no forwarded headers found)
**Example Docker Compose Configuration:**
```yaml
version: '3.8'
services:
nginx:
image: nginx:latest
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
networks:
- bangui-net
backend:
image: bangui:latest
environment:
BANGUI_TRUSTED_PROXIES: "10.0.0.0/8" # Trust Docker internal network
BANGUI_SESSION_COOKIE_SECURE: "false" # nginx terminates TLS
networks:
- bangui-net
networks:
bangui-net:
driver: bridge
```
**Example nginx Configuration:**
```nginx
upstream bangui_backend {
server backend:8000;
}
server {
listen 80;
server_name bangui.example.com;
location /api/ {
proxy_pass http://bangui_backend;
# Forward the original client IP
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
# Required for FastAPI to recognize the original protocol
proxy_set_header Host $host;
}
}
```
**Important Security Notes:**
- **Only trust IPs you control.** Never include untrusted networks or `0.0.0.0/0`. An attacker with network access to a trusted IP can forge `X-Forwarded-For` headers and bypass rate limits.
- **Validate proxy IPs carefully.** Use CIDR ranges that match your infrastructure (e.g., `10.0.0.0/8` for Docker, `172.31.0.0/16` for specific Docker networks).
- **Use HTTPS in production.** Ensure your nginx terminates TLS (uses HTTPS) and passes `X-Forwarded-Proto: https` so FastAPI's `Secure` cookie flag works correctly.
- **Beware of Header Spoofing.** `X-Forwarded-For` can contain multiple IPs (client, proxy1, proxy2). The leftmost IP is used as the original client. If an untrusted proxy is between the client and your BanGUI instance, attackers can still spoof headers. Always filter at the network level — only allow traffic from trusted proxies.
### IP Geolocation Resolution
BanGUI resolves IP addresses to country codes and network organization information for ban analytics and geomapping. The geolocation system implements a **primary + fallback** resolution strategy to balance security and availability: