From 846904f3dba6eb9b505c0b054693b16f2bae6828 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Tonh=C3=A4user?= Date: Sun, 9 Aug 2026 22:32:18 +0200 Subject: [PATCH] fix: harden editorial thumbnail authorization --- src/app/admin/redaktionen/[id]/alben/page.tsx | 2 +- .../assets/[assetId]/thumbnail/route.test.ts | 68 ++++++++++++++----- .../[assetId]/thumbnail/thumbnail-handler.ts | 33 +++++---- src/app/globals.css | 4 ++ src/components/brand/logo.test.tsx | 34 ++++++++++ src/components/brand/logo.tsx | 11 +-- src/modules/albums/catalog.test.ts | 16 +++++ src/modules/albums/catalog.ts | 17 ++++- src/modules/immich/client.test.ts | 23 +++++++ src/modules/immich/client.ts | 9 +++ src/modules/immich/types.ts | 1 + 11 files changed, 182 insertions(+), 36 deletions(-) create mode 100644 src/components/brand/logo.test.tsx diff --git a/src/app/admin/redaktionen/[id]/alben/page.tsx b/src/app/admin/redaktionen/[id]/alben/page.tsx index d1659d8..728f642 100644 --- a/src/app/admin/redaktionen/[id]/alben/page.tsx +++ b/src/app/admin/redaktionen/[id]/alben/page.tsx @@ -65,7 +65,7 @@ export default async function EditorialAlbumsPage({ {`Titelbild ) : ( diff --git a/src/app/api/assets/[assetId]/thumbnail/route.test.ts b/src/app/api/assets/[assetId]/thumbnail/route.test.ts index e4452fc..f0d2767 100644 --- a/src/app/api/assets/[assetId]/thumbnail/route.test.ts +++ b/src/app/api/assets/[assetId]/thumbnail/route.test.ts @@ -28,9 +28,9 @@ function thumbnail() { function createHandler(options?: { editorialError?: Error; grantedAlbumIds?: string[]; - albumAssets?: Array<{ id: string; type: "IMAGE"; albums: Array<{ id: string }> }>; - albumError?: Error; - adminAlbums?: typeof grantedAlbum[]; + assetAlbumIds?: string[]; + assetAlbumLookupError?: Error; + adminAlbumThumbnailAssetId?: string | null; }) { const dependencies = { requireActiveEditorial: vi @@ -42,14 +42,14 @@ function createHandler(options?: { requireAdmin: vi.fn().mockResolvedValue({ userId: "admin-1" }), getGrantedAlbumIds: vi.fn().mockResolvedValue(options?.grantedAlbumIds ?? ["allowed"]), immich: { - listAlbums: vi.fn().mockResolvedValue(options?.adminAlbums ?? [grantedAlbum]), + listAlbumsForAsset: vi.fn().mockImplementation(async () => { + if (options?.assetAlbumLookupError) throw options.assetAlbumLookupError; + return (options?.assetAlbumIds ?? ["allowed"]).map((id) => ({ id })); + }), getAlbum: vi.fn().mockImplementation(async () => { - if (options?.albumError) throw options.albumError; return { ...grantedAlbum, - assets: options?.albumAssets ?? [ - { id: "asset-1", type: "IMAGE", albums: [{ id: "allowed" }] }, - ], + albumThumbnailAssetId: options?.adminAlbumThumbnailAssetId ?? "cover-1", }; }), getThumbnail: vi.fn().mockResolvedValue(thumbnail()), @@ -58,15 +58,20 @@ function createHandler(options?: { return { handler: createThumbnailHandler(dependencies), dependencies }; } -function call(handler: ReturnType, assetId = "asset-1") { - return handler(new Request("http://portal.test/api/assets/asset-1/thumbnail"), { +function call( + handler: ReturnType, + assetId = "asset-1", + albumId?: string, +) { + const query = albumId ? `?albumId=${encodeURIComponent(albumId)}` : ""; + return handler(new Request(`http://portal.test/api/assets/${assetId}/thumbnail${query}`), { params: Promise.resolve({ assetId }), }); } test("streams a thumbnail when the requested asset belongs to any current grant", async () => { const { handler, dependencies } = createHandler({ - albumAssets: [{ id: "asset-1", type: "IMAGE", albums: [{ id: "other" }, { id: "allowed" }] }], + assetAlbumIds: ["other", "allowed"], }); const response = await call(handler); @@ -83,13 +88,14 @@ test("refuses a thumbnail immediately after its last grant is revoked", async () const response = await call(handler); expect(response.status).toBe(404); + expect(dependencies.immich.listAlbumsForAsset).not.toHaveBeenCalled(); expect(dependencies.immich.getAlbum).not.toHaveBeenCalled(); expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled(); }); test("uses an identical generic 404 for forbidden and missing assets", async () => { - const forbidden = createHandler({ albumAssets: [{ id: "different", type: "IMAGE", albums: [{ id: "allowed" }] }] }); - const missing = createHandler({ albumError: new Error("IMMICH_NOT_FOUND") }); + const forbidden = createHandler({ assetAlbumIds: ["different"] }); + const missing = createHandler({ assetAlbumLookupError: new Error("IMMICH_NOT_FOUND") }); const [forbiddenResponse, missingResponse] = await Promise.all([ call(forbidden.handler), @@ -107,25 +113,53 @@ test("uses an identical generic 404 for forbidden and missing assets", async () test("allows an admin only to load an existing Immich album cover", async () => { const { handler, dependencies } = createHandler({ editorialError: new PrincipalAuthorizationError("ADMIN_REQUIRED"), - adminAlbums: [grantedAlbum], + adminAlbumThumbnailAssetId: "cover-1", }); - const response = await call(handler, "cover-1"); + const response = await call(handler, "cover-1", "allowed"); expect(response.status).toBe(200); expect(dependencies.requireAdmin).toHaveBeenCalledTimes(1); expect(dependencies.getGrantedAlbumIds).not.toHaveBeenCalled(); + expect(dependencies.immich.getAlbum).toHaveBeenCalledWith("allowed"); expect(dependencies.immich.getThumbnail).toHaveBeenCalledWith("cover-1"); }); test("does not let an admin proxy an arbitrary non-cover asset", async () => { const { handler, dependencies } = createHandler({ editorialError: new PrincipalAuthorizationError("ADMIN_REQUIRED"), - adminAlbums: [grantedAlbum], + adminAlbumThumbnailAssetId: "cover-1", }); - const response = await call(handler, "asset-not-a-cover"); + const response = await call(handler, "asset-not-a-cover", "allowed"); expect(response.status).toBe(404); expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled(); }); + +test("uses one asset-album membership lookup for a 60-photo gallery regardless of grant count", async () => { + const grantedAlbumIds = Array.from({ length: 60 }, (_, index) => `grant-${index}`); + const { handler, dependencies } = createHandler({ + grantedAlbumIds, + assetAlbumIds: ["grant-59"], + }); + + const response = await call(handler); + + expect(response.status).toBe(200); + expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledTimes(1); + expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledWith("asset-1"); + expect(dependencies.immich.getAlbum).not.toHaveBeenCalled(); +}); + +test("does not let an admin use a cover without binding it to an album", async () => { + const { handler, dependencies } = createHandler({ + editorialError: new PrincipalAuthorizationError("ADMIN_REQUIRED"), + }); + + const response = await call(handler, "cover-1"); + + expect(response.status).toBe(404); + expect(dependencies.immich.getAlbum).not.toHaveBeenCalled(); + expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled(); +}); diff --git a/src/app/api/assets/[assetId]/thumbnail/thumbnail-handler.ts b/src/app/api/assets/[assetId]/thumbnail/thumbnail-handler.ts index e4660cf..33793b2 100644 --- a/src/app/api/assets/[assetId]/thumbnail/thumbnail-handler.ts +++ b/src/app/api/assets/[assetId]/thumbnail/thumbnail-handler.ts @@ -8,8 +8,8 @@ import type { ImmichBinary } from "@/modules/immich/types"; type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>; type ThumbnailImmich = { - listAlbums(): Promise>; - getAlbum(albumId: string): Promise<{ assets: Array<{ id: string; type: "IMAGE" }> }>; + listAlbumsForAsset(assetId: string): Promise>; + getAlbum(albumId: string): Promise<{ albumThumbnailAssetId: string | null }>; getThumbnail(assetId: string): Promise; }; @@ -25,6 +25,7 @@ type Access = { kind: "admin" } | { kind: "editorial"; editorialId: string }; export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencies) { return async function GET(request: Request, context: ThumbnailRouteContext): Promise { try { + const requestedUrl = new URL(request.url); const { assetId } = await context.params; if (!isSafeAssetId(assetId)) { return genericNotFound(); @@ -33,7 +34,11 @@ export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencie const access = await authorizeRequest(dependencies, request.headers); const authorized = access.kind === "admin" - ? await isAdminAlbumCover(dependencies.immich, assetId) + ? await isAdminAlbumCover( + dependencies.immich, + assetId, + requestedUrl.searchParams.get("albumId"), + ) : await isGrantedEditorialAsset(dependencies, access.editorialId, assetId); if (!authorized) { return genericNotFound(); @@ -74,17 +79,21 @@ async function isGrantedEditorialAsset( return false; } - const grantedAlbums = await Promise.all( - grantedAlbumIds.map((albumId) => dependencies.immich.getAlbum(albumId)), - ); - return grantedAlbums.some((album) => - album.assets.some((asset) => asset.id === assetId && asset.type === "IMAGE"), - ); + const assetAlbums = await dependencies.immich.listAlbumsForAsset(assetId); + const granted = new Set(grantedAlbumIds); + return assetAlbums.some((album) => granted.has(album.id)); } -async function isAdminAlbumCover(immich: ThumbnailImmich, assetId: string): Promise { - const albums = await immich.listAlbums(); - return albums.some((album) => album.albumThumbnailAssetId === assetId); +async function isAdminAlbumCover( + immich: ThumbnailImmich, + assetId: string, + albumId: string | null, +): Promise { + if (!albumId || !isSafeAssetId(albumId)) { + return false; + } + const album = await immich.getAlbum(albumId); + return album.albumThumbnailAssetId === assetId; } function thumbnailResponse(thumbnail: ImmichBinary): Response { diff --git a/src/app/globals.css b/src/app/globals.css index 85490aa..814ba9e 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -334,6 +334,10 @@ a { text-underline-offset: 0.28em; } +.portal-masthead :focus-visible { + outline-color: var(--paper); +} + .editorial-work-surface { width: min(100%, 108rem); margin: 0 auto; diff --git a/src/components/brand/logo.test.tsx b/src/components/brand/logo.test.tsx new file mode 100644 index 0000000..8319c65 --- /dev/null +++ b/src/components/brand/logo.test.tsx @@ -0,0 +1,34 @@ +// @vitest-environment jsdom + +import { readFileSync } from "node:fs"; + +import { render, screen } from "@testing-library/react"; +import { expect, test } from "vitest"; + +import { PortalShell } from "@/components/layout/portal-shell"; +import { BrandLogo } from "./logo"; + +test("uses each supplied logo's true intrinsic dimensions", () => { + const { rerender } = render(); + const logo = screen.getByAltText("Leon Tonhäuser Sportfotografie"); + expect(logo.getAttribute("width")).toBe("250"); + expect(logo.getAttribute("height")).toBe("250"); + + rerender(); + expect(logo.getAttribute("width")).toBe("1000"); + expect(logo.getAttribute("height")).toBe("1000"); +}); + +test("keeps masthead controls keyboard-focusable with a paper-coloured focus outline", () => { + render( + +

Archiv

+
, + ); + + expect(screen.getByRole("link", { name: /zur albenübersicht/i }).tagName).toBe("A"); + expect(screen.getByRole("link", { name: "Alben" }).tagName).toBe("A"); + const styles = readFileSync("src/app/globals.css", "utf8"); + expect(styles).toContain(".portal-masthead :focus-visible"); + expect(styles).toContain("outline-color: var(--paper)"); +}); diff --git a/src/components/brand/logo.tsx b/src/components/brand/logo.tsx index 95398f6..5c23c5b 100644 --- a/src/components/brand/logo.tsx +++ b/src/components/brand/logo.tsx @@ -5,15 +5,18 @@ type BrandLogoProps = { }; export function BrandLogo({ variant }: Readonly) { - const source = variant === "white" ? "/brand/logo-white.png" : "/brand/logo-black.png"; + const logo = + variant === "white" + ? { source: "/brand/logo-white.png", width: 250, height: 250 } + : { source: "/brand/logo-black.png", width: 1000, height: 1000 }; return ( Leon Tonhäuser Sportfotografie ); } diff --git a/src/modules/albums/catalog.test.ts b/src/modules/albums/catalog.test.ts index 552d625..1989e8a 100644 --- a/src/modules/albums/catalog.test.ts +++ b/src/modules/albums/catalog.test.ts @@ -104,6 +104,22 @@ test("normalizes descriptions and bounds invalid pagination before sending an up ); }); +test("passes a bounded decimal page string from the SSR query through to Immich", async () => { + const { catalog, immich } = createCatalog(); + + await catalog.searchVisiblePhotos("editorial-1", { page: "2" }); + expect(immich.searchPhotos).toHaveBeenLastCalledWith(expect.objectContaining({ page: 2 })); + + await catalog.searchVisiblePhotos("editorial-1", { page: "not-a-page" }); + expect(immich.searchPhotos).toHaveBeenLastCalledWith(expect.objectContaining({ page: 1 })); + + await catalog.searchVisiblePhotos("editorial-1", { page: "-2" }); + expect(immich.searchPhotos).toHaveBeenLastCalledWith(expect.objectContaining({ page: 1 })); + + await catalog.searchVisiblePhotos("editorial-1", { page: "100000" }); + expect(immich.searchPhotos).toHaveBeenLastCalledWith(expect.objectContaining({ page: 1_000 })); +}); + test("only returns the current editorial's albums from the Immich album list", async () => { const { catalog } = createCatalog({ grantedAlbumIds: ["allowed"] }); diff --git a/src/modules/albums/catalog.ts b/src/modules/albums/catalog.ts index 1ba04ff..3c506b6 100644 --- a/src/modules/albums/catalog.ts +++ b/src/modules/albums/catalog.ts @@ -93,10 +93,23 @@ function normalizeDescription(description: unknown): string | undefined { } function normalizePage(page: unknown): number { - if (typeof page !== "number" || !Number.isFinite(page) || !Number.isInteger(page)) { + const parsed = parsePage(page); + if (parsed === null) { return 1; } - return Math.min(MAX_PHOTO_PAGE, Math.max(1, page)); + return Math.min(MAX_PHOTO_PAGE, Math.max(1, parsed)); +} + +function parsePage(page: unknown): number | null { + if (typeof page === "number") { + return Number.isFinite(page) && Number.isInteger(page) ? page : null; + } + if (typeof page !== "string" || !/^\d+$/.test(page)) { + return null; + } + + const parsed = Number(page); + return Number.isSafeInteger(parsed) ? parsed : MAX_PHOTO_PAGE; } async function loadAlbums( diff --git a/src/modules/immich/client.test.ts b/src/modules/immich/client.test.ts index 6183811..b700169 100644 --- a/src/modules/immich/client.test.ts +++ b/src/modules/immich/client.test.ts @@ -38,6 +38,29 @@ test("lists albums through the documented API with server-side authentication", await expect(client.listAlbums()).resolves.toEqual([immichAlbum]); }); +test("lists only the albums containing an asset through the documented assetId query", async () => { + server.use( + http.get(`${baseUrl}/api/albums`, ({ request }) => { + const url = new URL(request.url); + expect(url.searchParams.get("assetId")).toBe("asset-1"); + expect(request.headers.get("x-api-key")).toBe(apiKey); + return HttpResponse.json([immichAlbum]); + }), + ); + + await expect(client.listAlbumsForAsset("asset-1")).resolves.toEqual([immichAlbum]); +}); + +test("validates the narrow asset-album response before authorizing a thumbnail", async () => { + server.use( + http.get(`${baseUrl}/api/albums`, () => HttpResponse.json([{ id: "missing-album-fields" }])), + ); + + await expect(client.listAlbumsForAsset("asset-1")).rejects.toMatchObject({ + code: "IMMICH_INVALID_RESPONSE", + }); +}); + test("gets album details from the documented album endpoint", async () => { server.use( http.get(`${baseUrl}/api/albums/album-1`, ({ request }) => { diff --git a/src/modules/immich/client.ts b/src/modules/immich/client.ts index 0d4025c..a5f1e2e 100644 --- a/src/modules/immich/client.ts +++ b/src/modules/immich/client.ts @@ -308,6 +308,15 @@ export function createImmichClient({ listAlbums(signal) { return requestJson("/albums", { method: "GET" }, z.array(albumSummarySchema), signal); }, + listAlbumsForAsset(assetId, signal) { + const query = new URLSearchParams({ assetId }); + return requestJson( + `/albums?${query.toString()}`, + { method: "GET" }, + z.array(albumSummarySchema), + signal, + ); + }, getAlbum(albumId, signal) { return requestJson( `/albums/${encodeURIComponent(albumId)}`, diff --git a/src/modules/immich/types.ts b/src/modules/immich/types.ts index a04a2b8..242bcac 100644 --- a/src/modules/immich/types.ts +++ b/src/modules/immich/types.ts @@ -36,6 +36,7 @@ export type ImmichBinary = { export interface ImmichClient { listAlbums(signal?: AbortSignal): Promise; + listAlbumsForAsset(assetId: string, signal?: AbortSignal): Promise; getAlbum(albumId: string, signal?: AbortSignal): Promise; searchPhotos( input: { albumIds: string[]; description?: string; page: number; size: number; type?: "IMAGE" },