Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/webhooks.email.test.ts
T

188 lines
8.8 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 resolveGmailMailboxRlsIdentities = vi.fn();
const resolveMicrosoftMailboxRlsIdentity = vi.fn();
const getGmailWebhookMailbox = vi.fn();
const getMicrosoftWebhookMailbox = vi.fn();
const recordEmailWebhookEvent = vi.fn();
vi.mock("@hivegrid/db/rls-resolvers.server", () => ({
resolveGmailMailboxRlsIdentities: (...args: unknown[]) => resolveGmailMailboxRlsIdentities(...args),
resolveMicrosoftMailboxRlsIdentity: (...args: unknown[]) => resolveMicrosoftMailboxRlsIdentity(...args),
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({
runWithRlsContext: (_context: unknown, callback: () => unknown) => callback(),
}));
vi.mock("~/modules/emailInbox/db/emailInbox.db.server", () => ({
getGmailWebhookMailbox: (...args: unknown[]) => getGmailWebhookMailbox(...args),
getMicrosoftWebhookMailbox: (...args: unknown[]) => getMicrosoftWebhookMailbox(...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";
resolveGmailMailboxRlsIdentities.mockResolvedValue([]);
resolveMicrosoftMailboxRlsIdentity.mockResolvedValue(null);
});
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 () => {
resolveGmailMailboxRlsIdentities.mockResolvedValue([{ tenantId: "t1", resourceId: "mb1", userId: "u1" }]);
getGmailWebhookMailbox.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(resolveGmailMailboxRlsIdentities).toHaveBeenCalledWith("gmail", "a@b.de");
expect(getGmailWebhookMailbox).toHaveBeenCalledWith({ tenantId: "t1", ownerUserId: "u1", mailboxId: "mb1", emailAddress: "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 () => {
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();
});
it("persists every exact mailbox when the same Gmail address belongs to multiple tenants", async () => {
resolveGmailMailboxRlsIdentities.mockResolvedValue([
{ tenantId: "t1", resourceId: "mb1", userId: "u1" },
{ tenantId: "t2", resourceId: "mb2", userId: "u2" },
]);
getGmailWebhookMailbox
.mockResolvedValueOnce({ id: "mb1", tenantId: "t1", ownerUserId: "u1" })
.mockResolvedValueOnce({ id: "mb2", tenantId: "t2", ownerUserId: "u2" });
const response = await call(
googleAction,
new Request("https://app.example.test/webhooks/email/google?token=shared-token", {
method: "POST",
body: pubsubBody({ emailAddress: "shared@example.test", historyId: 9 }),
}),
);
expect(response.status).toBe(200);
expect(recordEmailWebhookEvent).toHaveBeenCalledTimes(2);
expect(recordEmailWebhookEvent).toHaveBeenNthCalledWith(2, expect.objectContaining({ tenantId: "t2", mailboxId: "mb2" }));
});
it("acks a stale Gmail identity when its exact scoped re-read fails", async () => {
resolveGmailMailboxRlsIdentities.mockResolvedValue([{ tenantId: "t1", resourceId: "mb1", userId: "u1" }]);
getGmailWebhookMailbox.mockResolvedValue(null);
const response = await call(
googleAction,
new Request("https://app.example.test/webhooks/email/google?token=shared-token", {
method: "POST",
body: pubsubBody({ emailAddress: "shared@example.test" }),
}),
);
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 () => {
resolveMicrosoftMailboxRlsIdentity.mockImplementation(async (_subscriptionId: string, clientState: string) =>
clientState === "secret-1" ? { tenantId: "t1", resourceId: "mb1", userId: "u1" } : null,
);
getMicrosoftWebhookMailbox.mockResolvedValue({ id: "mb1", tenantId: "t1", ownerUserId: "u1" });
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" }) }),
);
expect(getMicrosoftWebhookMailbox).toHaveBeenCalledWith({
tenantId: "t1",
ownerUserId: "u1",
mailboxId: "mb1",
subscriptionId: "sub1",
clientState: "secret-1",
});
});
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();
});
it("acks malformed notification elements without querying a mailbox", async () => {
const body = JSON.stringify({ value: [null, 42, [], { subscriptionId: ["sub1"], clientState: "secret-1" }] });
const response = await call(microsoftAction, new Request("https://app.example.test/webhooks/email/microsoft", { method: "POST", body }));
expect(response.status).toBe(202);
expect(resolveMicrosoftMailboxRlsIdentity).not.toHaveBeenCalled();
expect(recordEmailWebhookEvent).not.toHaveBeenCalled();
});
it("rejects an oversized notification batch before any database lookup", async () => {
const notification = { subscriptionId: "sub1", clientState: "secret-1" };
const body = JSON.stringify({ value: Array.from({ length: 101 }, () => notification) });
const response = await call(microsoftAction, new Request("https://app.example.test/webhooks/email/microsoft", { method: "POST", body }));
expect(response.status).toBe(202);
expect(resolveMicrosoftMailboxRlsIdentity).not.toHaveBeenCalled();
expect(recordEmailWebhookEvent).not.toHaveBeenCalled();
});
});