import { drizzle } from "drizzle-orm/node-postgres"; import type { Pool } from "pg"; import { expect, test, vi } from "vitest"; import * as schema from "@/db/schema"; import { assertOriginalAccess } from "./photo-access"; const editorialId = "11111111-1111-4111-8111-111111111111"; const assetId = "22222222-2222-4222-8222-222222222222"; const albumId = "33333333-3333-4333-8333-333333333333"; function dependencies() { const query = vi.fn().mockResolvedValue({ rows: [[albumId]] }); const database = drizzle({ client: { query } as unknown as Pool, schema }); const searchPhotos = vi.fn().mockResolvedValue({ items: [{ id: assetId }] }); return { query, searchPhotos, check: () => assertOriginalAccess(editorialId, assetId, albumId, database, { searchPhotos }), }; } test("checks active editorial and exact grant both before and after checking photo membership", async () => { const { check, query, searchPhotos } = dependencies(); await expect(check()).resolves.toBeUndefined(); expect(query).toHaveBeenCalledTimes(2); const [statement, values] = query.mock.calls[0]; expect(statement.text).toContain('"editorial_accounts"."status"'); expect(statement.text).toContain('"album_grants"."revoked_at" is null'); expect(values).toEqual([editorialId, "active", albumId]); expect(searchPhotos).toHaveBeenCalledWith( { albumIds: [albumId], id: assetId, type: "IMAGE", withExif: false, page: 1, size: 1 }, undefined, ); }); test("does not load photo metadata from an already revoked album", async () => { const { check, query, searchPhotos } = dependencies(); query.mockResolvedValueOnce({ rows: [] }); await expect(check()).rejects.toMatchObject({ code: "ALBUM_NOT_GRANTED" }); expect(searchPhotos).not.toHaveBeenCalled(); }); test("fails closed if the grant is revoked while looking up membership", async () => { const { check, query } = dependencies(); query.mockResolvedValueOnce({ rows: [[albumId]] }).mockResolvedValueOnce({ rows: [] }); await expect(check()).rejects.toMatchObject({ code: "ALBUM_NOT_GRANTED" }); }); test("rejects when membership cannot be verified", async () => { const { check, searchPhotos } = dependencies(); searchPhotos.mockResolvedValueOnce({ items: [{ id: "another-photo" }] }); await expect(check()).rejects.toMatchObject({ code: "ASSET_NOT_IN_ALBUM" }); searchPhotos.mockRejectedValueOnce(new Error("upstream unavailable")); await expect(check()).rejects.toMatchObject({ code: "IMMICH_UNAVAILABLE" }); });