Files
immich-redaktions-plugin/src/modules/albums/grants.test.ts
T
Leon Tonhäuser dd60fd6ee6 feat: auto-assign new Immich albums via keyword rules
Auto-assignment rules were only applied when an admin clicked
"Regeln jetzt anwenden". New albums created in Immich therefore
never reached editorials automatically.

- applyAllRules() syncs every active editorial's keywords against the
  full album list in one pass and grants matches as system actor
- in-process scheduler (src/instrumentation.ts) runs the sync every
  AUTO_RULE_SYNC_INTERVAL_SECONDS (default 120s)
- POST /api/cron/album-sync allows external triggers via CRON_SECRET
- overlapping sync runs coalesce to avoid duplicate grants/emails
2026-08-25 01:05:04 +02:00

410 lines
12 KiB
TypeScript

import { expect, test, vi } from "vitest";
import {
ALBUM_GRANT_LOCK_ORDER,
AlbumGrantError,
createAlbumGrantService,
planAlbumGrantMutation,
planAlbumRevokeMutation,
type AlbumGrantRepository,
} from "./grants";
import { EDITORIAL_MUTATION_LOCK_ORDER } from "@/modules/editorials/service";
type Grant = { editorialId: string; albumId: string; revokedAt: Date | null };
type Audit = {
eventType: string;
actorUserId: string | null;
editorialId: string;
albumId: string;
previousValues: Record<string, unknown>;
newValues: Record<string, unknown>;
};
const editorialUuid = "1111111a-1111-4111-8111-11111111111a";
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[] = [];
const repository: AlbumGrantRepository = {
async listActiveAlbumIds(editorialId) {
return grants
.filter((grant) => grant.editorialId === editorialId && grant.revokedAt === null)
.map((grant) => grant.albumId);
},
async grant(input) {
const matching = grants.filter(
(grant) =>
grant.editorialId === input.editorialId &&
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) {
if (grant !== survivor) grant.revokedAt = new Date();
}
if (survivor) {
survivor.albumId = input.immichAlbumId;
survivor.revokedAt = null;
}
return false;
}
if (survivor) {
survivor.albumId = input.immichAlbumId;
survivor.revokedAt = null;
} else {
grants.push({ editorialId: input.editorialId, albumId: input.immichAlbumId, revokedAt: null });
}
audit.push({
eventType: "album_granted",
actorUserId: input.adminUserId,
editorialId: input.editorialId,
albumId: input.immichAlbumId,
previousValues: { granted: false },
newValues: { granted: true },
});
return true;
},
async revoke(input) {
const active = grants.filter(
(grant) =>
grant.editorialId === input.editorialId &&
grant.albumId.toLowerCase() === input.immichAlbumId &&
grant.revokedAt === null,
);
if (active.length === 0) return false;
for (const grant of active) {
grant.revokedAt = new Date();
}
audit.push({
eventType: "album_revoked",
actorUserId: input.adminUserId,
editorialId: input.editorialId,
albumId: input.immichAlbumId,
previousValues: { granted: true },
newValues: { granted: false },
});
return true;
},
};
return { repository, grants, audit };
}
function createService(initial: Grant[] = []) {
const { repository, grants, audit } = createRepository(initial);
const immich = {
getAlbum: vi.fn().mockResolvedValue({
id: albumUuid,
albumName: "Pressefotos",
description: null,
albumThumbnailAssetId: "cover-1",
assetCount: 4,
assets: [],
}),
listAlbums: vi.fn().mockResolvedValue([
{
id: albumUuid,
albumName: "Pressefotos",
description: null,
albumThumbnailAssetId: "cover-1",
assetCount: 4,
},
]),
};
return {
service: createAlbumGrantService({ repository, immich }),
immich,
grants,
audit,
};
}
test("refuses to grant an album that the service user cannot read", async () => {
const { service, immich } = createService();
immich.getAlbum.mockRejectedValue({ code: "IMMICH_NOT_FOUND" });
await expect(
service.grantAlbum({
editorialId: editorialUuid,
immichAlbumId: unavailableAlbumUuid,
adminUserId: adminUuid,
}),
).rejects.toMatchObject({ code: "ALBUM_NOT_ASSIGNABLE" });
});
test("canonicalizes UUID grant input before Immich and repository side effects", async () => {
const { service, immich, grants } = createService();
await service.grantAlbum({
editorialId: editorialUuid.toUpperCase(),
immichAlbumId: albumUuid.toUpperCase(),
adminUserId: adminUuid.toUpperCase(),
});
expect(immich.getAlbum).toHaveBeenCalledWith(albumUuid);
expect(grants).toEqual([
{ editorialId: editorialUuid, albumId: albumUuid, revokedAt: null },
]);
});
test("treats an uppercase historical album grant as the canonical active grant", async () => {
const { service, grants, audit } = createService([
{ editorialId: editorialUuid, albumId: albumUuid.toUpperCase(), revokedAt: null },
]);
await expect(service.getGrantedAlbumIds(editorialUuid)).resolves.toEqual([albumUuid]);
await service.grantAlbum({
editorialId: editorialUuid,
immichAlbumId: albumUuid,
adminUserId: adminUuid,
});
expect(grants).toHaveLength(1);
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 },
{ editorialId: editorialUuid, albumId: albumUuid, revokedAt: null },
]);
await service.revokeAlbum({
editorialId: editorialUuid,
immichAlbumId: albumUuid,
adminUserId: adminUuid,
});
expect(grants.filter((grant) => grant.revokedAt === null)).toHaveLength(0);
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();
await expect(
service.grantAlbum({
editorialId: editorialUuid,
immichAlbumId: "legacy-album",
adminUserId: adminUuid,
}),
).rejects.toMatchObject({ code: "INVALID_ALBUM_GRANT_INPUT" });
expect(immich.getAlbum).not.toHaveBeenCalled();
expect(grants).toHaveLength(0);
});
test("granting an album is idempotent and records one state-change audit event", async () => {
const { service, audit } = createService();
await service.grantAlbum({
editorialId: editorialUuid,
immichAlbumId: albumUuid,
adminUserId: adminUuid,
});
await service.grantAlbum({
editorialId: editorialUuid,
immichAlbumId: albumUuid,
adminUserId: adminUuid,
});
await expect(service.getGrantedAlbumIds(editorialUuid)).resolves.toEqual([albumUuid]);
expect(audit).toEqual([
expect.objectContaining({
eventType: "album_granted",
actorUserId: adminUuid,
editorialId: editorialUuid,
albumId: albumUuid,
previousValues: { granted: false },
newValues: { granted: true },
}),
]);
});
test("a revoked album can be re-granted without creating another current grant", async () => {
const { service, grants } = createService([
{
editorialId: editorialUuid,
albumId: albumUuid,
revokedAt: new Date("2026-08-08T00:00:00Z"),
},
]);
await service.grantAlbum({
editorialId: editorialUuid,
immichAlbumId: albumUuid,
adminUserId: adminUuid,
});
expect(grants).toHaveLength(1);
await expect(service.getGrantedAlbumIds(editorialUuid)).resolves.toEqual([albumUuid]);
});
test("revocation immediately removes the album from visible IDs and records the actor", async () => {
const { service, audit } = createService([
{ editorialId: editorialUuid, albumId: albumUuid, revokedAt: null },
]);
await service.revokeAlbum({
editorialId: editorialUuid,
immichAlbumId: albumUuid,
adminUserId: adminUuid,
});
await expect(service.getGrantedAlbumIds(editorialUuid)).resolves.not.toContain(albumUuid);
expect(audit).toContainEqual(
expect.objectContaining({
eventType: "album_revoked",
actorUserId: adminUuid,
editorialId: editorialUuid,
albumId: albumUuid,
previousValues: { granted: true },
newValues: { granted: false },
}),
);
});
test("uses the same lock order as approval so concurrent approval and revocation serialize", () => {
expect(ALBUM_GRANT_LOCK_ORDER).toEqual(EDITORIAL_MUTATION_LOCK_ORDER);
});
test("reports a stable unavailable error when the Immich album list cannot be loaded", async () => {
const { service, immich } = createService();
immich.listAlbums.mockRejectedValue({ code: "IMMICH_TIMEOUT" });
await expect(service.listAssignableAlbums(editorialUuid)).rejects.toEqual(
new AlbumGrantError("IMMICH_UNAVAILABLE"),
);
});