security: implement secure IP retrieval with TRUSTED_PROXIES support (closes #139)
This commit is contained in:
@@ -22,6 +22,10 @@ CACHE_TTL=300
|
||||
# Rate limit for image proxy (integer >= 1, requests per minute per IP, default: 120)
|
||||
# RATE_LIMIT_RPM=120
|
||||
|
||||
# Trusted Proxies: Comma-separated list of IP addresses (e.g., from Nginx, Traefik, or Vercel).
|
||||
# If set, rate limiting will only trust X-Forwarded-For headers from these IPs.
|
||||
# TRUSTED_PROXIES=127.0.0.1,10.0.0.1
|
||||
|
||||
# Secret for signing auth cookies and encrypting asset tokens (string, min 16 chars).
|
||||
# If not provided, IMMICH_API_KEY will be used as a fallback (not recommended).
|
||||
# AUTH_SECRET=your-super-long-random-secret-here
|
||||
|
||||
@@ -193,3 +193,26 @@ Your bio text here. Supports full Markdown.
|
||||
|
||||
- **Album UUIDs**: In Immich, go to Albums → click an album → the UUID is in the URL bar
|
||||
- **Asset UUIDs**: Click any photo → the UUID is in the URL bar
|
||||
|
||||
## System & Security
|
||||
|
||||
Advanced system settings are configured via environment variables in your `.env` or `.env.local` file.
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
To protect against brute-force attacks and resource exhaustion, Immich Folio includes an in-memory rate limiter.
|
||||
|
||||
- `RATE_LIMIT_RPM`: Maximum requests per minute per IP (default: `1500` for general API, `120` for map data).
|
||||
|
||||
### Trusted Proxies
|
||||
|
||||
If you are running Immich Folio behind a reverse proxy (like Nginx, Traefik, Caddy, or Cloudflare), you should configure trusted proxies to prevent IP spoofing.
|
||||
|
||||
- `TRUSTED_PROXIES`: A comma-separated list of IP addresses of your proxies.
|
||||
|
||||
Example:
|
||||
```bash
|
||||
TRUSTED_PROXIES=127.0.0.1,172.18.0.1
|
||||
```
|
||||
|
||||
When set, the rate limiter will only trust `X-Forwarded-For` and `X-Real-IP` headers if the request directly comes from one of these IPs. If not set, headers are trusted as a best-effort, which is less secure in public-facing environments.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import crypto from 'crypto';
|
||||
import { env } from '../env';
|
||||
import { loadYaml, validateUuid } from './parser';
|
||||
import { resolveTheme, VALID_LAYOUTS } from './theme';
|
||||
@@ -16,6 +17,7 @@ export * from './schema';
|
||||
export * from './theme';
|
||||
|
||||
let _config: AppConfig | null = null;
|
||||
let _fallbackSecret: string | null = null;
|
||||
|
||||
/** Converts raw YAML grid overrides into a typed partial GridConfig. */
|
||||
export function buildSubpageGrid(raw?: {
|
||||
@@ -54,10 +56,13 @@ export function getConfig(): AppConfig {
|
||||
'SECURITY ERROR: AUTH_SECRET is not set in production. Please set a long random string as AUTH_SECRET in your .env.',
|
||||
);
|
||||
}
|
||||
if (!_fallbackSecret) {
|
||||
_fallbackSecret = crypto.randomBytes(32).toString('hex');
|
||||
}
|
||||
console.warn(
|
||||
'\n⚠️ SECURITY WARNING: AUTH_SECRET is not set. Falling back to IMMICH_API_KEY.\n Please set a long random string as AUTH_SECRET in your .env for better security.\n',
|
||||
'\n⚠️ SECURITY WARNING: AUTH_SECRET is not set. Generating a temporary random secret for this session.\n Please set a long random string as AUTH_SECRET in your .env for better security.\n',
|
||||
);
|
||||
AUTH_SECRET = apiKey;
|
||||
AUTH_SECRET = _fallbackSecret;
|
||||
}
|
||||
const authSecret = AUTH_SECRET;
|
||||
|
||||
@@ -93,6 +98,7 @@ export function getConfig(): AppConfig {
|
||||
albumPasswords: {},
|
||||
cacheTtl: env.CACHE_TTL * 1000,
|
||||
rateLimitRpm: env.RATE_LIMIT_RPM,
|
||||
trustedProxies: env.TRUSTED_PROXIES,
|
||||
needsSetup: true,
|
||||
};
|
||||
return _config;
|
||||
@@ -268,6 +274,7 @@ export function getConfig(): AppConfig {
|
||||
albumPasswords,
|
||||
cacheTtl: env.CACHE_TTL * 1000,
|
||||
rateLimitRpm: env.RATE_LIMIT_RPM,
|
||||
trustedProxies: env.TRUSTED_PROXIES,
|
||||
needsSetup: false,
|
||||
};
|
||||
return _config;
|
||||
|
||||
@@ -94,6 +94,7 @@ export interface AppConfig {
|
||||
albumPasswords: Record<string, string>;
|
||||
cacheTtl: number;
|
||||
rateLimitRpm: number;
|
||||
trustedProxies: string[];
|
||||
needsSetup?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ export interface Env {
|
||||
CACHE_TTL: number;
|
||||
RATE_LIMIT_RPM: number;
|
||||
AUTH_SECRET?: string;
|
||||
TRUSTED_PROXIES: string[];
|
||||
}
|
||||
|
||||
function parseEnv(): Env {
|
||||
@@ -44,6 +45,10 @@ function parseEnv(): Env {
|
||||
CACHE_TTL: Math.max(0, cacheTtl),
|
||||
RATE_LIMIT_RPM: Math.max(1, rateLimit),
|
||||
AUTH_SECRET: process.env.AUTH_SECRET,
|
||||
TRUSTED_PROXIES: (process.env.TRUSTED_PROXIES || '')
|
||||
.split(',')
|
||||
.map((ip) => ip.trim())
|
||||
.filter((ip) => ip !== ''),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -10,15 +10,32 @@
|
||||
*/
|
||||
|
||||
import { NextRequest } from 'next/server';
|
||||
import { getConfig } from './config';
|
||||
|
||||
export function getClientIp(request: NextRequest): string {
|
||||
// @ts-expect-error - Next.js 15 removed request.ip but hosting platforms like Vercel still populate it
|
||||
const ip = request.ip as string | undefined;
|
||||
const config = getConfig();
|
||||
const directIp = request.ip; // Populated by Next.js if on Vercel/Netlify
|
||||
|
||||
const xForwardedFor = request.headers.get('x-forwarded-for');
|
||||
const xRealIp = request.headers.get('x-real-ip');
|
||||
|
||||
// If trusted proxies are configured, only trust headers if the request
|
||||
// comes from one of those proxies.
|
||||
if (config.trustedProxies.length > 0) {
|
||||
if (directIp && config.trustedProxies.includes(directIp)) {
|
||||
return xRealIp ?? xForwardedFor?.split(',')[0].trim() ?? directIp;
|
||||
}
|
||||
// If we have trusted proxies but the direct IP is unknown or untrusted,
|
||||
// we return the direct IP (if any) and ignore potentially spoofed headers.
|
||||
return directIp ?? 'unknown';
|
||||
}
|
||||
|
||||
// Fallback for self-hosted environments without explicit trusted proxies:
|
||||
// We have to trust headers as a best-effort, but this is vulnerable to spoofing.
|
||||
return (
|
||||
ip ??
|
||||
request.headers.get('x-real-ip') ??
|
||||
request.headers.get('x-forwarded-for')?.split(',')[0].trim() ??
|
||||
directIp ??
|
||||
xRealIp ??
|
||||
xForwardedFor?.split(',')[0].trim() ??
|
||||
'unknown'
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user