fix: enforce one active logical album grant

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 12:14:38 +02:00
1 parent 74ab2eb85f
commit c400167b8f
8 files changed
+575 -43

No files matched your search

+16 -1
View File
@@ -165,7 +165,22 @@ ALTER TABLE "download_events" ALTER COLUMN "legacy_intent" SET NOT NULL;--> stat
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_intent_kind_check" CHECK ("download_events"."intent_kind" in ('new_usage', 'repeat_download', 'legacy'));--> statement-breakpoint ALTER TABLE "download_events" ADD CONSTRAINT "download_events_intent_kind_check" CHECK ("download_events"."intent_kind" in ('new_usage', 'repeat_download', 'legacy'));--> statement-breakpoint
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_request_fingerprint_hex_check" CHECK ("download_events"."request_fingerprint" ~ '^[0-9a-f]{64}$');--> statement-breakpoint ALTER TABLE "download_events" ADD CONSTRAINT "download_events_request_fingerprint_hex_check" CHECK ("download_events"."request_fingerprint" ~ '^[0-9a-f]{64}$');--> statement-breakpoint
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_canonical_idempotency_key_check" CHECK ("download_events"."legacy_intent" OR "download_events"."idempotency_key" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$');--> statement-breakpoint ALTER TABLE "download_events" ADD CONSTRAINT "download_events_canonical_idempotency_key_check" CHECK ("download_events"."legacy_intent" OR "download_events"."idempotency_key" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$');--> statement-breakpoint
ALTER TABLE "album_grants" ADD CONSTRAINT "album_grants_canonical_immich_album_id_check" CHECK ("album_grants"."immich_album_id" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;--> statement-breakpoint WITH ranked_active_album_grants AS (
SELECT
"id",
row_number() OVER (
PARTITION BY "editorial_account_id", lower("immich_album_id")
ORDER BY ("immich_album_id" = lower("immich_album_id")) DESC, "granted_at", "id"
) AS survivor_order
FROM "album_grants"
WHERE "revoked_at" IS NULL
)
UPDATE "album_grants" AS grants
SET "revoked_at" = now()
FROM ranked_active_album_grants AS ranked
WHERE grants."id" = ranked."id" AND ranked.survivor_order > 1;--> statement-breakpoint
CREATE UNIQUE INDEX "album_grants_editorial_active_album_unique" ON "album_grants" ("editorial_account_id", lower("immich_album_id")) WHERE "revoked_at" IS NULL;--> statement-breakpoint
ALTER TABLE "album_grants" ADD CONSTRAINT "album_grants_immich_album_id_uuid_check" CHECK ("album_grants"."immich_album_id" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;--> statement-breakpoint
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_canonical_immich_asset_id_check" CHECK ("download_events"."immich_asset_id" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;--> statement-breakpoint ALTER TABLE "download_events" ADD CONSTRAINT "download_events_canonical_immich_asset_id_check" CHECK ("download_events"."immich_asset_id" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;--> statement-breakpoint
ALTER TABLE "usages" ADD CONSTRAINT "usages_canonical_immich_asset_id_check" CHECK ("usages"."immich_asset_id" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;--> statement-breakpoint ALTER TABLE "usages" ADD CONSTRAINT "usages_canonical_immich_asset_id_check" CHECK ("usages"."immich_asset_id" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;--> statement-breakpoint
ALTER TABLE "usages" ADD CONSTRAINT "usages_canonical_immich_album_id_check" CHECK ("usages"."immich_album_id_snapshot" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID; ALTER TABLE "usages" ADD CONSTRAINT "usages_canonical_immich_album_id_check" CHECK ("usages"."immich_album_id_snapshot" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;
+25 -3
View File
@@ -77,6 +77,28 @@
"concurrently": false, "concurrently": false,
"method": "btree", "method": "btree",
"with": {} "with": {}
},
"album_grants_editorial_active_album_unique": {
"name": "album_grants_editorial_active_album_unique",
"columns": [
{
"expression": "editorial_account_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "lower(\"immich_album_id\")",
"asc": true,
"isExpression": true,
"nulls": "last"
}
],
"isUnique": true,
"where": "\"album_grants\".\"revoked_at\" is null",
"concurrently": false,
"method": "btree",
"with": {}
} }
}, },
"foreignKeys": { "foreignKeys": {
@@ -111,9 +133,9 @@
"uniqueConstraints": {}, "uniqueConstraints": {},
"policies": {}, "policies": {},
"checkConstraints": { "checkConstraints": {
"album_grants_canonical_immich_album_id_check": { "album_grants_immich_album_id_uuid_check": {
"name": "album_grants_canonical_immich_album_id_check", "name": "album_grants_immich_album_id_uuid_check",
"value": "\"album_grants\".\"immich_album_id\" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'" "value": "\"album_grants\".\"immich_album_id\" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'"
} }
}, },
"isRLSEnabled": false "isRLSEnabled": false
+6 -3
View File
@@ -1,5 +1,5 @@
import { sql } from "drizzle-orm"; import { sql } from "drizzle-orm";
import { check, index, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"; import { check, index, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
import { users } from "./auth"; import { users } from "./auth";
import { editorialAccounts } from "./editorials"; import { editorialAccounts } from "./editorials";
@@ -21,9 +21,12 @@ export const albumGrants = pgTable(
(table) => [ (table) => [
index("album_grants_editorial_account_id_idx").on(table.editorialAccountId), index("album_grants_editorial_account_id_idx").on(table.editorialAccountId),
index("album_grants_immich_album_id_idx").on(table.immichAlbumId), index("album_grants_immich_album_id_idx").on(table.immichAlbumId),
uniqueIndex("album_grants_editorial_active_album_unique")
.on(table.editorialAccountId, sql`lower(${table.immichAlbumId})`)
.where(sql`${table.revokedAt} is null`),
check( check(
"album_grants_canonical_immich_album_id_check", "album_grants_immich_album_id_uuid_check",
sql`${table.immichAlbumId} ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`, sql`${table.immichAlbumId} ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`,
), ),
], ],
); );
+138 -15
View File
@@ -4,6 +4,8 @@ import {
ALBUM_GRANT_LOCK_ORDER, ALBUM_GRANT_LOCK_ORDER,
AlbumGrantError, AlbumGrantError,
createAlbumGrantService, createAlbumGrantService,
planAlbumGrantMutation,
planAlbumRevokeMutation,
type AlbumGrantRepository, type AlbumGrantRepository,
} from "./grants"; } from "./grants";
import { EDITORIAL_MUTATION_LOCK_ORDER } from "@/modules/editorials/service"; import { EDITORIAL_MUTATION_LOCK_ORDER } from "@/modules/editorials/service";
@@ -23,6 +25,96 @@ const albumUuid = "2222222b-2222-4222-8222-22222222222b";
const adminUuid = "3333333c-3333-4333-8333-33333333333c"; const adminUuid = "3333333c-3333-4333-8333-33333333333c";
const unavailableAlbumUuid = "4444444d-4444-4444-8444-44444444444d"; const unavailableAlbumUuid = "4444444d-4444-4444-8444-44444444444d";
const earlierGrant = new Date("2026-08-07T08:00:00.000Z");
const laterGrant = new Date("2026-08-08T08:00:00.000Z");
test("direct grant keeps the exact canonical row and retires every active case variant", () => {
expect(
planAlbumGrantMutation(
[
{
id: "00000000-0000-4000-8000-000000000001",
immichAlbumId: albumUuid.toUpperCase(),
grantedAt: earlierGrant,
revokedAt: null,
},
{
id: "00000000-0000-4000-8000-000000000002",
immichAlbumId: albumUuid,
grantedAt: laterGrant,
revokedAt: null,
},
],
albumUuid,
),
).toEqual({
survivorId: "00000000-0000-4000-8000-000000000002",
activeLoserIds: ["00000000-0000-4000-8000-000000000001"],
hadActiveGrant: true,
});
});
test("regrant chooses the oldest revoked case variant then its stable id", () => {
const revokedAt = new Date("2026-08-09T08:00:00.000Z");
expect(
planAlbumGrantMutation(
[
{
id: "00000000-0000-4000-8000-000000000003",
immichAlbumId: albumUuid.toUpperCase(),
grantedAt: laterGrant,
revokedAt,
},
{
id: "00000000-0000-4000-8000-000000000002",
immichAlbumId: "2222222B-2222-4222-8222-22222222222b",
grantedAt: earlierGrant,
revokedAt,
},
{
id: "00000000-0000-4000-8000-000000000001",
immichAlbumId: "2222222b-2222-4222-8222-22222222222B",
grantedAt: earlierGrant,
revokedAt,
},
],
albumUuid,
),
).toEqual({
survivorId: "00000000-0000-4000-8000-000000000001",
activeLoserIds: [],
hadActiveGrant: false,
});
});
test("revoke targets every active case-equivalent row", () => {
expect(
planAlbumRevokeMutation([
{
id: "00000000-0000-4000-8000-000000000003",
immichAlbumId: albumUuid.toUpperCase(),
grantedAt: laterGrant,
revokedAt: null,
},
{
id: "00000000-0000-4000-8000-000000000001",
immichAlbumId: albumUuid,
grantedAt: earlierGrant,
revokedAt: null,
},
{
id: "00000000-0000-4000-8000-000000000002",
immichAlbumId: albumUuid,
grantedAt: earlierGrant,
revokedAt: new Date("2026-08-09T08:00:00.000Z"),
},
]),
).toEqual([
"00000000-0000-4000-8000-000000000001",
"00000000-0000-4000-8000-000000000003",
]);
});
function createRepository(initial: Grant[] = []) { function createRepository(initial: Grant[] = []) {
const grants = [...initial]; const grants = [...initial];
const audit: Audit[] = []; const audit: Audit[] = [];
@@ -33,26 +125,28 @@ function createRepository(initial: Grant[] = []) {
.map((grant) => grant.albumId); .map((grant) => grant.albumId);
}, },
async grant(input) { async grant(input) {
const active = grants.filter( const matching = grants.filter(
(grant) => (grant) =>
grant.editorialId === input.editorialId && grant.editorialId === input.editorialId &&
grant.albumId.toLowerCase() === input.immichAlbumId && grant.albumId.toLowerCase() === input.immichAlbumId,
grant.revokedAt === null,
); );
const survivor =
matching.find((grant) => grant.albumId === input.immichAlbumId) ?? matching[0];
const active = matching.filter((grant) => grant.revokedAt === null);
if (active.length > 0) { if (active.length > 0) {
for (const grant of active) grant.albumId = input.immichAlbumId; for (const grant of active) {
if (grant !== survivor) grant.revokedAt = new Date();
}
if (survivor) {
survivor.albumId = input.immichAlbumId;
survivor.revokedAt = null;
}
return false; return false;
} }
const revoked = grants.find( if (survivor) {
(grant) => survivor.albumId = input.immichAlbumId;
grant.editorialId === input.editorialId && survivor.revokedAt = null;
grant.albumId.toLowerCase() === input.immichAlbumId &&
grant.revokedAt !== null,
);
if (revoked) {
revoked.albumId = input.immichAlbumId;
revoked.revokedAt = null;
} else { } else {
grants.push({ editorialId: input.editorialId, albumId: input.immichAlbumId, revokedAt: null }); grants.push({ editorialId: input.editorialId, albumId: input.immichAlbumId, revokedAt: null });
} }
@@ -75,7 +169,6 @@ function createRepository(initial: Grant[] = []) {
); );
if (active.length === 0) return false; if (active.length === 0) return false;
for (const grant of active) { for (const grant of active) {
grant.albumId = input.immichAlbumId;
grant.revokedAt = new Date(); grant.revokedAt = new Date();
} }
audit.push({ audit.push({
@@ -165,6 +258,37 @@ test("treats an uppercase historical album grant as the canonical active grant",
expect(audit).toHaveLength(0); expect(audit).toHaveLength(0);
}); });
test("returns one canonical active ID when historical rows contain case duplicates", async () => {
const { service } = createService([
{ editorialId: editorialUuid, albumId: albumUuid.toUpperCase(), revokedAt: null },
{ editorialId: editorialUuid, albumId: albumUuid, revokedAt: null },
]);
await expect(service.getGrantedAlbumIds(editorialUuid)).resolves.toEqual([albumUuid]);
});
test("direct grant consolidates active case variants without a second logical audit", async () => {
const { service, grants, audit } = createService([
{ editorialId: editorialUuid, albumId: albumUuid.toUpperCase(), revokedAt: null },
{ editorialId: editorialUuid, albumId: albumUuid, revokedAt: null },
]);
await service.grantAlbum({
editorialId: editorialUuid,
immichAlbumId: albumUuid,
adminUserId: adminUuid,
});
await service.grantAlbum({
editorialId: editorialUuid,
immichAlbumId: albumUuid,
adminUserId: adminUuid,
});
expect(grants.filter((grant) => grant.revokedAt === null)).toHaveLength(1);
await expect(service.getGrantedAlbumIds(editorialUuid)).resolves.toEqual([albumUuid]);
expect(audit).toHaveLength(0);
});
test("revokes and regrants case-duplicate historical rows as one canonical grant", async () => { test("revokes and regrants case-duplicate historical rows as one canonical grant", async () => {
const { service, grants, audit } = createService([ const { service, grants, audit } = createService([
{ editorialId: editorialUuid, albumId: albumUuid.toUpperCase(), revokedAt: null }, { editorialId: editorialUuid, albumId: albumUuid.toUpperCase(), revokedAt: null },
@@ -177,7 +301,6 @@ test("revokes and regrants case-duplicate historical rows as one canonical grant
adminUserId: adminUuid, adminUserId: adminUuid,
}); });
expect(grants.filter((grant) => grant.revokedAt === null)).toHaveLength(0); expect(grants.filter((grant) => grant.revokedAt === null)).toHaveLength(0);
expect(grants.every((grant) => grant.albumId === albumUuid)).toBe(true);
await service.grantAlbum({ await service.grantAlbum({
editorialId: editorialUuid, editorialId: editorialUuid,
+86 -16
View File
@@ -1,6 +1,6 @@
import "server-only"; import "server-only";
import { and, eq, inArray, isNull, sql } from "drizzle-orm"; import { and, asc, eq, inArray, isNull, sql } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres"; import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { db } from "@/db/client"; import { db } from "@/db/client";
@@ -24,6 +24,19 @@ export type AlbumGrantRepository = {
revoke(input: AlbumGrantInput): Promise<boolean>; revoke(input: AlbumGrantInput): Promise<boolean>;
}; };
export type AlbumGrantMutationCandidate = {
id: string;
immichAlbumId: string;
grantedAt: Date;
revokedAt: Date | null;
};
export type AlbumGrantMutationPlan = {
survivorId: string | null;
activeLoserIds: string[];
hadActiveGrant: boolean;
};
export const ALBUM_GRANT_LOCK_ORDER = EDITORIAL_MUTATION_LOCK_ORDER; export const ALBUM_GRANT_LOCK_ORDER = EDITORIAL_MUTATION_LOCK_ORDER;
export class AlbumGrantError extends Error { export class AlbumGrantError extends Error {
@@ -80,7 +93,7 @@ export function createAlbumGrantService({
async getGrantedAlbumIds(editorialId: string): Promise<string[]> { async getGrantedAlbumIds(editorialId: string): Promise<string[]> {
const albumIds = await repository.listActiveAlbumIds(normalizeIdentifier(editorialId)); const albumIds = await repository.listActiveAlbumIds(normalizeIdentifier(editorialId));
return albumIds.map(canonicalizeStoredIdentifier); return uniqueCanonicalIdentifiers(albumIds);
}, },
}; };
} }
@@ -94,7 +107,7 @@ export function createAlbumGrantRepository(
.select({ immichAlbumId: albumGrants.immichAlbumId }) .select({ immichAlbumId: albumGrants.immichAlbumId })
.from(albumGrants) .from(albumGrants)
.where(and(eq(albumGrants.editorialAccountId, editorialId), isNull(albumGrants.revokedAt))); .where(and(eq(albumGrants.editorialAccountId, editorialId), isNull(albumGrants.revokedAt)));
return grants.map((grant) => grant.immichAlbumId); return uniqueCanonicalIdentifiers(grants.map((grant) => grant.immichAlbumId));
}, },
async grant(input) { async grant(input) {
@@ -102,19 +115,27 @@ export function createAlbumGrantRepository(
await lockEditorialAlbumMutation(transaction, input.editorialId); await lockEditorialAlbumMutation(transaction, input.editorialId);
const editorial = await lockEditorial(transaction, input.editorialId); const editorial = await lockEditorial(transaction, input.editorialId);
const grants = await lockAlbumGrants(transaction, input.editorialId, input.immichAlbumId); const grants = await lockAlbumGrants(transaction, input.editorialId, input.immichAlbumId);
const activeGrants = grants.filter((grant) => grant.revokedAt === null); const plan = planAlbumGrantMutation(grants, input.immichAlbumId);
if (activeGrants.length > 0) { const changedAt = new Date();
if (plan.activeLoserIds.length > 0) {
await transaction await transaction
.update(albumGrants) .update(albumGrants)
.set({ immichAlbumId: input.immichAlbumId }) .set({ revokedAt: changedAt })
.where(inArray(albumGrants.id, activeGrants.map((grant) => grant.id))); .where(
and(inArray(albumGrants.id, plan.activeLoserIds), isNull(albumGrants.revokedAt)),
);
}
if (plan.hadActiveGrant) {
await transaction
.update(albumGrants)
.set({ immichAlbumId: input.immichAlbumId, revokedAt: null })
.where(eq(albumGrants.id, plan.survivorId!));
return false; return false;
} }
const changedAt = new Date(); if (plan.survivorId) {
const previousGrant =
grants.find((grant) => grant.immichAlbumId === input.immichAlbumId) ?? grants[0];
if (previousGrant) {
await transaction await transaction
.update(albumGrants) .update(albumGrants)
.set({ .set({
@@ -123,7 +144,7 @@ export function createAlbumGrantRepository(
grantedByUserId: input.adminUserId, grantedByUserId: input.adminUserId,
revokedAt: null, revokedAt: null,
}) })
.where(eq(albumGrants.id, previousGrant.id)); .where(eq(albumGrants.id, plan.survivorId));
} else { } else {
await transaction.insert(albumGrants).values({ await transaction.insert(albumGrants).values({
editorialAccountId: editorial.id, editorialAccountId: editorial.id,
@@ -160,18 +181,18 @@ export function createAlbumGrantRepository(
await lockEditorialAlbumMutation(transaction, input.editorialId); await lockEditorialAlbumMutation(transaction, input.editorialId);
const editorial = await lockEditorial(transaction, input.editorialId); const editorial = await lockEditorial(transaction, input.editorialId);
const grants = await lockAlbumGrants(transaction, input.editorialId, input.immichAlbumId); const grants = await lockAlbumGrants(transaction, input.editorialId, input.immichAlbumId);
const activeGrants = grants.filter((grant) => grant.revokedAt === null); const activeGrantIds = planAlbumRevokeMutation(grants);
if (activeGrants.length === 0) { if (activeGrantIds.length === 0) {
return false; return false;
} }
const changedAt = new Date(); const changedAt = new Date();
await transaction await transaction
.update(albumGrants) .update(albumGrants)
.set({ immichAlbumId: input.immichAlbumId, revokedAt: changedAt }) .set({ revokedAt: changedAt })
.where( .where(
and( and(
inArray(albumGrants.id, activeGrants.map((grant) => grant.id)), inArray(albumGrants.id, activeGrantIds),
isNull(albumGrants.revokedAt), isNull(albumGrants.revokedAt),
), ),
); );
@@ -233,6 +254,49 @@ function canonicalizeStoredIdentifier(value: string): string {
: value; : value;
} }
function uniqueCanonicalIdentifiers(values: string[]): string[] {
return [...new Set(values.map(canonicalizeStoredIdentifier))];
}
export function planAlbumGrantMutation(
grants: AlbumGrantMutationCandidate[],
canonicalImmichAlbumId: string,
): AlbumGrantMutationPlan {
const ordered = [...grants].sort((left, right) =>
compareGrantCandidates(left, right, canonicalImmichAlbumId),
);
const survivorId = ordered[0]?.id ?? null;
return {
survivorId,
activeLoserIds: ordered
.filter((grant) => grant.revokedAt === null && grant.id !== survivorId)
.map((grant) => grant.id),
hadActiveGrant: ordered.some((grant) => grant.revokedAt === null),
};
}
export function planAlbumRevokeMutation(grants: AlbumGrantMutationCandidate[]): string[] {
return grants
.filter((grant) => grant.revokedAt === null)
.map((grant) => grant.id)
.sort();
}
function compareGrantCandidates(
left: AlbumGrantMutationCandidate,
right: AlbumGrantMutationCandidate,
canonicalImmichAlbumId: string,
): number {
const exactCaseOrder =
Number(left.immichAlbumId !== canonicalImmichAlbumId) -
Number(right.immichAlbumId !== canonicalImmichAlbumId);
if (exactCaseOrder !== 0) return exactCaseOrder;
const grantedAtOrder = left.grantedAt.getTime() - right.grantedAt.getTime();
if (grantedAtOrder !== 0) return grantedAtOrder;
return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
}
function hasCode(error: unknown, code: string): boolean { function hasCode(error: unknown, code: string): boolean {
return typeof error === "object" && error !== null && "code" in error && error.code === code; return typeof error === "object" && error !== null && "code" in error && error.code === code;
} }
@@ -271,6 +335,7 @@ async function lockAlbumGrants(
.select({ .select({
id: albumGrants.id, id: albumGrants.id,
immichAlbumId: albumGrants.immichAlbumId, immichAlbumId: albumGrants.immichAlbumId,
grantedAt: albumGrants.grantedAt,
revokedAt: albumGrants.revokedAt, revokedAt: albumGrants.revokedAt,
}) })
.from(albumGrants) .from(albumGrants)
@@ -280,6 +345,11 @@ async function lockAlbumGrants(
sql`lower(${albumGrants.immichAlbumId}) = ${immichAlbumId}`, sql`lower(${albumGrants.immichAlbumId}) = ${immichAlbumId}`,
), ),
) )
.orderBy(
sql`case when ${albumGrants.immichAlbumId} = ${immichAlbumId} then 0 else 1 end`,
asc(albumGrants.grantedAt),
asc(albumGrants.id),
)
.for("update"); .for("update");
} }
+22 -2
View File
@@ -8,11 +8,12 @@ const migration = await readFile(
"utf8", "utf8",
); );
test("0002 retains legacy Immich text and gates only new non-canonical rows", () => { test("0002 retains legacy Immich text and accepts case-variant historical UUIDs", () => {
expect(migration).not.toMatch(/ALTER COLUMN "immich_[^"]+" SET DATA TYPE uuid/); expect(migration).not.toMatch(/ALTER COLUMN "immich_[^"]+" SET DATA TYPE uuid/);
expect(migration).toContain( expect(migration).toContain(
'ADD CONSTRAINT "album_grants_canonical_immich_album_id_check"', 'ADD CONSTRAINT "album_grants_immich_album_id_uuid_check"',
); );
expect(migration).toContain('CHECK ("album_grants"."immich_album_id" ~*');
expect(migration).toContain( expect(migration).toContain(
'ADD CONSTRAINT "usages_canonical_immich_asset_id_check"', 'ADD CONSTRAINT "usages_canonical_immich_asset_id_check"',
); );
@@ -25,6 +26,25 @@ test("0002 retains legacy Immich text and gates only new non-canonical rows", ()
expect(migration.match(/NOT VALID/g)).toHaveLength(4); expect(migration.match(/NOT VALID/g)).toHaveLength(4);
}); });
test("0002 consolidates active case duplicates before adding their partial unique index", () => {
const consolidation = migration.indexOf('ranked_active_album_grants AS');
const activeIndex = migration.indexOf(
'CREATE UNIQUE INDEX "album_grants_editorial_active_album_unique"',
);
expect(consolidation).toBeGreaterThan(-1);
expect(migration).toContain(
'PARTITION BY "editorial_account_id", lower("immich_album_id")',
);
expect(migration).toContain(
'ORDER BY ("immich_album_id" = lower("immich_album_id")) DESC, "granted_at", "id"',
);
expect(activeIndex).toBeGreaterThan(consolidation);
expect(migration).toContain(
'ON "album_grants" ("editorial_account_id", lower("immich_album_id")) WHERE "revoked_at" IS NULL',
);
});
test("0002 uses an explicit legacy kind instead of random UUID ordering for ambiguity", () => { test("0002 uses an explicit legacy kind instead of random UUID ordering for ambiguity", () => {
expect(migration).not.toContain('ORDER BY "authorized_at", "id"'); expect(migration).not.toContain('ORDER BY "authorized_at", "id"');
expect(migration).toContain("ELSE 'legacy'"); expect(migration).toContain("ELSE 'legacy'");
+5 -3
View File
@@ -301,13 +301,13 @@ test("0002 preserves dirty rows and reconstructs only provable legacy intents",
"insert into album_grants (editorial_account_id, immich_album_id) values ($1, $2)", "insert into album_grants (editorial_account_id, immich_album_id) values ($1, $2)",
[editorialId, "new-invalid-album"], [editorialId, "new-invalid-album"],
), ),
).rejects.toThrow(/album_grants_canonical_immich_album_id_check/); ).rejects.toThrow(/album_grants_immich_album_id_uuid_check/);
await expect( await expect(
testDb.pool.query( testDb.pool.query(
"update album_grants set revoked_at = now() where immich_album_id = $1", "update album_grants set revoked_at = now() where immich_album_id = $1",
[dirtyAlbumId], [dirtyAlbumId],
), ),
).rejects.toThrow(/album_grants_canonical_immich_album_id_check/); ).rejects.toThrow(/album_grants_immich_album_id_uuid_check/);
const grantService = createAlbumGrantService({ const grantService = createAlbumGrantService({
repository: createAlbumGrantRepository(testDb.database), repository: createAlbumGrantRepository(testDb.database),
@@ -336,7 +336,9 @@ test("0002 preserves dirty rows and reconstructs only provable legacy intents",
[validAlbumId], [validAlbumId],
); );
expect(canonicalGrantRows.rows).toHaveLength(2); expect(canonicalGrantRows.rows).toHaveLength(2);
expect(canonicalGrantRows.rows.every((row) => row.immich_album_id === validAlbumId)).toBe(true); expect(canonicalGrantRows.rows.map((row) => row.immich_album_id).sort()).toEqual(
[validAlbumId.toUpperCase(), validAlbumId].sort(),
);
expect(canonicalGrantRows.rows.every((row) => row.revoked_at !== null)).toBe(true); expect(canonicalGrantRows.rows.every((row) => row.revoked_at !== null)).toBe(true);
await grantService.grantAlbum({ await grantService.grantAlbum({
+277
View File
@@ -0,0 +1,277 @@
import { randomUUID } from "node:crypto";
import { afterAll, expect, test, vi } from "vitest";
import { createAlbumGrantRepository, createAlbumGrantService } from "@/modules/albums/grants";
import { startPostgres } from "./postgres";
const testDb = await startPostgres({ through: "0001_editorial_approval_notice.sql" });
afterAll(() => testDb.stop());
const directAlbumId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
const revokeAlbumId = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
const regrantAlbumId = "dddddddd-dddd-4ddd-8ddd-dddddddddddd";
const listAlbumId = "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee";
const migrationAlbumId = "ffffffff-ffff-4fff-8fff-ffffffffffff";
const earlierGrant = new Date("2026-08-07T08:00:00.000Z");
const laterGrant = new Date("2026-08-08T08:00:00.000Z");
const revokedAt = new Date("2026-08-09T08:00:00.000Z");
test("grant mutations and migration preserve one deterministic active logical grant", async () => {
const adminUserId = randomUUID();
const editorialId = randomUUID();
await testDb.pool.query(
`insert into users (id, name, email, email_verified)
values ($1, 'Grant Admin', $2, true)`,
[adminUserId, `${adminUserId}@example.com`],
);
await testDb.pool.query(
`insert into editorial_accounts (
id, user_id, name, contact_name, login_email, status, current_price_cents
) values ($1, $2, 'Grant Redaktion', 'Grant Kontakt', $3, 'active', 2300)`,
[editorialId, adminUserId, `${adminUserId}@example.com`],
);
await insertGrantRows(editorialId, adminUserId, [
{
id: "10000000-0000-4000-8000-000000000001",
albumId: directAlbumId.toUpperCase(),
grantedAt: earlierGrant,
revokedAt: null,
},
{
id: "10000000-0000-4000-8000-000000000002",
albumId: directAlbumId,
grantedAt: laterGrant,
revokedAt: null,
},
]);
await insertGrantRows(editorialId, adminUserId, [
{
id: "20000000-0000-4000-8000-000000000001",
albumId: revokeAlbumId.toUpperCase(),
grantedAt: earlierGrant,
revokedAt: null,
},
{
id: "20000000-0000-4000-8000-000000000002",
albumId: revokeAlbumId,
grantedAt: laterGrant,
revokedAt: null,
},
]);
await insertGrantRows(editorialId, adminUserId, [
{
id: "30000000-0000-4000-8000-000000000003",
albumId: regrantAlbumId.toUpperCase(),
grantedAt: laterGrant,
revokedAt,
},
{
id: "30000000-0000-4000-8000-000000000002",
albumId: "Dddddddd-dddd-4ddd-8ddd-dddddddddddd",
grantedAt: earlierGrant,
revokedAt,
},
{
id: "30000000-0000-4000-8000-000000000001",
albumId: "dddddddD-dddd-4ddd-8ddd-dddddddddddd",
grantedAt: earlierGrant,
revokedAt,
},
]);
await insertGrantRows(editorialId, adminUserId, [
{
id: "40000000-0000-4000-8000-000000000001",
albumId: listAlbumId.toUpperCase(),
grantedAt: earlierGrant,
revokedAt: null,
},
{
id: "40000000-0000-4000-8000-000000000002",
albumId: listAlbumId,
grantedAt: laterGrant,
revokedAt: null,
},
]);
await insertGrantRows(editorialId, adminUserId, [
{
id: "50000000-0000-4000-8000-000000000001",
albumId: migrationAlbumId.toUpperCase(),
grantedAt: earlierGrant,
revokedAt: null,
},
{
id: "50000000-0000-4000-8000-000000000002",
albumId: migrationAlbumId,
grantedAt: laterGrant,
revokedAt: null,
},
]);
const grantService = createAlbumGrantService({
repository: createAlbumGrantRepository(testDb.database),
immich: {
getAlbum: vi.fn().mockImplementation(async (id: string) => ({
id,
albumName: "Grant Album",
description: null,
albumThumbnailAssetId: null,
assetCount: 0,
assets: [],
})),
listAlbums: vi.fn(),
},
});
const listedBeforeCleanup = await grantService.getGrantedAlbumIds(editorialId);
expect(listedBeforeCleanup.filter((id) => id === listAlbumId)).toEqual([listAlbumId]);
await grantService.grantAlbum({
editorialId,
immichAlbumId: directAlbumId,
adminUserId,
});
await grantService.grantAlbum({
editorialId,
immichAlbumId: directAlbumId,
adminUserId,
});
expect(await activeGrantRows(editorialId, directAlbumId)).toEqual([
{
id: "10000000-0000-4000-8000-000000000002",
immich_album_id: directAlbumId,
},
]);
await expect(auditCount(editorialId, directAlbumId, "album_granted")).resolves.toBe(0);
await grantService.revokeAlbum({
editorialId,
immichAlbumId: revokeAlbumId,
adminUserId,
});
await expect(activeGrantRows(editorialId, revokeAlbumId)).resolves.toEqual([]);
await expect(auditCount(editorialId, revokeAlbumId, "album_revoked")).resolves.toBe(1);
await grantService.grantAlbum({
editorialId,
immichAlbumId: regrantAlbumId,
adminUserId,
});
await grantService.grantAlbum({
editorialId,
immichAlbumId: regrantAlbumId,
adminUserId,
});
expect(await activeGrantRows(editorialId, regrantAlbumId)).toEqual([
{
id: "30000000-0000-4000-8000-000000000001",
immich_album_id: regrantAlbumId,
},
]);
await expect(auditCount(editorialId, regrantAlbumId, "album_granted")).resolves.toBe(1);
await testDb.applyRemainingMigrations();
expect(await allGrantRows(editorialId, migrationAlbumId)).toEqual([
{
id: "50000000-0000-4000-8000-000000000001",
immich_album_id: migrationAlbumId.toUpperCase(),
revoked: true,
},
{
id: "50000000-0000-4000-8000-000000000002",
immich_album_id: migrationAlbumId,
revoked: false,
},
]);
await expect(
testDb.pool.query(
`insert into album_grants (
editorial_account_id, immich_album_id, granted_by_user_id
) values ($1, $2, $3)`,
[editorialId, migrationAlbumId.toUpperCase(), adminUserId],
),
).rejects.toThrow(/album_grants_editorial_active_album_unique/);
await expect(
testDb.pool.query(
`insert into album_grants (
editorial_account_id, immich_album_id, revoked_at, granted_by_user_id
) values ($1, $2, now(), $3)`,
[editorialId, migrationAlbumId.toUpperCase(), adminUserId],
),
).resolves.toBeDefined();
await expect(
testDb.pool.query(
"insert into album_grants (editorial_account_id, immich_album_id) values ($1, $2)",
[editorialId, "new-invalid-album"],
),
).rejects.toThrow(/album_grants_immich_album_id_uuid_check/);
await expect(
testDb.pool.query(
"update album_grants set revoked_at = revoked_at where id = $1",
["50000000-0000-4000-8000-000000000001"],
),
).resolves.toBeDefined();
});
type GrantSeed = {
id: string;
albumId: string;
grantedAt: Date;
revokedAt: Date | null;
};
async function insertGrantRows(editorialId: string, adminUserId: string, rows: GrantSeed[]) {
for (const row of rows) {
await testDb.pool.query(
`insert into album_grants (
id, editorial_account_id, immich_album_id, granted_at, revoked_at, granted_by_user_id
) values ($1, $2, $3, $4, $5, $6)`,
[row.id, editorialId, row.albumId, row.grantedAt, row.revokedAt, adminUserId],
);
}
}
async function activeGrantRows(editorialId: string, albumId: string) {
const result = await testDb.pool.query<{
id: string;
immich_album_id: string;
}>(
`select id, immich_album_id
from album_grants
where editorial_account_id = $1 and lower(immich_album_id) = $2 and revoked_at is null
order by id`,
[editorialId, albumId],
);
return result.rows;
}
async function allGrantRows(editorialId: string, albumId: string) {
const result = await testDb.pool.query<{
id: string;
immich_album_id: string;
revoked: boolean;
}>(
`select id, immich_album_id, revoked_at is not null as revoked
from album_grants
where editorial_account_id = $1 and lower(immich_album_id) = $2
order by id`,
[editorialId, albumId],
);
return result.rows;
}
async function auditCount(editorialId: string, albumId: string, eventType: string) {
const result = await testDb.pool.query<{ count: string }>(
`select count(*)::text as count
from audit_events
where event_type = $1
and entity_id = $2
and new_values->>'editorialId' = $3`,
[eventType, albumId, editorialId],
);
return Number(result.rows[0]?.count ?? 0);
}