175 lines
7.2 KiB
TypeScript
175 lines
7.2 KiB
TypeScript
// @vitest-environment node
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
|
import { db } from "~/utils/db.server";
|
|
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
|
import { getUser } from "~/utils/db/users.db.server";
|
|
import { requestWebhookReplay } from "~/services/admin/webhook-inbox.server";
|
|
import { action, loader } from "./webhooks";
|
|
|
|
vi.mock("react-i18next", () => ({
|
|
useTranslation: () => ({ t: (key: string, params?: Record<string, string | number>) => (params?.duration ? `${key}:${params.duration}` : key) }),
|
|
}));
|
|
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
|
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
|
vi.mock("~/components/ui/buttons/ButtonPrimary", () => ({ default: () => null }));
|
|
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf" }) }));
|
|
vi.mock("~/locale/format", () => ({
|
|
useLocaleFormatters: () => ({
|
|
dateTime: (value: Date) => value.toISOString(),
|
|
}),
|
|
}));
|
|
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
|
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
|
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(), validateCSRFToken: vi.fn() }));
|
|
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
|
|
vi.mock("~/services/admin/webhook-inbox.server", async () => {
|
|
const actual = await vi.importActual<typeof import("~/services/admin/webhook-inbox.server")>("~/services/admin/webhook-inbox.server");
|
|
return {
|
|
...actual,
|
|
requestWebhookReplay: vi.fn(),
|
|
};
|
|
});
|
|
vi.mock("~/utils/db.server", () => ({
|
|
db: {
|
|
eventWebhookAttempt: {
|
|
findMany: vi.fn(),
|
|
},
|
|
},
|
|
}));
|
|
|
|
function callLoader(url = "https://admin.example.test/system/webhooks") {
|
|
return loader({ request: new Request(url), params: {}, context: {} } as LoaderFunctionArgs);
|
|
}
|
|
|
|
function callAction(form: Record<string, string>) {
|
|
return action({
|
|
request: new Request("https://admin.example.test/system/webhooks", {
|
|
method: "POST",
|
|
body: new URLSearchParams(form),
|
|
}),
|
|
params: {},
|
|
context: {},
|
|
} as ActionFunctionArgs);
|
|
}
|
|
|
|
describe("admin webhooks route", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
process.env.APP_NAME = "HiveGrid";
|
|
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
|
vi.mocked(getTranslations).mockResolvedValue({
|
|
t: (key: string, params?: Record<string, string>) => (params?.attemptId ? `${key}:${params.attemptId}` : key),
|
|
} as never);
|
|
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
|
vi.mocked(getUserInfo).mockResolvedValue({ userId: "admin_1" } as never);
|
|
vi.mocked(getUser).mockResolvedValue({ id: "admin_1", email: "admin@hivegrid.de" } as never);
|
|
vi.mocked(requestWebhookReplay).mockResolvedValue({ replayAttemptId: "attempt_replay" } as never);
|
|
vi.mocked(db.eventWebhookAttempt.findMany).mockResolvedValue([
|
|
{
|
|
id: "attempt_failed",
|
|
eventId: "event_failed",
|
|
endpoint: "https://api.hivegrid.de/webhooks/mollie",
|
|
success: false,
|
|
status: 500,
|
|
message: "Provider timeout",
|
|
body: JSON.stringify({ token: "secret", kept: "value" }),
|
|
createdAt: new Date("2026-07-09T10:00:00.000Z"),
|
|
startedAt: new Date("2026-07-09T10:00:00.000Z"),
|
|
finishedAt: new Date("2026-07-09T10:00:01.000Z"),
|
|
event: {
|
|
id: "event_failed",
|
|
name: "billing.mollie.webhook",
|
|
resource: "billing",
|
|
tenantId: "tenant_1",
|
|
userId: null,
|
|
},
|
|
},
|
|
{
|
|
id: "attempt_delivered",
|
|
eventId: "event_delivered",
|
|
endpoint: "https://api.hivegrid.de/webhooks/lago",
|
|
success: true,
|
|
status: 204,
|
|
message: "Admin replay requested.",
|
|
body: "{}",
|
|
createdAt: new Date("2026-07-09T10:01:00.000Z"),
|
|
startedAt: new Date("2026-07-09T10:01:00.000Z"),
|
|
finishedAt: new Date("2026-07-09T10:01:00.500Z"),
|
|
event: {
|
|
id: "event_delivered",
|
|
name: "billing.lago.invoice",
|
|
resource: "billing",
|
|
tenantId: "tenant_1",
|
|
userId: null,
|
|
},
|
|
},
|
|
{
|
|
id: "attempt_queue_unavailable",
|
|
eventId: "event_queue_unavailable",
|
|
endpoint: "https://api.hivegrid.de/webhooks/lago",
|
|
success: false,
|
|
status: 503,
|
|
message: "admin.webhooks.messages.queueUnavailable",
|
|
body: "{}",
|
|
createdAt: new Date("2026-07-09T10:02:00.000Z"),
|
|
startedAt: new Date("2026-07-09T10:02:00.000Z"),
|
|
finishedAt: new Date("2026-07-09T10:02:00.500Z"),
|
|
event: {
|
|
id: "event_queue_unavailable",
|
|
name: "billing.lago.invoice",
|
|
resource: "billing",
|
|
tenantId: "tenant_1",
|
|
userId: null,
|
|
},
|
|
},
|
|
] as never);
|
|
});
|
|
|
|
it("checks event permission and builds the webhook inbox", async () => {
|
|
const data = await callLoader();
|
|
|
|
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.events.view");
|
|
expect(db.eventWebhookAttempt.findMany).toHaveBeenCalledWith(expect.objectContaining({ take: 100 }));
|
|
expect(data.vm.status).toBe("ready");
|
|
if (data.vm.status !== "ready") return;
|
|
expect(data.vm.data.summary).toMatchObject({ totalCount: 3, failedCount: 2, deliveredCount: 1 });
|
|
expect(data.vm.data.rows.find((row) => row.id === "attempt_failed")?.payloadPreview).toContain("[REDACTED]");
|
|
expect(data.vm.data.rows.find((row) => row.id === "attempt_delivered")?.message).toBe("admin.webhooks.messages.replayRequested");
|
|
expect(data.vm.data.rows.find((row) => row.id === "attempt_queue_unavailable")?.message).toBe("admin.webhooks.messages.queueUnavailable");
|
|
});
|
|
|
|
it("filters rows by delivery status", async () => {
|
|
const data = await callLoader("https://admin.example.test/system/webhooks?status=delivered");
|
|
|
|
expect(data.filter).toBe("delivered");
|
|
expect(data.vm.status).toBe("ready");
|
|
if (data.vm.status !== "ready") return;
|
|
expect(data.vm.data.rows).toHaveLength(1);
|
|
expect(data.vm.data.rows[0].id).toBe("attempt_delivered");
|
|
});
|
|
|
|
it("routes replay form submissions to the audited admin service", async () => {
|
|
const response = (await callAction({
|
|
csrf: "csrf",
|
|
action: "request-replay",
|
|
attemptId: "attempt_failed",
|
|
reason: "Provider Timeout erneut ausliefern",
|
|
})) as Response;
|
|
|
|
await expect(response.json()).resolves.toEqual({ success: "admin.webhooks.actions.replayRequested:attempt_replay" });
|
|
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.events.view");
|
|
expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request));
|
|
expect(requestWebhookReplay).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
attemptId: "attempt_failed",
|
|
reason: "Provider Timeout erneut ausliefern",
|
|
actorUserId: "admin_1",
|
|
actorEmail: "admin@hivegrid.de",
|
|
})
|
|
);
|
|
});
|
|
});
|