: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cdp): share one apns provider token across pods (#113411)
Daniel Marchuke0a50dac2b51
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts b/nodejs/src/cdp/services/messaging/push-notification.service.test.tsindex cfad579a7aa1..aa66c119843b 100644--- a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts+++ b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts@@ -1,4 +1,4 @@-import { generateKeyPairSync } from 'crypto'+import { createHash, generateKeyPairSync } from 'crypto'import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '~/cdp/_tests/examples'import { createExampleInvocation, createHogFunction } from '~/cdp/_tests/fixtures'@@ -93,7 +93,10 @@ describe('PushNotificationService', () => {}valkeyStore = new Map<string, string>()- mockValkeySet = jest.fn((key: string, value: string) => {+ mockValkeySet = jest.fn((key: string, value: string, ...args: (string | number)[]) => {+ if (args.includes('NX') && valkeyStore.has(key)) {+ return null+ }valkeyStore.set(key, value)return 'OK'})@@ -662,8 +665,130 @@ describe('PushNotificationService', () => {expect.stringContaining('@posthog/apns-provider-jwt/'),expect.any(String),'EX',- 2700+ 2700,+ 'NX'+ )+ })++ it.each([+ ['concurrent sends on one pod', 1],+ ['concurrent sends across pods sharing Valkey', 3],+ ])('presents one APNS provider token for %s', async (_name, podCount) => {+ const pods = Array.from(+ { length: podCount },+ () => new PushNotificationService(integrationManager, encryptedFields, fetchUtils, mockValkey)+ )+ mockTrackedFetch.mockResolvedValue({+ fetchError: null,+ fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },+ fetchDuration: 15,+ })+ mockTrackedFetch.mockClear()++ await Promise.all(+ Array.from({ length: 20 }, (_, i) =>+ pods[i % podCount].executeSendPushNotification(+ createSendPushNotificationInvocation({+ '$device_push_subscription_com.example.app': encryptedFields.encrypt(`apns-device-${i}`),+ })+ )+ )+ )++ const authHeaders = new Set(+ mockTrackedFetch.mock.calls.map((call: any) => call[0].fetchParams.headers.Authorization))+ expect(mockTrackedFetch).toHaveBeenCalledTimes(20)+ expect(authHeaders.size).toBe(1)+ })++ it('expires an adopted APNS token by its own issue time, not by when this pod read it', async () => {+ const nowMs = 1_800_000_000_000+ jest.spyOn(Date, 'now').mockReturnValue(nowMs)+ const b64 = (o: object): string => Buffer.from(JSON.stringify(o)).toString('base64url')+ const fortyMinutesOld = `${b64({ alg: 'ES256', kid: 'KEY123' })}.${b64({ iss: 'TEAM456', iat: nowMs / 1000 - 40 * 60 })}.sig`+ const cacheKey = `@posthog/apns-provider-jwt/${createHash('sha256').update(`TEAM456:KEY123:${testEcKey}`).digest('hex')}`+ valkeyStore.set(cacheKey, fortyMinutesOld)++ let valkeyUp = true+ let firstReadFails = true+ const flakyValkey = {+ useClient: jest.fn((opts: { name: string }, fn: any) => {+ if (!valkeyUp) {+ return null+ }+ if (opts.name === 'apns-jwt-read' && firstReadFails) {+ firstReadFails = false+ return null+ }+ return fn({ get: (key: string) => valkeyStore.get(key) ?? null, set: mockValkeySet })+ }),+ } as any+ const pod = new PushNotificationService(integrationManager, encryptedFields, fetchUtils, flakyValkey)+ mockTrackedFetch.mockResolvedValue({+ fetchError: null,+ fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },+ fetchDuration: 15,+ })+ mockTrackedFetch.mockClear()+ const send = (): Promise<any> =>+ pod.executeSendPushNotification(+ createSendPushNotificationInvocation({+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),+ })+ )++ await send()+ valkeyUp = false+ jest.spyOn(Date, 'now').mockReturnValue(nowMs + 10 * 60 * 1000)+ await send()++ const authHeaders = mockTrackedFetch.mock.calls.map(+ (call: any) => call[0].fetchParams.headers.Authorization+ )+ expect(authHeaders[0]).toBe(`bearer ${fortyMinutesOld}`)+ expect(authHeaders[1]).not.toBe(`bearer ${fortyMinutesOld}`)+ })++ it('keeps presenting the shared APNS token after a read misses it during a Valkey fault', async () => {+ const b64 = (o: object): string => Buffer.from(JSON.stringify(o)).toString('base64url')+ const shared = `${b64({ alg: 'ES256', kid: 'KEY123' })}.${b64({ iss: 'TEAM456', iat: Math.floor(Date.now() / 1000) })}.sig`+ const cacheKey = `@posthog/apns-provider-jwt/${createHash('sha256').update(`TEAM456:KEY123:${testEcKey}`).digest('hex')}`+ valkeyStore.set(cacheKey, shared)++ // The first send misses both reads, loses SET NX to the shared token and falls back to its own.+ const readUp = [false, false, true, false]+ const flakyValkey = {+ useClient: jest.fn((opts: { name: string }, fn: any) => {+ if (opts.name === 'apns-jwt-read' && !readUp.shift()) {+ return null+ }+ return fn({ get: (key: string) => valkeyStore.get(key) ?? null, set: mockValkeySet })+ }),+ } as any+ const pod = new PushNotificationService(integrationManager, encryptedFields, fetchUtils, flakyValkey)+ mockTrackedFetch.mockResolvedValue({+ fetchError: null,+ fetchResponse: { status: 200, text: () => Promise.resolve(''), dump: () => Promise.resolve() },+ fetchDuration: 15,+ })+ mockTrackedFetch.mockClear()+ const send = (): Promise<any> =>+ pod.executeSendPushNotification(+ createSendPushNotificationInvocation({+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),+ })+ )++ await send()+ await send()+ await send()++ const authHeaders = mockTrackedFetch.mock.calls.map(+ (call: any) => call[0].fetchParams.headers.Authorization+ )+ expect(authHeaders[0]).not.toBe(`bearer ${shared}`)+ expect(authHeaders.slice(1)).toEqual([`bearer ${shared}`, `bearer ${shared}`])})it('reuses the pod-local APNS token when Valkey is unavailable', async () => {@@ -691,15 +816,15 @@ describe('PushNotificationService', () => {)mockTrackedFetch.mockClear()- await send()+ await Promise.all([send(), send(), send()])await send()const authHeaders = mockTrackedFetch.mock.calls.map((call: any) => call[0].fetchParams.headers.Authorization)- expect(authHeaders).toHaveLength(2)+ expect(authHeaders).toHaveLength(4)expect(authHeaders[0]).toEqual(expect.stringContaining('bearer '))- expect(authHeaders[0]).toBe(authHeaders[1])+ expect(new Set(authHeaders).size).toBe(1)})it('sets apns-priority to 5 for passive interruption level', async () => {diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.ts b/nodejs/src/cdp/services/messaging/push-notification.service.tsindex b6ff3016bb04..e0ba11e7b834 100644--- a/nodejs/src/cdp/services/messaging/push-notification.service.ts+++ b/nodejs/src/cdp/services/messaging/push-notification.service.ts@@ -69,6 +69,15 @@ const pushNotificationRescheduledCounter = new Counter({// keyed by the auth key id so the whole fleet reuses one token per key rather than minting one per send.const APNS_JWT_CACHE_PREFIX = '@posthog/apns-provider-jwt/'const APNS_JWT_TTL_SECONDS = 45 * 60++function apnsJwtIssuedAtMs(jwt: string): number | null {+ try {+ const iat = parseJSON(Buffer.from(jwt.split('.')[1], 'base64url').toString()).iat+ return typeof iat === 'number' ? iat * 1000 : null+ } catch {+ return null+ }+}// Apple asks providers to keep a connection open for hours to days, and treats rapid reconnects as abuse. undici// sends an HTTP/2 ping every 60 s by default, which keeps the egress proxy tunnel open across the idle window.const APNS_IDLE_TIMEOUT_MS = 60 * 60 * 1000@@ -204,6 +213,7 @@ export class PushNotificationService {// to one token per pod per TTL. It is a fallback, not the cache: Valkey is still read first, so the// fleet normally shares one token per key.private apnsJwtLocalCache = new Map<string, { jwt: string; expiresAtMs: number }>()+ private apnsJwtInFlight = new Map<string, Promise<string>>()@instrumented('push-notification.executeSendPushNotification')async executeSendPushNotification(@@ -690,10 +700,25 @@ export class PushNotificationService {const keyFingerprint = createHash('sha256').update(`${teamId}:${keyId}:${signingKey}`).digest('hex')const cacheKey = `${APNS_JWT_CACHE_PREFIX}${keyFingerprint}`+ const inFlight = this.apnsJwtInFlight.get(cacheKey)+ if (inFlight) {+ return inFlight+ }+ const lookup = this.resolveApnsJwt(cacheKey, teamId, keyId, signingKey).finally(() =>+ this.apnsJwtInFlight.delete(cacheKey)+ )+ this.apnsJwtInFlight.set(cacheKey, lookup)+ return lookup+ }++ private async resolveApnsJwt(cacheKey: string, teamId: string, keyId: string, signingKey: string): Promise<string> {const cached = await this.valkey.useClient({ name: 'apns-jwt-read', failOpen: true }, (client) =>client.get(cacheKey))if (cached) {+ if (this.apnsJwtLocalCache.get(cacheKey)?.jwt !== cached) {+ this.rememberApnsJwtLocally(cacheKey, cached)+ }return cached}@@ -709,18 +734,28 @@ export class PushNotificationService {const sign = createSign('SHA256')sign.update(signingInput)const signature = sign.sign({ key: signingKey, dsaEncoding: 'ieee-p1363' }, 'base64url')- const jwt = `${signingInput}.${signature}`+ const minted = `${signingInput}.${signature}`- this.rememberApnsJwtLocally(cacheKey, jwt)- await this.valkey.useClient({ name: 'apns-jwt-write', failOpen: true }, (client) =>- client.set(cacheKey, jwt, 'EX', APNS_JWT_TTL_SECONDS)+ // ES256 signatures are randomized, so pods that miss together mint different tokens. Keep the first.+ const stored = await this.valkey.useClient({ name: 'apns-jwt-write', failOpen: true }, (client) =>+ client.set(cacheKey, minted, 'EX', APNS_JWT_TTL_SECONDS, 'NX'))+ let jwt = minted+ if (stored !== 'OK') {+ const winner = await this.valkey.useClient({ name: 'apns-jwt-read', failOpen: true }, (client) =>+ client.get(cacheKey)+ )+ jwt = winner ?? minted+ }+ this.rememberApnsJwtLocally(cacheKey, jwt)return jwt}private rememberApnsJwtLocally(cacheKey: string, jwt: string): void {const nowMs = Date.now()- this.apnsJwtLocalCache.set(cacheKey, { jwt, expiresAtMs: nowMs + APNS_JWT_TTL_SECONDS * 1000 })+ // An adopted token can be older than this pod's read of it, and Apple rejects one past an hour.+ const issuedAtMs = apnsJwtIssuedAtMs(jwt) ?? nowMs+ this.apnsJwtLocalCache.set(cacheKey, { jwt, expiresAtMs: issuedAtMs + APNS_JWT_TTL_SECONDS * 1000 })if (this.apnsJwtLocalCache.size <= APNS_JWT_LOCAL_CACHE_MAX) {return