security: fix pre-auth bypasses and restore Immich 3.x compatibility (#378)
Seven security issues from an audit, plus album pages and the map coming up empty against Immich 3.x. Verified against a real Immich 3.0.3 instance in a production build. Security: - Admin session forgery via a hardcoded 'dev-fallback-secret' signing key that bypassed the production AUTH_SECRET guard - /api/map ignored album passwords and returned working asset tokens; rewriting ?size=thumbnail to ?size=original downloaded full-resolution originals from protected albums - Admin login had no rate limit, and the client IP came from a spoofable header, so rotating it bypassed every limit in the app - Raw Immich asset UUIDs were serialized into the RSC payload - Album tokens never expired server-side; a captured token replayed forever - Path traversal into the Immich API via an unvalidated album id - /admin ran with no enforced CSP (only Report-Only reached it) TRUSTED_PROXIES is replaced by TRUSTED_PROXY_HOPS. The old variable matched proxy IPs against the socket peer address, which self-hosted Next.js never exposes, so the check could never pass: unset, the limiter read a spoofable header; set, every request shared one bucket and a single client could rate-limit the whole site. Migrates automatically. Immich 3.x: GET /albums/:id no longer embeds assets. Assets now come from POST /search/metadata with withExif: true — without that flag EXIF is omitted and grid aspect ratios, the lightbox panel and map markers stay empty. Drops support for Immich below 3.0, which now logs a warning. Upgrade: requires Immich 3.0+; set TRUSTED_PROXY_HOPS (nginx = 1); visitors of protected areas and admin sessions must log in once more. 91 unit tests (25 new); the new admin-auth and rate-limit cases were confirmed to fail against the pre-fix code. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -25,6 +25,7 @@ import {
|
||||
assetExifSummary,
|
||||
assetAspectRatio,
|
||||
} from '@/lib/urls';
|
||||
import { encodeAssetId } from '@/lib/tokens';
|
||||
import { getConfig, type GridConfig } from '@/lib/config';
|
||||
import { isProtected, isAuthenticated } from '@/lib/auth';
|
||||
import PasswordGate from '@/components/PasswordGate';
|
||||
@@ -96,7 +97,9 @@ function toPhotoItems(assets: ImmichAsset[], showExif: boolean): PhotoItem[] {
|
||||
const exif = showExif && a.type === 'IMAGE' ? assetExifSummary(a) : undefined;
|
||||
const isVideo = a.type === 'VIDEO';
|
||||
return {
|
||||
id: a.id,
|
||||
// Opaque token, never the raw Immich UUID — this object is serialized
|
||||
// into the RSC payload and shipped to the browser. Used only as a React key.
|
||||
id: encodeAssetId(a.id),
|
||||
type: isVideo ? 'video' : 'image',
|
||||
thumbUrl: imageUrl(a.id, 'preview'),
|
||||
previewUrl: imageUrl(a.id, 'preview'),
|
||||
|
||||
@@ -5,6 +5,16 @@ export const metadata: Metadata = {
|
||||
robots: { index: false, follow: false },
|
||||
};
|
||||
|
||||
/**
|
||||
* Required for the CSP nonce. The admin page is a pure client component, so
|
||||
* Next.js would statically prerender it at build time — and a prerendered HTML
|
||||
* file cannot carry the per-request nonce that middleware.ts issues. Since the
|
||||
* CSP uses 'strict-dynamic' (which makes 'self' inert), unnonced script tags
|
||||
* are blocked and the panel never hydrates. Rendering per request lets Next.js
|
||||
* stamp the nonce onto the script tags it emits.
|
||||
*/
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default function AdminLayout({ children }: { children: React.ReactNode }) {
|
||||
return <div className="admin-layout">{children}</div>;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { isAdminAuthenticated, isAdminEnabled } from '@/lib/admin/auth';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { isUuid } from '@/lib/uuid';
|
||||
|
||||
interface ImmichAlbumDetail {
|
||||
assets: Array<{
|
||||
@@ -35,8 +36,14 @@ export async function GET(
|
||||
|
||||
const { albumId } = await params;
|
||||
|
||||
// Without this, `..%2f..%2fusers` resolves inside fetch() to an arbitrary
|
||||
// Immich endpoint, called with the server's API key.
|
||||
if (!isUuid(albumId)) {
|
||||
return NextResponse.json({ error: 'Invalid album ID' }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${config.immich.apiUrl}/albums/${albumId}`, {
|
||||
const res = await fetch(`${config.immich.apiUrl}/albums/${encodeURIComponent(albumId)}`, {
|
||||
headers: {
|
||||
'x-api-key': config.immich.apiKey,
|
||||
Accept: 'application/json',
|
||||
|
||||
@@ -7,9 +7,25 @@ import {
|
||||
COOKIE_NAME,
|
||||
SESSION_DURATION_MS,
|
||||
} from '@/lib/admin/auth';
|
||||
import { checkRateLimit, getClientIp } from '@/lib/rate-limit';
|
||||
|
||||
/** Admin login attempts per minute per IP — the highest-value credential in the app. */
|
||||
const ADMIN_AUTH_RPM = 5;
|
||||
|
||||
/** POST: Login with admin password. */
|
||||
export async function POST(request: NextRequest) {
|
||||
const ip = getClientIp(request);
|
||||
const rl = checkRateLimit(`admin-auth:${ip}`, ADMIN_AUTH_RPM);
|
||||
if (!rl.success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Too many requests' },
|
||||
{
|
||||
status: 429,
|
||||
headers: { 'Retry-After': String(Math.ceil((rl.resetAt - Date.now()) / 1000)) },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAdminEnabled()) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Admin panel is not enabled. Set ADMIN_PASSWORD in your environment.' },
|
||||
|
||||
@@ -6,11 +6,9 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { isAdminAuthenticated, isAdminEnabled } from '@/lib/admin/auth';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { isUuid } from '@/lib/uuid';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
if (!isAdminEnabled()) {
|
||||
return NextResponse.json({ error: 'Admin not enabled' }, { status: 403 });
|
||||
}
|
||||
@@ -25,22 +23,17 @@ export async function GET(
|
||||
|
||||
const { id: assetId } = await params;
|
||||
|
||||
// Validate it looks like a UUID
|
||||
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
if (!uuidRegex.test(assetId)) {
|
||||
if (!isUuid(assetId)) {
|
||||
return NextResponse.json({ error: 'Invalid asset ID' }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(
|
||||
`${config.immich.apiUrl}/assets/${assetId}/thumbnail?size=thumbnail`,
|
||||
{
|
||||
headers: {
|
||||
'x-api-key': config.immich.apiKey,
|
||||
Accept: 'application/octet-stream',
|
||||
},
|
||||
const res = await fetch(`${config.immich.apiUrl}/assets/${assetId}/thumbnail?size=thumbnail`, {
|
||||
headers: {
|
||||
'x-api-key': config.immich.apiKey,
|
||||
Accept: 'application/octet-stream',
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
return NextResponse.json({ error: 'Asset not found' }, { status: 404 });
|
||||
|
||||
@@ -27,7 +27,7 @@ function widthToSize(w: number): ImageSize {
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
// ── Rate limiting ──────────────────────────────────
|
||||
const ip = getClientIp(request);
|
||||
const { success, remaining, resetAt } = checkRateLimit(ip, getConfig().rateLimitRpm);
|
||||
const { success, remaining, resetAt } = checkRateLimit(`image:${ip}`, getConfig().rateLimitRpm);
|
||||
|
||||
if (!success) {
|
||||
const retryAfter = Math.ceil((resetAt - Date.now()) / 1000);
|
||||
|
||||
@@ -14,10 +14,12 @@ import { checkRateLimit, getClientIp } from '@/lib/rate-limit';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/** Map data is cached client-side, so a low limit is plenty. */
|
||||
const MAP_RPM = 120;
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
// Rate limit: 120 requests/minute per IP (map data is cached client-side; this guards against abuse)
|
||||
const ip = getClientIp(request);
|
||||
const rl = checkRateLimit(ip, 120);
|
||||
const rl = checkRateLimit(`map:${ip}`, MAP_RPM);
|
||||
if (!rl.success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Too many requests' },
|
||||
@@ -43,28 +45,50 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
const locations = await getMapData();
|
||||
|
||||
// Filter locations and albums based on auth
|
||||
const authCache = new Map<string, boolean>();
|
||||
// Filter locations and albums based on auth.
|
||||
// An album is visible only if BOTH its subpage gate (if any) and its own
|
||||
// album-level password gate are satisfied. Standalone albums are NOT
|
||||
// implicitly public — they can carry their own password.
|
||||
const subpageAuthCache = new Map<string, boolean>();
|
||||
const albumAuthCache = new Map<string, boolean>();
|
||||
|
||||
const isSubpageAllowed = (slug: string): boolean => {
|
||||
const cached = subpageAuthCache.get(slug);
|
||||
if (cached !== undefined) return cached;
|
||||
const result = isAuthenticated(slug, getCookie);
|
||||
subpageAuthCache.set(slug, result);
|
||||
return result;
|
||||
};
|
||||
|
||||
const isAlbumAllowed = (albumId: string): boolean => {
|
||||
const cached = albumAuthCache.get(albumId);
|
||||
if (cached !== undefined) return cached;
|
||||
const result = isAuthenticated(albumId, getCookie, 'album');
|
||||
albumAuthCache.set(albumId, result);
|
||||
return result;
|
||||
};
|
||||
|
||||
const publicLocations = locations
|
||||
.map((loc) => {
|
||||
// Only keep albums the user is allowed to see
|
||||
const allowedAlbums = loc.albums.filter((a) => {
|
||||
if (!a.subpageSlug) return true; // Standalone albums are public
|
||||
if (authCache.has(a.subpageSlug)) return authCache.get(a.subpageSlug)!;
|
||||
const result = isAuthenticated(a.subpageSlug, getCookie);
|
||||
authCache.set(a.subpageSlug, result);
|
||||
return result;
|
||||
});
|
||||
const allowedAlbums = loc.albums.filter(
|
||||
(a) => (!a.subpageSlug || isSubpageAllowed(a.subpageSlug)) && isAlbumAllowed(a.id),
|
||||
);
|
||||
|
||||
if (allowedAlbums.length === 0) return null;
|
||||
|
||||
// Aggregate over visible albums only, so neither the marker position,
|
||||
// the photo count, nor the cover asset reveals a protected album.
|
||||
const photoCount = allowedAlbums.reduce((sum, a) => sum + a.photoCount, 0);
|
||||
const latSum = allowedAlbums.reduce((sum, a) => sum + a.latSum, 0);
|
||||
const lngSum = allowedAlbums.reduce((sum, a) => sum + a.lngSum, 0);
|
||||
|
||||
return {
|
||||
city: loc.city,
|
||||
country: loc.country,
|
||||
lat: loc.lat,
|
||||
lng: loc.lng,
|
||||
photoCount: loc.photoCount, // Note: This count might be slightly off if some photos are in hidden albums
|
||||
coverUrl: imageUrl(loc.coverAssetId, 'thumbnail'),
|
||||
lat: latSum / photoCount,
|
||||
lng: lngSum / photoCount,
|
||||
photoCount,
|
||||
coverUrl: imageUrl(allowedAlbums[0].coverAssetId, 'thumbnail'),
|
||||
albums: allowedAlbums.map((a) => ({
|
||||
name: a.name,
|
||||
url: a.subpageSlug ? `/${a.subpageSlug}/${a.slug}` : `/${a.slug}`,
|
||||
|
||||
@@ -11,11 +11,19 @@ import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { checkRateLimit, getClientIp } from '@/lib/rate-limit';
|
||||
|
||||
/**
|
||||
* OG image rendering runs satori + resvg per request and each unique ?title
|
||||
* misses every cache tier, so this is far more expensive than an image proxy
|
||||
* hit. It must not inherit RATE_LIMIT_RPM (default 1500) — that turns the
|
||||
* endpoint into an unauthenticated CPU amplifier.
|
||||
*/
|
||||
const OG_RPM = 30;
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const ip = getClientIp(request);
|
||||
const { theme, rateLimitRpm } = getConfig();
|
||||
const { theme } = getConfig();
|
||||
|
||||
const { success } = checkRateLimit(`og:${ip}`, rateLimitRpm);
|
||||
const { success } = checkRateLimit(`og:${ip}`, OG_RPM);
|
||||
if (!success) {
|
||||
return new NextResponse('Too many requests', { status: 429 });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user