Files
immich-folio/app/api/image/__tests__/image-route.test.ts

135 lines
4.8 KiB
TypeScript
Raw Normal View History

Close the gaps left after v0.9.2's outage handling: route tests, stale cache, loading states (#397) * docs: brainstorm resilience/adoption features and plan follow-up work Brainstorm and deep-dive on where Immich Folio breaks under Immich outages and what blocks self-hosted adoption, plus an implementation plan for the remaining gaps after v0.9.2 (route-handler tests, stale-while-error caching, loading skeletons). * test: enable route-handler tests and cover admin guards and image content-type vitest.config.ts only ran lib/__tests__/**, so route handlers were structurally untestable. Two mechanisms live only at the route level and cannot be extracted the way lib/imageSize.ts was: the admin auth guards and the image proxy's Content-Type sanitisation (the stored-XSS fix from c2fa8e7). Both were correct but unverified by any test. Adds a table-driven test over all ten guarded /api/admin/* handlers, including a filesystem walk that fails if a future route is added without a row in the table. Adds a route-level test for /api/image/[id] covering token validation, the six Content-Type rewrite cases, ETag/304, and the 404 vs 503 (ImmichUnavailableError) distinction. Verified both catch real regressions by temporarily removing the admin guards and the Content-Type rewrite and confirming the expected tests fail, then restoring and confirming green again. 134 new tests (244 total, up from 210), tsc 0 errors, build succeeds. * feat: serve stale cache entries while Immich is unavailable v0.9.2 (#394) correctly split "gone" (404/410) from "unavailable" (ImmichUnavailableError), and pages now render a 5xx instead of a false 404 during an outage — but that 5xx still replaced a gallery that had loaded fine seconds earlier. lib/cache.ts deleted expired entries on access, so nothing survived long enough to fall back to. Cache entries now carry two deadlines: staleAt (the existing CACHE_TTL, after which get() still reports a miss) and hardExpiresAt (the new STALE_MAX_AGE, default 24h, after which the entry is dropped entirely). Between the two, getStale() can still return the data. getAlbums(), getAlbum() and getAssetInfo() catch ImmichUnavailableError and fall back to getStale() before propagating. The two MISSING-sentinel writes (definitive 404s) are deliberately left on the short cacheTtl window — a corrected asset ID should take effect after the normal TTL, not sit in the 24h stale window meant for outages. STALE_MAX_AGE=0 disables the fallback. Verified the fallback only engages on a real outage, not on a cache hit at the TTL boundary, and that a definitive 404 still reports missing rather than falling back. 256 tests (up from 244), tsc 0 errors, build succeeds. * feat: add loading skeletons for dynamic gallery routes Every gallery route is force-dynamic and waits on a live Immich round-trip — up to IMMICH_TIMEOUT_MS when the server is struggling — with nothing rendered until it resolves. loading.tsx renders instantly while the page component awaits its data. Not browser-verified against live data: this worktree has no .env.local and only .example content files, so the app boots into setup mode (confirmed the dev server starts cleanly and the setup screen renders, HTTP 200). tsc 0 errors, build succeeds, no new lint errors. * docs: document stale cache window, image token revocation, route-test convention - README: STALE_MAX_AGE env var and a "Behaviour when Immich is unreachable" section (stale-serves-until-STALE_MAX_AGE, 503 not 404, outages never cached). - docs/gallery-config.md: new "Image Token Revocation" subsection under System & Security — un-publishing an album does not revoke already issued image URLs; rotating AUTH_SECRET does. - CLAUDE.md: updated cache description to cover the stale window and MISSING sentinel, and a new code-convention note that route-level logic (guards, header sanitisation) should get a route-level test rather than being extracted into lib/ just to reach the test runner. --------- Co-authored-by: ralksta <ralksta@users.noreply.github.com>
2026-08-07 11:07:34 +02:00
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { NextRequest } from 'next/server';
import { GET } from '../[id]/route';
import { encodeAssetId } from '@/lib/tokens';
import { immich, ImmichUnavailableError } from '@/lib/immich';
const published = vi.hoisted(() => ({ value: true }));
vi.mock('@/lib/publishedAssets', () => ({
isPublishedAsset: async () => published.value,
}));
vi.mock('@/lib/admin/auth', () => ({
isAdminAuthenticated: async () => false,
}));
Close the gaps left after v0.9.2's outage handling: route tests, stale cache, loading states (#397) * docs: brainstorm resilience/adoption features and plan follow-up work Brainstorm and deep-dive on where Immich Folio breaks under Immich outages and what blocks self-hosted adoption, plus an implementation plan for the remaining gaps after v0.9.2 (route-handler tests, stale-while-error caching, loading skeletons). * test: enable route-handler tests and cover admin guards and image content-type vitest.config.ts only ran lib/__tests__/**, so route handlers were structurally untestable. Two mechanisms live only at the route level and cannot be extracted the way lib/imageSize.ts was: the admin auth guards and the image proxy's Content-Type sanitisation (the stored-XSS fix from c2fa8e7). Both were correct but unverified by any test. Adds a table-driven test over all ten guarded /api/admin/* handlers, including a filesystem walk that fails if a future route is added without a row in the table. Adds a route-level test for /api/image/[id] covering token validation, the six Content-Type rewrite cases, ETag/304, and the 404 vs 503 (ImmichUnavailableError) distinction. Verified both catch real regressions by temporarily removing the admin guards and the Content-Type rewrite and confirming the expected tests fail, then restoring and confirming green again. 134 new tests (244 total, up from 210), tsc 0 errors, build succeeds. * feat: serve stale cache entries while Immich is unavailable v0.9.2 (#394) correctly split "gone" (404/410) from "unavailable" (ImmichUnavailableError), and pages now render a 5xx instead of a false 404 during an outage — but that 5xx still replaced a gallery that had loaded fine seconds earlier. lib/cache.ts deleted expired entries on access, so nothing survived long enough to fall back to. Cache entries now carry two deadlines: staleAt (the existing CACHE_TTL, after which get() still reports a miss) and hardExpiresAt (the new STALE_MAX_AGE, default 24h, after which the entry is dropped entirely). Between the two, getStale() can still return the data. getAlbums(), getAlbum() and getAssetInfo() catch ImmichUnavailableError and fall back to getStale() before propagating. The two MISSING-sentinel writes (definitive 404s) are deliberately left on the short cacheTtl window — a corrected asset ID should take effect after the normal TTL, not sit in the 24h stale window meant for outages. STALE_MAX_AGE=0 disables the fallback. Verified the fallback only engages on a real outage, not on a cache hit at the TTL boundary, and that a definitive 404 still reports missing rather than falling back. 256 tests (up from 244), tsc 0 errors, build succeeds. * feat: add loading skeletons for dynamic gallery routes Every gallery route is force-dynamic and waits on a live Immich round-trip — up to IMMICH_TIMEOUT_MS when the server is struggling — with nothing rendered until it resolves. loading.tsx renders instantly while the page component awaits its data. Not browser-verified against live data: this worktree has no .env.local and only .example content files, so the app boots into setup mode (confirmed the dev server starts cleanly and the setup screen renders, HTTP 200). tsc 0 errors, build succeeds, no new lint errors. * docs: document stale cache window, image token revocation, route-test convention - README: STALE_MAX_AGE env var and a "Behaviour when Immich is unreachable" section (stale-serves-until-STALE_MAX_AGE, 503 not 404, outages never cached). - docs/gallery-config.md: new "Image Token Revocation" subsection under System & Security — un-publishing an album does not revoke already issued image URLs; rotating AUTH_SECRET does. - CLAUDE.md: updated cache description to cover the stale window and MISSING sentinel, and a new code-convention note that route-level logic (guards, header sanitisation) should get a route-level test rather than being extracted into lib/ just to reach the test runner. --------- Co-authored-by: ralksta <ralksta@users.noreply.github.com>
2026-08-07 11:07:34 +02:00
vi.mock('@/lib/immich', async () => {
const actual = await vi.importActual<typeof import('@/lib/immich')>('@/lib/immich');
return {
// Keep the real error class — the route branches on `instanceof`.
ImmichUnavailableError: actual.ImmichUnavailableError,
immich: { streamAsset: vi.fn() },
};
});
const mockStream = immich.streamAsset as unknown as ReturnType<typeof vi.fn>;
const ASSET_ID = '11111111-2222-3333-4444-555555555555';
/** Stream stub — the route only forwards the body, it never reads it. */
function fakeBody(contentType: string) {
return {
stream: new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array([1, 2, 3]));
controller.close();
},
}),
contentType,
contentLength: '3',
};
}
function call(token: string, query = '', headers?: Record<string, string>) {
const req = new NextRequest(`http://localhost/api/image/${token}${query}`, { headers });
return GET(req, { params: Promise.resolve({ id: token }) });
}
describe('GET /api/image/[id]', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('rejects a raw Immich UUID instead of an encoded token', async () => {
const res = await call(ASSET_ID);
expect(res.status).toBe(400);
expect(mockStream).not.toHaveBeenCalled();
});
it('rejects a syntactically broken token', async () => {
const res = await call('v2:not-valid-base64url!!');
expect(res.status).toBe(400);
expect(mockStream).not.toHaveBeenCalled();
});
it('refuses an asset the site no longer shows, without caching the refusal', async () => {
published.value = false;
try {
const res = await call(encodeAssetId(ASSET_ID));
expect(res.status).toBe(404);
expect(res.headers.get('Cache-Control')).toBe('no-store');
expect(mockStream).not.toHaveBeenCalled();
} finally {
published.value = true;
}
});
Close the gaps left after v0.9.2's outage handling: route tests, stale cache, loading states (#397) * docs: brainstorm resilience/adoption features and plan follow-up work Brainstorm and deep-dive on where Immich Folio breaks under Immich outages and what blocks self-hosted adoption, plus an implementation plan for the remaining gaps after v0.9.2 (route-handler tests, stale-while-error caching, loading skeletons). * test: enable route-handler tests and cover admin guards and image content-type vitest.config.ts only ran lib/__tests__/**, so route handlers were structurally untestable. Two mechanisms live only at the route level and cannot be extracted the way lib/imageSize.ts was: the admin auth guards and the image proxy's Content-Type sanitisation (the stored-XSS fix from c2fa8e7). Both were correct but unverified by any test. Adds a table-driven test over all ten guarded /api/admin/* handlers, including a filesystem walk that fails if a future route is added without a row in the table. Adds a route-level test for /api/image/[id] covering token validation, the six Content-Type rewrite cases, ETag/304, and the 404 vs 503 (ImmichUnavailableError) distinction. Verified both catch real regressions by temporarily removing the admin guards and the Content-Type rewrite and confirming the expected tests fail, then restoring and confirming green again. 134 new tests (244 total, up from 210), tsc 0 errors, build succeeds. * feat: serve stale cache entries while Immich is unavailable v0.9.2 (#394) correctly split "gone" (404/410) from "unavailable" (ImmichUnavailableError), and pages now render a 5xx instead of a false 404 during an outage — but that 5xx still replaced a gallery that had loaded fine seconds earlier. lib/cache.ts deleted expired entries on access, so nothing survived long enough to fall back to. Cache entries now carry two deadlines: staleAt (the existing CACHE_TTL, after which get() still reports a miss) and hardExpiresAt (the new STALE_MAX_AGE, default 24h, after which the entry is dropped entirely). Between the two, getStale() can still return the data. getAlbums(), getAlbum() and getAssetInfo() catch ImmichUnavailableError and fall back to getStale() before propagating. The two MISSING-sentinel writes (definitive 404s) are deliberately left on the short cacheTtl window — a corrected asset ID should take effect after the normal TTL, not sit in the 24h stale window meant for outages. STALE_MAX_AGE=0 disables the fallback. Verified the fallback only engages on a real outage, not on a cache hit at the TTL boundary, and that a definitive 404 still reports missing rather than falling back. 256 tests (up from 244), tsc 0 errors, build succeeds. * feat: add loading skeletons for dynamic gallery routes Every gallery route is force-dynamic and waits on a live Immich round-trip — up to IMMICH_TIMEOUT_MS when the server is struggling — with nothing rendered until it resolves. loading.tsx renders instantly while the page component awaits its data. Not browser-verified against live data: this worktree has no .env.local and only .example content files, so the app boots into setup mode (confirmed the dev server starts cleanly and the setup screen renders, HTTP 200). tsc 0 errors, build succeeds, no new lint errors. * docs: document stale cache window, image token revocation, route-test convention - README: STALE_MAX_AGE env var and a "Behaviour when Immich is unreachable" section (stale-serves-until-STALE_MAX_AGE, 503 not 404, outages never cached). - docs/gallery-config.md: new "Image Token Revocation" subsection under System & Security — un-publishing an album does not revoke already issued image URLs; rotating AUTH_SECRET does. - CLAUDE.md: updated cache description to cover the stale window and MISSING sentinel, and a new code-convention note that route-level logic (guards, header sanitisation) should get a route-level test rather than being extracted into lib/ just to reach the test runner. --------- Co-authored-by: ralksta <ralksta@users.noreply.github.com>
2026-08-07 11:07:34 +02:00
it('serves a valid token', async () => {
mockStream.mockResolvedValue(fakeBody('image/jpeg'));
const res = await call(encodeAssetId(ASSET_ID));
expect(res.status).toBe(200);
expect(mockStream).toHaveBeenCalledWith(ASSET_ID, 'preview');
});
// Regression guard for the stored-XSS fix in c2fa8e7. An SVG served as
// image/svg+xml executes script in the browser under our own origin.
// This logic lives in the route and cannot be extracted the way
// lib/imageSize.ts was, so a route-level test is the only way to pin it.
it.each([
['image/svg+xml', 'application/octet-stream'],
['text/xml', 'application/octet-stream'],
['text/html', 'application/octet-stream'],
['application/octet-stream', 'image/jpeg'],
['image/jpeg', 'image/jpeg'],
['image/webp', 'image/webp'],
])('rewrites upstream Content-Type %s to %s', async (upstream, expected) => {
mockStream.mockResolvedValue(fakeBody(upstream));
const res = await call(encodeAssetId(ASSET_ID));
expect(res.headers.get('Content-Type')).toBe(expected);
});
it('returns 304 with no body when the ETag matches', async () => {
mockStream.mockResolvedValue(fakeBody('image/jpeg'));
const token = encodeAssetId(ASSET_ID);
const first = await call(token);
const etag = first.headers.get('ETag');
expect(etag).toBeTruthy();
const res = await call(token, '', { 'if-none-match': etag as string });
expect(res.status).toBe(304);
expect(await res.text()).toBe('');
});
it('never leaks the raw asset UUID in response headers', async () => {
mockStream.mockResolvedValue(fakeBody('image/jpeg'));
const res = await call(encodeAssetId(ASSET_ID));
const headerDump = JSON.stringify([...res.headers.entries()]);
expect(headerDump).not.toContain(ASSET_ID);
});
it('404s when the asset is genuinely gone', async () => {
mockStream.mockResolvedValue(null);
const res = await call(encodeAssetId(ASSET_ID));
expect(res.status).toBe(404);
expect(res.headers.get('Cache-Control')).toBe('no-store');
});
it('503s when Immich is unavailable, and does not let it be cached', async () => {
mockStream.mockRejectedValue(new ImmichUnavailableError('upstream down'));
const res = await call(encodeAssetId(ASSET_ID));
expect(res.status).toBe(503);
expect(res.headers.get('Cache-Control')).toBe('no-store');
expect(res.headers.get('Retry-After')).toBeTruthy();
});
});