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
9 files changed
+577 -45

No files matched your search

+6 -3
View File
@@ -1,5 +1,5 @@
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 { editorialAccounts } from "./editorials";
@@ -21,9 +21,12 @@ export const albumGrants = pgTable(
(table) => [
index("album_grants_editorial_account_id_idx").on(table.editorialAccountId),
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(
"album_grants_canonical_immich_album_id_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}$'`,
"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}$'`,
),
],
);
+138 -15
View File
@@ -4,6 +4,8 @@ import {
ALBUM_GRANT_LOCK_ORDER,
AlbumGrantError,
createAlbumGrantService,
planAlbumGrantMutation,
planAlbumRevokeMutation,
type AlbumGrantRepository,
} from "./grants";
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 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[] = []) {
const grants = [...initial];
const audit: Audit[] = [];
@@ -33,26 +125,28 @@ function createRepository(initial: Grant[] = []) {
.map((grant) => grant.albumId);
},
async grant(input) {
const active = grants.filter(
const matching = grants.filter(
(grant) =>
grant.editorialId === input.editorialId &&
grant.albumId.toLowerCase() === input.immichAlbumId &&
grant.revokedAt === null,
grant.albumId.toLowerCase() === input.immichAlbumId,
);
const survivor =
matching.find((grant) => grant.albumId === input.immichAlbumId) ?? matching[0];
const active = matching.filter((grant) => grant.revokedAt === null);
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;
}
const revoked = grants.find(
(grant) =>
grant.editorialId === input.editorialId &&
grant.albumId.toLowerCase() === input.immichAlbumId &&
grant.revokedAt !== null,
);
if (revoked) {
revoked.albumId = input.immichAlbumId;
revoked.revokedAt = null;
if (survivor) {
survivor.albumId = input.immichAlbumId;
survivor.revokedAt = null;
} else {
grants.push({ editorialId: input.editorialId, albumId: input.immichAlbumId, revokedAt: null });
}
@@ -75,7 +169,6 @@ function createRepository(initial: Grant[] = []) {
);
if (active.length === 0) return false;
for (const grant of active) {
grant.albumId = input.immichAlbumId;
grant.revokedAt = new Date();
}
audit.push({
@@ -165,6 +258,37 @@ test("treats an uppercase historical album grant as the canonical active grant",
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 () => {
const { service, grants, audit } = createService([
{ 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,
});
expect(grants.filter((grant) => grant.revokedAt === null)).toHaveLength(0);
expect(grants.every((grant) => grant.albumId === albumUuid)).toBe(true);
await service.grantAlbum({
editorialId: editorialUuid,
+86 -16
View File
@@ -1,6 +1,6 @@
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 { db } from "@/db/client";
@@ -24,6 +24,19 @@ export type AlbumGrantRepository = {
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 class AlbumGrantError extends Error {
@@ -80,7 +93,7 @@ export function createAlbumGrantService({
async getGrantedAlbumIds(editorialId: string): Promise<string[]> {
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 })
.from(albumGrants)
.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) {
@@ -102,19 +115,27 @@ export function createAlbumGrantRepository(
await lockEditorialAlbumMutation(transaction, input.editorialId);
const editorial = await lockEditorial(transaction, input.editorialId);
const grants = await lockAlbumGrants(transaction, input.editorialId, input.immichAlbumId);
const activeGrants = grants.filter((grant) => grant.revokedAt === null);
if (activeGrants.length > 0) {
const plan = planAlbumGrantMutation(grants, input.immichAlbumId);
const changedAt = new Date();
if (plan.activeLoserIds.length > 0) {
await transaction
.update(albumGrants)
.set({ immichAlbumId: input.immichAlbumId })
.where(inArray(albumGrants.id, activeGrants.map((grant) => grant.id)));
.set({ revokedAt: changedAt })
.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;
}
const changedAt = new Date();
const previousGrant =
grants.find((grant) => grant.immichAlbumId === input.immichAlbumId) ?? grants[0];
if (previousGrant) {
if (plan.survivorId) {
await transaction
.update(albumGrants)
.set({
@@ -123,7 +144,7 @@ export function createAlbumGrantRepository(
grantedByUserId: input.adminUserId,
revokedAt: null,
})
.where(eq(albumGrants.id, previousGrant.id));
.where(eq(albumGrants.id, plan.survivorId));
} else {
await transaction.insert(albumGrants).values({
editorialAccountId: editorial.id,
@@ -160,18 +181,18 @@ export function createAlbumGrantRepository(
await lockEditorialAlbumMutation(transaction, input.editorialId);
const editorial = await lockEditorial(transaction, input.editorialId);
const grants = await lockAlbumGrants(transaction, input.editorialId, input.immichAlbumId);
const activeGrants = grants.filter((grant) => grant.revokedAt === null);
if (activeGrants.length === 0) {
const activeGrantIds = planAlbumRevokeMutation(grants);
if (activeGrantIds.length === 0) {
return false;
}
const changedAt = new Date();
await transaction
.update(albumGrants)
.set({ immichAlbumId: input.immichAlbumId, revokedAt: changedAt })
.set({ revokedAt: changedAt })
.where(
and(
inArray(albumGrants.id, activeGrants.map((grant) => grant.id)),
inArray(albumGrants.id, activeGrantIds),
isNull(albumGrants.revokedAt),
),
);
@@ -233,6 +254,49 @@ function canonicalizeStoredIdentifier(value: string): string {
: 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 {
return typeof error === "object" && error !== null && "code" in error && error.code === code;
}
@@ -271,6 +335,7 @@ async function lockAlbumGrants(
.select({
id: albumGrants.id,
immichAlbumId: albumGrants.immichAlbumId,
grantedAt: albumGrants.grantedAt,
revokedAt: albumGrants.revokedAt,
})
.from(albumGrants)
@@ -280,6 +345,11 @@ async function lockAlbumGrants(
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");
}