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.

feat(cdp): fail closed when minting email tracking codes without a key (#67397)

Daniel Marchukbaffe1004426
diff --git a/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts b/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts
index 9fb74438052c..04a30470c82b 100644
--- a/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/tracking-code.test.ts
@@ -1,6 +1,6 @@
import { defaultConfig } from '~/common/config/config'
-import { EmailTrackingCodeSigner, trackingCodeMintCounter } from './tracking-code'
+import { EmailTrackingCodeSigner, hasEmailSigningKey, trackingCodeMintCounter } from './tracking-code'
const TRACKING_URL = 'http://localhost:8010'
@@ -275,11 +275,11 @@ describe('email tracking code', () => {
expect(spacedSigner.parse(code)?.format).toBe('signed')
})
- it('emits unsigned codes when no signing key is configured', () => {
+ it('fails closed instead of minting an unsigned code when no signing key is configured', () => {
const unsignedSigner = new EmailTrackingCodeSigner('', TRACKING_URL)
- const code = unsignedSigner.generate({ functionId: 'fn', id: 'inv', teamId: 1 })
- expect(code).not.toContain('.')
- expect(unsignedSigner.parse(code)?.format).toBe('unsigned')
+ expect(() => unsignedSigner.generate({ functionId: 'fn', id: 'inv', teamId: 1 })).toThrow(
+ /no signing key configured/
+ )
})
})
@@ -289,15 +289,36 @@ describe('email tracking code', () => {
return metric.values.find((v) => v.labels.format === format)?.value ?? 0
}
- // The keyless branch is silent without this counter; it is the proof that fail-closed (#62624)
- // is safe to enable, so guard that generate() labels each minted code correctly.
+ it('counts a signed mint when a key is configured', async () => {
+ const before = await mintCount('signed')
+ new EmailTrackingCodeSigner(defaultConfig.ENCRYPTION_SALT_KEYS, TRACKING_URL).generate({
+ functionId: 'fn',
+ id: 'inv',
+ teamId: 1,
+ })
+ expect(await mintCount('signed')).toBe(before + 1)
+ })
+
+ // Fail-closed still records the attempt before throwing, so a bypassed boot guard stays attributable.
+ it('records an unsigned mint before failing closed when no key is configured', async () => {
+ const before = await mintCount('unsigned')
+ expect(() =>
+ new EmailTrackingCodeSigner('', TRACKING_URL).generate({ functionId: 'fn', id: 'inv', teamId: 1 })
+ ).toThrow()
+ expect(await mintCount('unsigned')).toBe(before + 1)
+ })
+ })
+
+ describe('hasEmailSigningKey', () => {
+ // Guards the boot-time check: a whitespace/comma-only value must read as "no key" so a keyless
+ // email deployment refuses to start, while a real (possibly space-padded) key reads as present.
it.each([
- { name: 'signed when a key is configured', keys: defaultConfig.ENCRYPTION_SALT_KEYS, format: 'signed' },
- { name: 'unsigned when no key is configured', keys: '', format: 'unsigned' },
- ])('counts a mint as $name', async ({ keys, format }) => {
- const before = await mintCount(format)
- new EmailTrackingCodeSigner(keys, TRACKING_URL).generate({ functionId: 'fn', id: 'inv', teamId: 1 })
- expect(await mintCount(format)).toBe(before + 1)
+ { name: 'a configured key', keys: 'a-signing-key-000000000000000000', expected: true },
+ { name: 'a space-padded key in a rotation list', keys: 'first-key-0000, second-key-0000', expected: true },
+ { name: 'an empty string', keys: '', expected: false },
+ { name: 'whitespace and commas only', keys: ' , ', expected: false },
+ ])('is $expected for $name', ({ keys, expected }) => {
+ expect(hasEmailSigningKey(keys)).toBe(expected)
})
})
})
diff --git a/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts b/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
index d61358da68f2..876635e7febc 100644
--- a/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
+++ b/nodejs/src/cdp/services/messaging/helpers/tracking-code.ts
@@ -20,10 +20,10 @@ export const trackingCodeFormatCounter = new Counter({
// Mint-time signal: counts every code generate() produces, labelled by whether a signing key was
// available. Unlike the parse-time counter above (which only sees codes that come back via the SES
-// webhook or click endpoints), this fires on the send path itself, so a sustained `unsigned` rate
-// pinpoints an email-sending deployment running without ENCRYPTION_SALT_KEYS. Watching this reach
-// zero is the prerequisite for making generate() fail closed (#62624). Note it counts per generate()
-// call (header + pixel + each redirect link), not per email, so it is a rate signal, not an email count.
+// webhook or click endpoints), this fires on the send path itself. Now that generate() fails closed,
+// an `unsigned` sample means a keyless deployment attempted a mint right before the send was refused —
+// a config alarm, not a benign tail. Note it counts per generate() call (header + pixel + each redirect
+// link), not per email, so it is a rate signal, not an email count.
export const trackingCodeMintCounter = new Counter({
name: 'email_tracking_code_mint_total',
help: 'Count of email tracking codes minted by signature format (signed when a key is configured)',
@@ -55,6 +55,21 @@ export type TrackingInvocation = Pick<CyclotronJobInvocationHogFunction, 'functi
export type TrackingCodeFormat = 'signed' | 'unsigned'
+// Parses the comma-separated ENCRYPTION_SALT_KEYS into the usable key list. Shared by the signer
+// and the boot-time guard so "is a signing key configured?" has a single definition.
+function parseSigningKeys(encryptionSaltKeys: string): string[] {
+ return (encryptionSaltKeys || '')
+ .split(',')
+ .map((key) => key.trim())
+ .filter(Boolean)
+}
+
+// Whether at least one email tracking-code signing key is configured. The boot-time guard uses this
+// to refuse to start an email-sending deployment that would otherwise mint unsigned tracking links.
+export function hasEmailSigningKey(encryptionSaltKeys: string): boolean {
+ return parseSigningKeys(encryptionSaltKeys).length > 0
+}
+
export type ParsedTrackingCode = {
functionId: string
invocationId: string
@@ -77,10 +92,7 @@ export class EmailTrackingCodeSigner {
encryptionSaltKeys: string,
private trackingUrl: string
) {
- this.signingKeys = (encryptionSaltKeys || '')
- .split(',')
- .map((key) => key.trim())
- .filter(Boolean)
+ this.signingKeys = parseSigningKeys(encryptionSaltKeys)
}
private signPayload(payload: string, key: string): string {
@@ -166,11 +178,14 @@ export class EmailTrackingCodeSigner {
`${invocation.functionId}:${invocation.id}:${invocation.teamId}:${actionId}:${parentRunId}:${isTest ? '1' : ''}:${distinctId}`
)
if (this.signingKeys.length === 0) {
- // Fail open while signing rolls out so sends never break; tighten to throw once enforced (#62624).
- // The mint counter makes this branch observable so we can confirm it is never hit in prod
- // before flipping to fail-closed.
+ // Fail closed (#62624): a deployment with no signing key must never mint unsigned tracking
+ // links. Email-sending deployments are guarded at boot (see hasEmailSigningKey), so this is
+ // unreachable in prod; the counter still records the attempt before we refuse, keeping the
+ // failure attributable if the guard is ever bypassed.
trackingCodeMintCounter.inc({ format: 'unsigned' })
- return payload
+ throw new Error(
+ 'Cannot mint email tracking code: no signing key configured (ENCRYPTION_SALT_KEYS is empty)'
+ )
}
trackingCodeMintCounter.inc({ format: 'signed' })
return `${payload}.${this.signPayload(payload, this.signingKeys[0])}`
diff --git a/nodejs/src/server.ts b/nodejs/src/server.ts
index 0dfc398806c5..5d893286b1da 100644
--- a/nodejs/src/server.ts
+++ b/nodejs/src/server.ts
@@ -46,6 +46,7 @@ import { CyclotronJobQueueKafka } from './cdp/services/job-queue/job-queue-kafka
import { CyclotronJobQueuePostgres } from './cdp/services/job-queue/job-queue-postgres'
import { CyclotronJobQueuePostgresV2 } from './cdp/services/job-queue/job-queue-postgres-v2'
import { CyclotronJobQueueRateLimitedPostgresV2 } from './cdp/services/job-queue/job-queue-rate-limited-postgres-v2'
+import { hasEmailSigningKey } from './cdp/services/messaging/helpers/tracking-code'
import { createSesRateLimiterValkeyPool } from './cdp/services/rate-limiter/rate-limiter-valkey-pool'
import { RateLimiterService } from './cdp/services/rate-limiter/rate-limiter.service'
import { EncryptedFields } from './cdp/utils/encryption-utils'
@@ -305,6 +306,17 @@ export class PluginServer implements NodeServer {
})
}
+ // Boot-time guard: an email-sending deployment must carry a signing key, otherwise every send
+ // would either mint an unsigned tracking link or (now that generate() fails closed) fail. Refuse
+ // to start instead of degrading silently. Both email workers below sign tracking codes.
+ const isEmailWorker = capabilities.cdpCyclotronWorkerEmail || capabilities.cdpCyclotronWorkerEmailLegacyPg
+ if (isEmailWorker && !hasEmailSigningKey(this.config.ENCRYPTION_SALT_KEYS)) {
+ throw new Error(
+ 'Email worker requires ENCRYPTION_SALT_KEYS to sign tracking codes — refusing to start. ' +
+ 'Configure ENCRYPTION_SALT_KEYS so outbound emails never mint unsigned tracking links.'
+ )
+ }
+
// Transitional drain for email jobs stranded on the legacy V1 queue — the email worker
// run against V1, sending inline. Delete once V1 'email' throughput is ~0.
if (capabilities.cdpCyclotronWorkerEmailLegacyPg) {