347 lines
13 KiB
TypeScript
347 lines
13 KiB
TypeScript
/**
|
|
* Submission API smoke-tests. Covers the three documented anti-spam layers
|
|
* (origin allowlist, honeypot silent-drop, per-IP rate-limit) plus the
|
|
* happy-path persistence call. Heavy collaborators (Prisma + SharedStore +
|
|
* feature-flags + Turnstile fetch) are mocked at the module boundary so the
|
|
* tests stay hermetic + fast.
|
|
*/
|
|
import { describe, expect, it, vi, beforeEach } from "vitest";
|
|
import { HONEYPOT_FIELD_KEY } from "@hivegrid/form-widget";
|
|
|
|
const formRow = {
|
|
id: "form_1",
|
|
tenantId: "t_1",
|
|
isEnabled: true,
|
|
subtype: "standard",
|
|
definition: {
|
|
title: "Contact",
|
|
submitLabel: "Send",
|
|
successMessage: "Thanks",
|
|
fields: [
|
|
{ key: "email", type: "email", label: "Email", required: true },
|
|
{ key: HONEYPOT_FIELD_KEY, type: "honeypot", label: "Leave empty" },
|
|
],
|
|
},
|
|
allowedOrigins: ["https://allowed.example.com"],
|
|
targetType: "generic",
|
|
targetEntityId: null,
|
|
fieldMapping: {},
|
|
config: {},
|
|
webhookUrl: null,
|
|
notifyEmails: ["ops@example.com"],
|
|
};
|
|
|
|
const mocks = vi.hoisted(() => ({
|
|
createSubmission: vi.fn(async () => ({ id: "sub_1" })),
|
|
createFormFileMany: vi.fn(async () => ({ count: 1 })),
|
|
createFileEntityLinkMany: vi.fn(async () => ({ count: 1 })),
|
|
createFile: vi.fn(async () => ({ id: "file_1" })),
|
|
updateFile: vi.fn(async () => ({ id: "file_1" })),
|
|
deleteFile: vi.fn(async () => ({ id: "file_1" })),
|
|
publishOutboxEvent: vi.fn(async () => ({ id: "ob_1" })),
|
|
putBufferAsFile: vi.fn(async () => undefined),
|
|
deleteStoredFile: vi.fn(async () => undefined),
|
|
withStorageReservation: vi.fn(),
|
|
enqueueFileScan: vi.fn(async () => undefined),
|
|
enqueueFilePreview: vi.fn(async () => undefined),
|
|
consumeRateLimit: vi.fn(),
|
|
resolvePublicFormKeyRlsIdentity: vi.fn(async (formKey: string) => (formKey === "key_missing" ? null : { tenantId: "t_1", resourceId: "form_1" })),
|
|
}));
|
|
|
|
vi.mock("@hivegrid/db/rls-resolvers.server", () => ({
|
|
resolvePublicFormKeyRlsIdentity: mocks.resolvePublicFormKeyRlsIdentity,
|
|
}));
|
|
|
|
vi.mock("@hivegrid/db/storage-capacity.server", () => ({
|
|
withTenantStorageWriteReservation: (...args: unknown[]) => mocks.withStorageReservation(...args),
|
|
}));
|
|
|
|
vi.mock("@hivegrid/db/outbox", () => ({
|
|
publishOutboxEvent: (...args: unknown[]) => mocks.publishOutboxEvent(...args),
|
|
}));
|
|
|
|
vi.mock("~/utils/db.server", () => {
|
|
const tx = {
|
|
formSubmission: { create: mocks.createSubmission },
|
|
formFile: { createMany: mocks.createFormFileMany },
|
|
fileEntityLink: { createMany: mocks.createFileEntityLinkMany },
|
|
};
|
|
return {
|
|
db: {
|
|
form: {
|
|
findFirst: vi.fn(async () => ({ ...formRow })),
|
|
},
|
|
formSubmission: { create: mocks.createSubmission, findUnique: vi.fn(async () => null) },
|
|
file: { create: mocks.createFile, update: mocks.updateFile, delete: mocks.deleteFile },
|
|
$transaction: vi.fn(async (fn: (tx: typeof tx) => Promise<unknown>) => fn(tx)),
|
|
},
|
|
};
|
|
});
|
|
|
|
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
|
withTenantRLS: async (_tenantId: string, callback: (tx: { file: { create: typeof mocks.createFile } }) => Promise<unknown>) =>
|
|
callback({ file: { create: mocks.createFile } }),
|
|
}));
|
|
|
|
vi.mock("~/utils/logger.server", () => ({
|
|
createScopedLogger: () => ({
|
|
info: () => undefined,
|
|
warn: () => undefined,
|
|
error: () => undefined,
|
|
}),
|
|
}));
|
|
|
|
vi.mock("~/utils/services/.server/featureFlagEvaluator.server", () => ({
|
|
evaluateFlagForContext: vi.fn(async () => ({ enabled: false, reason: "disabled" })),
|
|
}));
|
|
|
|
vi.mock("~/utils/integrations/storageService", () => ({
|
|
resolveStorageBucket: () => "uploads",
|
|
putBufferAsFile: (...args: unknown[]) => mocks.putBufferAsFile(...args),
|
|
deleteFile: (...args: unknown[]) => mocks.deleteStoredFile(...args),
|
|
}));
|
|
|
|
vi.mock("~/utils/integrations/fileScanQueue.server", () => ({
|
|
enqueueFileScan: (...args: unknown[]) => mocks.enqueueFileScan(...args),
|
|
}));
|
|
|
|
vi.mock("~/utils/integrations/filePreviewQueue.server", () => ({
|
|
enqueueFilePreview: (...args: unknown[]) => mocks.enqueueFilePreview(...args),
|
|
}));
|
|
|
|
vi.mock("~/shared-store.server", () => {
|
|
const memory = new Map<string, number>();
|
|
return {
|
|
getSharedStore: () => ({
|
|
// The route only calls helpers via createSlidingWindowRateLimiter; we
|
|
// hand the limiter a real MemoryAdapter-backed store from shared-store.
|
|
// For tests we stub eval to no-op via override below.
|
|
}),
|
|
__memory: memory,
|
|
};
|
|
});
|
|
|
|
vi.mock("~/services/auth/auth-rate-limit-key.server", () => ({
|
|
getPseudonymousAuthBucketKey: ({ scope }: { scope?: string }) => `pseudonymous-${scope ?? "pair"}`,
|
|
}));
|
|
|
|
vi.mock("@hivegrid/shared-store", async (orig) => {
|
|
const real = (await orig()) as Record<string, unknown>;
|
|
return {
|
|
...real,
|
|
createSlidingWindowRateLimiter: () => ({
|
|
consume: mocks.consumeRateLimit,
|
|
reset: async () => undefined,
|
|
}),
|
|
};
|
|
});
|
|
|
|
async function loadAction() {
|
|
const mod = await import("./api.embed.forms.$formKey.submit");
|
|
return mod.action;
|
|
}
|
|
|
|
function makeRequest(body: unknown, origin: string | null): Request {
|
|
const params = new URLSearchParams();
|
|
params.set("__payload", typeof body === "string" ? body : JSON.stringify(body));
|
|
return new Request("https://forms.example.com/api/embed/forms/key_1/submit", {
|
|
method: "POST",
|
|
body: params.toString(),
|
|
headers: {
|
|
"content-type": "application/x-www-form-urlencoded",
|
|
...(origin ? { origin } : {}),
|
|
// Trusted proxy-set header — the endpoint no longer keys the per-IP
|
|
// limiter on the client-spoofable X-Forwarded-For.
|
|
"cf-connecting-ip": "1.2.3.4",
|
|
"user-agent": "vitest",
|
|
},
|
|
});
|
|
}
|
|
|
|
describe("api.embed.forms.$formKey.submit action", () => {
|
|
beforeEach(() => {
|
|
formRow.subtype = "standard";
|
|
mocks.createSubmission.mockClear();
|
|
mocks.createFormFileMany.mockClear();
|
|
mocks.createFileEntityLinkMany.mockClear();
|
|
mocks.createFile.mockClear();
|
|
mocks.updateFile.mockClear();
|
|
mocks.deleteFile.mockClear();
|
|
mocks.putBufferAsFile.mockClear();
|
|
mocks.deleteStoredFile.mockClear();
|
|
mocks.withStorageReservation.mockReset();
|
|
mocks.withStorageReservation.mockImplementation(async (input) => {
|
|
const stored = await input.upload();
|
|
return input.runTransaction((tx) => input.commit(tx, stored));
|
|
});
|
|
mocks.enqueueFileScan.mockClear();
|
|
mocks.enqueueFilePreview.mockClear();
|
|
mocks.publishOutboxEvent.mockClear();
|
|
mocks.consumeRateLimit.mockReset();
|
|
mocks.resolvePublicFormKeyRlsIdentity.mockClear();
|
|
mocks.consumeRateLimit.mockResolvedValue({ allowed: true, remaining: 9, oldestAt: null });
|
|
});
|
|
|
|
it("returns 404 for an unknown form key", async () => {
|
|
const action = await loadAction();
|
|
const res = await action({
|
|
params: { formKey: "key_missing" },
|
|
request: makeRequest({ values: { email: "a@b.co" }, gdprAccepted: true }, "https://allowed.example.com"),
|
|
});
|
|
expect(res.status).toBe(404);
|
|
});
|
|
|
|
it("keeps authenticated portal forms outside the anonymous embed endpoint", async () => {
|
|
formRow.subtype = "portal_form";
|
|
const action = await loadAction();
|
|
const res = await action({
|
|
params: { formKey: "key_1" },
|
|
request: makeRequest({ values: { email: "a@b.co" }, gdprAccepted: true }, "https://allowed.example.com"),
|
|
});
|
|
expect(res.status).toBe(404);
|
|
expect(mocks.createSubmission).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("returns 403 when origin is not allowlisted", async () => {
|
|
const action = await loadAction();
|
|
const res = await action({
|
|
params: { formKey: "key_1" },
|
|
request: makeRequest({ values: { email: "a@b.co" }, gdprAccepted: true }, "https://evil.example.com"),
|
|
});
|
|
expect(res.status).toBe(403);
|
|
expect(mocks.createSubmission).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("silently drops (204) when honeypot is filled", async () => {
|
|
const action = await loadAction();
|
|
const res = await action({
|
|
params: { formKey: "key_1" },
|
|
request: makeRequest({ values: { email: "a@b.co", [HONEYPOT_FIELD_KEY]: "bot" }, gdprAccepted: true }, "https://allowed.example.com"),
|
|
});
|
|
expect(res.status).toBe(204);
|
|
expect(mocks.createSubmission).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("fails closed before parsing when rate-limit storage is unavailable", async () => {
|
|
const action = await loadAction();
|
|
mocks.consumeRateLimit.mockRejectedValueOnce(new Error("redis unavailable"));
|
|
const res = await action({
|
|
params: { formKey: "key_1" },
|
|
request: makeRequest({ values: { email: "a@b.co" }, gdprAccepted: true }, "https://allowed.example.com"),
|
|
});
|
|
expect(res.status).toBe(503);
|
|
const body = (await res.json()) as { errorCode: string };
|
|
expect(body.errorCode).toBe("RATE_LIMIT_IP");
|
|
expect(mocks.createSubmission).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects missing required fields with 400", async () => {
|
|
const action = await loadAction();
|
|
const res = await action({
|
|
params: { formKey: "key_1" },
|
|
request: makeRequest({ values: { email: "" }, gdprAccepted: true }, "https://allowed.example.com"),
|
|
});
|
|
expect(res.status).toBe(400);
|
|
expect(mocks.createSubmission).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects malformed email with 400", async () => {
|
|
const action = await loadAction();
|
|
const res = await action({
|
|
params: { formKey: "key_1" },
|
|
request: makeRequest({ values: { email: "not-an-email" }, gdprAccepted: true }, "https://allowed.example.com"),
|
|
});
|
|
expect(res.status).toBe(400);
|
|
});
|
|
|
|
it("persists submission on the happy path", async () => {
|
|
const action = await loadAction();
|
|
const res = await action({
|
|
params: { formKey: "key_1" },
|
|
request: makeRequest({ values: { email: "alice@example.com" }, gdprAccepted: true }, "https://allowed.example.com"),
|
|
});
|
|
expect(res.status).toBe(200);
|
|
const json = (await res.json()) as { ok: boolean };
|
|
expect(json.ok).toBe(true);
|
|
expect(mocks.createSubmission).toHaveBeenCalledTimes(1);
|
|
const args = mocks.createSubmission.mock.calls[0]![0] as { data: { tenantId: string; status: string } };
|
|
expect(args.data.tenantId).toBe("t_1");
|
|
expect(args.data.status).toBe("received");
|
|
});
|
|
|
|
it("publishes a form.submission.process outbox event with the submission payload", async () => {
|
|
const action = await loadAction();
|
|
const res = await action({
|
|
params: { formKey: "key_1" },
|
|
request: makeRequest({ values: { email: "alice@example.com" }, gdprAccepted: true }, "https://allowed.example.com"),
|
|
});
|
|
expect(res.status).toBe(200);
|
|
expect(mocks.publishOutboxEvent).toHaveBeenCalledTimes(1);
|
|
const call = mocks.publishOutboxEvent.mock.calls[0]!;
|
|
const args = call[1] as {
|
|
tenantId: string;
|
|
type: string;
|
|
dispatchKey: string;
|
|
payload: {
|
|
submissionId: string;
|
|
formId: string;
|
|
targetType: string;
|
|
notifyEmails: string[];
|
|
values: Record<string, unknown>;
|
|
};
|
|
};
|
|
expect(args.type).toBe("form.submission.process");
|
|
expect(args.tenantId).toBe("t_1");
|
|
expect(args.dispatchKey).toBe("form-submission:sub_1");
|
|
expect(args.payload.submissionId).toBe("sub_1");
|
|
expect(args.payload.formId).toBe("form_1");
|
|
expect(args.payload.targetType).toBe("generic");
|
|
expect(args.payload.notifyEmails).toEqual(["ops@example.com"]);
|
|
expect(args.payload.values).toEqual({ email: "alice@example.com" });
|
|
});
|
|
|
|
it("prepares uploaded files and lets the clean scan verdict enqueue the preview", async () => {
|
|
const { prepareUploadedFiles } = await import("~/modules/formWidget/services/embedFormSubmission.server");
|
|
const formBody = new FormData();
|
|
const file = new File(["hello"], "contract.pdf", { type: "application/pdf" });
|
|
Object.defineProperty(file, "arrayBuffer", { value: async () => new TextEncoder().encode("hello").buffer });
|
|
formBody.set("attachment", file);
|
|
const prepared = await prepareUploadedFiles({
|
|
tenantId: "t_1",
|
|
formBody,
|
|
fields: [
|
|
{
|
|
key: "attachment",
|
|
type: "file",
|
|
label: "Attachment",
|
|
required: true,
|
|
validationRules: { acceptedFileTypes: ["application/pdf"], maxFileSizeMb: 1 },
|
|
},
|
|
],
|
|
});
|
|
expect(prepared).toEqual([{ fieldKey: "attachment", fileId: expect.stringMatching(/^file_/u), kind: "file" }]);
|
|
expect(mocks.withStorageReservation).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
reservation: expect.objectContaining({ tenantId: "t_1", actorUserId: "system:form", sizeBytes: 5 }),
|
|
})
|
|
);
|
|
expect(mocks.createFile).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
data: expect.objectContaining({ tenantId: "t_1", displayName: "contract.pdf", source: "form_submission" }),
|
|
})
|
|
);
|
|
expect(mocks.putBufferAsFile).toHaveBeenCalledWith(
|
|
expect.objectContaining({ bucket: "uploads", key: expect.stringMatching(/^tenants\/t_1\/files\/file_/u) })
|
|
);
|
|
expect(mocks.enqueueFileScan).toHaveBeenCalledOnce();
|
|
expect(mocks.enqueueFilePreview).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("returns 405 on GET", async () => {
|
|
const action = await loadAction();
|
|
const req = new Request("https://forms.example.com/api/embed/forms/key_1/submit", { method: "GET" });
|
|
const res = await action({ params: { formKey: "key_1" }, request: req });
|
|
expect(res.status).toBe(405);
|
|
});
|
|
});
|