Merge pull request 'Stop a saved Rule from taking uploads it does not own' (#120) from adilallo/fix/CR-467-upload-ownership into main
Reviewed-on: #120
This commit was merged in pull request #120.
This commit is contained in:
commit
53e27ef122
10 files changed
+923
-12
No files matched your search
@@ -9,12 +9,14 @@ import {
|
|||||||
} from "../../../../../lib/server/responses";
|
} from "../../../../../lib/server/responses";
|
||||||
import { getSessionUser } from "../../../../../lib/server/session";
|
import { getSessionUser } from "../../../../../lib/server/session";
|
||||||
import { apiRoute } from "../../../../../lib/server/apiRoute";
|
import { apiRoute } from "../../../../../lib/server/apiRoute";
|
||||||
|
import { logRouteError } from "../../../../../lib/server/requestId";
|
||||||
|
import { copyNamedUploadsForRule } from "../../../../../lib/server/uploads/copyNamedUploads";
|
||||||
|
|
||||||
type RouteContext = { params: Promise<{ id: string }> };
|
type RouteContext = { params: Promise<{ id: string }> };
|
||||||
|
|
||||||
export const POST = apiRoute<RouteContext>(
|
export const POST = apiRoute<RouteContext>(
|
||||||
"rules.byId.duplicate",
|
"rules.byId.duplicate",
|
||||||
async (_request, context) => {
|
async (_request, context, { requestId }) => {
|
||||||
if (!isDatabaseConfigured()) {
|
if (!isDatabaseConfigured()) {
|
||||||
return dbUnavailable();
|
return dbUnavailable();
|
||||||
}
|
}
|
||||||
@@ -44,6 +46,23 @@ export const POST = apiRoute<RouteContext>(
|
|||||||
document: source.document,
|
document: source.document,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
try {
|
||||||
|
await copyNamedUploadsForRule({
|
||||||
|
document: source.document,
|
||||||
|
sourceRuleId: source.id,
|
||||||
|
destRuleId: newRule.id,
|
||||||
|
userId: user.id,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
try {
|
||||||
|
await prisma.publishedRule.delete({ where: { id: newRule.id } });
|
||||||
|
} catch (delErr) {
|
||||||
|
logRouteError("rules.byId.duplicate", requestId, delErr, {
|
||||||
|
phase: "rollbackDuplicateAfterCopyFailure",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
rule: {
|
rule: {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
} from "../../../../../lib/server/responses";
|
} from "../../../../../lib/server/responses";
|
||||||
import { getSessionUser } from "../../../../../lib/server/session";
|
import { getSessionUser } from "../../../../../lib/server/session";
|
||||||
import { apiRoute } from "../../../../../lib/server/apiRoute";
|
import { apiRoute } from "../../../../../lib/server/apiRoute";
|
||||||
|
import { logRouteError } from "../../../../../lib/server/requestId";
|
||||||
import { rateLimitKey } from "../../../../../lib/server/rateLimit";
|
import { rateLimitKey } from "../../../../../lib/server/rateLimit";
|
||||||
import { readLimitedJson } from "../../../../../lib/server/validation/requestBody";
|
import { readLimitedJson } from "../../../../../lib/server/validation/requestBody";
|
||||||
import { jsonFromZodError } from "../../../../../lib/server/validation/zodHttp";
|
import { jsonFromZodError } from "../../../../../lib/server/validation/zodHttp";
|
||||||
@@ -22,12 +23,13 @@ import {
|
|||||||
findCopiedNameHit,
|
findCopiedNameHit,
|
||||||
stripCopiedRuleDocument,
|
stripCopiedRuleDocument,
|
||||||
} from "../../../../../lib/create/copiedRuleDocument";
|
} from "../../../../../lib/create/copiedRuleDocument";
|
||||||
|
import { copyNamedUploadsForRule } from "../../../../../lib/server/uploads/copyNamedUploads";
|
||||||
|
|
||||||
type RouteContext = { params: Promise<{ id: string }> };
|
type RouteContext = { params: Promise<{ id: string }> };
|
||||||
|
|
||||||
export const POST = apiRoute<RouteContext>(
|
export const POST = apiRoute<RouteContext>(
|
||||||
"rules.byId.makeCopy",
|
"rules.byId.makeCopy",
|
||||||
async (request, context) => {
|
async (request, context, { requestId }) => {
|
||||||
if (!isDatabaseConfigured()) {
|
if (!isDatabaseConfigured()) {
|
||||||
return dbUnavailable();
|
return dbUnavailable();
|
||||||
}
|
}
|
||||||
@@ -88,13 +90,31 @@ export const POST = apiRoute<RouteContext>(
|
|||||||
document: documentParsed.data as Prisma.InputJsonValue,
|
document: documentParsed.data as Prisma.InputJsonValue,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
let document: unknown;
|
||||||
|
try {
|
||||||
|
document = await copyNamedUploadsForRule({
|
||||||
|
document: documentParsed.data,
|
||||||
|
sourceRuleId: stakeholder.rule.id,
|
||||||
|
destRuleId: newRule.id,
|
||||||
|
userId: user.id,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
try {
|
||||||
|
await prisma.publishedRule.delete({ where: { id: newRule.id } });
|
||||||
|
} catch (delErr) {
|
||||||
|
logRouteError("rules.byId.makeCopy", requestId, delErr, {
|
||||||
|
phase: "rollbackMakeCopyAfterCopyFailure",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
rule: {
|
rule: {
|
||||||
id: newRule.id,
|
id: newRule.id,
|
||||||
title: newRule.title,
|
title: newRule.title,
|
||||||
summary: newRule.summary,
|
summary: newRule.summary,
|
||||||
document: documentParsed.data,
|
document,
|
||||||
copiedFromTitle: stakeholder.rule.title,
|
copiedFromTitle: stakeholder.rule.title,
|
||||||
copiedNameHit,
|
copiedNameHit,
|
||||||
createdAt: newRule.createdAt,
|
createdAt: newRule.createdAt,
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
import { copyFile, unlink } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import type { Prisma } from "@prisma/client";
|
||||||
|
import { logger } from "../../logger";
|
||||||
|
import { prisma } from "../db";
|
||||||
|
import {
|
||||||
|
extractUploadIdsFromUnknown,
|
||||||
|
rewriteUploadIdsInUnknown,
|
||||||
|
} from "./extractUploadIds";
|
||||||
|
import { resolveUploadedFileById } from "./resolveUploadedFile";
|
||||||
|
import { extensionForMime } from "./uploadConstants";
|
||||||
|
import { ensureUploadRootExists, getUploadRootFromEnv } from "./uploadRoot";
|
||||||
|
|
||||||
|
type SourceUploadRow = {
|
||||||
|
id: string;
|
||||||
|
mimeType: string;
|
||||||
|
byteLength: number;
|
||||||
|
purpose: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type CopiedUpload = { id: string; absolutePath: string };
|
||||||
|
|
||||||
|
async function copyOneUpload(opts: {
|
||||||
|
row: SourceUploadRow;
|
||||||
|
root: string;
|
||||||
|
destRuleId: string;
|
||||||
|
userId: string;
|
||||||
|
}): Promise<CopiedUpload | null> {
|
||||||
|
const resolved = await resolveUploadedFileById(opts.row.id);
|
||||||
|
if (!resolved) {
|
||||||
|
logger.warn("[uploads] skip copy; missing file", opts.row.id);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const newId = randomUUID();
|
||||||
|
const ext =
|
||||||
|
extensionForMime(opts.row.mimeType) || path.extname(resolved.absolutePath);
|
||||||
|
const destPath = path.join(opts.root, `${newId}${ext}`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await copyFile(resolved.absolutePath, destPath);
|
||||||
|
await prisma.upload.create({
|
||||||
|
data: {
|
||||||
|
id: newId,
|
||||||
|
mimeType: opts.row.mimeType,
|
||||||
|
byteLength: opts.row.byteLength,
|
||||||
|
purpose: opts.row.purpose,
|
||||||
|
userId: opts.userId,
|
||||||
|
ruleId: opts.destRuleId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return { id: newId, absolutePath: destPath };
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn("[uploads] failed to copy upload", opts.row.id, err);
|
||||||
|
await unlink(destPath).catch(() => undefined);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Give `destRuleId` its own copies of files this document names that belong
|
||||||
|
* to `sourceRuleId` or are not linked to any Rule, rewrite paths, and persist
|
||||||
|
* the rewritten document. Throws when that save fails, after dropping the
|
||||||
|
* copies just made.
|
||||||
|
*/
|
||||||
|
export async function copyNamedUploadsForRule(opts: {
|
||||||
|
document: unknown;
|
||||||
|
sourceRuleId: string;
|
||||||
|
destRuleId: string;
|
||||||
|
userId: string;
|
||||||
|
}): Promise<unknown> {
|
||||||
|
const ids = extractUploadIdsFromUnknown(opts.document);
|
||||||
|
if (ids.length === 0) return opts.document;
|
||||||
|
|
||||||
|
const rows = await prisma.upload.findMany({
|
||||||
|
where: {
|
||||||
|
id: { in: ids },
|
||||||
|
OR: [{ ruleId: opts.sourceRuleId }, { ruleId: null }],
|
||||||
|
},
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
mimeType: true,
|
||||||
|
byteLength: true,
|
||||||
|
purpose: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (rows.length === 0) return opts.document;
|
||||||
|
|
||||||
|
const root = getUploadRootFromEnv();
|
||||||
|
if (!root) {
|
||||||
|
logger.warn("[uploads] skip copy; UPLOAD_ROOT unset");
|
||||||
|
return opts.document;
|
||||||
|
}
|
||||||
|
await ensureUploadRootExists(root);
|
||||||
|
|
||||||
|
const replacements = new Map<string, string>();
|
||||||
|
const copies: CopiedUpload[] = [];
|
||||||
|
for (const row of rows) {
|
||||||
|
const copied = await copyOneUpload({
|
||||||
|
row,
|
||||||
|
root,
|
||||||
|
destRuleId: opts.destRuleId,
|
||||||
|
userId: opts.userId,
|
||||||
|
});
|
||||||
|
if (!copied) continue;
|
||||||
|
replacements.set(row.id, copied.id);
|
||||||
|
copies.push(copied);
|
||||||
|
}
|
||||||
|
if (replacements.size === 0) return opts.document;
|
||||||
|
|
||||||
|
const document = rewriteUploadIdsInUnknown(opts.document, replacements);
|
||||||
|
try {
|
||||||
|
await prisma.publishedRule.update({
|
||||||
|
where: { id: opts.destRuleId },
|
||||||
|
data: { document: document as Prisma.InputJsonValue },
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn(
|
||||||
|
"[uploads] failed to persist copied upload paths",
|
||||||
|
opts.destRuleId,
|
||||||
|
err,
|
||||||
|
);
|
||||||
|
await dropCopies(copies);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
return document;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function dropCopies(copies: CopiedUpload[]): Promise<void> {
|
||||||
|
if (copies.length === 0) return;
|
||||||
|
await prisma.upload
|
||||||
|
.deleteMany({ where: { id: { in: copies.map((copy) => copy.id) } } })
|
||||||
|
.catch((err) => {
|
||||||
|
logger.warn("[uploads] failed to drop copies after persist error", err);
|
||||||
|
});
|
||||||
|
await Promise.all(
|
||||||
|
copies.map((copy) =>
|
||||||
|
unlink(copy.absolutePath).catch((err) => {
|
||||||
|
logger.warn("[uploads] failed to remove copy after persist error", err);
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,14 +3,19 @@ import { isValidUploadFileId } from "./uploadConstants";
|
|||||||
const UPLOAD_PATH_RE =
|
const UPLOAD_PATH_RE =
|
||||||
/\/api\/uploads\/([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})/gi;
|
/\/api\/uploads\/([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})/gi;
|
||||||
|
|
||||||
|
function stringifyUnknown(value: unknown): string | null {
|
||||||
|
try {
|
||||||
|
return JSON.stringify(value ?? null);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** UUID stems referenced as `/api/uploads/{id}` inside JSON. */
|
/** UUID stems referenced as `/api/uploads/{id}` inside JSON. */
|
||||||
export function extractUploadIdsFromUnknown(value: unknown): string[] {
|
export function extractUploadIdsFromUnknown(value: unknown): string[] {
|
||||||
let text: string;
|
const text = stringifyUnknown(value);
|
||||||
try {
|
if (text == null) return [];
|
||||||
text = JSON.stringify(value ?? null);
|
UPLOAD_PATH_RE.lastIndex = 0;
|
||||||
} catch {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
const ids = new Set<string>();
|
const ids = new Set<string>();
|
||||||
for (const match of text.matchAll(UPLOAD_PATH_RE)) {
|
for (const match of text.matchAll(UPLOAD_PATH_RE)) {
|
||||||
const id = match[1]?.toLowerCase();
|
const id = match[1]?.toLowerCase();
|
||||||
@@ -18,3 +23,23 @@ export function extractUploadIdsFromUnknown(value: unknown): string[] {
|
|||||||
}
|
}
|
||||||
return [...ids];
|
return [...ids];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Rewrite `/api/uploads/{id}` paths using `replacements` (old id → new id). */
|
||||||
|
export function rewriteUploadIdsInUnknown(
|
||||||
|
value: unknown,
|
||||||
|
replacements: ReadonlyMap<string, string>,
|
||||||
|
): unknown {
|
||||||
|
if (replacements.size === 0) return value;
|
||||||
|
const text = stringifyUnknown(value);
|
||||||
|
if (text == null) return value;
|
||||||
|
UPLOAD_PATH_RE.lastIndex = 0;
|
||||||
|
const rewritten = text.replace(UPLOAD_PATH_RE, (full, id: string) => {
|
||||||
|
const next = replacements.get(id.toLowerCase());
|
||||||
|
return next ? `/api/uploads/${next}` : full;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
return JSON.parse(rewritten) as unknown;
|
||||||
|
} catch {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,67 @@
|
|||||||
import { logger } from "../../logger";
|
import { logger } from "../../logger";
|
||||||
import { prisma } from "../db";
|
import { prisma } from "../db";
|
||||||
import { extractUploadIdsFromUnknown } from "./extractUploadIds";
|
import { extractUploadIdsFromUnknown } from "./extractUploadIds";
|
||||||
|
import { browserHoldsUploadGrant } from "./uploadGrantCookie";
|
||||||
|
|
||||||
|
type UploadClaimRow = {
|
||||||
|
id: string;
|
||||||
|
userId: string | null;
|
||||||
|
ruleId: string | null;
|
||||||
|
draftId: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
async function loadUploadRows(ids: string[]): Promise<UploadClaimRow[]> {
|
||||||
|
if (ids.length === 0) return [];
|
||||||
|
return prisma.upload.findMany({
|
||||||
|
where: { id: { in: ids } },
|
||||||
|
select: { id: true, userId: true, ruleId: true, draftId: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A save may take a file only when it is unlinked (or already on this Rule)
|
||||||
|
* and was made by this account or browser.
|
||||||
|
*/
|
||||||
|
async function idsClaimableForRule(
|
||||||
|
rows: UploadClaimRow[],
|
||||||
|
opts: { ruleId: string; userId: string | null },
|
||||||
|
): Promise<string[]> {
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const row of rows) {
|
||||||
|
if (row.ruleId != null && row.ruleId !== opts.ruleId) continue;
|
||||||
|
if (row.ruleId === opts.ruleId) {
|
||||||
|
out.push(row.id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (opts.userId != null && row.userId === opts.userId) {
|
||||||
|
out.push(row.id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (row.userId == null && (await browserHoldsUploadGrant(row.id))) {
|
||||||
|
out.push(row.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function idsClaimableForDraft(
|
||||||
|
rows: UploadClaimRow[],
|
||||||
|
opts: { draftId: string; userId: string },
|
||||||
|
): Promise<string[]> {
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const row of rows) {
|
||||||
|
if (row.ruleId != null) continue;
|
||||||
|
if (row.draftId != null && row.draftId !== opts.draftId) continue;
|
||||||
|
if (row.userId === opts.userId) {
|
||||||
|
out.push(row.id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (row.userId == null && (await browserHoldsUploadGrant(row.id))) {
|
||||||
|
out.push(row.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
export async function linkUploadsToRule(opts: {
|
export async function linkUploadsToRule(opts: {
|
||||||
ruleId: string;
|
ruleId: string;
|
||||||
@@ -10,8 +71,19 @@ export async function linkUploadsToRule(opts: {
|
|||||||
const ids = extractUploadIdsFromUnknown(opts.document);
|
const ids = extractUploadIdsFromUnknown(opts.document);
|
||||||
if (ids.length === 0) return;
|
if (ids.length === 0) return;
|
||||||
try {
|
try {
|
||||||
|
const rows = await loadUploadRows(ids);
|
||||||
|
const claimable = await idsClaimableForRule(rows, opts);
|
||||||
|
if (claimable.length === 0) return;
|
||||||
await prisma.upload.updateMany({
|
await prisma.upload.updateMany({
|
||||||
where: { id: { in: ids } },
|
where: {
|
||||||
|
id: { in: claimable },
|
||||||
|
AND: [
|
||||||
|
{ OR: [{ ruleId: null }, { ruleId: opts.ruleId }] },
|
||||||
|
opts.userId
|
||||||
|
? { OR: [{ userId: opts.userId }, { userId: null }] }
|
||||||
|
: { userId: null },
|
||||||
|
],
|
||||||
|
},
|
||||||
data: {
|
data: {
|
||||||
ruleId: opts.ruleId,
|
ruleId: opts.ruleId,
|
||||||
draftId: null,
|
draftId: null,
|
||||||
@@ -31,8 +103,18 @@ export async function linkUploadsToDraft(opts: {
|
|||||||
const ids = extractUploadIdsFromUnknown(opts.payload);
|
const ids = extractUploadIdsFromUnknown(opts.payload);
|
||||||
if (ids.length === 0) return;
|
if (ids.length === 0) return;
|
||||||
try {
|
try {
|
||||||
|
const rows = await loadUploadRows(ids);
|
||||||
|
const claimable = await idsClaimableForDraft(rows, opts);
|
||||||
|
if (claimable.length === 0) return;
|
||||||
await prisma.upload.updateMany({
|
await prisma.upload.updateMany({
|
||||||
where: { id: { in: ids }, ruleId: null },
|
where: {
|
||||||
|
id: { in: claimable },
|
||||||
|
ruleId: null,
|
||||||
|
AND: [
|
||||||
|
{ OR: [{ draftId: null }, { draftId: opts.draftId }] },
|
||||||
|
{ OR: [{ userId: opts.userId }, { userId: null }] },
|
||||||
|
],
|
||||||
|
},
|
||||||
data: {
|
data: {
|
||||||
draftId: opts.draftId,
|
draftId: opts.draftId,
|
||||||
userId: opts.userId,
|
userId: opts.userId,
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
import { mkdtemp, readdir, readFile, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const getUploadRootFromEnvMock = vi.fn();
|
||||||
|
const findManyMock = vi.fn();
|
||||||
|
const createMock = vi.fn();
|
||||||
|
const deleteManyMock = vi.fn();
|
||||||
|
const updateRuleMock = vi.fn();
|
||||||
|
let uploadRoot: string | null = null;
|
||||||
|
|
||||||
|
vi.mock("../../lib/server/uploads/uploadRoot", async () => {
|
||||||
|
const actual = await vi.importActual<
|
||||||
|
typeof import("../../lib/server/uploads/uploadRoot")
|
||||||
|
>("../../lib/server/uploads/uploadRoot");
|
||||||
|
return {
|
||||||
|
...actual,
|
||||||
|
getUploadRootFromEnv: () => getUploadRootFromEnvMock(),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mock("../../lib/server/db", () => ({
|
||||||
|
prisma: {
|
||||||
|
upload: {
|
||||||
|
findMany: (...args: unknown[]) => findManyMock(...args),
|
||||||
|
create: (...args: unknown[]) => createMock(...args),
|
||||||
|
deleteMany: (...args: unknown[]) => deleteManyMock(...args),
|
||||||
|
},
|
||||||
|
publishedRule: {
|
||||||
|
update: (...args: unknown[]) => updateRuleMock(...args),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { copyNamedUploadsForRule } from "../../lib/server/uploads/copyNamedUploads";
|
||||||
|
|
||||||
|
const SOURCE_ID = "550e8400-e29b-41d4-a716-446655440000";
|
||||||
|
const OTHER_ID = "550e8400-e29b-41d4-a716-446655440001";
|
||||||
|
const PNG_1X1 = Buffer.from(
|
||||||
|
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
|
||||||
|
"base64",
|
||||||
|
);
|
||||||
|
|
||||||
|
describe("copyNamedUploadsForRule", () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
uploadRoot = await mkdtemp(path.join(tmpdir(), "cr-upload-copy-"));
|
||||||
|
getUploadRootFromEnvMock.mockReset();
|
||||||
|
getUploadRootFromEnvMock.mockImplementation(() => uploadRoot);
|
||||||
|
findManyMock.mockReset();
|
||||||
|
createMock.mockReset();
|
||||||
|
deleteManyMock.mockReset();
|
||||||
|
updateRuleMock.mockReset();
|
||||||
|
deleteManyMock.mockResolvedValue({ count: 0 });
|
||||||
|
createMock.mockImplementation(async ({ data }: { data: { id: string } }) => data);
|
||||||
|
updateRuleMock.mockResolvedValue({});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
uploadRoot = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
it("copies files owned by the source Rule and rewrites the dest document", async () => {
|
||||||
|
await writeFile(path.join(uploadRoot!, `${SOURCE_ID}.png`), PNG_1X1);
|
||||||
|
findManyMock.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: SOURCE_ID,
|
||||||
|
mimeType: "image/png",
|
||||||
|
byteLength: PNG_1X1.length,
|
||||||
|
purpose: "communityAvatar",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
const document = {
|
||||||
|
communityAvatarUrl: `/api/uploads/${SOURCE_ID}`,
|
||||||
|
leftover: `/api/uploads/${OTHER_ID}`,
|
||||||
|
};
|
||||||
|
const result = (await copyNamedUploadsForRule({
|
||||||
|
document,
|
||||||
|
sourceRuleId: "rule-src",
|
||||||
|
destRuleId: "rule-dest",
|
||||||
|
userId: "user-1",
|
||||||
|
})) as {
|
||||||
|
communityAvatarUrl: string;
|
||||||
|
leftover: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(findManyMock).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
where: {
|
||||||
|
id: { in: [SOURCE_ID, OTHER_ID] },
|
||||||
|
OR: [{ ruleId: "rule-src" }, { ruleId: null }],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(createMock).toHaveBeenCalledTimes(1);
|
||||||
|
const createdId = createMock.mock.calls[0]![0].data.id as string;
|
||||||
|
expect(createdId).not.toBe(SOURCE_ID);
|
||||||
|
expect(createMock.mock.calls[0]![0].data).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
mimeType: "image/png",
|
||||||
|
purpose: "communityAvatar",
|
||||||
|
userId: "user-1",
|
||||||
|
ruleId: "rule-dest",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(result.communityAvatarUrl).toBe(`/api/uploads/${createdId}`);
|
||||||
|
expect(result.leftover).toBe(`/api/uploads/${OTHER_ID}`);
|
||||||
|
expect(updateRuleMock).toHaveBeenCalledWith({
|
||||||
|
where: { id: "rule-dest" },
|
||||||
|
data: { document: result },
|
||||||
|
});
|
||||||
|
const files = await readdir(uploadRoot!);
|
||||||
|
expect(files).toContain(`${SOURCE_ID}.png`);
|
||||||
|
expect(files).toContain(`${createdId}.png`);
|
||||||
|
expect(await readFile(path.join(uploadRoot!, `${createdId}.png`))).toEqual(
|
||||||
|
PNG_1X1,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves the document unchanged when the source Rule owns none of the named files", async () => {
|
||||||
|
const document = { logo: `/api/uploads/${SOURCE_ID}` };
|
||||||
|
findManyMock.mockResolvedValueOnce([]);
|
||||||
|
const result = await copyNamedUploadsForRule({
|
||||||
|
document,
|
||||||
|
sourceRuleId: "rule-src",
|
||||||
|
destRuleId: "rule-dest",
|
||||||
|
userId: "user-1",
|
||||||
|
});
|
||||||
|
expect(result).toBe(document);
|
||||||
|
expect(createMock).not.toHaveBeenCalled();
|
||||||
|
expect(updateRuleMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("drops the copies and throws when the rewritten document cannot be saved", async () => {
|
||||||
|
await writeFile(path.join(uploadRoot!, `${SOURCE_ID}.png`), PNG_1X1);
|
||||||
|
findManyMock.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: SOURCE_ID,
|
||||||
|
mimeType: "image/png",
|
||||||
|
byteLength: PNG_1X1.length,
|
||||||
|
purpose: "communityAvatar",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
updateRuleMock.mockRejectedValueOnce(new Error("persist failed"));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
copyNamedUploadsForRule({
|
||||||
|
document: { communityAvatarUrl: `/api/uploads/${SOURCE_ID}` },
|
||||||
|
sourceRuleId: "rule-src",
|
||||||
|
destRuleId: "rule-dest",
|
||||||
|
userId: "user-1",
|
||||||
|
}),
|
||||||
|
).rejects.toThrow("persist failed");
|
||||||
|
|
||||||
|
const createdId = createMock.mock.calls[0]![0].data.id as string;
|
||||||
|
expect(deleteManyMock).toHaveBeenCalledWith({
|
||||||
|
where: { id: { in: [createdId] } },
|
||||||
|
});
|
||||||
|
const files = await readdir(uploadRoot!);
|
||||||
|
expect(files).toContain(`${SOURCE_ID}.png`);
|
||||||
|
expect(files).not.toContain(`${createdId}.png`);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import { extractUploadIdsFromUnknown } from "../../lib/server/uploads/extractUploadIds";
|
import {
|
||||||
|
extractUploadIdsFromUnknown,
|
||||||
|
rewriteUploadIdsInUnknown,
|
||||||
|
} from "../../lib/server/uploads/extractUploadIds";
|
||||||
|
|
||||||
const ID = "550e8400-e29b-41d4-a716-446655440000";
|
const ID = "550e8400-e29b-41d4-a716-446655440000";
|
||||||
|
const NEXT = "550e8400-e29b-41d4-a716-446655440001";
|
||||||
|
|
||||||
describe("extractUploadIdsFromUnknown", () => {
|
describe("extractUploadIdsFromUnknown", () => {
|
||||||
it("collects unique upload ids from nested JSON", () => {
|
it("collects unique upload ids from nested JSON", () => {
|
||||||
@@ -18,3 +22,27 @@ describe("extractUploadIdsFromUnknown", () => {
|
|||||||
expect(extractUploadIdsFromUnknown({ text: "no files" })).toEqual([]);
|
expect(extractUploadIdsFromUnknown({ text: "no files" })).toEqual([]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("rewriteUploadIdsInUnknown", () => {
|
||||||
|
it("rewrites matching paths and leaves others", () => {
|
||||||
|
expect(
|
||||||
|
rewriteUploadIdsInUnknown(
|
||||||
|
{
|
||||||
|
logo: `/api/uploads/${ID}`,
|
||||||
|
nested: { also: `/api/uploads/${ID}` },
|
||||||
|
other: `/api/uploads/${NEXT}`,
|
||||||
|
},
|
||||||
|
new Map([[ID, "6ba7b810-9dad-41d1-80b4-00c04fd430c8"]]),
|
||||||
|
),
|
||||||
|
).toEqual({
|
||||||
|
logo: "/api/uploads/6ba7b810-9dad-41d1-80b4-00c04fd430c8",
|
||||||
|
nested: { also: "/api/uploads/6ba7b810-9dad-41d1-80b4-00c04fd430c8" },
|
||||||
|
other: `/api/uploads/${NEXT}`,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns the original value when there is nothing to replace", () => {
|
||||||
|
const value = { text: "no files" };
|
||||||
|
expect(rewriteUploadIdsInUnknown(value, new Map())).toBe(value);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const findManyMock = vi.fn();
|
||||||
|
const updateManyMock = vi.fn();
|
||||||
|
const browserHoldsUploadGrantMock = vi.fn();
|
||||||
|
|
||||||
|
vi.mock("../../lib/server/db", () => ({
|
||||||
|
prisma: {
|
||||||
|
upload: {
|
||||||
|
findMany: (...args: unknown[]) => findManyMock(...args),
|
||||||
|
updateMany: (...args: unknown[]) => updateManyMock(...args),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../../lib/server/uploads/uploadGrantCookie", () => ({
|
||||||
|
browserHoldsUploadGrant: (...args: unknown[]) =>
|
||||||
|
browserHoldsUploadGrantMock(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import {
|
||||||
|
linkUploadsToDraft,
|
||||||
|
linkUploadsToRule,
|
||||||
|
} from "../../lib/server/uploads/linkUploads";
|
||||||
|
|
||||||
|
const OWNED = "550e8400-e29b-41d4-a716-446655440000";
|
||||||
|
const FOREIGN = "550e8400-e29b-41d4-a716-446655440001";
|
||||||
|
const UNOWNED = "550e8400-e29b-41d4-a716-446655440002";
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
findManyMock.mockReset();
|
||||||
|
updateManyMock.mockReset();
|
||||||
|
browserHoldsUploadGrantMock.mockReset();
|
||||||
|
updateManyMock.mockResolvedValue({ count: 0 });
|
||||||
|
browserHoldsUploadGrantMock.mockResolvedValue(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("linkUploadsToRule", () => {
|
||||||
|
it("does not query when the document names no uploads", async () => {
|
||||||
|
await linkUploadsToRule({
|
||||||
|
ruleId: "rule-1",
|
||||||
|
document: { text: "none" },
|
||||||
|
userId: "user-1",
|
||||||
|
});
|
||||||
|
expect(findManyMock).not.toHaveBeenCalled();
|
||||||
|
expect(updateManyMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not take a file already linked to another Rule", async () => {
|
||||||
|
findManyMock.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: OWNED,
|
||||||
|
userId: "user-1",
|
||||||
|
ruleId: "rule-other",
|
||||||
|
draftId: null,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
await linkUploadsToRule({
|
||||||
|
ruleId: "rule-1",
|
||||||
|
document: { logo: `/api/uploads/${OWNED}` },
|
||||||
|
userId: "user-1",
|
||||||
|
});
|
||||||
|
expect(updateManyMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not take another account's unlinked file", async () => {
|
||||||
|
findManyMock.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: FOREIGN,
|
||||||
|
userId: "user-2",
|
||||||
|
ruleId: null,
|
||||||
|
draftId: null,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
await linkUploadsToRule({
|
||||||
|
ruleId: "rule-1",
|
||||||
|
document: { logo: `/api/uploads/${FOREIGN}` },
|
||||||
|
userId: "user-1",
|
||||||
|
});
|
||||||
|
expect(updateManyMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("links this account's unlinked file and skips a foreign one named beside it", async () => {
|
||||||
|
findManyMock.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: OWNED,
|
||||||
|
userId: "user-1",
|
||||||
|
ruleId: null,
|
||||||
|
draftId: "draft-1",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: FOREIGN,
|
||||||
|
userId: "user-2",
|
||||||
|
ruleId: "rule-other",
|
||||||
|
draftId: null,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
await linkUploadsToRule({
|
||||||
|
ruleId: "rule-1",
|
||||||
|
document: {
|
||||||
|
logo: `/api/uploads/${OWNED}`,
|
||||||
|
other: `/api/uploads/${FOREIGN}`,
|
||||||
|
},
|
||||||
|
userId: "user-1",
|
||||||
|
});
|
||||||
|
expect(updateManyMock).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
where: expect.objectContaining({
|
||||||
|
id: { in: [OWNED] },
|
||||||
|
}),
|
||||||
|
data: expect.objectContaining({
|
||||||
|
ruleId: "rule-1",
|
||||||
|
draftId: null,
|
||||||
|
userId: "user-1",
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("links an unowned file when this browser holds the grant", async () => {
|
||||||
|
findManyMock.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: UNOWNED,
|
||||||
|
userId: null,
|
||||||
|
ruleId: null,
|
||||||
|
draftId: null,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
browserHoldsUploadGrantMock.mockResolvedValueOnce(true);
|
||||||
|
await linkUploadsToRule({
|
||||||
|
ruleId: "rule-1",
|
||||||
|
document: { logo: `/api/uploads/${UNOWNED}` },
|
||||||
|
userId: "user-1",
|
||||||
|
});
|
||||||
|
expect(browserHoldsUploadGrantMock).toHaveBeenCalledWith(UNOWNED);
|
||||||
|
expect(updateManyMock).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
where: expect.objectContaining({
|
||||||
|
id: { in: [UNOWNED] },
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not take an unowned file without a grant", async () => {
|
||||||
|
findManyMock.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: UNOWNED,
|
||||||
|
userId: null,
|
||||||
|
ruleId: null,
|
||||||
|
draftId: null,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
await linkUploadsToRule({
|
||||||
|
ruleId: "rule-1",
|
||||||
|
document: { logo: `/api/uploads/${UNOWNED}` },
|
||||||
|
userId: "user-1",
|
||||||
|
});
|
||||||
|
expect(updateManyMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("may restamp files already on this Rule", async () => {
|
||||||
|
findManyMock.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: OWNED,
|
||||||
|
userId: null,
|
||||||
|
ruleId: "rule-1",
|
||||||
|
draftId: null,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
await linkUploadsToRule({
|
||||||
|
ruleId: "rule-1",
|
||||||
|
document: { logo: `/api/uploads/${OWNED}` },
|
||||||
|
userId: "user-1",
|
||||||
|
});
|
||||||
|
expect(updateManyMock).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
where: expect.objectContaining({
|
||||||
|
id: { in: [OWNED] },
|
||||||
|
}),
|
||||||
|
data: expect.objectContaining({
|
||||||
|
ruleId: "rule-1",
|
||||||
|
userId: "user-1",
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("linkUploadsToDraft", () => {
|
||||||
|
it("does not take a file already on a Rule", async () => {
|
||||||
|
findManyMock.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: OWNED,
|
||||||
|
userId: "user-1",
|
||||||
|
ruleId: "rule-1",
|
||||||
|
draftId: null,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
await linkUploadsToDraft({
|
||||||
|
draftId: "draft-1",
|
||||||
|
payload: { logo: `/api/uploads/${OWNED}` },
|
||||||
|
userId: "user-1",
|
||||||
|
});
|
||||||
|
expect(updateManyMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not take a file linked to another draft", async () => {
|
||||||
|
findManyMock.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: FOREIGN,
|
||||||
|
userId: "user-2",
|
||||||
|
ruleId: null,
|
||||||
|
draftId: "draft-other",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
await linkUploadsToDraft({
|
||||||
|
draftId: "draft-1",
|
||||||
|
payload: { logo: `/api/uploads/${FOREIGN}` },
|
||||||
|
userId: "user-1",
|
||||||
|
});
|
||||||
|
expect(updateManyMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("links this account's unlinked file", async () => {
|
||||||
|
findManyMock.mockResolvedValueOnce([
|
||||||
|
{
|
||||||
|
id: OWNED,
|
||||||
|
userId: "user-1",
|
||||||
|
ruleId: null,
|
||||||
|
draftId: null,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
await linkUploadsToDraft({
|
||||||
|
draftId: "draft-1",
|
||||||
|
payload: { logo: `/api/uploads/${OWNED}` },
|
||||||
|
userId: "user-1",
|
||||||
|
});
|
||||||
|
expect(updateManyMock).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
where: expect.objectContaining({
|
||||||
|
id: { in: [OWNED] },
|
||||||
|
}),
|
||||||
|
data: {
|
||||||
|
draftId: "draft-1",
|
||||||
|
userId: "user-1",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
|||||||
const isDatabaseConfiguredMock = vi.fn();
|
const isDatabaseConfiguredMock = vi.fn();
|
||||||
const findUniqueMock = vi.fn();
|
const findUniqueMock = vi.fn();
|
||||||
const createMock = vi.fn();
|
const createMock = vi.fn();
|
||||||
|
const deleteMock = vi.fn();
|
||||||
const getSessionUserMock = vi.fn();
|
const getSessionUserMock = vi.fn();
|
||||||
|
|
||||||
vi.mock("../../lib/server/env", () => ({
|
vi.mock("../../lib/server/env", () => ({
|
||||||
@@ -15,6 +16,7 @@ vi.mock("../../lib/server/db", () => ({
|
|||||||
publishedRule: {
|
publishedRule: {
|
||||||
findUnique: (...args: unknown[]) => findUniqueMock(...args),
|
findUnique: (...args: unknown[]) => findUniqueMock(...args),
|
||||||
create: (...args: unknown[]) => createMock(...args),
|
create: (...args: unknown[]) => createMock(...args),
|
||||||
|
delete: (...args: unknown[]) => deleteMock(...args),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
@@ -23,7 +25,12 @@ vi.mock("../../lib/server/session", () => ({
|
|||||||
getSessionUser: () => getSessionUserMock(),
|
getSessionUser: () => getSessionUserMock(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
vi.mock("../../lib/server/uploads/copyNamedUploads", () => ({
|
||||||
|
copyNamedUploadsForRule: vi.fn().mockResolvedValue({}),
|
||||||
|
}));
|
||||||
|
|
||||||
import { POST } from "../../app/api/rules/[id]/duplicate/route";
|
import { POST } from "../../app/api/rules/[id]/duplicate/route";
|
||||||
|
import { copyNamedUploadsForRule } from "../../lib/server/uploads/copyNamedUploads";
|
||||||
|
|
||||||
function makeContext(id: string) {
|
function makeContext(id: string) {
|
||||||
return { params: Promise.resolve({ id }) };
|
return { params: Promise.resolve({ id }) };
|
||||||
@@ -33,7 +40,11 @@ beforeEach(() => {
|
|||||||
isDatabaseConfiguredMock.mockReset();
|
isDatabaseConfiguredMock.mockReset();
|
||||||
findUniqueMock.mockReset();
|
findUniqueMock.mockReset();
|
||||||
createMock.mockReset();
|
createMock.mockReset();
|
||||||
|
deleteMock.mockReset();
|
||||||
getSessionUserMock.mockReset();
|
getSessionUserMock.mockReset();
|
||||||
|
deleteMock.mockResolvedValue({});
|
||||||
|
vi.mocked(copyNamedUploadsForRule).mockReset();
|
||||||
|
vi.mocked(copyNamedUploadsForRule).mockResolvedValue({});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("POST /api/rules/[id]/duplicate", () => {
|
describe("POST /api/rules/[id]/duplicate", () => {
|
||||||
@@ -101,5 +112,40 @@ describe("POST /api/rules/[id]/duplicate", () => {
|
|||||||
const body = (await res.json()) as { rule: { id: string; title: string } };
|
const body = (await res.json()) as { rule: { id: string; title: string } };
|
||||||
expect(body.rule.id).toBe("r2");
|
expect(body.rule.id).toBe("r2");
|
||||||
expect(body.rule.title).toBe("Original (Copy)");
|
expect(body.rule.title).toBe("Original (Copy)");
|
||||||
|
expect(copyNamedUploadsForRule).toHaveBeenCalledWith({
|
||||||
|
document: { x: 1 },
|
||||||
|
sourceRuleId: "r1",
|
||||||
|
destRuleId: "r2",
|
||||||
|
userId: "u1",
|
||||||
|
});
|
||||||
|
expect(deleteMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes the new rule when copying its uploads fails", async () => {
|
||||||
|
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||||
|
getSessionUserMock.mockResolvedValue({ id: "u1", email: "a@b.c" });
|
||||||
|
findUniqueMock.mockResolvedValueOnce({
|
||||||
|
id: "r1",
|
||||||
|
userId: "u1",
|
||||||
|
title: "Original",
|
||||||
|
summary: "S",
|
||||||
|
document: { x: 1 },
|
||||||
|
});
|
||||||
|
createMock.mockResolvedValueOnce({
|
||||||
|
id: "r2",
|
||||||
|
title: "Original (Copy)",
|
||||||
|
summary: "S",
|
||||||
|
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||||
|
updatedAt: new Date("2026-01-01T00:00:00Z"),
|
||||||
|
});
|
||||||
|
vi.mocked(copyNamedUploadsForRule).mockRejectedValueOnce(
|
||||||
|
new Error("persist failed"),
|
||||||
|
);
|
||||||
|
const res = await POST(
|
||||||
|
new NextRequest("https://x.test/api/rules/r1/duplicate"),
|
||||||
|
makeContext("r1"),
|
||||||
|
);
|
||||||
|
expect(res.status).toBe(500);
|
||||||
|
expect(deleteMock).toHaveBeenCalledWith({ where: { id: "r2" } });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
|||||||
|
|
||||||
const findFirstStakeholderMock = vi.fn();
|
const findFirstStakeholderMock = vi.fn();
|
||||||
const createRuleMock = vi.fn();
|
const createRuleMock = vi.fn();
|
||||||
|
const deleteRuleMock = vi.fn();
|
||||||
const getSessionUserMock = vi.fn();
|
const getSessionUserMock = vi.fn();
|
||||||
const rateLimitKeyMock = vi.fn(
|
const rateLimitKeyMock = vi.fn(
|
||||||
(
|
(
|
||||||
@@ -31,11 +32,19 @@ vi.mock("../../lib/server/db", () => ({
|
|||||||
},
|
},
|
||||||
publishedRule: {
|
publishedRule: {
|
||||||
create: (...args: unknown[]) => createRuleMock(...args),
|
create: (...args: unknown[]) => createRuleMock(...args),
|
||||||
|
delete: (...args: unknown[]) => deleteRuleMock(...args),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
vi.mock("../../lib/server/uploads/copyNamedUploads", () => ({
|
||||||
|
copyNamedUploadsForRule: vi.fn(
|
||||||
|
async ({ document }: { document: unknown }) => document,
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
import { POST } from "../../app/api/rules/[id]/make-copy/route";
|
import { POST } from "../../app/api/rules/[id]/make-copy/route";
|
||||||
|
import { copyNamedUploadsForRule } from "../../lib/server/uploads/copyNamedUploads";
|
||||||
|
|
||||||
const viewer = { id: "user-2", email: "reader@example.com" };
|
const viewer = { id: "user-2", email: "reader@example.com" };
|
||||||
const routeCtx = { params: Promise.resolve({ id: "rule-1" }) };
|
const routeCtx = { params: Promise.resolve({ id: "rule-1" }) };
|
||||||
@@ -43,10 +52,16 @@ const routeCtx = { params: Promise.resolve({ id: "rule-1" }) };
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
findFirstStakeholderMock.mockReset();
|
findFirstStakeholderMock.mockReset();
|
||||||
createRuleMock.mockReset();
|
createRuleMock.mockReset();
|
||||||
|
deleteRuleMock.mockReset();
|
||||||
getSessionUserMock.mockReset();
|
getSessionUserMock.mockReset();
|
||||||
|
deleteRuleMock.mockResolvedValue({});
|
||||||
rateLimitKeyMock.mockReset();
|
rateLimitKeyMock.mockReset();
|
||||||
rateLimitKeyMock.mockReturnValue({ ok: true as const });
|
rateLimitKeyMock.mockReturnValue({ ok: true as const });
|
||||||
getSessionUserMock.mockResolvedValue(viewer);
|
getSessionUserMock.mockResolvedValue(viewer);
|
||||||
|
vi.mocked(copyNamedUploadsForRule).mockReset();
|
||||||
|
vi.mocked(copyNamedUploadsForRule).mockImplementation(
|
||||||
|
async ({ document }: { document: unknown }) => document,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("POST /api/rules/[id]/make-copy", () => {
|
describe("POST /api/rules/[id]/make-copy", () => {
|
||||||
@@ -141,5 +156,122 @@ describe("POST /api/rules/[id]/make-copy", () => {
|
|||||||
expect(body.rule.id).toBe("rule-copy");
|
expect(body.rule.id).toBe("rule-copy");
|
||||||
expect(body.rule.copiedFromTitle).toBe("Juniper Street Food Share");
|
expect(body.rule.copiedFromTitle).toBe("Juniper Street Food Share");
|
||||||
expect(body.rule.copiedNameHit?.entryTitle).toBe("Care");
|
expect(body.rule.copiedNameHit?.entryTitle).toBe("Care");
|
||||||
|
expect(copyNamedUploadsForRule).toHaveBeenCalledWith({
|
||||||
|
document: expect.not.objectContaining({
|
||||||
|
communityAvatarUrl: "https://example.test/a.png",
|
||||||
|
}),
|
||||||
|
sourceRuleId: "rule-1",
|
||||||
|
destRuleId: "rule-copy",
|
||||||
|
userId: viewer.id,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns copied attachment paths from the new Rule's files", async () => {
|
||||||
|
const ATTACH = "550e8400-e29b-41d4-a716-446655440000";
|
||||||
|
const COPIED = "550e8400-e29b-41d4-a716-446655440099";
|
||||||
|
findFirstStakeholderMock.mockResolvedValueOnce({
|
||||||
|
id: "st-1",
|
||||||
|
rule: {
|
||||||
|
id: "rule-1",
|
||||||
|
title: "Juniper Street Food Share",
|
||||||
|
userId: "owner-1",
|
||||||
|
document: {
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
categoryName: "Values",
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
title: "Care",
|
||||||
|
body: "We care.",
|
||||||
|
blocks: [{ assetUrl: `/api/uploads/${ATTACH}` }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
createRuleMock.mockResolvedValueOnce({
|
||||||
|
id: "rule-copy",
|
||||||
|
title: "New group",
|
||||||
|
summary: null,
|
||||||
|
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||||
|
updatedAt: new Date("2026-01-01T00:00:00Z"),
|
||||||
|
});
|
||||||
|
vi.mocked(copyNamedUploadsForRule).mockResolvedValueOnce({
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
categoryName: "Values",
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
title: "Care",
|
||||||
|
body: "We care.",
|
||||||
|
blocks: [{ assetUrl: `/api/uploads/${COPIED}` }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await POST(
|
||||||
|
new NextRequest("https://x.test/api/rules/rule-1/make-copy", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ title: "New group" }),
|
||||||
|
headers: { "content-type": "application/json" },
|
||||||
|
}),
|
||||||
|
routeCtx,
|
||||||
|
);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = (await res.json()) as { rule: { document: unknown } };
|
||||||
|
expect(body.rule.document).toEqual({
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
categoryName: "Values",
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
title: "Care",
|
||||||
|
body: "We care.",
|
||||||
|
blocks: [{ assetUrl: `/api/uploads/${COPIED}` }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(deleteRuleMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes the new rule when copying its uploads fails", async () => {
|
||||||
|
findFirstStakeholderMock.mockResolvedValueOnce({
|
||||||
|
id: "st-1",
|
||||||
|
rule: {
|
||||||
|
id: "rule-1",
|
||||||
|
title: "Juniper Street Food Share",
|
||||||
|
userId: "owner-1",
|
||||||
|
document: {
|
||||||
|
sections: [{ categoryName: "Values", entries: [] }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
createRuleMock.mockResolvedValueOnce({
|
||||||
|
id: "rule-copy",
|
||||||
|
title: "New group",
|
||||||
|
summary: null,
|
||||||
|
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||||
|
updatedAt: new Date("2026-01-01T00:00:00Z"),
|
||||||
|
});
|
||||||
|
vi.mocked(copyNamedUploadsForRule).mockRejectedValueOnce(
|
||||||
|
new Error("persist failed"),
|
||||||
|
);
|
||||||
|
|
||||||
|
const res = await POST(
|
||||||
|
new NextRequest("https://x.test/api/rules/rule-1/make-copy", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ title: "New group" }),
|
||||||
|
headers: { "content-type": "application/json" },
|
||||||
|
}),
|
||||||
|
routeCtx,
|
||||||
|
);
|
||||||
|
expect(res.status).toBe(500);
|
||||||
|
expect(deleteRuleMock).toHaveBeenCalledWith({ where: { id: "rule-copy" } });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user