: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): forward the regional token error instead of masking it (#85747)
Matt Brookerfbe2ff03c790
diff --git a/services/oauth-proxy/src/handlers/token.ts b/services/oauth-proxy/src/handlers/token.tsindex 6cccb0c47b64..bf5f5a1b379f 100644--- a/services/oauth-proxy/src/handlers/token.ts+++ b/services/oauth-proxy/src/handlers/token.ts@@ -6,7 +6,7 @@ import {putRegionSelection,resolveMappingRewrite,} from '@/lib/kv'-import { proxyPostWithClientId, tryBothRegions } from '@/lib/proxy'+import { preferClientError, proxyPostWithClientId, tryBothRegions } from '@/lib/proxy'import { errorResponse } from '@/lib/validation'/**@@ -117,6 +117,8 @@ export async function handleToken(request: Request, kv: KVNamespace): Promise<Reif (clientId) {const mapping = await getClientMapping(kv, clientId)if (mapping) {+ let bestFailure: Response | null = null+for (const candidateRegion of ['us', 'eu'] as Region[]) {const rewrite = resolveMappingRewrite(mapping, candidateRegion)if (!rewrite) {@@ -159,15 +161,32 @@ export async function handleToken(request: Request, kv: KVNamespace): Promise<Re)return response}++ bestFailure = bestFailure ? preferClientError(bestFailure, response) : response}- console.info(+ if (bestFailure) {+ console.error(+ JSON.stringify({+ handler: 'token',+ grant_type: grantType,+ client_id_prefix: clientIdPrefix,+ region_source: 'mapping_try_both',+ resolved_region: 'none',+ status: bestFailure.status,+ })+ )+ return bestFailure+ }++ console.error(JSON.stringify({handler: 'token',grant_type: grantType,client_id_prefix: clientIdPrefix,region_source: 'mapping_try_both',resolved_region: 'none',+ error: 'no_region_candidates',}))return new Response(@@ -191,16 +210,19 @@ export async function handleToken(request: Request, kv: KVNamespace): Promise<Re}))const { response, region } = await tryBothRegions(rebuild(), '/oauth/token/')- console.info(- JSON.stringify({- handler: 'token',- grant_type: grantType,- client_id_prefix: clientIdPrefix,- region_source: 'try_both',- resolved_region: region,- status: response.status,- })- )+ const summary = JSON.stringify({+ handler: 'token',+ grant_type: grantType,+ client_id_prefix: clientIdPrefix,+ region_source: 'try_both',+ resolved_region: region,+ status: response.status,+ })+ if (region) {+ console.info(summary)+ } else {+ console.error(summary)+ }return response}diff --git a/services/oauth-proxy/src/lib/proxy.ts b/services/oauth-proxy/src/lib/proxy.tsindex ec290eef3e64..1773404b6927 100644--- a/services/oauth-proxy/src/lib/proxy.ts+++ b/services/oauth-proxy/src/lib/proxy.ts@@ -80,7 +80,10 @@ export async function proxyPostWithClientId(* Try a POST request against US first, then EU if US fails.* Used for token exchange fallback when region is unknown.*/-export async function tryBothRegions(request: Request, path: string): Promise<{ response: Response; region: Region }> {+export async function tryBothRegions(+ request: Request,+ path: string+): Promise<{ response: Response; region: Region | null }> {const body = await request.text()const headers = new Headers(request.headers)headers.delete('host')@@ -119,20 +122,34 @@ export async function tryBothRegions(request: Request, path: string): Promise<{return { response: euResponse, region: 'eu' }}- console.info(+ const forwarded = preferClientError(usResponse, euResponse)+ console.error(JSON.stringify({fn: 'tryBothRegions',path,resolved: 'none',us_status: usResponse.status,eu_status: euResponse.status,+ forwarded_from: forwarded === usResponse ? 'us' : 'eu',}))- return {- response: new Response(- JSON.stringify({ error: 'invalid_request', error_description: 'Unable to determine region' }),- { status: 400, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' } }- ),- region: 'us',+ return { response: forwarded, region: null }+}++/**+ * Pick which of two rejections to forward to the client.+ *+ * A 4xx carries the OAuth error code the client acts on: `invalid_grant` tells it+ * to discard the token and re-authorize. A 5xx only says one region was unhealthy,+ * which must not be reported as a dead grant.+ */+export function preferClientError(first: Response, second: Response): Response {+ if (isClientError(first)) {+ return first}+ return isClientError(second) ? second : first+}++function isClientError(response: Response): boolean {+ return response.status >= 400 && response.status < 500}diff --git a/services/oauth-proxy/tests/token.test.ts b/services/oauth-proxy/tests/token.test.tsindex b610ac83833d..5cf38d77fe91 100644--- a/services/oauth-proxy/tests/token.test.ts+++ b/services/oauth-proxy/tests/token.test.ts@@ -342,57 +342,131 @@ describe('handleToken', () => {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}`) {+ it.each([+ {+ scenario: 'both regions reject the grant',+ usStatus: 400,+ usBody: JSON.stringify({ error: 'invalid_grant', error_description: 'US rejected' }),+ euStatus: 400,+ euBody: JSON.stringify({ error: 'invalid_grant', error_description: 'EU rejected' }),+ expectedStatus: 400,+ expectedBody: JSON.stringify({ error: 'invalid_grant', error_description: 'US rejected' }),+ },+ {+ scenario: 'US is unhealthy and EU returns a client error',+ usStatus: 502,+ usBody: 'bad gateway',+ euStatus: 400,+ euBody: JSON.stringify({ error: 'invalid_grant', error_description: 'EU rejected' }),+ expectedStatus: 400,+ expectedBody: JSON.stringify({ error: 'invalid_grant', error_description: 'EU rejected' }),+ },+ ])(+ 'forwards the regional response on the mapping path when $scenario',+ async ({ usStatus, usBody, euStatus, euBody, expectedStatus, expectedBody }) => {+ 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)- }- 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(usBody, { status: usStatus }))+ .mockResolvedValueOnce(new Response(euBody, { status: euStatus }))+ )- 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)++ expect(response.status).toBe(expectedStatus)+ expect(await response.text()).toBe(expectedBody)+ // Tried both regions+ expect(vi.mocked(fetch)).toHaveBeenCalledTimes(2)+ // Did not re-store region+ expect(vi.mocked(mockKV.put)).not.toHaveBeenCalled()+ }+ )++ it.each([+ {+ scenario: 'both regions reject the grant',+ usStatus: 400,+ usBody: JSON.stringify({ error: 'invalid_grant', error_description: 'Token is expired' }),+ euStatus: 400,+ euBody: JSON.stringify({ error: 'invalid_grant', error_description: 'Token is expired' }),+ expectedStatus: 400,+ expectedBody: JSON.stringify({ error: 'invalid_grant', error_description: 'Token is expired' }),+ },+ {+ scenario: 'US is unhealthy and EU returns a client error',+ usStatus: 502,+ usBody: 'bad gateway',+ euStatus: 400,+ euBody: JSON.stringify({ error: 'invalid_grant' }),+ expectedStatus: 400,+ expectedBody: JSON.stringify({ error: 'invalid_grant' }),+ },+ {+ scenario: 'both regions are unhealthy',+ usStatus: 500,+ usBody: 'upstream failure',+ euStatus: 503,+ euBody: 'service unavailable',+ expectedStatus: 500,+ expectedBody: 'upstream failure',+ },+ {+ scenario: 'US answers below 400 and EU returns a client error',+ usStatus: 302,+ usBody: '',+ euStatus: 400,+ euBody: JSON.stringify({ error: 'invalid_grant' }),+ expectedStatus: 400,+ expectedBody: JSON.stringify({ error: 'invalid_grant' }),+ },+ ])(+ 'forwards the regional response when $scenario',+ async ({ usStatus, usBody, euStatus, euBody, expectedStatus, expectedBody }) => {+ mockKVGetValue(mockKV, null)++ vi.stubGlobal(+ 'fetch',+ vi+ .fn()+ .mockResolvedValueOnce(new Response(usBody, { status: usStatus }))+ .mockResolvedValueOnce(new Response(euBody, { status: euStatus }))+ )- 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 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_dead&client_id=unknown_client',+ })- const response = await handleToken(request, mockKV)- const data = (await response.json()) as Record<string, unknown>+ const response = await handleToken(request, mockKV)- 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()- })+ expect(response.status).toBe(expectedStatus)+ expect(await response.text()).toBe(expectedBody)+ expect(vi.mocked(fetch)).toHaveBeenCalledTimes(2)+ }+ )it('does not use client mapping for authorization_code even when mapping exists', async () => {const clientHash = await hashKey('proxy_client_authcode')