: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): key the intercepted callback by a proxy nonce (#97529)
Matt Brookerad8dc015697c
diff --git a/services/oauth-proxy/README.md b/services/oauth-proxy/README.mdindex bc1234bcfa5e..ec9273d7567d 100644--- a/services/oauth-proxy/README.md+++ b/services/oauth-proxy/README.md@@ -34,9 +34,11 @@ Trailing slashes are optional; paths are normalized before matching.2. **Authorize.**`/oauth/authorize` serves a static region picker.The picker re-requests the same URL with `_region=us|eu` appended.- The worker stores that choice in KV under both the `state` and the `client_id`, swaps in the regional `client_id`, replaces `redirect_uri` with the proxy callback, and redirects to the region.+ The worker stores the region choice in KV under the `client_id`, swaps in the regional `client_id`, replaces `redirect_uri` with the proxy callback, and redirects to the region.+ For clients with a stored `redirect_uris` list, it also generates a nonce, stores the client's original `redirect_uri` and `state` under it, and sends the regional server that nonce as `state` instead of the client's own.3. **Callback.**- The regional server sends the user to `/oauth/callback`, which looks up the client's original `redirect_uri` by `state` and forwards every query param on to it.+ The regional server sends the user to `/oauth/callback` with the nonce from step 2 as `state`.+ The worker looks up and deletes the matching record, then forwards every query param to the client's original `redirect_uri`, restoring the client's own `state`.The client never sees a regional URL, so its token request comes back through the proxy.4. **Token.**`/oauth/token` looks up the region by `client_id`.@@ -54,13 +56,16 @@ Clients registered directly against a region keep their own `redirect_uri` and f## KV keys-| Key | TTL | Value |-| ------------------- | ------ | --------------------------------------------------------------- |-| `client:<proxy_id>` | none | US and EU `client_id`s, secrets, and registered `redirect_uris` |-| `region:<sha256>` | 1 hour | `us` or `eu`, stored under both `state` and `client_id` |-| `callback:<sha256>` | 1 hour | The client's original `redirect_uri` |+| Key | TTL | Value |+| --------------------------- | ------ | --------------------------------------------------------------------- |+| `client:<proxy_id>` | none | US and EU `client_id`s, secrets, and registered `redirect_uris` |+| `region:<sha256>` | 1 hour | `us` or `eu`, stored under `client_id` |+| `callback:<sha256>` | 1 hour | The client's original `redirect_uri`, stored under `client_id` |+| `pending_callback:<sha256>` | 1 hour | The client's original `redirect_uri` and `state`, under a proxy nonce |-Key material is SHA-256 hashed because `state` is opaque and can exceed Cloudflare's 512 byte key limit.+Key material is SHA-256 hashed because `state` and the nonce are opaque and can exceed Cloudflare's 512 byte key limit.+`pending_callback:` records are deleted once `/oauth/callback` reads them, so a nonce is single-use.+KV is eventually consistent across Cloudflare's edge locations, so this single-use guarantee is best effort; the authorization code itself is still single-use at the regional server.## Developmentdiff --git a/services/oauth-proxy/src/handlers/authorize.ts b/services/oauth-proxy/src/handlers/authorize.tsindex 53c73bf8e233..49d9d567b5b0 100644--- a/services/oauth-proxy/src/handlers/authorize.ts+++ b/services/oauth-proxy/src/handlers/authorize.ts@@ -1,5 +1,11 @@import { type Region, baseUrlForRegion } from '@/lib/constants'-import { type ClientMapping, getClientMapping, putCallbackRedirectUri, putRegionSelection } from '@/lib/kv'+import {+ type ClientMapping,+ getClientMapping,+ putCallbackRedirectUri,+ putPendingCallback,+ putRegionSelection,+} from '@/lib/kv'import { type ValidationError, errorResponse } from '@/lib/validation'import REGION_PICKER_HTML from '../static/region-picker.html'@@ -72,24 +78,17 @@ async function redirectToRegionalAuthorize(url: URL, region: Region, kv: KVNamesreturn errorResponse(redirectUriError)}- // Store region selection keyed by both state and client_id.- // The token exchange only has client_id (state is not sent to the token endpoint),- // but we also store by state for the callback interception.const kvWrites: Promise<void>[] = []- if (state) {- kvWrites.push(putRegionSelection(kv, state, region))- }if (clientId) {kvWrites.push(putRegionSelection(kv, clientId, region))}- // Store original redirect_uri and intercept callback only for clients with stored- // redirect_uris (the proxy callback URL is only in their registered redirect_uris).- // Legacy clients without redirect_uris fall through to regional server validation.+ // Only proxy-registered clients have the proxy callback in their registered redirect_uris.+ let nonce: string | null = nullif (mapping?.redirect_uris && originalRedirectUri) {- if (state) {- kvWrites.push(putCallbackRedirectUri(kv, state, originalRedirectUri))- }+ // A proxy nonce keys the record so knowing the client's state cannot overwrite it.+ nonce = crypto.randomUUID()+ kvWrites.push(putPendingCallback(kv, nonce, { redirect_uri: originalRedirectUri, state: state ?? null }))if (clientId) {kvWrites.push(putCallbackRedirectUri(kv, clientId, originalRedirectUri))}@@ -111,6 +110,9 @@ async function redirectToRegionalAuthorize(url: URL, region: Region, kv: KVNamesif (key === '_region') {continue}+ if (key === 'state' && nonce) {+ continue+ }if (key === 'client_id' && regionalClientId) {regionalUrl.searchParams.set(key, regionalClientId)} else if (key === 'redirect_uri' && mapping?.redirect_uris) {@@ -119,6 +121,9 @@ async function redirectToRegionalAuthorize(url: URL, region: Region, kv: KVNamesregionalUrl.searchParams.set(key, value)}}+ if (nonce) {+ regionalUrl.searchParams.set('state', nonce)+ }return Response.redirect(regionalUrl.toString(), 302)}diff --git a/services/oauth-proxy/src/handlers/callback.ts b/services/oauth-proxy/src/handlers/callback.tsindex 75ad9b5f74f6..3137a10ec5de 100644--- a/services/oauth-proxy/src/handlers/callback.ts+++ b/services/oauth-proxy/src/handlers/callback.ts@@ -1,4 +1,4 @@-import { getCallbackRedirectUri } from '@/lib/kv'+import { deletePendingCallback, getPendingCallback } from '@/lib/kv'/*** OAuth Callback Interception — proxy receives the regional server's callback@@ -15,16 +15,28 @@ export async function handleCallback(request: Request, kv: KVNamespace): Promisereturn new Response('Missing state parameter', { status: 400 })}- const originalRedirectUri = await getCallbackRedirectUri(kv, state)- if (!originalRedirectUri) {+ const record = await getPendingCallback(kv, state)+ if (!record) {return new Response('State expired or invalid', { status: 400 })}- // Forward all query params (code, state, error, error_description) to the client- const clientUrl = new URL(originalRedirectUri)+ // A transient KV failure here should not turn an already-verified callback into a 500.+ try {+ await deletePendingCallback(kv, state)+ } catch {+ console.warn(JSON.stringify({ handler: 'callback', error: 'pending_callback_delete_failed' }))+ }++ const clientUrl = new URL(record.redirect_uri)for (const [key, value] of url.searchParams.entries()) {+ if (key === 'state') {+ continue+ }clientUrl.searchParams.set(key, value)}+ if (record.state !== null) {+ clientUrl.searchParams.set('state', record.state)+ }return Response.redirect(clientUrl.toString(), 302)}diff --git a/services/oauth-proxy/src/lib/kv.ts b/services/oauth-proxy/src/lib/kv.tsindex 11e1dba588ba..25bf24fe38ea 100644--- a/services/oauth-proxy/src/lib/kv.ts+++ b/services/oauth-proxy/src/lib/kv.ts@@ -12,9 +12,11 @@ export interface ClientMapping {const CLIENT_PREFIX = 'client:'const REGION_PREFIX = 'region:'const CALLBACK_PREFIX = 'callback:'+const PENDING_CALLBACK_PREFIX = 'pending_callback:'const REGION_SELECTION_TTL = 3600const CALLBACK_TTL = 3600+const PENDING_CALLBACK_TTL = 3600// Cloudflare KV caps key names at 512 bytes. Callers may pass opaque values// (notably the OAuth `state` parameter) that exceed that limit, so we derive@@ -57,6 +59,26 @@ export async function getCallbackRedirectUri(kv: KVNamespace, key: string): Promreturn kv.get(`${CALLBACK_PREFIX}${await hashKey(key)}`)}+export interface PendingCallback {+ redirect_uri: string+ state: string | null+}++export async function putPendingCallback(kv: KVNamespace, nonce: string, record: PendingCallback): Promise<void> {+ await kv.put(`${PENDING_CALLBACK_PREFIX}${await hashKey(nonce)}`, JSON.stringify(record), {+ expirationTtl: PENDING_CALLBACK_TTL,+ })+}++export async function getPendingCallback(kv: KVNamespace, nonce: string): Promise<PendingCallback | null> {+ const data = await kv.get(`${PENDING_CALLBACK_PREFIX}${await hashKey(nonce)}`, 'json')+ return data as PendingCallback | null+}++export async function deletePendingCallback(kv: KVNamespace, nonce: string): Promise<void> {+ await kv.delete(`${PENDING_CALLBACK_PREFIX}${await hashKey(nonce)}`)+}+/*** 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_iddiff --git a/services/oauth-proxy/tests/authorize.test.ts b/services/oauth-proxy/tests/authorize.test.tsindex 057b659021e0..1f24bcd5f5a9 100644--- a/services/oauth-proxy/tests/authorize.test.ts+++ b/services/oauth-proxy/tests/authorize.test.ts@@ -108,7 +108,7 @@ describe('handleAuthorize', () => {expect(data.error_description).toBe('redirect_uri is not registered for this client')})- it('stores region selection and callback redirect_uri keyed by state and client_id', async () => {+ it('stores region selection and callback redirect_uri keyed by client_id, and a pending callback keyed by nonce', async () => {const mapping = {us_client_id: 'us_id',eu_client_id: 'eu_id',@@ -125,31 +125,38 @@ describe('handleAuthorize', () => {const request = new Request('https://oauth.posthog.com/oauth/authorize/?client_id=us_id&redirect_uri=http://localhost:3000/callback&response_type=code&state=abc123&_region=eu')- await handleAuthorize(request, mockKV)+ const response = await handleAuthorize(request, mockKV)++ const location = new URL(response.headers.get('location')!)+ const nonce = location.searchParams.get('state')!+ expect(nonce).not.toBe('abc123')const putCalls = vi.mocked(mockKV.put).mock.calls- const stateHash = await hashKey('abc123')const clientHash = await hashKey('us_id')+ const nonceHash = await hashKey(nonce)- // Region selection stored by both state and client_id- const regionByState = putCalls.find(([key]) => (key as string) === `region:${stateHash}`)const regionByClient = putCalls.find(([key]) => (key as string) === `region:${clientHash}`)- expect(regionByState).toBeTruthy()- expect(regionByState![1]).toBe('eu')expect(regionByClient).toBeTruthy()expect(regionByClient![1]).toBe('eu')- // Callback redirect_uri stored by both state and client_id- const callbackByState = putCalls.find(([key]) => (key as string) === `callback:${stateHash}`)const callbackByClient = putCalls.find(([key]) => (key as string) === `callback:${clientHash}`)- expect(callbackByState).toBeTruthy()- expect(callbackByState![1]).toBe('http://localhost:3000/callback')expect(callbackByClient).toBeTruthy()expect(callbackByClient![1]).toBe('http://localhost:3000/callback')++ const pendingByNonce = putCalls.find(([key]) => (key as string) === `pending_callback:${nonceHash}`)+ expect(pendingByNonce).toBeTruthy()+ expect(JSON.parse(pendingByNonce![1] as string)).toEqual({+ redirect_uri: 'http://localhost:3000/callback',+ state: 'abc123',+ })++ const stateHash = await hashKey('abc123')+ expect(putCalls.find(([key]) => (key as string) === `region:${stateHash}`)).toBeUndefined()+ expect(putCalls.find(([key]) => (key as string) === `callback:${stateHash}`)).toBeUndefined()})- it('writes bounded-length KV keys even for very large state values', async () => {+ it('writes bounded-length KV keys even for very large state values, and holds the state in the flow record', async () => {const mapping = {us_client_id: 'us_id',eu_client_id: 'eu_id',@@ -171,11 +178,22 @@ describe('handleAuthorize', () => {const response = await handleAuthorize(request, mockKV)expect(response.status).toBe(302)++ const location = new URL(response.headers.get('location')!)+ const nonce = location.searchParams.get('state')!+ expect(nonce).not.toBe(longState)+ expect(nonce.length).toBeLessThan(100)+const putCalls = vi.mocked(mockKV.put).mock.callsexpect(putCalls.length).toBeGreaterThan(0)for (const [key] of putCalls) {expect((key as string).length).toBeLessThanOrEqual(512)}++ const nonceHash = await hashKey(nonce)+ const pendingCallback = putCalls.find(([key]) => (key as string) === `pending_callback:${nonceHash}`)+ expect(pendingCallback).toBeTruthy()+ expect((JSON.parse(pendingCallback![1] as string) as { state: string }).state).toBe(longState)})it('passes redirect_uri through without interception for legacy clients (no stored redirect_uris)', async () => {diff --git a/services/oauth-proxy/tests/callback.test.ts b/services/oauth-proxy/tests/callback.test.tsindex bc6179a8fa84..44a204056430 100644--- a/services/oauth-proxy/tests/callback.test.ts+++ b/services/oauth-proxy/tests/callback.test.ts@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import { handleCallback } from '@/handlers/callback'import { hashKey } from '@/lib/kv'-import { createMockKV, mockKVGet } from './helpers'+import { createInMemoryKV, createMockKV, mockKVGet } from './helpers'const mockKV = createMockKV()@@ -12,16 +12,18 @@ beforeEach(() => {})describe('handleCallback', () => {- it('redirects to original redirect_uri with code and state', async () => {- const stateHash = await hashKey('test_state_123')+ it("redirects to original redirect_uri with code and the client's original state", async () => {+ const nonceHash = await hashKey('proxy_nonce_123')mockKVGet(mockKV, (key: string) => {- if (key === `callback:${stateHash}`) {- return Promise.resolve('http://localhost:3000/callback')+ if (key === `pending_callback:${nonceHash}`) {+ return Promise.resolve({ redirect_uri: 'http://localhost:3000/callback', state: 'test_state_123' })}return Promise.resolve(null)})- const request = new Request('https://oauth.posthog.com/oauth/callback/?code=auth_code_abc&state=test_state_123')+ const request = new Request(+ 'https://oauth.posthog.com/oauth/callback/?code=auth_code_abc&state=proxy_nonce_123'+ )const response = await handleCallback(request, mockKV)expect(response.status).toBe(302)@@ -31,6 +33,65 @@ describe('handleCallback', () => {expect(location.searchParams.get('state')).toBe('test_state_123')})+ it('deletes the flow record after reading it, so the nonce is single-use', async () => {+ const kv = createInMemoryKV()+ const nonceHash = await hashKey('single_use_nonce')+ await kv.put(+ `pending_callback:${nonceHash}`,+ JSON.stringify({ redirect_uri: 'http://localhost:3000/callback', state: 'orig_state' })+ )++ const request = new Request(+ 'https://oauth.posthog.com/oauth/callback/?code=auth_code_abc&state=single_use_nonce'+ )+ const first = await handleCallback(request, kv)+ expect(first.status).toBe(302)++ const second = await handleCallback(request, kv)+ expect(second.status).toBe(400)+ expect(await second.text()).toBe('State expired or invalid')+ })++ it('still redirects to the client when deleting the flow record fails', async () => {+ const nonceHash = await hashKey('delete_fails_nonce')+ mockKVGet(mockKV, (key: string) => {+ if (key === `pending_callback:${nonceHash}`) {+ return Promise.resolve({ redirect_uri: 'http://localhost:3000/callback', state: 'orig_state' })+ }+ return Promise.resolve(null)+ })+ vi.mocked(mockKV.delete).mockRejectedValue(new Error('KV transient failure'))++ const request = new Request(+ 'https://oauth.posthog.com/oauth/callback/?code=auth_code_abc&state=delete_fails_nonce'+ )+ const response = await handleCallback(request, mockKV)++ expect(response.status).toBe(302)+ const location = new URL(response.headers.get('location')!)+ expect(location.origin + location.pathname).toBe('http://localhost:3000/callback')+ expect(location.searchParams.get('code')).toBe('auth_code_abc')+ expect(location.searchParams.get('state')).toBe('orig_state')+ })++ it('carries no state param when the flow record has no client state', async () => {+ const nonceHash = await hashKey('nonce_no_state')+ mockKVGet(mockKV, (key: string) => {+ if (key === `pending_callback:${nonceHash}`) {+ return Promise.resolve({ redirect_uri: 'http://localhost:3000/callback', state: null })+ }+ return Promise.resolve(null)+ })++ const request = new Request('https://oauth.posthog.com/oauth/callback/?code=auth_code_abc&state=nonce_no_state')+ const response = await handleCallback(request, mockKV)++ expect(response.status).toBe(302)+ const location = new URL(response.headers.get('location')!)+ expect(location.searchParams.get('code')).toBe('auth_code_abc')+ expect(location.searchParams.has('state')).toBe(false)+ })+it('returns 400 when state parameter is missing', async () => {const request = new Request('https://oauth.posthog.com/oauth/callback/?code=auth_code_abc')const response = await handleCallback(request, mockKV)@@ -39,7 +100,7 @@ describe('handleCallback', () => {expect(await response.text()).toBe('Missing state parameter')})- it('returns 400 when state is expired or unknown', async () => {+ it('returns 400 when the nonce is expired or unknown', async () => {mockKVGet(mockKV, () => Promise.resolve(null))const request = new Request('https://oauth.posthog.com/oauth/callback/?code=auth_code_abc&state=expired_state')@@ -49,17 +110,17 @@ describe('handleCallback', () => {expect(await response.text()).toBe('State expired or invalid')})- it('forwards error params to client redirect_uri', async () => {- const stateHash = await hashKey('err_state')+ it("forwards error params to the client's redirect_uri and restores its original state", async () => {+ const nonceHash = await hashKey('err_nonce')mockKVGet(mockKV, (key: string) => {- if (key === `callback:${stateHash}`) {- return Promise.resolve('http://localhost:3000/callback')+ if (key === `pending_callback:${nonceHash}`) {+ return Promise.resolve({ redirect_uri: 'http://localhost:3000/callback', state: 'client_err_state' })}return Promise.resolve(null)})const request = new Request(- 'https://oauth.posthog.com/oauth/callback/?error=access_denied&error_description=User+denied+access&state=err_state'+ 'https://oauth.posthog.com/oauth/callback/?error=access_denied&error_description=User+denied+access&state=err_nonce')const response = await handleCallback(request, mockKV)@@ -67,6 +128,6 @@ describe('handleCallback', () => {const location = new URL(response.headers.get('location')!)expect(location.searchParams.get('error')).toBe('access_denied')expect(location.searchParams.get('error_description')).toBe('User denied access')- expect(location.searchParams.get('state')).toBe('err_state')+ expect(location.searchParams.get('state')).toBe('client_err_state')})})diff --git a/services/oauth-proxy/tests/helpers.ts b/services/oauth-proxy/tests/helpers.tsindex 037d54328d7b..cb6a57ab14a3 100644--- a/services/oauth-proxy/tests/helpers.ts+++ b/services/oauth-proxy/tests/helpers.ts@@ -10,6 +10,29 @@ export function createMockKV(): KVNamespace {} as unknown as KVNamespace}+export function createInMemoryKV(): KVNamespace {+ const store = new Map<string, string>()+ return {+ get: vi.fn((key: string, options?: unknown) => {+ const value = store.get(key)+ if (value === undefined) {+ return Promise.resolve(null)+ }+ return Promise.resolve(options === 'json' ? JSON.parse(value) : value)+ }),+ put: vi.fn((key: string, value: string) => {+ store.set(key, value)+ return Promise.resolve(undefined)+ }),+ delete: vi.fn((key: string) => {+ store.delete(key)+ return Promise.resolve(undefined)+ }),+ list: vi.fn(),+ getWithMetadata: vi.fn(),+ } as unknown as KVNamespace+}+// eslint-disable-next-line @typescript-eslint/no-explicit-anytype AnyFn = (...args: any[]) => anydiff --git a/services/oauth-proxy/tests/security.test.ts b/services/oauth-proxy/tests/security.test.tsnew file mode 100644index 000000000000..8f7c54cea7b7--- /dev/null+++ b/services/oauth-proxy/tests/security.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest'++import { handleAuthorize } from '@/handlers/authorize'+import { handleCallback } from '@/handlers/callback'+import { putClientMapping } from '@/lib/kv'++import { createInMemoryKV } from './helpers'++describe('cross-client state collision', () => {+ it("does not let a second client's flow steal the first client's authorization code", async () => {+ const kv = createInMemoryKV()++ await putClientMapping(kv, 'clientA', {+ us_client_id: 'clientA_us',+ eu_client_id: 'clientA_eu',+ redirect_uris: ['https://a.example/cb'],+ created_at: Date.now(),+ })+ await putClientMapping(kv, 'clientB', {+ us_client_id: 'clientB_us',+ eu_client_id: 'clientB_eu',+ redirect_uris: ['https://b.example/cb'],+ created_at: Date.now(),+ })++ const requestA = new Request(+ 'https://oauth.posthog.com/oauth/authorize/?client_id=clientA&redirect_uri=https://a.example/cb&response_type=code&state=shared&_region=us'+ )+ const responseA = await handleAuthorize(requestA, kv)+ const locationA = new URL(responseA.headers.get('location')!)+ const stateSentForA = locationA.searchParams.get('state')!++ const requestB = new Request(+ 'https://oauth.posthog.com/oauth/authorize/?client_id=clientB&redirect_uri=https://b.example/cb&response_type=code&state=shared&_region=us'+ )+ await handleAuthorize(requestB, kv)++ const callbackRequest = new Request(+ `https://oauth.posthog.com/oauth/callback/?code=victim_auth_code&state=${stateSentForA}`+ )+ const callbackResponse = await handleCallback(callbackRequest, kv)++ expect(callbackResponse.status).toBe(302)+ const location = new URL(callbackResponse.headers.get('location')!)+ expect(location.origin + location.pathname).toBe('https://a.example/cb')+ expect(location.searchParams.get('code')).toBe('victim_auth_code')+ expect(location.searchParams.get('state')).toBe('shared')+ })+})