fix: harden legacy normalization and grants

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 11:53:28 +02:00
1 parent 3cdca5c82c
commit 74ab2eb85f
5 files changed
+198 -20

No files matched your search

+12 -3
View File
@@ -49,12 +49,18 @@ legacy_event_candidates AS (
AND usage."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}$' AND usage."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}$'
AND usage."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}$' AND usage."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}$'
AND 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}$' AND 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}$'
AND usage."purpose" = btrim(usage."purpose") AND octet_length(usage."purpose") = char_length(usage."purpose")
AND usage."purpose" !~ '[[:cntrl:]]'
AND left(usage."purpose", 1) <> ' '
AND right(usage."purpose", 1) <> ' '
AND char_length(usage."purpose") BETWEEN 3 AND 200 AND char_length(usage."purpose") BETWEEN 3 AND 200
AND ( AND (
usage."internal_reference" IS NULL usage."internal_reference" IS NULL
OR ( OR (
usage."internal_reference" = btrim(usage."internal_reference") octet_length(usage."internal_reference") = char_length(usage."internal_reference")
AND usage."internal_reference" !~ '[[:cntrl:]]'
AND left(usage."internal_reference", 1) <> ' '
AND right(usage."internal_reference", 1) <> ' '
AND usage."internal_reference" <> '' AND usage."internal_reference" <> ''
AND char_length(usage."internal_reference") <= 200 AND char_length(usage."internal_reference") <= 200
) )
@@ -72,7 +78,10 @@ legacy_event_candidates AS (
AND lower(events."immich_asset_id") = lower(usage."immich_asset_id") AND lower(events."immich_asset_id") = lower(usage."immich_asset_id")
AND 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}$' AND 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}$'
AND 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}$' AND 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}$'
AND events."repeat_download_note" = btrim(events."repeat_download_note") AND octet_length(events."repeat_download_note") = char_length(events."repeat_download_note")
AND events."repeat_download_note" !~ '[[:cntrl:]]'
AND left(events."repeat_download_note", 1) <> ' '
AND right(events."repeat_download_note", 1) <> ' '
AND events."repeat_download_note" <> '' AND events."repeat_download_note" <> ''
AND char_length(events."repeat_download_note") <= 200 AND char_length(events."repeat_download_note") <= 200
AND NOT EXISTS ( AND NOT EXISTS (
+35 -5
View File
@@ -33,13 +33,16 @@ function createRepository(initial: Grant[] = []) {
.map((grant) => grant.albumId); .map((grant) => grant.albumId);
}, },
async grant(input) { async grant(input) {
const active = grants.find( const active = 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, grant.revokedAt === null,
); );
if (active) return false; if (active.length > 0) {
for (const grant of active) grant.albumId = input.immichAlbumId;
return false;
}
const revoked = grants.find( const revoked = grants.find(
(grant) => (grant) =>
@@ -48,6 +51,7 @@ function createRepository(initial: Grant[] = []) {
grant.revokedAt !== null, grant.revokedAt !== null,
); );
if (revoked) { if (revoked) {
revoked.albumId = input.immichAlbumId;
revoked.revokedAt = null; 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 });
@@ -63,14 +67,17 @@ function createRepository(initial: Grant[] = []) {
return true; return true;
}, },
async revoke(input) { async revoke(input) {
const active = grants.find( const active = 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, grant.revokedAt === null,
); );
if (!active) return false; if (active.length === 0) return false;
active.revokedAt = new Date(); for (const grant of active) {
grant.albumId = input.immichAlbumId;
grant.revokedAt = new Date();
}
audit.push({ audit.push({
eventType: "album_revoked", eventType: "album_revoked",
actorUserId: input.adminUserId, actorUserId: input.adminUserId,
@@ -158,6 +165,29 @@ test("treats an uppercase historical album grant as the canonical active grant",
expect(audit).toHaveLength(0); 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 },
{ editorialId: editorialUuid, albumId: albumUuid, revokedAt: null },
]);
await service.revokeAlbum({
editorialId: editorialUuid,
immichAlbumId: albumUuid,
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,
immichAlbumId: albumUuid,
adminUserId: adminUuid,
});
expect(grants.filter((grant) => grant.revokedAt === null)).toHaveLength(1);
expect(audit.map((event) => event.eventType)).toEqual(["album_revoked", "album_granted"]);
});
test("rejects a non-UUID grant before external side effects", async () => { test("rejects a non-UUID grant before external side effects", async () => {
const { service, immich, grants } = createService(); const { service, immich, grants } = createService();
+24 -9
View File
@@ -1,6 +1,6 @@
import "server-only"; import "server-only";
import { and, eq, isNull, sql } from "drizzle-orm"; import { and, 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";
@@ -102,17 +102,23 @@ 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 activeGrant = grants.find((grant) => grant.revokedAt === null); const activeGrants = grants.filter((grant) => grant.revokedAt === null);
if (activeGrant) { if (activeGrants.length > 0) {
await transaction
.update(albumGrants)
.set({ immichAlbumId: input.immichAlbumId })
.where(inArray(albumGrants.id, activeGrants.map((grant) => grant.id)));
return false; return false;
} }
const changedAt = new Date(); const changedAt = new Date();
const previousGrant = grants[0]; const previousGrant =
grants.find((grant) => grant.immichAlbumId === input.immichAlbumId) ?? grants[0];
if (previousGrant) { if (previousGrant) {
await transaction await transaction
.update(albumGrants) .update(albumGrants)
.set({ .set({
immichAlbumId: input.immichAlbumId,
grantedAt: changedAt, grantedAt: changedAt,
grantedByUserId: input.adminUserId, grantedByUserId: input.adminUserId,
revokedAt: null, revokedAt: null,
@@ -154,16 +160,21 @@ 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 activeGrant = grants.find((grant) => grant.revokedAt === null); const activeGrants = grants.filter((grant) => grant.revokedAt === null);
if (!activeGrant) { if (activeGrants.length === 0) {
return false; return false;
} }
const changedAt = new Date(); const changedAt = new Date();
await transaction await transaction
.update(albumGrants) .update(albumGrants)
.set({ revokedAt: changedAt }) .set({ immichAlbumId: input.immichAlbumId, revokedAt: changedAt })
.where(and(eq(albumGrants.id, activeGrant.id), isNull(albumGrants.revokedAt))); .where(
and(
inArray(albumGrants.id, activeGrants.map((grant) => grant.id)),
isNull(albumGrants.revokedAt),
),
);
await transaction.insert(auditEvents).values({ await transaction.insert(auditEvents).values({
eventType: "album_revoked", eventType: "album_revoked",
actorUserId: input.adminUserId, actorUserId: input.adminUserId,
@@ -257,7 +268,11 @@ async function lockAlbumGrants(
immichAlbumId: string, immichAlbumId: string,
) { ) {
return transaction return transaction
.select({ id: albumGrants.id, revokedAt: albumGrants.revokedAt }) .select({
id: albumGrants.id,
immichAlbumId: albumGrants.immichAlbumId,
revokedAt: albumGrants.revokedAt,
})
.from(albumGrants) .from(albumGrants)
.where( .where(
and( and(
+10
View File
@@ -31,3 +31,13 @@ test("0002 uses an explicit legacy kind instead of random UUID ordering for ambi
expect(migration).toContain("in ('new_usage', 'repeat_download', 'legacy')"); expect(migration).toContain("in ('new_usage', 'repeat_download', 'legacy')");
expect(migration).toContain("case_colliding_idempotency_keys"); expect(migration).toContain("case_colliding_idempotency_keys");
}); });
test("0002 reconstructs only already-normalized printable ASCII text", () => {
expect(migration).not.toContain("btrim(");
expect(migration).toContain(
'octet_length(usage."purpose") = char_length(usage."purpose")',
);
expect(migration).toContain("!~ '[[:cntrl:]]'");
expect(migration).toContain("left(usage.\"purpose\", 1) <> ' '");
expect(migration).toContain("right(events.\"repeat_download_note\", 1) <> ' '");
});
+117 -3
View File
@@ -4,6 +4,7 @@ import { eq } from "drizzle-orm";
import { afterAll, expect, test, vi } from "vitest"; import { afterAll, expect, test, vi } from "vitest";
import { downloadEvents } from "@/db/schema"; import { downloadEvents } from "@/db/schema";
import { createAlbumGrantRepository, createAlbumGrantService } from "@/modules/albums/grants";
import { createUsageService, createUsageServiceRepository } from "@/modules/usages/service"; import { createUsageService, createUsageServiceRepository } from "@/modules/usages/service";
import { requestFingerprint } from "@/modules/usages/types"; import { requestFingerprint } from "@/modules/usages/types";
import { startPostgres } from "./postgres"; import { startPostgres } from "./postgres";
@@ -17,6 +18,8 @@ const validAlbumId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
const cleanKey = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; const cleanKey = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
const collidingKey = "dddddddd-dddd-4ddd-8ddd-dddddddddddd"; const collidingKey = "dddddddd-dddd-4ddd-8ddd-dddddddddddd";
const authorizedAt = new Date("2026-08-09T08:00:00.000Z"); const authorizedAt = new Date("2026-08-09T08:00:00.000Z");
const repeatAt = new Date("2026-08-09T08:01:00.000Z");
const laterNullAt = new Date("2026-08-09T08:02:00.000Z");
async function insertLegacyUsage({ async function insertLegacyUsage({
editorialId, editorialId,
@@ -85,8 +88,8 @@ test("0002 preserves dirty rows and reconstructs only provable legacy intents",
); );
await testDb.pool.query( await testDb.pool.query(
`insert into album_grants (editorial_account_id, immich_album_id) `insert into album_grants (editorial_account_id, immich_album_id)
values ($1, $2), ($1, $3)`, values ($1, $2), ($1, $3), ($1, $4)`,
[editorialId, validAlbumId.toUpperCase(), "legacy album / 2019"], [editorialId, validAlbumId.toUpperCase(), "legacy album / 2019", validAlbumId],
); );
const cleanUsageId = await insertLegacyUsage({ const cleanUsageId = await insertLegacyUsage({
@@ -101,6 +104,48 @@ test("0002 preserves dirty rows and reconstructs only provable legacy intents",
idempotencyKey: cleanKey.toUpperCase(), idempotencyKey: cleanKey.toUpperCase(),
}); });
const repeatUsageId = await insertLegacyUsage({ editorialId });
const repeatInitialEventId = await insertLegacyEvent({ editorialId, usageId: repeatUsageId });
const provableRepeatEventId = await insertLegacyEvent({
editorialId,
usageId: repeatUsageId,
note: "Web-Ausgabe",
at: repeatAt,
});
const laterNullEventId = await insertLegacyEvent({
editorialId,
usageId: repeatUsageId,
at: laterNullAt,
});
const tabPurposeUsageId = await insertLegacyUsage({
editorialId,
purpose: "\tTitelgeschichte",
});
const tabPurposeEventId = await insertLegacyEvent({
editorialId,
usageId: tabPurposeUsageId,
});
const newlineReferenceUsageId = await insertLegacyUsage({
editorialId,
reference: "Ausgabe 8/26\n",
});
const newlineReferenceEventId = await insertLegacyEvent({
editorialId,
usageId: newlineReferenceUsageId,
});
const nbspNoteUsageId = await insertLegacyUsage({ editorialId });
const nbspNoteInitialEventId = await insertLegacyEvent({
editorialId,
usageId: nbspNoteUsageId,
});
const nbspNoteEventId = await insertLegacyEvent({
editorialId,
usageId: nbspNoteUsageId,
note: "\u00a0Web-Ausgabe",
at: repeatAt,
});
const dirtyAssetId = "legacy-asset/not-a-uuid"; const dirtyAssetId = "legacy-asset/not-a-uuid";
const dirtyAlbumId = "legacy album / 2019"; const dirtyAlbumId = "legacy album / 2019";
const dirtyUsageId = await insertLegacyUsage({ const dirtyUsageId = await insertLegacyUsage({
@@ -190,7 +235,7 @@ test("0002 preserves dirty rows and reconstructs only provable legacy intents",
`select id, idempotency_key, immich_asset_id, intent_kind, request_fingerprint `select id, idempotency_key, immich_asset_id, intent_kind, request_fingerprint
from download_events`, from download_events`,
); );
expect(migratedEvents.rows).toHaveLength(7); expect(migratedEvents.rows).toHaveLength(14);
const byId = new Map(migratedEvents.rows.map((row) => [row.id, row])); const byId = new Map(migratedEvents.rows.map((row) => [row.id, row]));
expect(byId.get(cleanEventId)).toMatchObject({ expect(byId.get(cleanEventId)).toMatchObject({
idempotency_key: cleanKey, idempotency_key: cleanKey,
@@ -210,7 +255,21 @@ test("0002 preserves dirty rows and reconstructs only provable legacy intents",
immich_asset_id: dirtyAssetId, immich_asset_id: dirtyAssetId,
intent_kind: "legacy", intent_kind: "legacy",
}); });
expect(byId.get(repeatInitialEventId)?.intent_kind).toBe("new_usage");
expect(byId.get(provableRepeatEventId)).toMatchObject({
intent_kind: "repeat_download",
request_fingerprint: requestFingerprint({
kind: "repeat_download",
editorialId,
usageId: repeatUsageId,
note: "Web-Ausgabe",
}),
});
for (const id of [ for (const id of [
laterNullEventId,
tabPurposeEventId,
newlineReferenceEventId,
nbspNoteEventId,
...equalTimeEventIds, ...equalTimeEventIds,
contradictoryEventId, contradictoryEventId,
...collisionEventIds, ...collisionEventIds,
@@ -218,6 +277,7 @@ test("0002 preserves dirty rows and reconstructs only provable legacy intents",
expect(byId.get(id)?.intent_kind).toBe("legacy"); expect(byId.get(id)?.intent_kind).toBe("legacy");
expect(byId.get(id)?.request_fingerprint).toMatch(/^[0-9a-f]{64}$/); expect(byId.get(id)?.request_fingerprint).toMatch(/^[0-9a-f]{64}$/);
} }
expect(byId.get(nbspNoteInitialEventId)?.intent_kind).toBe("new_usage");
expect(collisionEventIds.map((id) => byId.get(id)?.idempotency_key).sort()).toEqual( expect(collisionEventIds.map((id) => byId.get(id)?.idempotency_key).sort()).toEqual(
[collidingKey.toUpperCase(), collidingKey].sort(), [collidingKey.toUpperCase(), collidingKey].sort(),
); );
@@ -236,6 +296,60 @@ test("0002 preserves dirty rows and reconstructs only provable legacy intents",
); );
expect(dirtyGrant.rows).toEqual([{ immich_album_id: dirtyAlbumId }]); expect(dirtyGrant.rows).toEqual([{ immich_album_id: dirtyAlbumId }]);
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_canonical_immich_album_id_check/);
await expect(
testDb.pool.query(
"update album_grants set revoked_at = now() where immich_album_id = $1",
[dirtyAlbumId],
),
).rejects.toThrow(/album_grants_canonical_immich_album_id_check/);
const grantService = createAlbumGrantService({
repository: createAlbumGrantRepository(testDb.database),
immich: {
getAlbum: vi.fn().mockResolvedValue({
id: validAlbumId,
albumName: "Legacy Album",
description: null,
albumThumbnailAssetId: null,
assetCount: 0,
assets: [],
}),
listAlbums: vi.fn(),
},
});
await grantService.revokeAlbum({
editorialId,
immichAlbumId: validAlbumId,
adminUserId: userId,
});
let canonicalGrantRows = await testDb.pool.query<{
immich_album_id: string;
revoked_at: Date | null;
}>(
"select immich_album_id, revoked_at from album_grants where lower(immich_album_id) = $1",
[validAlbumId],
);
expect(canonicalGrantRows.rows).toHaveLength(2);
expect(canonicalGrantRows.rows.every((row) => row.immich_album_id === validAlbumId)).toBe(true);
expect(canonicalGrantRows.rows.every((row) => row.revoked_at !== null)).toBe(true);
await grantService.grantAlbum({
editorialId,
immichAlbumId: validAlbumId,
adminUserId: userId,
});
canonicalGrantRows = await testDb.pool.query(
"select immich_album_id, revoked_at from album_grants where lower(immich_album_id) = $1",
[validAlbumId],
);
expect(canonicalGrantRows.rows.filter((row) => row.revoked_at === null)).toHaveLength(1);
await expect( await expect(
usageService.createNewUsage({ usageService.createNewUsage({
editorialId, editorialId,