fix: harden legacy normalization and grants
This commit is contained in:
1 parent
3cdca5c82c
commit
74ab2eb85f
5 files changed
+198
-20
No files matched your search
@@ -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_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 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 (
|
||||
usage."internal_reference" IS NULL
|
||||
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 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 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."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 char_length(events."repeat_download_note") <= 200
|
||||
AND NOT EXISTS (
|
||||
|
||||
@@ -33,13 +33,16 @@ function createRepository(initial: Grant[] = []) {
|
||||
.map((grant) => grant.albumId);
|
||||
},
|
||||
async grant(input) {
|
||||
const active = grants.find(
|
||||
const active = grants.filter(
|
||||
(grant) =>
|
||||
grant.editorialId === input.editorialId &&
|
||||
grant.albumId.toLowerCase() === input.immichAlbumId &&
|
||||
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(
|
||||
(grant) =>
|
||||
@@ -48,6 +51,7 @@ function createRepository(initial: Grant[] = []) {
|
||||
grant.revokedAt !== null,
|
||||
);
|
||||
if (revoked) {
|
||||
revoked.albumId = input.immichAlbumId;
|
||||
revoked.revokedAt = null;
|
||||
} else {
|
||||
grants.push({ editorialId: input.editorialId, albumId: input.immichAlbumId, revokedAt: null });
|
||||
@@ -63,14 +67,17 @@ function createRepository(initial: Grant[] = []) {
|
||||
return true;
|
||||
},
|
||||
async revoke(input) {
|
||||
const active = grants.find(
|
||||
const active = grants.filter(
|
||||
(grant) =>
|
||||
grant.editorialId === input.editorialId &&
|
||||
grant.albumId.toLowerCase() === input.immichAlbumId &&
|
||||
grant.revokedAt === null,
|
||||
);
|
||||
if (!active) return false;
|
||||
active.revokedAt = new Date();
|
||||
if (active.length === 0) return false;
|
||||
for (const grant of active) {
|
||||
grant.albumId = input.immichAlbumId;
|
||||
grant.revokedAt = new Date();
|
||||
}
|
||||
audit.push({
|
||||
eventType: "album_revoked",
|
||||
actorUserId: input.adminUserId,
|
||||
@@ -158,6 +165,29 @@ test("treats an uppercase historical album grant as the canonical active grant",
|
||||
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 () => {
|
||||
const { service, immich, grants } = createService();
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
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 { db } from "@/db/client";
|
||||
@@ -102,17 +102,23 @@ 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 activeGrant = grants.find((grant) => grant.revokedAt === null);
|
||||
if (activeGrant) {
|
||||
const activeGrants = grants.filter((grant) => grant.revokedAt === null);
|
||||
if (activeGrants.length > 0) {
|
||||
await transaction
|
||||
.update(albumGrants)
|
||||
.set({ immichAlbumId: input.immichAlbumId })
|
||||
.where(inArray(albumGrants.id, activeGrants.map((grant) => grant.id)));
|
||||
return false;
|
||||
}
|
||||
|
||||
const changedAt = new Date();
|
||||
const previousGrant = grants[0];
|
||||
const previousGrant =
|
||||
grants.find((grant) => grant.immichAlbumId === input.immichAlbumId) ?? grants[0];
|
||||
if (previousGrant) {
|
||||
await transaction
|
||||
.update(albumGrants)
|
||||
.set({
|
||||
immichAlbumId: input.immichAlbumId,
|
||||
grantedAt: changedAt,
|
||||
grantedByUserId: input.adminUserId,
|
||||
revokedAt: null,
|
||||
@@ -154,16 +160,21 @@ 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 activeGrant = grants.find((grant) => grant.revokedAt === null);
|
||||
if (!activeGrant) {
|
||||
const activeGrants = grants.filter((grant) => grant.revokedAt === null);
|
||||
if (activeGrants.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const changedAt = new Date();
|
||||
await transaction
|
||||
.update(albumGrants)
|
||||
.set({ revokedAt: changedAt })
|
||||
.where(and(eq(albumGrants.id, activeGrant.id), isNull(albumGrants.revokedAt)));
|
||||
.set({ immichAlbumId: input.immichAlbumId, revokedAt: changedAt })
|
||||
.where(
|
||||
and(
|
||||
inArray(albumGrants.id, activeGrants.map((grant) => grant.id)),
|
||||
isNull(albumGrants.revokedAt),
|
||||
),
|
||||
);
|
||||
await transaction.insert(auditEvents).values({
|
||||
eventType: "album_revoked",
|
||||
actorUserId: input.adminUserId,
|
||||
@@ -257,7 +268,11 @@ async function lockAlbumGrants(
|
||||
immichAlbumId: string,
|
||||
) {
|
||||
return transaction
|
||||
.select({ id: albumGrants.id, revokedAt: albumGrants.revokedAt })
|
||||
.select({
|
||||
id: albumGrants.id,
|
||||
immichAlbumId: albumGrants.immichAlbumId,
|
||||
revokedAt: albumGrants.revokedAt,
|
||||
})
|
||||
.from(albumGrants)
|
||||
.where(
|
||||
and(
|
||||
|
||||
@@ -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("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) <> ' '");
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import { eq } from "drizzle-orm";
|
||||
import { afterAll, expect, test, vi } from "vitest";
|
||||
|
||||
import { downloadEvents } from "@/db/schema";
|
||||
import { createAlbumGrantRepository, createAlbumGrantService } from "@/modules/albums/grants";
|
||||
import { createUsageService, createUsageServiceRepository } from "@/modules/usages/service";
|
||||
import { requestFingerprint } from "@/modules/usages/types";
|
||||
import { startPostgres } from "./postgres";
|
||||
@@ -17,6 +18,8 @@ const validAlbumId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
|
||||
const cleanKey = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
|
||||
const collidingKey = "dddddddd-dddd-4ddd-8ddd-dddddddddddd";
|
||||
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({
|
||||
editorialId,
|
||||
@@ -85,8 +88,8 @@ test("0002 preserves dirty rows and reconstructs only provable legacy intents",
|
||||
);
|
||||
await testDb.pool.query(
|
||||
`insert into album_grants (editorial_account_id, immich_album_id)
|
||||
values ($1, $2), ($1, $3)`,
|
||||
[editorialId, validAlbumId.toUpperCase(), "legacy album / 2019"],
|
||||
values ($1, $2), ($1, $3), ($1, $4)`,
|
||||
[editorialId, validAlbumId.toUpperCase(), "legacy album / 2019", validAlbumId],
|
||||
);
|
||||
|
||||
const cleanUsageId = await insertLegacyUsage({
|
||||
@@ -101,6 +104,48 @@ test("0002 preserves dirty rows and reconstructs only provable legacy intents",
|
||||
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 dirtyAlbumId = "legacy album / 2019";
|
||||
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
|
||||
from download_events`,
|
||||
);
|
||||
expect(migratedEvents.rows).toHaveLength(7);
|
||||
expect(migratedEvents.rows).toHaveLength(14);
|
||||
const byId = new Map(migratedEvents.rows.map((row) => [row.id, row]));
|
||||
expect(byId.get(cleanEventId)).toMatchObject({
|
||||
idempotency_key: cleanKey,
|
||||
@@ -210,7 +255,21 @@ test("0002 preserves dirty rows and reconstructs only provable legacy intents",
|
||||
immich_asset_id: dirtyAssetId,
|
||||
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 [
|
||||
laterNullEventId,
|
||||
tabPurposeEventId,
|
||||
newlineReferenceEventId,
|
||||
nbspNoteEventId,
|
||||
...equalTimeEventIds,
|
||||
contradictoryEventId,
|
||||
...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)?.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(
|
||||
[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 }]);
|
||||
|
||||
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(
|
||||
usageService.createNewUsage({
|
||||
editorialId,
|
||||
|
||||
Reference in new issue
Block a user