feat: add editorial album permissions
This commit is contained in:
1 parent
0fe2c80cda
commit
4af86f6eb9
5 files changed
+633
No files matched your search
@@ -0,0 +1,182 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
ALBUM_GRANT_LOCK_ORDER,
|
||||
AlbumGrantError,
|
||||
createAlbumGrantService,
|
||||
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;
|
||||
editorialId: string;
|
||||
albumId: string;
|
||||
previousValues: Record<string, unknown>;
|
||||
newValues: Record<string, unknown>;
|
||||
};
|
||||
|
||||
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 active = grants.find(
|
||||
(grant) =>
|
||||
grant.editorialId === input.editorialId &&
|
||||
grant.albumId === input.immichAlbumId &&
|
||||
grant.revokedAt === null,
|
||||
);
|
||||
if (active) return false;
|
||||
|
||||
const revoked = grants.find(
|
||||
(grant) =>
|
||||
grant.editorialId === input.editorialId &&
|
||||
grant.albumId === input.immichAlbumId &&
|
||||
grant.revokedAt !== null,
|
||||
);
|
||||
if (revoked) {
|
||||
revoked.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.find(
|
||||
(grant) =>
|
||||
grant.editorialId === input.editorialId &&
|
||||
grant.albumId === input.immichAlbumId &&
|
||||
grant.revokedAt === null,
|
||||
);
|
||||
if (!active) return false;
|
||||
active.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: "album-1",
|
||||
albumName: "Pressefotos",
|
||||
description: null,
|
||||
albumThumbnailAssetId: "cover-1",
|
||||
assetCount: 4,
|
||||
assets: [],
|
||||
}),
|
||||
listAlbums: vi.fn().mockResolvedValue([
|
||||
{
|
||||
id: "album-1",
|
||||
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: "e1", immichAlbumId: "hidden", adminUserId: "a1" }),
|
||||
).rejects.toMatchObject({ code: "ALBUM_NOT_ASSIGNABLE" });
|
||||
});
|
||||
|
||||
test("granting an album is idempotent and records one state-change audit event", async () => {
|
||||
const { service, audit } = createService();
|
||||
|
||||
await service.grantAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" });
|
||||
await service.grantAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" });
|
||||
|
||||
await expect(service.getGrantedAlbumIds("e1")).resolves.toEqual(["album-1"]);
|
||||
expect(audit).toEqual([
|
||||
expect.objectContaining({
|
||||
eventType: "album_granted",
|
||||
actorUserId: "a1",
|
||||
editorialId: "e1",
|
||||
albumId: "album-1",
|
||||
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: "e1", albumId: "album-1", revokedAt: new Date("2026-08-08T00:00:00Z") },
|
||||
]);
|
||||
|
||||
await service.grantAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" });
|
||||
|
||||
expect(grants).toHaveLength(1);
|
||||
await expect(service.getGrantedAlbumIds("e1")).resolves.toEqual(["album-1"]);
|
||||
});
|
||||
|
||||
test("revocation immediately removes the album from visible IDs and records the actor", async () => {
|
||||
const { service, audit } = createService([
|
||||
{ editorialId: "e1", albumId: "album-1", revokedAt: null },
|
||||
]);
|
||||
|
||||
await service.revokeAlbum({ editorialId: "e1", immichAlbumId: "album-1", adminUserId: "a1" });
|
||||
|
||||
await expect(service.getGrantedAlbumIds("e1")).resolves.not.toContain("album-1");
|
||||
expect(audit).toContainEqual(
|
||||
expect.objectContaining({
|
||||
eventType: "album_revoked",
|
||||
actorUserId: "a1",
|
||||
editorialId: "e1",
|
||||
albumId: "album-1",
|
||||
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("e1")).rejects.toEqual(
|
||||
new AlbumGrantError("IMMICH_UNAVAILABLE"),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,258 @@
|
||||
import "server-only";
|
||||
|
||||
import { and, eq, isNull, sql } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
import { albumGrants, auditEvents, editorialAccounts } from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
import { EDITORIAL_MUTATION_LOCK_ORDER } from "@/modules/editorials/service";
|
||||
import { immichClient } from "@/modules/immich/client";
|
||||
import type { ImmichAlbumSummary, ImmichClient } from "@/modules/immich/types";
|
||||
|
||||
export type AssignableAlbum = ImmichAlbumSummary & { isGranted: boolean };
|
||||
|
||||
export type AlbumGrantInput = {
|
||||
editorialId: string;
|
||||
immichAlbumId: string;
|
||||
adminUserId: string;
|
||||
};
|
||||
|
||||
export type AlbumGrantRepository = {
|
||||
listActiveAlbumIds(editorialId: string): Promise<string[]>;
|
||||
grant(input: AlbumGrantInput): Promise<boolean>;
|
||||
revoke(input: AlbumGrantInput): Promise<boolean>;
|
||||
};
|
||||
|
||||
export const ALBUM_GRANT_LOCK_ORDER = EDITORIAL_MUTATION_LOCK_ORDER;
|
||||
|
||||
export class AlbumGrantError extends Error {
|
||||
readonly name = "AlbumGrantError";
|
||||
|
||||
constructor(
|
||||
readonly code:
|
||||
| "ALBUM_NOT_ASSIGNABLE"
|
||||
| "IMMICH_UNAVAILABLE"
|
||||
| "EDITORIAL_NOT_FOUND"
|
||||
| "INVALID_ALBUM_GRANT_INPUT",
|
||||
) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
export function createAlbumGrantService({
|
||||
repository,
|
||||
immich,
|
||||
}: {
|
||||
repository: AlbumGrantRepository;
|
||||
immich: Pick<ImmichClient, "getAlbum" | "listAlbums">;
|
||||
}) {
|
||||
return {
|
||||
async listAssignableAlbums(editorialId: string): Promise<AssignableAlbum[]> {
|
||||
assertIdentifier(editorialId);
|
||||
const [albums, grantedAlbumIds] = await Promise.all([
|
||||
loadAlbums(immich),
|
||||
repository.listActiveAlbumIds(editorialId),
|
||||
]);
|
||||
const granted = new Set(grantedAlbumIds);
|
||||
return albums.map((album) => ({ ...album, isGranted: granted.has(album.id) }));
|
||||
},
|
||||
|
||||
async grantAlbum(input: AlbumGrantInput): Promise<void> {
|
||||
assertInput(input);
|
||||
try {
|
||||
await immich.getAlbum(input.immichAlbumId);
|
||||
} catch (error) {
|
||||
if (hasCode(error, "IMMICH_NOT_FOUND")) {
|
||||
throw new AlbumGrantError("ALBUM_NOT_ASSIGNABLE");
|
||||
}
|
||||
throw new AlbumGrantError("IMMICH_UNAVAILABLE");
|
||||
}
|
||||
await repository.grant(input);
|
||||
},
|
||||
|
||||
async revokeAlbum(input: AlbumGrantInput): Promise<void> {
|
||||
assertInput(input);
|
||||
await repository.revoke(input);
|
||||
},
|
||||
|
||||
async getGrantedAlbumIds(editorialId: string): Promise<string[]> {
|
||||
assertIdentifier(editorialId);
|
||||
return repository.listActiveAlbumIds(editorialId);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createAlbumGrantRepository(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
): AlbumGrantRepository {
|
||||
return {
|
||||
async listActiveAlbumIds(editorialId) {
|
||||
const grants = await database
|
||||
.select({ immichAlbumId: albumGrants.immichAlbumId })
|
||||
.from(albumGrants)
|
||||
.where(and(eq(albumGrants.editorialAccountId, editorialId), isNull(albumGrants.revokedAt)));
|
||||
return grants.map((grant) => grant.immichAlbumId);
|
||||
},
|
||||
|
||||
async grant(input) {
|
||||
return database.transaction(async (transaction) => {
|
||||
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) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const changedAt = new Date();
|
||||
const previousGrant = grants[0];
|
||||
if (previousGrant) {
|
||||
await transaction
|
||||
.update(albumGrants)
|
||||
.set({
|
||||
grantedAt: changedAt,
|
||||
grantedByUserId: input.adminUserId,
|
||||
revokedAt: null,
|
||||
})
|
||||
.where(eq(albumGrants.id, previousGrant.id));
|
||||
} else {
|
||||
await transaction.insert(albumGrants).values({
|
||||
editorialAccountId: editorial.id,
|
||||
immichAlbumId: input.immichAlbumId,
|
||||
grantedAt: changedAt,
|
||||
grantedByUserId: input.adminUserId,
|
||||
});
|
||||
}
|
||||
|
||||
await transaction.insert(auditEvents).values({
|
||||
eventType: "album_granted",
|
||||
actorUserId: input.adminUserId,
|
||||
actorType: "admin",
|
||||
entityType: "album_grant",
|
||||
entityId: input.immichAlbumId,
|
||||
previousValues: {
|
||||
editorialId: editorial.id,
|
||||
immichAlbumId: input.immichAlbumId,
|
||||
granted: false,
|
||||
},
|
||||
newValues: {
|
||||
editorialId: editorial.id,
|
||||
immichAlbumId: input.immichAlbumId,
|
||||
granted: true,
|
||||
},
|
||||
occurredAt: changedAt,
|
||||
});
|
||||
return true;
|
||||
});
|
||||
},
|
||||
|
||||
async revoke(input) {
|
||||
return database.transaction(async (transaction) => {
|
||||
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) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const changedAt = new Date();
|
||||
await transaction
|
||||
.update(albumGrants)
|
||||
.set({ revokedAt: changedAt })
|
||||
.where(and(eq(albumGrants.id, activeGrant.id), isNull(albumGrants.revokedAt)));
|
||||
await transaction.insert(auditEvents).values({
|
||||
eventType: "album_revoked",
|
||||
actorUserId: input.adminUserId,
|
||||
actorType: "admin",
|
||||
entityType: "album_grant",
|
||||
entityId: input.immichAlbumId,
|
||||
previousValues: {
|
||||
editorialId: editorial.id,
|
||||
immichAlbumId: input.immichAlbumId,
|
||||
granted: true,
|
||||
},
|
||||
newValues: {
|
||||
editorialId: editorial.id,
|
||||
immichAlbumId: input.immichAlbumId,
|
||||
granted: false,
|
||||
},
|
||||
occurredAt: changedAt,
|
||||
});
|
||||
return true;
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function loadAlbums(immich: Pick<ImmichClient, "listAlbums">): Promise<ImmichAlbumSummary[]> {
|
||||
try {
|
||||
return await immich.listAlbums();
|
||||
} catch {
|
||||
throw new AlbumGrantError("IMMICH_UNAVAILABLE");
|
||||
}
|
||||
}
|
||||
|
||||
function assertInput(input: AlbumGrantInput): void {
|
||||
assertIdentifier(input.editorialId);
|
||||
assertIdentifier(input.immichAlbumId);
|
||||
assertIdentifier(input.adminUserId);
|
||||
}
|
||||
|
||||
function assertIdentifier(value: string): void {
|
||||
if (!value.trim()) {
|
||||
throw new AlbumGrantError("INVALID_ALBUM_GRANT_INPUT");
|
||||
}
|
||||
}
|
||||
|
||||
function hasCode(error: unknown, code: string): boolean {
|
||||
return typeof error === "object" && error !== null && "code" in error && error.code === code;
|
||||
}
|
||||
|
||||
async function lockEditorialAlbumMutation(
|
||||
transaction: NodePgDatabase<typeof schema>,
|
||||
editorialId: string,
|
||||
): Promise<void> {
|
||||
await transaction.execute(
|
||||
sql`select pg_advisory_xact_lock(hashtextextended(${editorialId}, 0))`,
|
||||
);
|
||||
}
|
||||
|
||||
async function lockEditorial(
|
||||
transaction: NodePgDatabase<typeof schema>,
|
||||
editorialId: string,
|
||||
): Promise<{ id: string }> {
|
||||
const [editorial] = await transaction
|
||||
.select({ id: editorialAccounts.id })
|
||||
.from(editorialAccounts)
|
||||
.where(eq(editorialAccounts.id, editorialId))
|
||||
.for("update")
|
||||
.limit(1);
|
||||
if (!editorial) {
|
||||
throw new AlbumGrantError("EDITORIAL_NOT_FOUND");
|
||||
}
|
||||
return editorial;
|
||||
}
|
||||
|
||||
async function lockAlbumGrants(
|
||||
transaction: NodePgDatabase<typeof schema>,
|
||||
editorialId: string,
|
||||
immichAlbumId: string,
|
||||
) {
|
||||
return transaction
|
||||
.select({ id: albumGrants.id, revokedAt: albumGrants.revokedAt })
|
||||
.from(albumGrants)
|
||||
.where(
|
||||
and(
|
||||
eq(albumGrants.editorialAccountId, editorialId),
|
||||
eq(albumGrants.immichAlbumId, immichAlbumId),
|
||||
),
|
||||
)
|
||||
.for("update");
|
||||
}
|
||||
|
||||
export const albumGrantService = createAlbumGrantService({
|
||||
repository: createAlbumGrantRepository(db),
|
||||
immich: immichClient,
|
||||
});
|
||||
Reference in new issue
Block a user