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): retry an apns send once with a new provider token after apple rejects it (#114706)

Daniel Marchukc1bb71578b6d
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
index aa66c119843b..b6fe0fa1f897 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.test.ts
@@ -105,6 +105,14 @@ describe('PushNotificationService', () => {
fn({
get: (key: string) => valkeyStore.get(key) ?? null,
set: mockValkeySet,
+ eval: (_script: string, _keys: number, key: string, rejected: string) => {
+ const current = valkeyStore.get(key) ?? null
+ if (current === rejected) {
+ valkeyStore.delete(key)
+ return null
+ }
+ return current
+ },
})
),
} as any
@@ -989,6 +997,146 @@ describe('PushNotificationService', () => {
expect(result.error).toContain('InvalidProviderToken')
})
+ describe('when APNs rejects the provider token', () => {
+ const apnsResponse = (status: number, reason?: string): any => ({
+ fetchError: null,
+ fetchResponse: {
+ status,
+ text: () => Promise.resolve(reason ? JSON.stringify({ reason }) : ''),
+ dump: () => Promise.resolve(),
+ },
+ fetchDuration: 10,
+ })
+ const send = (): Promise<any> =>
+ service.executeSendPushNotification(
+ createSendPushNotificationInvocation({
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),
+ })
+ )
+ const sentTokens = (): string[] =>
+ mockTrackedFetch.mock.calls.map((call: any) => call[0].fetchParams.headers.Authorization)
+ const jwtCacheKey = `@posthog/apns-provider-jwt/${createHash('sha256').update(`TEAM456:KEY123:${testEcKey}`).digest('hex')}`
+
+ beforeEach(() => {
+ mockTrackedFetch.mockReset()
+ })
+
+ it.each(['InvalidProviderToken', 'ExpiredProviderToken'])(
+ 'retries once with a new token after %s',
+ async (reason) => {
+ mockTrackedFetch
+ .mockResolvedValueOnce(apnsResponse(403, reason))
+ .mockResolvedValueOnce(apnsResponse(200))
+
+ const result = await send()
+
+ expect(result.error).toBeUndefined()
+ expect(result.metrics).toContainEqual(
+ expect.objectContaining({ metric_name: 'push_sent', count: 1 })
+ )
+ const [rejected, retried] = sentTokens()
+ expect(retried).not.toEqual(rejected)
+ expect(`bearer ${valkeyStore.get(jwtCacheKey)}`).toEqual(retried)
+ }
+ )
+
+ it('signs at most one new token per refresh window for a key', async () => {
+ mockTrackedFetch.mockResolvedValue(apnsResponse(403, 'InvalidProviderToken'))
+
+ const results = [await send(), await send(), await send()]
+
+ for (const result of results) {
+ expect(result.error).toContain('InvalidProviderToken')
+ }
+ expect(mockTrackedFetch).toHaveBeenCalledTimes(4)
+ expect(new Set(sentTokens()).size).toBe(2)
+ expect(mockValkeySet).toHaveBeenCalledWith(
+ expect.stringContaining('@posthog/apns-provider-jwt-refresh/'),
+ expect.any(String),
+ 'EX',
+ 1200,
+ 'NX'
+ )
+ })
+
+ it('reuses a token another pod already put in place of the rejected one', async () => {
+ mockTrackedFetch
+ .mockImplementationOnce(() => {
+ valkeyStore.set(jwtCacheKey, 'token-from-another-pod')
+ return Promise.resolve(apnsResponse(403, 'InvalidProviderToken'))
+ })
+ .mockResolvedValueOnce(apnsResponse(200))
+
+ const result = await send()
+
+ expect(result.error).toBeUndefined()
+ expect(sentTokens()[1]).toBe('bearer token-from-another-pod')
+ expect(valkeyStore.get(jwtCacheKey)).toBe('token-from-another-pod')
+ expect([...valkeyStore.keys()].some((key) => key.includes('jwt-refresh'))).toBe(false)
+ })
+
+ it('adopts the token another pod signs while this pod waits for the refresh claim', async () => {
+ const set = mockValkeySet.getMockImplementation()!
+ mockValkeySet.mockImplementation((key: string, ...rest: any[]) => {
+ if (key.includes('jwt-refresh')) {
+ valkeyStore.set(key, String(Date.now()))
+ valkeyStore.set(jwtCacheKey, 'token-from-another-pod')
+ return null
+ }
+ return set(key, ...rest)
+ })
+ mockTrackedFetch
+ .mockResolvedValueOnce(apnsResponse(403, 'InvalidProviderToken'))
+ .mockResolvedValueOnce(apnsResponse(200))
+
+ const result = await send()
+
+ expect(result.error).toBeUndefined()
+ expect(sentTokens()[1]).toBe('bearer token-from-another-pod')
+ })
+
+ it('does not wait for a replacement when the refresh was claimed long ago', async () => {
+ const refreshKey = jwtCacheKey.replace('apns-provider-jwt/', 'apns-provider-jwt-refresh/')
+ valkeyStore.set(refreshKey, String(Date.now() - 5 * 60 * 1000))
+ mockTrackedFetch.mockResolvedValue(apnsResponse(403, 'InvalidProviderToken'))
+
+ const result = await send()
+
+ expect(result.error).toContain('InvalidProviderToken')
+ const cacheReads = mockValkey.useClient.mock.calls.filter(
+ ([opts]: any) => opts.name === 'apns-jwt-read'
+ )
+ expect(cacheReads).toHaveLength(2)
+ })
+
+ it('signs no new tokens for a rejected key while Valkey is down', async () => {
+ const pod = new PushNotificationService(integrationManager, encryptedFields, fetchUtils, {
+ useClient: jest.fn(() => null),
+ } as any)
+ mockTrackedFetch.mockResolvedValue(apnsResponse(403, 'InvalidProviderToken'))
+
+ for (let i = 0; i < 3; i++) {
+ await pod.executeSendPushNotification(
+ createSendPushNotificationInvocation({
+ '$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),
+ })
+ )
+ }
+
+ expect(mockTrackedFetch).toHaveBeenCalledTimes(3)
+ expect(new Set(sentTokens()).size).toBe(1)
+ })
+
+ it('does not retry when the rejection is not about the provider token', async () => {
+ mockTrackedFetch.mockResolvedValue(apnsResponse(403, 'TopicDisallowed'))
+
+ const result = await send()
+
+ expect(result.error).toContain('TopicDisallowed')
+ expect(mockTrackedFetch).toHaveBeenCalledTimes(1)
+ })
+ })
+
it('does not let custom data overwrite the reserved aps payload', async () => {
const invocation = createSendPushNotificationInvocation({
'$device_push_subscription_com.example.app': encryptedFields.encrypt('apns-device-token'),
diff --git a/nodejs/src/cdp/services/messaging/push-notification.service.ts b/nodejs/src/cdp/services/messaging/push-notification.service.ts
index e0ba11e7b834..668ac0941da7 100644
--- a/nodejs/src/cdp/services/messaging/push-notification.service.ts
+++ b/nodejs/src/cdp/services/messaging/push-notification.service.ts
@@ -1,6 +1,7 @@
import { createHash, createSign } from 'crypto'
import { DateTime } from 'luxon'
import { Counter, Histogram } from 'prom-client'
+import { setTimeout as sleep } from 'timers/promises'
import {
CyclotronInvocationQueueParametersSendPushNotificationType,
@@ -58,6 +59,12 @@ const pushNotificationSendDurationMs = new Histogram({
buckets: [10, 25, 50, 100, 200, 500, 1000, 2000, 5000, 10000],
})
+const apnsProviderTokenRefreshCounter = new Counter({
+ name: 'push_notification_apns_token_refresh_total',
+ help: 'APNs provider tokens replaced after Apple rejected one. outcome: minted = a new token was signed; adopted = another pod had already replaced it; skipped = a refresh for this key happened inside the refresh window.',
+ labelNames: ['outcome'],
+})
+
const pushNotificationRescheduledCounter = new Counter({
name: 'push_notification_rescheduled_total',
help: 'Push sends rescheduled after a transient provider failure (throttle / 5xx / network) instead of being dropped. A sustained rate for one platform means that provider is rate-limiting the sending project.',
@@ -70,6 +77,25 @@ const pushNotificationRescheduledCounter = new Counter({
const APNS_JWT_CACHE_PREFIX = '@posthog/apns-provider-jwt/'
const APNS_JWT_TTL_SECONDS = 45 * 60
+// Apple can reject a token it accepted minutes earlier. One new token per key per window keeps a key that
+// keeps getting rejected under Apple's refresh limit.
+const APNS_JWT_REFRESH_PREFIX = '@posthog/apns-provider-jwt-refresh/'
+const APNS_JWT_REFRESH_WINDOW_SECONDS = 20 * 60
+const APNS_REJECTED_TOKEN_CODES = new Set(['InvalidProviderToken', 'ExpiredProviderToken'])
+const APNS_JWT_REPLACEMENT_POLLS = 5
+const APNS_JWT_REPLACEMENT_POLL_MS = 100
+const APNS_JWT_FRESH_CLAIM_MS = 2000
+
+// Keeps a token another pod already put in place of the rejected one.
+const APNS_JWT_DROP_IF_REJECTED_SCRIPT = `
+local current = redis.call('GET', KEYS[1])
+if current == ARGV[1] then
+ redis.call('DEL', KEYS[1])
+ return false
+end
+return current
+`
+
function apnsJwtIssuedAtMs(jwt: string): number | null {
try {
const iat = parseJSON(Buffer.from(jwt.split('.')[1], 'base64url').toString()).iat
@@ -564,7 +590,7 @@ export class PushNotificationService {
return false
}
- const jwt = await this.generateApnsJwt(appleTeamId, keyId, signingKey)
+ let jwt = await this.generateApnsJwt(appleTeamId, keyId, signingKey)
const apnsHost =
integration.config.environment === 'sandbox' ? 'api.sandbox.push.apple.com' : 'api.push.apple.com'
const templateId = result.invocation.hogFunction.template_id ?? 'unknown'
@@ -574,15 +600,31 @@ export class PushNotificationService {
// is worth re-running depends on any device being retriable, not on which failed last.
let retriableFailure: PushSendError | undefined
const failures: PushSendError[] = []
+ let tokenRefreshed = false
for (const subscription of subscriptions) {
- const outcome = await this.sendOneApns(
+ let outcome = await this.sendOneApns(
result,
params,
subscription,
{ apnsHost, bundleId, jwt, templateId },
addLog
)
+ if (!tokenRefreshed && outcome.error?.code && APNS_REJECTED_TOKEN_CODES.has(outcome.error.code)) {
+ tokenRefreshed = true
+ const refreshed = await this.refreshApnsJwt(appleTeamId, keyId, signingKey, jwt)
+ if (refreshed) {
+ jwt = refreshed
+ addLog('warn', 'APNs rejected the provider token. Retrying once with a new token.')
+ outcome = await this.sendOneApns(
+ result,
+ params,
+ subscription,
+ { apnsHost, bundleId, jwt, templateId },
+ addLog
+ )
+ }
+ }
if (outcome.sent) {
delivered++
} else if (outcome.unregistered) {
@@ -692,13 +734,16 @@ export class PushNotificationService {
return { sent: true }
}
+ // Key the cache on a fingerprint of the signing-key material, not on the team id / key id — those
+ // come from tenant-controlled integration config, so another team could set matching values to
+ // collide with or poison this shared cache entry. Hashing the signing key makes the key unforgeable
+ // while still letting the fleet reuse one token per signing key.
+ private apnsKeyFingerprint(teamId: string, keyId: string, signingKey: string): string {
+ return createHash('sha256').update(`${teamId}:${keyId}:${signingKey}`).digest('hex')
+ }
+
private async generateApnsJwt(teamId: string, keyId: string, signingKey: string): Promise<string> {
- // Key the cache on a fingerprint of the signing-key material, not on the team id / key id — those
- // come from tenant-controlled integration config, so another team could set matching values to
- // collide with or poison this shared cache entry. Hashing the signing key makes the key unforgeable
- // while still letting the fleet reuse one token per signing key.
- const keyFingerprint = createHash('sha256').update(`${teamId}:${keyId}:${signingKey}`).digest('hex')
- const cacheKey = `${APNS_JWT_CACHE_PREFIX}${keyFingerprint}`
+ const cacheKey = `${APNS_JWT_CACHE_PREFIX}${this.apnsKeyFingerprint(teamId, keyId, signingKey)}`
const inFlight = this.apnsJwtInFlight.get(cacheKey)
if (inFlight) {
@@ -711,6 +756,76 @@ export class PushNotificationService {
return lookup
}
+ private async refreshApnsJwt(
+ teamId: string,
+ keyId: string,
+ signingKey: string,
+ rejectedJwt: string
+ ): Promise<string | null> {
+ const fingerprint = this.apnsKeyFingerprint(teamId, keyId, signingKey)
+ const cacheKey = `${APNS_JWT_CACHE_PREFIX}${fingerprint}`
+
+ const replacement = await this.readReplacementApnsJwt(cacheKey, rejectedJwt)
+ if (replacement) {
+ return replacement
+ }
+
+ // Fails closed: without Valkey a pod cannot tell whether the fleet already refreshed this key.
+ const refreshKey = `${APNS_JWT_REFRESH_PREFIX}${fingerprint}`
+ const claimed = await this.valkey.useClient({ name: 'apns-jwt-refresh', failOpen: true }, (client) =>
+ client.set(refreshKey, String(Date.now()), 'EX', APNS_JWT_REFRESH_WINDOW_SECONDS, 'NX')
+ )
+ if (claimed !== 'OK') {
+ const claimedAtMs = Number(
+ await this.valkey.useClient({ name: 'apns-jwt-refresh-read', failOpen: true }, (client) =>
+ client.get(refreshKey)
+ )
+ )
+ // Only a recent claim can still be signing. A key Apple keeps rejecting must not make every send wait.
+ const polls = Date.now() - claimedAtMs < APNS_JWT_FRESH_CLAIM_MS ? APNS_JWT_REPLACEMENT_POLLS : 0
+ for (let attempt = 0; attempt < polls; attempt++) {
+ await sleep(APNS_JWT_REPLACEMENT_POLL_MS)
+ const adopted = await this.readReplacementApnsJwt(cacheKey, rejectedJwt)
+ if (adopted) {
+ return adopted
+ }
+ }
+ apnsProviderTokenRefreshCounter.labels({ outcome: 'skipped' }).inc()
+ return null
+ }
+
+ if (this.apnsJwtLocalCache.get(cacheKey)?.jwt === rejectedJwt) {
+ this.apnsJwtLocalCache.delete(cacheKey)
+ }
+ const current = await this.valkey.useClient({ name: 'apns-jwt-drop', failOpen: true }, (client) =>
+ client.eval(APNS_JWT_DROP_IF_REJECTED_SCRIPT, 1, cacheKey, rejectedJwt)
+ )
+ if (typeof current === 'string' && current !== rejectedJwt) {
+ this.rememberApnsJwtLocally(cacheKey, current)
+ apnsProviderTokenRefreshCounter.labels({ outcome: 'adopted' }).inc()
+ return current
+ }
+
+ const jwt = await this.generateApnsJwt(teamId, keyId, signingKey)
+ if (jwt === rejectedJwt) {
+ return null
+ }
+ apnsProviderTokenRefreshCounter.labels({ outcome: 'minted' }).inc()
+ return jwt
+ }
+
+ private async readReplacementApnsJwt(cacheKey: string, rejectedJwt: string): Promise<string | null> {
+ const current = await this.valkey.useClient({ name: 'apns-jwt-read', failOpen: true }, (client) =>
+ client.get(cacheKey)
+ )
+ if (!current || current === rejectedJwt) {
+ return null
+ }
+ this.rememberApnsJwtLocally(cacheKey, current)
+ apnsProviderTokenRefreshCounter.labels({ outcome: 'adopted' }).inc()
+ return current
+ }
+
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)