Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(cdp): auto-confirm SES SNS subscriptions on real AWS payloads (#78745)

Harley Alexander434ac861188d
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
index 200d80cacb32..fc6c9f4e901d 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.test.ts
@@ -437,61 +437,70 @@ describe('SesWebhookHandler', () => {
expect(result.metrics).toEqual([])
})
+ // Real SNS SubscriptionConfirmation shape: SubscribeURL is a top-level envelope field and
+ // Message is human-readable text, not JSON.
+ const buildConfirmationEnvelope = (subscribeUrl: string): Record<string, any> => ({
+ Type: 'SubscriptionConfirmation',
+ MessageId: 'sns-msg-1',
+ Token: 'token-123',
+ TopicArn: 'arn:aws:sns:us-east-1:123456789012:ses-topic',
+ Message:
+ 'You have chosen to subscribe to the topic arn:aws:sns:us-east-1:123456789012:ses-topic.\nTo confirm the subscription, visit the SubscribeURL included in this message.',
+ SubscribeURL: subscribeUrl,
+ Timestamp: '2025-10-03T12:10:00Z',
+ SignatureVersion: '1',
+ Signature: 'fake',
+ SigningCertURL: 'https://sns.us-east-1.amazonaws.com/cert.pem',
+ })
+
it('confirms SubscriptionConfirmation with valid SNS SubscribeURL', async () => {
const fetchSpy = jest.spyOn(handler as any, 'fetchText').mockResolvedValue('')
- const snsEnvelope = {
- Type: 'SubscriptionConfirmation',
- MessageId: 'sns-msg-1',
- Token: 'token-123',
- TopicArn: 'arn:aws:sns:us-east-1:123456789012:ses-topic',
- Message: JSON.stringify({
- SubscribeURL:
- 'https://sns.us-east-1.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-east-1:123456789012:ses-topic&Token=token-123',
- }),
- Timestamp: '2025-10-03T12:10:00Z',
- SignatureVersion: '1',
- Signature: 'fake',
- SigningCertURL: 'https://sns.us-east-1.amazonaws.com/cert.pem',
- }
+ const snsEnvelope = buildConfirmationEnvelope(
+ 'https://sns.us-east-1.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-east-1:123456789012:ses-topic&Token=token-123'
+ )
const result = await handler.handleWebhook({ body: snsEnvelope, headers: {}, verifySignature: false })
expect(result.status).toBe(200)
expect(fetchSpy).toHaveBeenCalledWith(expect.stringContaining('https://sns.us-east-1.amazonaws.com/'))
fetchSpy.mockRestore()
})
- it('rejects SubscriptionConfirmation with non-SNS SubscribeURL', async () => {
- const snsEnvelope = {
- Type: 'SubscriptionConfirmation',
- MessageId: 'sns-msg-1',
- Token: 'token-123',
- TopicArn: 'arn:aws:sns:us-east-1:123456789012:ses-topic',
- Message: JSON.stringify({
- SubscribeURL: 'https://evil.lhr.life/latest/meta-data/iam/security-credentials/role',
- }),
- Timestamp: '2025-10-03T12:10:00Z',
- SignatureVersion: '1',
- Signature: 'fake',
- SigningCertURL: 'https://sns.us-east-1.amazonaws.com/cert.pem',
- }
- const result = await handler.handleWebhook({ body: snsEnvelope, headers: {}, verifySignature: false })
- expect(result.status).toBe(403)
+ it('confirms a signed SubscriptionConfirmation end to end (SubscribeURL is part of the signed string)', async () => {
+ const { generateKeyPairSync, createSign } = jest.requireActual<typeof import('node:crypto')>('node:crypto')
+ const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 })
+ const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString()
+
+ const envelope = buildConfirmationEnvelope(
+ 'https://sns.us-east-1.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-east-1:123456789012:ses-topic&Token=token-123'
+ )
+ // String to sign per AWS SNS SignatureVersion=1 for SubscriptionConfirmation:
+ // alphabetical key/value lines incl. the top-level SubscribeURL.
+ const stringToSign =
+ ['Message', 'MessageId', 'SubscribeURL', 'Timestamp', 'Token', 'TopicArn', 'Type']
+ .map((k) => `${k}\n${envelope[k]}`)
+ .join('\n') + '\n'
+ const sign = createSign('RSA-SHA1')
+ sign.update(stringToSign, 'utf8')
+ envelope.Signature = sign.sign(privateKey, 'base64')
+
+ const fetchSpy = jest
+ .spyOn(handler as any, 'fetchText')
+ .mockImplementation((url) => Promise.resolve((url as string).endsWith('.pem') ? publicKeyPem : ''))
+
+ const result = await handler.handleWebhook({ body: envelope, headers: {}, verifySignature: true })
+ expect(result.status).toBe(200)
+ expect(fetchSpy).toHaveBeenCalledWith(envelope.SubscribeURL)
+ fetchSpy.mockRestore()
})
- it('rejects SubscriptionConfirmation with HTTP SubscribeURL', async () => {
- const snsEnvelope = {
- Type: 'SubscriptionConfirmation',
- MessageId: 'sns-msg-1',
- Token: 'token-123',
- TopicArn: 'arn:aws:sns:us-east-1:123456789012:ses-topic',
- Message: JSON.stringify({
- SubscribeURL: 'http://sns.us-east-1.amazonaws.com/subscribe',
- }),
- Timestamp: '2025-10-03T12:10:00Z',
- SignatureVersion: '1',
- Signature: 'fake',
- SigningCertURL: 'https://sns.us-east-1.amazonaws.com/cert.pem',
- }
- const result = await handler.handleWebhook({ body: snsEnvelope, headers: {}, verifySignature: false })
+ it.each([
+ ['non-SNS SubscribeURL', 'https://evil.lhr.life/latest/meta-data/iam/security-credentials/role'],
+ ['HTTP SubscribeURL', 'http://sns.us-east-1.amazonaws.com/subscribe'],
+ ])('rejects SubscriptionConfirmation with %s', async (_label, subscribeUrl) => {
+ const result = await handler.handleWebhook({
+ body: buildConfirmationEnvelope(subscribeUrl),
+ headers: {},
+ verifySignature: false,
+ })
expect(result.status).toBe(403)
})
@@ -747,7 +756,16 @@ describe('SesWebhookHandler', () => {
Type: envelopeType,
MessageId: 'sns-msg-1',
TopicArn: topicArn,
- Message: envelopeType === 'Notification' ? JSON.stringify(innerRecord) : JSON.stringify({}),
+ Message:
+ envelopeType === 'Notification'
+ ? JSON.stringify(innerRecord)
+ : `You have chosen to subscribe to the topic ${topicArn}.`,
+ ...(envelopeType === 'SubscriptionConfirmation'
+ ? {
+ Token: 'token-123',
+ SubscribeURL: 'https://sns.us-east-1.amazonaws.com/?Action=ConfirmSubscription',
+ }
+ : {}),
Timestamp: '2025-10-03T12:10:00Z',
SignatureVersion: '1',
Signature: 'stubbed',
diff --git a/nodejs/src/cdp/services/messaging/helpers/ses.ts b/nodejs/src/cdp/services/messaging/helpers/ses.ts
index 2c633e1ff25a..4d5fabc67b83 100644
--- a/nodejs/src/cdp/services/messaging/helpers/ses.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/ses.ts
@@ -18,7 +18,10 @@ const SnsEnvelopeSchema = z.object({
Token: z.string().optional(),
TopicArn: z.string(),
Subject: z.string().optional(),
- Message: z.string(), // either SES event JSON (Notification) or a confirmation message
+ Message: z.string(), // either SES event JSON (Notification) or human-readable confirmation text
+ // Top-level on (Un)SubscribeConfirmation payloads and part of their signed string, so it must
+ // survive schema parsing for signature verification to succeed.
+ SubscribeURL: z.string().optional(),
Timestamp: z.string(),
SignatureVersion: z.enum(['1']),
Signature: z.string(),
@@ -394,7 +397,7 @@ export class SesWebhookHandler {
} else if (m.Type === 'SubscriptionConfirmation' || m.Type === 'UnsubscribeConfirmation') {
pushKV('Message', m.Message)
pushKV('MessageId', m.MessageId)
- pushKV('SubscribeURL', (m as any).SubscribeURL) // present in confirmation payload body, not in envelope schema
+ pushKV('SubscribeURL', m.SubscribeURL)
pushKV('Timestamp', m.Timestamp)
pushKV('Token', m.Token!)
pushKV('TopicArn', m.TopicArn)
@@ -484,19 +487,19 @@ export class SesWebhookHandler {
// Handle confirmation flow
if (parsed.mode === 'sns' && 'envelope' in parsed && parsed.envelope?.Type === 'SubscriptionConfirmation') {
logger.info('[SesWebhookHandler] confirming subscription', { envelope: parsed.envelope })
- // Confirm by visiting SubscribeURL (contained in the *message JSON*, not envelope.Message field here)
- // We need to fetch the inner message JSON to get SubscribeURL
- const env = parsed.envelope
- const inner = parseJSON(env.Message) as { SubscribeURL?: string }
- logger.info('[SesWebhookHandler] confirming subscription', { inner })
- if (inner.SubscribeURL) {
- if (!this.isValidSnsSubscribeUrl(inner.SubscribeURL)) {
+ // Confirm by visiting the top-level SubscribeURL field; Message is human-readable text here.
+ const subscribeUrl = parsed.envelope.SubscribeURL
+ if (subscribeUrl) {
+ if (!this.isValidSnsSubscribeUrl(subscribeUrl)) {
logger.warn('[SesWebhookHandler] Invalid SubscribeURL, rejecting', {
- url: inner.SubscribeURL,
+ url: subscribeUrl,
})
return { status: 403, body: { error: 'Invalid SubscribeURL' } }
}
- await this.fetchText(inner.SubscribeURL)
+ await this.fetchText(subscribeUrl)
+ } else {
+ logger.warn('[SesWebhookHandler] SubscriptionConfirmation without SubscribeURL - cannot confirm')
+ return { status: 400, body: { error: 'Missing SubscribeURL' } }
}
return { status: 200, body: { ok: true } }
}