fix: harden editorial thumbnail authorization

This commit is contained in:
Leon Tonhäuser committed 2026-08-09 22:32:18 +02:00
1 parent 66f0599653
commit 846904f3db
11 files changed
+182 -36

No files matched your search

@@ -65,7 +65,7 @@ export default async function EditorialAlbumsPage({
<Image <Image
alt={`Titelbild von ${album.albumName}`} alt={`Titelbild von ${album.albumName}`}
height={120} height={120}
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail`} src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
width={160} width={160}
/> />
) : ( ) : (
@@ -28,9 +28,9 @@ function thumbnail() {
function createHandler(options?: { function createHandler(options?: {
editorialError?: Error; editorialError?: Error;
grantedAlbumIds?: string[]; grantedAlbumIds?: string[];
albumAssets?: Array<{ id: string; type: "IMAGE"; albums: Array<{ id: string }> }>; assetAlbumIds?: string[];
albumError?: Error; assetAlbumLookupError?: Error;
adminAlbums?: typeof grantedAlbum[]; adminAlbumThumbnailAssetId?: string | null;
}) { }) {
const dependencies = { const dependencies = {
requireActiveEditorial: vi requireActiveEditorial: vi
@@ -42,14 +42,14 @@ function createHandler(options?: {
requireAdmin: vi.fn().mockResolvedValue({ userId: "admin-1" }), requireAdmin: vi.fn().mockResolvedValue({ userId: "admin-1" }),
getGrantedAlbumIds: vi.fn().mockResolvedValue(options?.grantedAlbumIds ?? ["allowed"]), getGrantedAlbumIds: vi.fn().mockResolvedValue(options?.grantedAlbumIds ?? ["allowed"]),
immich: { 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 () => { getAlbum: vi.fn().mockImplementation(async () => {
if (options?.albumError) throw options.albumError;
return { return {
...grantedAlbum, ...grantedAlbum,
assets: options?.albumAssets ?? [ albumThumbnailAssetId: options?.adminAlbumThumbnailAssetId ?? "cover-1",
{ id: "asset-1", type: "IMAGE", albums: [{ id: "allowed" }] },
],
}; };
}), }),
getThumbnail: vi.fn().mockResolvedValue(thumbnail()), getThumbnail: vi.fn().mockResolvedValue(thumbnail()),
@@ -58,15 +58,20 @@ function createHandler(options?: {
return { handler: createThumbnailHandler(dependencies), dependencies }; return { handler: createThumbnailHandler(dependencies), dependencies };
} }
function call(handler: ReturnType<typeof createThumbnailHandler>, assetId = "asset-1") { function call(
return handler(new Request("http://portal.test/api/assets/asset-1/thumbnail"), { handler: ReturnType<typeof createThumbnailHandler>,
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 }), params: Promise.resolve({ assetId }),
}); });
} }
test("streams a thumbnail when the requested asset belongs to any current grant", async () => { test("streams a thumbnail when the requested asset belongs to any current grant", async () => {
const { handler, dependencies } = createHandler({ const { handler, dependencies } = createHandler({
albumAssets: [{ id: "asset-1", type: "IMAGE", albums: [{ id: "other" }, { id: "allowed" }] }], assetAlbumIds: ["other", "allowed"],
}); });
const response = await call(handler); 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); const response = await call(handler);
expect(response.status).toBe(404); expect(response.status).toBe(404);
expect(dependencies.immich.listAlbumsForAsset).not.toHaveBeenCalled();
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled(); expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled(); expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled();
}); });
test("uses an identical generic 404 for forbidden and missing assets", async () => { test("uses an identical generic 404 for forbidden and missing assets", async () => {
const forbidden = createHandler({ albumAssets: [{ id: "different", type: "IMAGE", albums: [{ id: "allowed" }] }] }); const forbidden = createHandler({ assetAlbumIds: ["different"] });
const missing = createHandler({ albumError: new Error("IMMICH_NOT_FOUND") }); const missing = createHandler({ assetAlbumLookupError: new Error("IMMICH_NOT_FOUND") });
const [forbiddenResponse, missingResponse] = await Promise.all([ const [forbiddenResponse, missingResponse] = await Promise.all([
call(forbidden.handler), 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 () => { test("allows an admin only to load an existing Immich album cover", async () => {
const { handler, dependencies } = createHandler({ const { handler, dependencies } = createHandler({
editorialError: new PrincipalAuthorizationError("ADMIN_REQUIRED"), 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(response.status).toBe(200);
expect(dependencies.requireAdmin).toHaveBeenCalledTimes(1); expect(dependencies.requireAdmin).toHaveBeenCalledTimes(1);
expect(dependencies.getGrantedAlbumIds).not.toHaveBeenCalled(); expect(dependencies.getGrantedAlbumIds).not.toHaveBeenCalled();
expect(dependencies.immich.getAlbum).toHaveBeenCalledWith("allowed");
expect(dependencies.immich.getThumbnail).toHaveBeenCalledWith("cover-1"); expect(dependencies.immich.getThumbnail).toHaveBeenCalledWith("cover-1");
}); });
test("does not let an admin proxy an arbitrary non-cover asset", async () => { test("does not let an admin proxy an arbitrary non-cover asset", async () => {
const { handler, dependencies } = createHandler({ const { handler, dependencies } = createHandler({
editorialError: new PrincipalAuthorizationError("ADMIN_REQUIRED"), 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(response.status).toBe(404);
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled(); 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();
});
@@ -8,8 +8,8 @@ import type { ImmichBinary } from "@/modules/immich/types";
type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>; type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
type ThumbnailImmich = { type ThumbnailImmich = {
listAlbums(): Promise<Array<{ albumThumbnailAssetId: string | null }>>; listAlbumsForAsset(assetId: string): Promise<Array<{ id: string }>>;
getAlbum(albumId: string): Promise<{ assets: Array<{ id: string; type: "IMAGE" }> }>; getAlbum(albumId: string): Promise<{ albumThumbnailAssetId: string | null }>;
getThumbnail(assetId: string): Promise<ImmichBinary>; getThumbnail(assetId: string): Promise<ImmichBinary>;
}; };
@@ -25,6 +25,7 @@ type Access = { kind: "admin" } | { kind: "editorial"; editorialId: string };
export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencies) { export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencies) {
return async function GET(request: Request, context: ThumbnailRouteContext): Promise<Response> { return async function GET(request: Request, context: ThumbnailRouteContext): Promise<Response> {
try { try {
const requestedUrl = new URL(request.url);
const { assetId } = await context.params; const { assetId } = await context.params;
if (!isSafeAssetId(assetId)) { if (!isSafeAssetId(assetId)) {
return genericNotFound(); return genericNotFound();
@@ -33,7 +34,11 @@ export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencie
const access = await authorizeRequest(dependencies, request.headers); const access = await authorizeRequest(dependencies, request.headers);
const authorized = const authorized =
access.kind === "admin" access.kind === "admin"
? await isAdminAlbumCover(dependencies.immich, assetId) ? await isAdminAlbumCover(
dependencies.immich,
assetId,
requestedUrl.searchParams.get("albumId"),
)
: await isGrantedEditorialAsset(dependencies, access.editorialId, assetId); : await isGrantedEditorialAsset(dependencies, access.editorialId, assetId);
if (!authorized) { if (!authorized) {
return genericNotFound(); return genericNotFound();
@@ -74,17 +79,21 @@ async function isGrantedEditorialAsset(
return false; return false;
} }
const grantedAlbums = await Promise.all( const assetAlbums = await dependencies.immich.listAlbumsForAsset(assetId);
grantedAlbumIds.map((albumId) => dependencies.immich.getAlbum(albumId)), const granted = new Set(grantedAlbumIds);
); return assetAlbums.some((album) => granted.has(album.id));
return grantedAlbums.some((album) =>
album.assets.some((asset) => asset.id === assetId && asset.type === "IMAGE"),
);
} }
async function isAdminAlbumCover(immich: ThumbnailImmich, assetId: string): Promise<boolean> { async function isAdminAlbumCover(
const albums = await immich.listAlbums(); immich: ThumbnailImmich,
return albums.some((album) => album.albumThumbnailAssetId === assetId); assetId: string,
albumId: string | null,
): Promise<boolean> {
if (!albumId || !isSafeAssetId(albumId)) {
return false;
}
const album = await immich.getAlbum(albumId);
return album.albumThumbnailAssetId === assetId;
} }
function thumbnailResponse(thumbnail: ImmichBinary): Response { function thumbnailResponse(thumbnail: ImmichBinary): Response {
+4
View File
@@ -334,6 +334,10 @@ a {
text-underline-offset: 0.28em; text-underline-offset: 0.28em;
} }
.portal-masthead :focus-visible {
outline-color: var(--paper);
}
.editorial-work-surface { .editorial-work-surface {
width: min(100%, 108rem); width: min(100%, 108rem);
margin: 0 auto; margin: 0 auto;
+34
View File
@@ -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(<BrandLogo variant="white" />);
const logo = screen.getByAltText("Leon Tonhäuser Sportfotografie");
expect(logo.getAttribute("width")).toBe("250");
expect(logo.getAttribute("height")).toBe("250");
rerender(<BrandLogo variant="black" />);
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(
<PortalShell>
<p>Archiv</p>
</PortalShell>,
);
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)");
});
+7 -4
View File
@@ -5,15 +5,18 @@ type BrandLogoProps = {
}; };
export function BrandLogo({ variant }: Readonly<BrandLogoProps>) { export function BrandLogo({ variant }: Readonly<BrandLogoProps>) {
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 ( return (
<img <img
alt="Leon Tonhäuser Sportfotografie" alt="Leon Tonhäuser Sportfotografie"
className="brand-logo" className="brand-logo"
height="64" height={logo.height}
src={source} src={logo.source}
width="250" width={logo.width}
/> />
); );
} }
+16
View File
@@ -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 () => { test("only returns the current editorial's albums from the Immich album list", async () => {
const { catalog } = createCatalog({ grantedAlbumIds: ["allowed"] }); const { catalog } = createCatalog({ grantedAlbumIds: ["allowed"] });
+15 -2
View File
@@ -93,10 +93,23 @@ function normalizeDescription(description: unknown): string | undefined {
} }
function normalizePage(page: unknown): number { 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 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( async function loadAlbums(
+23
View File
@@ -38,6 +38,29 @@ test("lists albums through the documented API with server-side authentication",
await expect(client.listAlbums()).resolves.toEqual([immichAlbum]); 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 () => { test("gets album details from the documented album endpoint", async () => {
server.use( server.use(
http.get(`${baseUrl}/api/albums/album-1`, ({ request }) => { http.get(`${baseUrl}/api/albums/album-1`, ({ request }) => {
+9
View File
@@ -308,6 +308,15 @@ export function createImmichClient({
listAlbums(signal) { listAlbums(signal) {
return requestJson<ImmichAlbumSummary[]>("/albums", { method: "GET" }, z.array(albumSummarySchema), signal); return requestJson<ImmichAlbumSummary[]>("/albums", { method: "GET" }, z.array(albumSummarySchema), signal);
}, },
listAlbumsForAsset(assetId, signal) {
const query = new URLSearchParams({ assetId });
return requestJson<ImmichAlbumSummary[]>(
`/albums?${query.toString()}`,
{ method: "GET" },
z.array(albumSummarySchema),
signal,
);
},
getAlbum(albumId, signal) { getAlbum(albumId, signal) {
return requestJson<ImmichAlbum>( return requestJson<ImmichAlbum>(
`/albums/${encodeURIComponent(albumId)}`, `/albums/${encodeURIComponent(albumId)}`,
+1
View File
@@ -36,6 +36,7 @@ export type ImmichBinary = {
export interface ImmichClient { export interface ImmichClient {
listAlbums(signal?: AbortSignal): Promise<ImmichAlbumSummary[]>; listAlbums(signal?: AbortSignal): Promise<ImmichAlbumSummary[]>;
listAlbumsForAsset(assetId: string, signal?: AbortSignal): Promise<ImmichAlbumSummary[]>;
getAlbum(albumId: string, signal?: AbortSignal): Promise<ImmichAlbum>; getAlbum(albumId: string, signal?: AbortSignal): Promise<ImmichAlbum>;
searchPhotos( searchPhotos(
input: { albumIds: string[]; description?: string; page: number; size: number; type?: "IMAGE" }, input: { albumIds: string[]; description?: string; page: number; size: number; type?: "IMAGE" },