: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(oauth-proxy): use client mapping for refresh_token when region KV expires (#57247)
Vojta Bartoš51ccaac58c51
diff --git a/services/oauth-proxy/src/handlers/token.ts b/services/oauth-proxy/src/handlers/token.tsindex ab8cd289e3ae..8370adeaaf58 100644--- a/services/oauth-proxy/src/handlers/token.ts+++ b/services/oauth-proxy/src/handlers/token.ts@@ -1,5 +1,11 @@import type { Region } from '@/lib/constants'-import { getCallbackRedirectUri, getClientMapping, getRegionSelection } from '@/lib/kv'+import {+ getCallbackRedirectUri,+ getClientMapping,+ getRegionSelection,+ putRegionSelection,+ resolveMappingRewrite,+} from '@/lib/kv'import { proxyPostWithClientId, tryBothRegions } from '@/lib/proxy'/**@@ -102,6 +108,79 @@ export async function handleToken(request: Request, kv: KVNamespace): Promise<Re)}+ // If the client was registered through the proxy, we have a permanent mapping+ // of proxy client_id → regional client_ids. Try each region with the correctly+ // rewritten client_id/secret so the regional server recognizes the client.+ // Without this, tryBothRegions sends the proxy (US) client_id to both regions,+ // and EU rejects it because it only knows its own EU client_id.+ if (clientId) {+ const mapping = await getClientMapping(kv, clientId)+ if (mapping) {+ for (const candidateRegion of ['us', 'eu'] as Region[]) {+ const rewrite = resolveMappingRewrite(mapping, candidateRegion)+ if (!rewrite) {+ continue+ }++ console.info(+ JSON.stringify({+ handler: 'token',+ grant_type: grantType,+ client_id_prefix: clientIdPrefix,+ region_source: 'mapping_try_both',+ candidate_region: candidateRegion,+ })+ )++ const response = await proxyPostWithClientId(+ rebuild(),+ candidateRegion,+ '/oauth/token/',+ clientId,+ rewrite.regionalClientId,+ undefined,+ rewrite.clientSecretRewrite+ )++ if (response.ok) {+ // Re-store the region so subsequent refreshes take the fast path+ await putRegionSelection(kv, clientId, candidateRegion)++ console.info(+ JSON.stringify({+ handler: 'token',+ grant_type: grantType,+ client_id_prefix: clientIdPrefix,+ region_source: 'mapping_try_both',+ resolved_region: candidateRegion,+ status: response.status,+ })+ )+ return response+ }+ }++ console.info(+ JSON.stringify({+ handler: 'token',+ grant_type: grantType,+ client_id_prefix: clientIdPrefix,+ region_source: 'mapping_try_both',+ resolved_region: 'none',+ })+ )+ return new Response(+ JSON.stringify({+ error: 'invalid_request',+ error_description: 'Unable to determine region',+ }),+ { status: 400, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' } }+ )+ }+ }++ // No mapping — client may have registered directly with a regional server.+ // Try both regions with the raw request.console.info(JSON.stringify({handler: 'token',@@ -134,22 +213,16 @@ async function proxyWithMapping(if (proxyClientId) {const mapping = await getClientMapping(kv, proxyClientId)if (mapping) {- const regionalClientId = region === 'eu' ? mapping.eu_client_id : mapping.us_client_id- if (regionalClientId) {- const proxySecret = mapping.us_client_secret- const regionalSecret = region === 'eu' ? mapping.eu_client_secret : mapping.us_client_secret- let clientSecretRewrite: { from: string; to: string } | undefined- if (proxySecret && regionalSecret && proxySecret !== regionalSecret) {- clientSecretRewrite = { from: proxySecret, to: regionalSecret }- }+ const rewrite = resolveMappingRewrite(mapping, region)+ if (rewrite) {return proxyPostWithClientId(request,region,'/oauth/token/',proxyClientId,- regionalClientId,+ rewrite.regionalClientId,redirectUriRewrite,- clientSecretRewrite+ rewrite.clientSecretRewrite)}}diff --git a/services/oauth-proxy/src/lib/kv.ts b/services/oauth-proxy/src/lib/kv.tsindex 2e374a1ddef2..11e1dba588ba 100644--- a/services/oauth-proxy/src/lib/kv.ts+++ b/services/oauth-proxy/src/lib/kv.ts@@ -56,3 +56,27 @@ export async function putCallbackRedirectUri(kv: KVNamespace, key: string, redirexport async function getCallbackRedirectUri(kv: KVNamespace, key: string): Promise<string | null> {return kv.get(`${CALLBACK_PREFIX}${await hashKey(key)}`)}++/**+ * Derive the regional client_id and optional client_secret rewrite for a given+ * region from a client mapping. Returns null if the mapping has no client_id+ * for the requested region.+ */+export function resolveMappingRewrite(+ mapping: ClientMapping,+ region: Region+): { regionalClientId: string; clientSecretRewrite?: { from: string; to: string } } | null {+ const regionalClientId = region === 'eu' ? mapping.eu_client_id : mapping.us_client_id+ if (!regionalClientId) {+ return null+ }++ const proxySecret = mapping.us_client_secret+ const regionalSecret = region === 'eu' ? mapping.eu_client_secret : mapping.us_client_secret+ let clientSecretRewrite: { from: string; to: string } | undefined+ if (proxySecret && regionalSecret && proxySecret !== regionalSecret) {+ clientSecretRewrite = { from: proxySecret, to: regionalSecret }+ }++ return { regionalClientId, clientSecretRewrite }+}diff --git a/services/oauth-proxy/tests/token.test.ts b/services/oauth-proxy/tests/token.test.tsindex ee2d38b18d5a..b610ac83833d 100644--- a/services/oauth-proxy/tests/token.test.ts+++ b/services/oauth-proxy/tests/token.test.ts@@ -182,7 +182,7 @@ describe('handleToken', () => {expect(data.error_description).toBe('Malformed JSON body')})- it('falls back to try-both for refresh_token grants', async () => {+ it('falls back to try-both for refresh_token grants without mapping', async () => {mockKVGetValue(mockKV, null)vi.stubGlobal(@@ -218,4 +218,356 @@ describe('handleToken', () => {expect(data.access_token).toBe('pha_eu_refreshed')expect(vi.mocked(fetch)).toHaveBeenCalledTimes(2)})++ it('uses client mapping for refresh_token when region KV has expired', async () => {+ const clientHash = await hashKey('proxy_client_mapped')+ mockKVGet(mockKV, (key: string, type?: unknown) => {+ // Region KV has expired — return null+ if (key === `region:${clientHash}`) {+ return Promise.resolve(null)+ }+ // Client mapping is permanent — still available+ if (key === 'client:proxy_client_mapped' && type === 'json') {+ return Promise.resolve({+ us_client_id: 'proxy_client_mapped',+ eu_client_id: 'eu_real_id',+ us_client_secret: 'us_secret',+ eu_client_secret: 'eu_secret',+ created_at: Date.now(),+ })+ }+ return Promise.resolve(null)+ })++ vi.stubGlobal(+ 'fetch',+ vi+ .fn()+ // US attempt fails — refresh token was issued by EU+ .mockResolvedValueOnce(+ new Response(JSON.stringify({ error: 'invalid_grant' }), {+ status: 400,+ headers: { 'Content-Type': 'application/json' },+ })+ )+ // EU attempt succeeds with correctly rewritten client_id+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ access_token: 'pha_eu_refreshed',+ token_type: 'bearer',+ }),+ { status: 200, headers: { 'Content-Type': 'application/json' } }+ )+ )+ )++ const request = new Request('https://oauth.posthog.com/oauth/token/', {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: 'grant_type=refresh_token&refresh_token=rt_eu_token&client_id=proxy_client_mapped&client_secret=us_secret',+ })++ const response = await handleToken(request, mockKV)+ const data = (await response.json()) as Record<string, unknown>++ expect(response.status).toBe(200)+ expect(data.access_token).toBe('pha_eu_refreshed')++ // Verify US attempt used the US client_id (which is the proxy client_id)+ const usCall = vi.mocked(fetch).mock.calls[0]!+ const usBody = new URLSearchParams(usCall[1]!.body as string)+ expect(String(usCall[0])).toMatch(/^https:\/\/us\.posthog\.com/)+ expect(usBody.get('client_id')).toBe('proxy_client_mapped')+ expect(usBody.get('client_secret')).toBe('us_secret')++ // Verify EU attempt used the rewritten EU client_id and secret+ const euCall = vi.mocked(fetch).mock.calls[1]!+ const euBody = new URLSearchParams(euCall[1]!.body as string)+ expect(String(euCall[0])).toMatch(/^https:\/\/eu\.posthog\.com/)+ expect(euBody.get('client_id')).toBe('eu_real_id')+ expect(euBody.get('client_secret')).toBe('eu_secret')++ // Verify region was re-stored in KV for subsequent requests+ expect(vi.mocked(mockKV.put)).toHaveBeenCalledWith(`region:${clientHash}`, 'eu', { expirationTtl: 3600 })+ })++ it('uses client mapping and succeeds on first region (US) without trying EU', async () => {+ const clientHash = await hashKey('proxy_client_us')+ mockKVGet(mockKV, (key: string, type?: unknown) => {+ if (key === `region:${clientHash}`) {+ return Promise.resolve(null)+ }+ if (key === 'client:proxy_client_us' && type === 'json') {+ return Promise.resolve({+ us_client_id: 'proxy_client_us',+ eu_client_id: 'eu_real_id',+ created_at: Date.now(),+ })+ }+ return Promise.resolve(null)+ })++ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValueOnce(+ new Response(JSON.stringify({ access_token: 'pha_us_refreshed', token_type: 'bearer' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ })+ )+ )++ const request = new Request('https://oauth.posthog.com/oauth/token/', {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: 'grant_type=refresh_token&refresh_token=rt_us_token&client_id=proxy_client_us',+ })++ const response = await handleToken(request, mockKV)+ const data = (await response.json()) as Record<string, unknown>++ expect(response.status).toBe(200)+ expect(data.access_token).toBe('pha_us_refreshed')+ // Only one fetch call — did not try EU+ expect(vi.mocked(fetch)).toHaveBeenCalledTimes(1)++ // Verify US attempt used the correct client_id+ const usCall = vi.mocked(fetch).mock.calls[0]!+ const usBody = new URLSearchParams(usCall[1]!.body as string)+ expect(String(usCall[0])).toMatch(/^https:\/\/us\.posthog\.com/)+ expect(usBody.get('client_id')).toBe('proxy_client_us')++ // Region re-stored as US+ expect(vi.mocked(mockKV.put)).toHaveBeenCalledWith(`region:${clientHash}`, 'us', { expirationTtl: 3600 })+ })++ it('returns error when mapping exists but both regions reject the refresh_token', async () => {+ const clientHash = await hashKey('proxy_client_bad')+ mockKVGet(mockKV, (key: string, type?: unknown) => {+ if (key === `region:${clientHash}`) {+ return Promise.resolve(null)+ }+ if (key === 'client:proxy_client_bad' && type === 'json') {+ return Promise.resolve({+ us_client_id: 'proxy_client_bad',+ eu_client_id: 'eu_real_id',+ created_at: Date.now(),+ })+ }+ return Promise.resolve(null)+ })++ vi.stubGlobal(+ 'fetch',+ vi+ .fn()+ .mockResolvedValueOnce(+ new Response(JSON.stringify({ error: 'invalid_grant' }), {+ status: 400,+ headers: { 'Content-Type': 'application/json' },+ })+ )+ .mockResolvedValueOnce(+ new Response(JSON.stringify({ error: 'invalid_grant' }), {+ status: 400,+ headers: { 'Content-Type': 'application/json' },+ })+ )+ )++ const request = new Request('https://oauth.posthog.com/oauth/token/', {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: 'grant_type=refresh_token&refresh_token=rt_expired&client_id=proxy_client_bad',+ })++ const response = await handleToken(request, mockKV)+ const data = (await response.json()) as Record<string, unknown>++ expect(response.status).toBe(400)+ expect(data.error).toBe('invalid_request')+ expect(data.error_description).toBe('Unable to determine region')+ // Tried both regions+ expect(vi.mocked(fetch)).toHaveBeenCalledTimes(2)+ // Did not re-store region+ expect(vi.mocked(mockKV.put)).not.toHaveBeenCalled()+ })++ it('does not use client mapping for authorization_code even when mapping exists', async () => {+ const clientHash = await hashKey('proxy_client_authcode')+ mockKVGet(mockKV, (key: string, type?: unknown) => {+ if (key === `region:${clientHash}`) {+ return Promise.resolve(null)+ }+ if (key === 'client:proxy_client_authcode' && type === 'json') {+ return Promise.resolve({+ us_client_id: 'proxy_client_authcode',+ eu_client_id: 'eu_real_id',+ created_at: Date.now(),+ })+ }+ return Promise.resolve(null)+ })++ const request = new Request('https://oauth.posthog.com/oauth/token/', {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: 'grant_type=authorization_code&code=test_code&client_id=proxy_client_authcode',+ })++ const response = await handleToken(request, mockKV)+ const data = (await response.json()) as Record<string, unknown>++ // Should return error, not attempt mapping-based routing+ expect(response.status).toBe(400)+ expect(data.error_description).toBe('Unable to determine region for this authorization code')+ expect(vi.mocked(fetch)).not.toHaveBeenCalled()+ })++ it('uses client mapping with JSON content type', async () => {+ const clientHash = await hashKey('proxy_client_json')+ mockKVGet(mockKV, (key: string, type?: unknown) => {+ if (key === `region:${clientHash}`) {+ return Promise.resolve(null)+ }+ if (key === 'client:proxy_client_json' && type === 'json') {+ return Promise.resolve({+ us_client_id: 'proxy_client_json',+ eu_client_id: 'eu_json_id',+ created_at: Date.now(),+ })+ }+ return Promise.resolve(null)+ })++ vi.stubGlobal(+ 'fetch',+ vi+ .fn()+ .mockResolvedValueOnce(+ new Response(JSON.stringify({ error: 'invalid_grant' }), {+ status: 400,+ headers: { 'Content-Type': 'application/json' },+ })+ )+ .mockResolvedValueOnce(+ new Response(JSON.stringify({ access_token: 'pha_eu_json', token_type: 'bearer' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ })+ )+ )++ const request = new Request('https://oauth.posthog.com/oauth/token/', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ grant_type: 'refresh_token',+ refresh_token: 'rt_json_token',+ client_id: 'proxy_client_json',+ }),+ })++ const response = await handleToken(request, mockKV)+ const data = (await response.json()) as Record<string, unknown>++ expect(response.status).toBe(200)+ expect(data.access_token).toBe('pha_eu_json')++ // Verify EU attempt rewrote the client_id in JSON body+ const euCall = vi.mocked(fetch).mock.calls[1]!+ const euBody = JSON.parse(euCall[1]!.body as string) as Record<string, unknown>+ expect(euBody.client_id).toBe('eu_json_id')+ })++ it('skips EU when eu_client_id is null in the mapping', async () => {+ const clientHash = await hashKey('proxy_client_us_only')+ mockKVGet(mockKV, (key: string, type?: unknown) => {+ if (key === `region:${clientHash}`) {+ return Promise.resolve(null)+ }+ if (key === 'client:proxy_client_us_only' && type === 'json') {+ return Promise.resolve({+ us_client_id: 'proxy_client_us_only',+ eu_client_id: null,+ created_at: Date.now(),+ })+ }+ return Promise.resolve(null)+ })++ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValueOnce(+ new Response(JSON.stringify({ access_token: 'pha_us_only', token_type: 'bearer' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ })+ )+ )++ const request = new Request('https://oauth.posthog.com/oauth/token/', {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: 'grant_type=refresh_token&refresh_token=rt_token&client_id=proxy_client_us_only',+ })++ const response = await handleToken(request, mockKV)+ const data = (await response.json()) as Record<string, unknown>++ expect(response.status).toBe(200)+ expect(data.access_token).toBe('pha_us_only')+ // Only US was tried — EU was skipped because eu_client_id is null+ expect(vi.mocked(fetch)).toHaveBeenCalledTimes(1)+ const usCall = vi.mocked(fetch).mock.calls[0]!+ expect(String(usCall[0])).toMatch(/^https:\/\/us\.posthog\.com/)+ expect(vi.mocked(mockKV.put)).toHaveBeenCalledWith(`region:${clientHash}`, 'us', { expirationTtl: 3600 })+ })++ it('skips US when us_client_id is null in the mapping', async () => {+ const clientHash = await hashKey('proxy_client_eu_only')+ mockKVGet(mockKV, (key: string, type?: unknown) => {+ if (key === `region:${clientHash}`) {+ return Promise.resolve(null)+ }+ if (key === 'client:proxy_client_eu_only' && type === 'json') {+ return Promise.resolve({+ us_client_id: null,+ eu_client_id: 'eu_only_id',+ created_at: Date.now(),+ })+ }+ return Promise.resolve(null)+ })++ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValueOnce(+ new Response(JSON.stringify({ access_token: 'pha_eu_only', token_type: 'bearer' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ })+ )+ )++ const request = new Request('https://oauth.posthog.com/oauth/token/', {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: 'grant_type=refresh_token&refresh_token=rt_token&client_id=proxy_client_eu_only',+ })++ const response = await handleToken(request, mockKV)+ const data = (await response.json()) as Record<string, unknown>++ expect(response.status).toBe(200)+ expect(data.access_token).toBe('pha_eu_only')+ // Only EU was tried — US was skipped because us_client_id is null+ expect(vi.mocked(fetch)).toHaveBeenCalledTimes(1)+ const euCall = vi.mocked(fetch).mock.calls[0]!+ expect(String(euCall[0])).toMatch(/^https:\/\/eu\.posthog\.com/)+ const euBody = new URLSearchParams(euCall[1]!.body as string)+ expect(euBody.get('client_id')).toBe('eu_only_id')+ expect(vi.mocked(mockKV.put)).toHaveBeenCalledWith(`region:${clientHash}`, 'eu', { expirationTtl: 3600 })+ })})