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:
137
lib/__tests__/admin-auth.test.ts
Normal file
137
lib/__tests__/admin-auth.test.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import crypto from 'crypto';
|
||||
|
||||
// next/headers is only used by isAdminAuthenticated(), which we do not exercise here.
|
||||
vi.mock('next/headers', () => ({ cookies: async () => ({ get: () => undefined }) }));
|
||||
|
||||
const ADMIN_PASSWORD = 'correct-horse-battery-staple';
|
||||
const AUTH_SECRET = 'test-auth-secret-32-chars-long-min';
|
||||
|
||||
vi.mock('../env', () => ({
|
||||
env: {
|
||||
get AUTH_SECRET() {
|
||||
return process.env.__TEST_AUTH_SECRET;
|
||||
},
|
||||
get ADMIN_PASSWORD() {
|
||||
return process.env.__TEST_ADMIN_PASSWORD;
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
/** Import fresh so module-level state cannot leak between cases. */
|
||||
async function loadAuth() {
|
||||
vi.resetModules();
|
||||
return import('../admin/auth');
|
||||
}
|
||||
|
||||
function forgeToken(signingKey: Buffer, payload: object): string {
|
||||
const data = Buffer.from(JSON.stringify(payload)).toString('base64url');
|
||||
const sig = crypto.createHmac('sha256', signingKey).update(data).digest('base64url');
|
||||
return `${data}.${sig}`;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.__TEST_AUTH_SECRET = AUTH_SECRET;
|
||||
process.env.__TEST_ADMIN_PASSWORD = ADMIN_PASSWORD;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.__TEST_AUTH_SECRET;
|
||||
delete process.env.__TEST_ADMIN_PASSWORD;
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe('admin session tokens', () => {
|
||||
it('accepts a token it just issued', async () => {
|
||||
const { createAdminToken, verifyAdminToken } = await loadAuth();
|
||||
expect(verifyAdminToken(createAdminToken())).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a token forged with the old hardcoded dev fallback secret', async () => {
|
||||
const { verifyAdminToken } = await loadAuth();
|
||||
// The exact key an attacker could derive from the public source before the fix.
|
||||
const legacyKey = crypto.createHash('sha256').update('admin:dev-fallback-secret').digest();
|
||||
const forged = forgeToken(legacyKey, {
|
||||
role: 'admin',
|
||||
iat: Date.now(),
|
||||
exp: Date.now() + 60_000,
|
||||
});
|
||||
expect(verifyAdminToken(forged)).toBe(false);
|
||||
});
|
||||
|
||||
it('does not fall back to a guessable secret when AUTH_SECRET is unset in dev', async () => {
|
||||
delete process.env.__TEST_AUTH_SECRET;
|
||||
const { verifyAdminToken } = await loadAuth();
|
||||
const legacyKey = crypto.createHash('sha256').update('admin:dev-fallback-secret').digest();
|
||||
const forged = forgeToken(legacyKey, {
|
||||
role: 'admin',
|
||||
iat: Date.now(),
|
||||
exp: Date.now() + 60_000,
|
||||
});
|
||||
expect(verifyAdminToken(forged)).toBe(false);
|
||||
});
|
||||
|
||||
it('throws rather than signing with a guessable secret when AUTH_SECRET is unset in production', async () => {
|
||||
delete process.env.__TEST_AUTH_SECRET;
|
||||
vi.stubEnv('NODE_ENV', 'production');
|
||||
const { createAdminToken } = await loadAuth();
|
||||
expect(() => createAdminToken()).toThrow(/AUTH_SECRET/);
|
||||
});
|
||||
|
||||
it('returns false (not throw) for a malformed cookie with a short signature', async () => {
|
||||
const { verifyAdminToken } = await loadAuth();
|
||||
// Pre-fix this hit crypto.timingSafeEqual outside the try block -> RangeError -> HTTP 500.
|
||||
expect(() => verifyAdminToken('a.b')).not.toThrow();
|
||||
expect(verifyAdminToken('a.b')).toBe(false);
|
||||
expect(verifyAdminToken('not-a-token')).toBe(false);
|
||||
expect(verifyAdminToken('')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects an expired token', async () => {
|
||||
const { verifyAdminToken } = await loadAuth();
|
||||
const key = crypto
|
||||
.createHash('sha256')
|
||||
.update(`admin:${AUTH_SECRET}:${ADMIN_PASSWORD}`)
|
||||
.digest();
|
||||
const expired = forgeToken(key, { role: 'admin', iat: 0, exp: Date.now() - 1000 });
|
||||
expect(verifyAdminToken(expired)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a validly signed token whose role is not admin', async () => {
|
||||
const { verifyAdminToken } = await loadAuth();
|
||||
const key = crypto
|
||||
.createHash('sha256')
|
||||
.update(`admin:${AUTH_SECRET}:${ADMIN_PASSWORD}`)
|
||||
.digest();
|
||||
const wrongRole = forgeToken(key, { role: 'viewer', iat: 0, exp: Date.now() + 60_000 });
|
||||
expect(verifyAdminToken(wrongRole)).toBe(false);
|
||||
});
|
||||
|
||||
it('invalidates existing sessions when ADMIN_PASSWORD is rotated', async () => {
|
||||
const first = await loadAuth();
|
||||
const token = first.createAdminToken();
|
||||
expect(first.verifyAdminToken(token)).toBe(true);
|
||||
|
||||
process.env.__TEST_ADMIN_PASSWORD = 'a-brand-new-password';
|
||||
const second = await loadAuth();
|
||||
expect(second.verifyAdminToken(token)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('verifyAdminPassword', () => {
|
||||
it('accepts the configured password and rejects others', async () => {
|
||||
const { verifyAdminPassword } = await loadAuth();
|
||||
expect(verifyAdminPassword(ADMIN_PASSWORD)).toBe(true);
|
||||
expect(verifyAdminPassword('wrong')).toBe(false);
|
||||
expect(verifyAdminPassword(`${ADMIN_PASSWORD}x`)).toBe(false);
|
||||
expect(verifyAdminPassword('')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects everything when no ADMIN_PASSWORD is configured', async () => {
|
||||
delete process.env.__TEST_ADMIN_PASSWORD;
|
||||
const { verifyAdminPassword, isAdminEnabled } = await loadAuth();
|
||||
expect(isAdminEnabled()).toBe(false);
|
||||
expect(verifyAdminPassword('')).toBe(false);
|
||||
expect(verifyAdminPassword('anything')).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user