Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 58 additions & 20 deletions apps/web/src/app/api/ses_callback/route.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { env } from "~/env";
import { db } from "~/server/db";
import { logger } from "~/server/logger/log";
import { parseSesHook, SesHookParser } from "~/server/service/ses-hook-parser";
import { SesHookParser } from "~/server/service/ses-hook-parser";
import { SesSettingsService } from "~/server/service/ses-settings-service";
import { SnsNotificationMessage } from "~/types/aws-types";
import {
isSnsNotificationMessage,
isTrustedSnsSubscriptionUrl,
verifySnsMessageSignature,
} from "~/server/security/sns-message-validator";
import type { SnsNotificationMessage } from "~/types/aws-types";

export const dynamic = "force-dynamic";

Expand All @@ -12,16 +16,21 @@ export async function GET() {
}

export async function POST(req: Request) {
const data = await req.json();
let data: unknown;
try {
data = await req.json();
} catch {
return Response.json({ data: "Invalid JSON" }, { status: 400 });
}

console.log(data, data.Message);
if (!isSnsNotificationMessage(data)) {
return Response.json({ data: "Event is not valid" }, { status: 401 });
}

const isEventValid = await checkEventValidity(data);

console.log("Is event valid: ", isEventValid);

if (!isEventValid) {
return Response.json({ data: "Event is not valid" });
return Response.json({ data: "Event is not valid" }, { status: 401 });
}

if (data.Type === "SubscriptionConfirmation") {
Expand Down Expand Up @@ -50,10 +59,44 @@ export async function POST(req: Request) {
/**
* Handles the subscription confirmation event. called only once for a webhook
*/
async function handleSubscription(message: any) {
await fetch(message.SubscribeURL, {
method: "GET",
});
async function handleSubscription(message: SnsNotificationMessage) {
if (
!message.SubscribeURL ||
!isTrustedSnsSubscriptionUrl(message.SubscribeURL, message.TopicArn)
) {
return Response.json(
{ data: "Subscription URL is not valid" },
{ status: 400 },
);
}

try {
const response = await fetch(message.SubscribeURL, {
method: "GET",
redirect: "error",
signal: AbortSignal.timeout(5_000),
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.

if (!response.ok) {
logger.warn(
{ status: response.status, topicArn: message.TopicArn },
"SNS subscription confirmation failed",
);
return Response.json(
{ data: "Subscription confirmation failed" },
{ status: 502 },
);
}
} catch (error) {
logger.warn(
{ err: error, topicArn: message.TopicArn },
"SNS subscription confirmation request failed",
);
return Response.json(
{ data: "Subscription confirmation failed" },
{ status: 502 },
);
}

const topicArn = message.TopicArn as string;
const setting = await db.sesSetting.findFirst({
Expand Down Expand Up @@ -81,19 +124,14 @@ async function handleSubscription(message: any) {
}

/**
* A simple check to ensure that the event is from the correct topic
* Ensure the event is signed by SNS and belongs to a configured topic.
*/
async function checkEventValidity(message: SnsNotificationMessage) {
if (env.NODE_ENV === "development") {
return true;
}

const { TopicArn } = message;
const configuredTopicArn = await SesSettingsService.getTopicArns();

if (!configuredTopicArn.includes(TopicArn)) {
if (!configuredTopicArn.includes(message.TopicArn)) {
return false;
}

return true;
return verifySnsMessageSignature(message);
}
228 changes: 228 additions & 0 deletions apps/web/src/app/api/ses_callback/route.unit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
import { createSign, generateKeyPairSync } from "node:crypto";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import type { SnsNotificationMessage } from "~/types/aws-types";

const mocks = vi.hoisted(() => ({
getTopicArns: vi.fn(),
findSetting: vi.fn(),
updateSetting: vi.fn(),
invalidateCache: vi.fn(),
queue: vi.fn(),
}));

vi.mock("~/server/db", () => ({
db: {
sesSetting: {
findFirst: mocks.findSetting,
update: mocks.updateSetting,
},
},
}));

vi.mock("~/server/service/ses-settings-service", () => ({
SesSettingsService: {
getTopicArns: mocks.getTopicArns,
invalidateCache: mocks.invalidateCache,
},
}));

vi.mock("~/server/service/ses-hook-parser", () => ({
SesHookParser: {
queue: mocks.queue,
},
}));

import { POST } from "./route";

const topicArn = "arn:aws:sns:eu-west-1:123456789012:usesend-events";
const { privateKey, publicKey } = generateKeyPairSync("rsa", {
modulusLength: 2048,
});
const publicKeyPem = publicKey
.export({ type: "spki", format: "pem" })
.toString();

function signedNotification(): SnsNotificationMessage {
const message: SnsNotificationMessage = {
Type: "Notification",
MessageId: "11111111-2222-3333-4444-555555555555",
TopicArn: topicArn,
Subject: "Amazon SES Email Event Notification",
Message: '{"eventType":"Delivery"}',
Timestamp: "2026-08-22T12:34:56.000Z",
SignatureVersion: "2",
Signature: "",
SigningCertURL:
"https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-test.pem",
};
const payload = [
"Message",
"MessageId",
"Subject",
"Timestamp",
"TopicArn",
"Type",
]
.map(
(field) =>
`${field}\n${message[field as keyof SnsNotificationMessage]}\n`,
)
.join("");
const signer = createSign("RSA-SHA256");
signer.update(payload, "utf8");
signer.end();
message.Signature = signer.sign(privateKey, "base64");
return message;
}

function signedSubscriptionConfirmation(): SnsNotificationMessage {
const message: SnsNotificationMessage = {
Type: "SubscriptionConfirmation",
MessageId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
TopicArn: topicArn,
Message: "You have chosen to subscribe to the topic.",
Timestamp: "2026-08-22T12:34:56.000Z",
SignatureVersion: "2",
Signature: "",
SigningCertURL:
"https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-test.pem",
SubscribeURL:
"https://sns.eu-west-1.amazonaws.com/?Action=ConfirmSubscription&Token=test",
Token: "test-token",
};
const payload = [
"Message",
"MessageId",
"SubscribeURL",
"Timestamp",
"Token",
"TopicArn",
"Type",
]
.map(
(field) =>
`${field}\n${message[field as keyof SnsNotificationMessage]}\n`,
)
.join("");
const signer = createSign("RSA-SHA256");
signer.update(payload, "utf8");
signer.end();
message.Signature = signer.sign(privateKey, "base64");
return message;
}

function requestFor(message: SnsNotificationMessage) {
return new Request("https://send.growthpath.systems/api/ses_callback", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(message),
});
}

describe("SES callback", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getTopicArns.mockResolvedValue([topicArn]);
mocks.findSetting.mockResolvedValue({ id: "setting_1" });
mocks.updateSetting.mockResolvedValue({ id: "setting_1" });
mocks.queue.mockResolvedValue(true);
});

afterEach(() => {
vi.unstubAllGlobals();
});

it("queues a legitimately signed SNS notification", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(new Response(publicKeyPem, { status: 200 })),
);
const message = signedNotification();

const response = await POST(requestFor(message));

expect(response.status).toBe(200);
expect(mocks.queue).toHaveBeenCalledWith({
event: { eventType: "Delivery" },
messageId: message.MessageId,
});
});

it("rejects a tampered notification before it reaches the event queue", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(new Response(publicKeyPem, { status: 200 })),
);
const message = signedNotification();
message.Message = '{"eventType":"Complaint"}';

const response = await POST(requestFor(message));

expect(response.status).toBe(401);
expect(mocks.queue).not.toHaveBeenCalled();
});

it("does not follow a subscription URL from an unsigned request", async () => {
const fetchMock = vi
.fn()
.mockResolvedValue(new Response(publicKeyPem, { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
const message = signedNotification();
message.Type = "SubscriptionConfirmation";
message.SubscribeURL = "https://internal.example/metadata";
message.Token = "attacker-token";

const response = await POST(requestFor(message));

expect(response.status).toBe(401);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith(
new URL(message.SigningCertURL),
expect.objectContaining({ redirect: "error" }),
);
});

it("confirms an authentic SNS subscription before recording success", async () => {
const message = signedSubscriptionConfirmation();
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response(publicKeyPem, { status: 200 }))
.mockResolvedValueOnce(new Response(null, { status: 200 }));
vi.stubGlobal("fetch", fetchMock);

const response = await POST(requestFor(message));

expect(response.status).toBe(200);
expect(fetchMock).toHaveBeenNthCalledWith(
2,
message.SubscribeURL,
expect.objectContaining({
redirect: "error",
signal: expect.any(AbortSignal),
}),
);
expect(mocks.updateSetting).toHaveBeenCalledWith({
where: { id: "setting_1" },
data: { callbackSuccess: true },
});
expect(mocks.invalidateCache).toHaveBeenCalledOnce();
});

it("does not record a failed SNS subscription confirmation", async () => {
const message = signedSubscriptionConfirmation();
vi.stubGlobal(
"fetch",
vi
.fn()
.mockResolvedValueOnce(new Response(publicKeyPem, { status: 200 }))
.mockResolvedValueOnce(new Response(null, { status: 500 })),
);

const response = await POST(requestFor(message));

expect(response.status).toBe(502);
expect(mocks.updateSetting).not.toHaveBeenCalled();
expect(mocks.invalidateCache).not.toHaveBeenCalled();
});
});
Loading