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
alt={`Titelbild von ${album.albumName}`}
height={120}
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail`}
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
width={160}
/>
) : (
@@ -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<typeof createThumbnailHandler>, assetId = "asset-1") {
return handler(new Request("http://portal.test/api/assets/asset-1/thumbnail"), {
function call(
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 }),
});
}
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();
});
@@ -8,8 +8,8 @@ import type { ImmichBinary } from "@/modules/immich/types";
type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
type ThumbnailImmich = {
listAlbums(): Promise<Array<{ albumThumbnailAssetId: string | null }>>;
getAlbum(albumId: string): Promise<{ assets: Array<{ id: string; type: "IMAGE" }> }>;
listAlbumsForAsset(assetId: string): Promise<Array<{ id: string }>>;
getAlbum(albumId: string): Promise<{ albumThumbnailAssetId: string | null }>;
getThumbnail(assetId: string): Promise<ImmichBinary>;
};
@@ -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<Response> {
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<boolean> {
const albums = await immich.listAlbums();
return albums.some((album) => album.albumThumbnailAssetId === assetId);
async function isAdminAlbumCover(
immich: ThumbnailImmich,
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 {
+4
View File
@@ -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;