Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/webhooks.email.test.ts
T
2026-07-08 16:15:37 +02:00

107 lines
5.0 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ActionFunctionArgs } from "react-router";
// VA-P23 — provider webhook ingest contracts: Graph validation handshake +
// clientState auth, Gmail Pub/Sub shared-token auth + payload decode. Both
// endpoints ALWAYS ack (2xx) so providers never retry-storm; only verified
// notifications are persisted.
const findMailboxByWebhookSubscription = vi.fn();
const findMailboxByEmailAddress = vi.fn();
const recordEmailWebhookEvent = vi.fn();
vi.mock("~/modules/emailInbox/db/emailInbox.db.server", () => ({
findMailboxByWebhookSubscription: (...args: unknown[]) => findMailboxByWebhookSubscription(...args),
findMailboxByEmailAddress: (...args: unknown[]) => findMailboxByEmailAddress(...args),
recordEmailWebhookEvent: (...args: unknown[]) => recordEmailWebhookEvent(...args),
}));
import { action as googleAction } from "./webhooks.email.google";
import { action as microsoftAction } from "./webhooks.email.microsoft";
function call(action: typeof googleAction, request: Request) {
return action({ request, params: {}, context: {}, unstable_pattern: "webhooks.email" } as ActionFunctionArgs);
}
beforeEach(() => {
vi.clearAllMocks();
process.env.GOOGLE_GMAIL_PUBSUB_VERIFICATION_TOKEN = "shared-token";
});
afterEach(() => {
delete process.env.GOOGLE_GMAIL_PUBSUB_VERIFICATION_TOKEN;
});
function pubsubBody(payload: Record<string, unknown>): string {
return JSON.stringify({ message: { data: Buffer.from(JSON.stringify(payload), "utf8").toString("base64url"), messageId: "pm-1" } });
}
describe("Gmail Pub/Sub webhook", () => {
it("acks without persisting when the shared token is wrong", async () => {
const response = await call(
googleAction,
new Request("https://app.example.test/webhooks/email/google?token=WRONG", { method: "POST", body: pubsubBody({ emailAddress: "a@b.de", historyId: 5 }) }),
);
expect(response.status).toBe(200);
expect(recordEmailWebhookEvent).not.toHaveBeenCalled();
});
it("persists a pending event for a known mailbox address", async () => {
findMailboxByEmailAddress.mockResolvedValue({ id: "mb1", tenantId: "t1", ownerUserId: "u1" });
const response = await call(
googleAction,
new Request("https://app.example.test/webhooks/email/google?token=shared-token", { method: "POST", body: pubsubBody({ emailAddress: "A@B.de", historyId: 5 }) }),
);
expect(response.status).toBe(200);
expect(findMailboxByEmailAddress).toHaveBeenCalledWith("gmail", "A@B.de");
expect(recordEmailWebhookEvent).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: "t1", mailboxId: "mb1", provider: "gmail", notificationPayload: expect.objectContaining({ historyId: "5" }) }),
);
});
it("acks unknown addresses without persisting", async () => {
findMailboxByEmailAddress.mockResolvedValue(null);
const response = await call(
googleAction,
new Request("https://app.example.test/webhooks/email/google?token=shared-token", { method: "POST", body: pubsubBody({ emailAddress: "ghost@b.de" }) }),
);
expect(response.status).toBe(200);
expect(recordEmailWebhookEvent).not.toHaveBeenCalled();
});
});
describe("Microsoft Graph webhook", () => {
it("echoes the validation token as text/plain (subscription handshake)", async () => {
const response = await call(
microsoftAction,
new Request("https://app.example.test/webhooks/email/microsoft?validationToken=abc%20123", { method: "POST" }),
);
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toBe("text/plain");
await expect(response.text()).resolves.toBe("abc 123");
expect(recordEmailWebhookEvent).not.toHaveBeenCalled();
});
it("persists only notifications whose clientState matches the stored secret", async () => {
findMailboxByWebhookSubscription.mockResolvedValue({ id: "mb1", tenantId: "t1", ownerUserId: "u1", webhookClientState: "secret-1" });
const body = JSON.stringify({
value: [
{ subscriptionId: "sub1", clientState: "secret-1", changeType: "created", resource: "/me/messages/x", resourceData: { id: "x" } },
{ subscriptionId: "sub1", clientState: "WRONG", changeType: "created" },
],
});
const response = await call(microsoftAction, new Request("https://app.example.test/webhooks/email/microsoft", { method: "POST", body }));
expect(response.status).toBe(202);
expect(recordEmailWebhookEvent).toHaveBeenCalledTimes(1);
expect(recordEmailWebhookEvent).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: "t1", mailboxId: "mb1", provider: "microsoft", notificationPayload: expect.objectContaining({ resourceId: "x" }) }),
);
});
it("acks malformed bodies without persisting", async () => {
const response = await call(microsoftAction, new Request("https://app.example.test/webhooks/email/microsoft", { method: "POST", body: "not-json" }));
expect(response.status).toBe(202);
expect(recordEmailWebhookEvent).not.toHaveBeenCalled();
});
});