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.

refactor(oauth-proxy): introduce reusable request validators (#72684)

Rafael Audibert0cd5ef65dd34
diff --git a/services/oauth-proxy/src/handlers/authorize.ts b/services/oauth-proxy/src/handlers/authorize.ts
index 6b1ef28abde4..53c73bf8e233 100644
--- a/services/oauth-proxy/src/handlers/authorize.ts
+++ b/services/oauth-proxy/src/handlers/authorize.ts
@@ -1,5 +1,6 @@
import { type Region, baseUrlForRegion } from '@/lib/constants'
import { type ClientMapping, getClientMapping, putCallbackRedirectUri, putRegionSelection } from '@/lib/kv'
+import { type ValidationError, errorResponse } from '@/lib/validation'
import REGION_PICKER_HTML from '../static/region-picker.html'
@@ -12,26 +13,17 @@ const REGION_PICKER_HEADERS: Record<string, string> = {
'Referrer-Policy': 'no-referrer',
}
-// OAuth request parameters MUST NOT be included more than once (RFC 6749 §3.1).
-// We enforce it because the proxy reads these with `.get()` (first value) for KV
-// keying but forwards the last value to the regional server via `.set()`. A
-// duplicated `state` splits those two reads, letting an attacker route a victim's
-// callback to a preloaded redirect URI. `resource` (RFC 8707) is intentionally
-// excluded — it is allowed to repeat.
-const SINGLE_VALUED_PARAMS = [
- 'state',
- 'client_id',
- 'redirect_uri',
- 'response_type',
- 'scope',
- 'code_challenge',
- 'code_challenge_method',
-] as const
-
-function findDuplicatedParam(url: URL): string | null {
- for (const param of SINGLE_VALUED_PARAMS) {
- if (url.searchParams.getAll(param).length > 1) {
- return param
+// Prevent open redirects: for clients registered through the proxy (which have
+// stored redirect_uris), the requested redirect_uri must be one of them. Legacy
+// clients without stored redirect_uris fall through to regional server validation.
+function validateRegisteredRedirectUri(
+ redirectUri: string | null,
+ mapping: ClientMapping | null
+): ValidationError | null {
+ if (mapping?.redirect_uris && redirectUri && !mapping.redirect_uris.includes(redirectUri)) {
+ return {
+ error: 'invalid_request',
+ error_description: 'redirect_uri is not registered for this client',
}
}
return null
@@ -49,17 +41,6 @@ function findDuplicatedParam(url: URL): string | null {
export async function handleAuthorize(request: Request, kv: KVNamespace): Promise<Response> {
const url = new URL(request.url)
- const duplicatedParam = findDuplicatedParam(url)
- if (duplicatedParam) {
- return new Response(
- JSON.stringify({
- error: 'invalid_request',
- error_description: `Duplicate ${duplicatedParam} parameter is not allowed`,
- }),
- { status: 400, headers: { 'Content-Type': 'application/json' } }
- )
- }
-
// If region is already selected (via query param from the picker page),
// redirect to the regional authorize endpoint
const selectedRegion = url.searchParams.get('_region') as Region | null
@@ -86,18 +67,9 @@ async function redirectToRegionalAuthorize(url: URL, region: Region, kv: KVNames
}
}
- // Validate redirect_uri against registered URIs to prevent open redirects.
- // Only enforced for clients registered through the proxy (which have stored redirect_uris).
- if (mapping?.redirect_uris && originalRedirectUri) {
- if (!mapping.redirect_uris.includes(originalRedirectUri)) {
- return new Response(
- JSON.stringify({
- error: 'invalid_request',
- error_description: 'redirect_uri is not registered for this client',
- }),
- { status: 400, headers: { 'Content-Type': 'application/json' } }
- )
- }
+ const redirectUriError = validateRegisteredRedirectUri(originalRedirectUri, mapping)
+ if (redirectUriError) {
+ return errorResponse(redirectUriError)
}
// Store region selection keyed by both state and client_id.
diff --git a/services/oauth-proxy/src/handlers/passthrough.ts b/services/oauth-proxy/src/handlers/passthrough.ts
index 636b5739d7f5..faa95fbb7272 100644
--- a/services/oauth-proxy/src/handlers/passthrough.ts
+++ b/services/oauth-proxy/src/handlers/passthrough.ts
@@ -1,6 +1,7 @@
import { POSTHOG_EU_BASE_URL, POSTHOG_US_BASE_URL } from '@/lib/constants'
import { getClientMapping, getRegionSelection } from '@/lib/kv'
import { proxyPostWithClientId, proxyToRegion, tryBothRegions } from '@/lib/proxy'
+import { errorResponse } from '@/lib/validation'
/**
* Passthrough handlers for OAuth endpoints that simply need to reach the correct region.
@@ -79,10 +80,7 @@ async function routeByClientId(request: Request, kv: KVNamespace, path: string):
const json = JSON.parse(body) as Record<string, unknown>
clientId = (json.client_id as string) || null
} catch {
- return new Response(
- JSON.stringify({ error: 'invalid_request', error_description: 'Malformed JSON body' }),
- { status: 400, headers: { 'Content-Type': 'application/json' } }
- )
+ return errorResponse({ error: 'invalid_request', error_description: 'Malformed JSON body' })
}
} else {
const params = new URLSearchParams(body)
diff --git a/services/oauth-proxy/src/handlers/token.ts b/services/oauth-proxy/src/handlers/token.ts
index 8370adeaaf58..6cccb0c47b64 100644
--- a/services/oauth-proxy/src/handlers/token.ts
+++ b/services/oauth-proxy/src/handlers/token.ts
@@ -7,6 +7,7 @@ import {
resolveMappingRewrite,
} from '@/lib/kv'
import { proxyPostWithClientId, tryBothRegions } from '@/lib/proxy'
+import { errorResponse } from '@/lib/validation'
/**
* OAuth Token Exchange — proxy to the correct region.
@@ -29,9 +30,9 @@ export async function handleToken(request: Request, kv: KVNamespace): Promise<Re
clientId = (json.client_id as string) || null
grantType = (json.grant_type as string) || null
} catch {
- return new Response(
- JSON.stringify({ error: 'invalid_request', error_description: 'Malformed JSON body' }),
- { status: 400, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' } }
+ return errorResponse(
+ { error: 'invalid_request', error_description: 'Malformed JSON body' },
+ { 'Cache-Control': 'no-store' }
)
}
} else {
diff --git a/services/oauth-proxy/src/index.ts b/services/oauth-proxy/src/index.ts
index 0732bdf2cac9..63d27bcda95c 100644
--- a/services/oauth-proxy/src/index.ts
+++ b/services/oauth-proxy/src/index.ts
@@ -13,6 +13,7 @@ import { handleMetadata } from '@/handlers/metadata'
import { handleIntrospect, handleJwks, handleRevoke, handleUserInfo } from '@/handlers/passthrough'
import { handleRegister } from '@/handlers/register'
import { handleToken } from '@/handlers/token'
+import { type Validator, errorResponse, noDuplicateParams, runValidators } from '@/lib/validation'
export interface Env {
AUTH_KV: KVNamespace
@@ -23,6 +24,7 @@ type Handler = (request: Request, kv: KVNamespace) => Response | Promise<Respons
interface Route {
paths: string[]
method?: string
+ validators?: Validator[]
handler: Handler
}
@@ -46,6 +48,21 @@ const routes: Route[] = [
},
{
paths: ['/oauth/authorize', '/authorize'],
+ // The proxy reads these with `.get()` (first value) for KV keying but forwards
+ // the last value downstream via `.set()`; a duplicate would split those reads
+ // and let an attacker route a victim's callback to a preloaded redirect URI.
+ // `resource` (RFC 8707) is intentionally excluded — it is allowed to repeat.
+ validators: [
+ noDuplicateParams(
+ 'state',
+ 'client_id',
+ 'redirect_uri',
+ 'response_type',
+ 'scope',
+ 'code_challenge',
+ 'code_challenge_method'
+ ),
+ ],
handler: handleAuthorize,
},
{
@@ -84,6 +101,12 @@ export default {
continue
}
if (route.paths.some((p) => normalizePath(p) === normalized)) {
+ if (route.validators) {
+ const validationError = runValidators(route.validators, request, url)
+ if (validationError) {
+ return errorResponse(validationError)
+ }
+ }
return await route.handler(request, env.AUTH_KV)
}
}
diff --git a/services/oauth-proxy/src/lib/validation.ts b/services/oauth-proxy/src/lib/validation.ts
new file mode 100644
index 000000000000..139d808f062c
--- /dev/null
+++ b/services/oauth-proxy/src/lib/validation.ts
@@ -0,0 +1,57 @@
+/**
+ * Request validation primitives.
+ *
+ * A `Validator` is a pure function of the request that returns a `ValidationError`
+ * when a rule is broken, or `null` when it passes. Routes declare validators in
+ * `index.ts` and the router runs them before the handler, so request-shape rules
+ * live in one place instead of being smeared across controllers.
+ *
+ * Validators are intentionally synchronous and stateless. Rules that need I/O
+ * (e.g. checking a value against a stored KV mapping) stay in the handler, which
+ * can still reuse `ValidationError` + `errorResponse` for a consistent 400.
+ */
+
+export interface ValidationError {
+ error: string
+ error_description: string
+}
+
+export type Validator = (request: Request, url: URL) => ValidationError | null
+
+/** Render a `ValidationError` as an OAuth-style 400 JSON response. */
+export function errorResponse(error: ValidationError, extraHeaders: Record<string, string> = {}): Response {
+ return new Response(JSON.stringify(error), {
+ status: 400,
+ headers: { 'Content-Type': 'application/json', ...extraHeaders },
+ })
+}
+
+/** Run validators in order, returning the first failure (or `null` if all pass). */
+export function runValidators(validators: Validator[], request: Request, url: URL): ValidationError | null {
+ for (const validate of validators) {
+ const error = validate(request, url)
+ if (error) {
+ return error
+ }
+ }
+ return null
+}
+
+/**
+ * Rejects a request that repeats any of the named query params.
+ *
+ * OAuth request parameters MUST NOT be included more than once (RFC 6749 §3.1).
+ */
+export function noDuplicateParams(...params: string[]): Validator {
+ return (_request, url) => {
+ for (const param of params) {
+ if (url.searchParams.getAll(param).length > 1) {
+ return {
+ error: 'invalid_request',
+ error_description: `Duplicate ${param} parameter is not allowed`,
+ }
+ }
+ }
+ return null
+ }
+}
diff --git a/services/oauth-proxy/tests/authorize.test.ts b/services/oauth-proxy/tests/authorize.test.ts
index 5471ecca732d..057b659021e0 100644
--- a/services/oauth-proxy/tests/authorize.test.ts
+++ b/services/oauth-proxy/tests/authorize.test.ts
@@ -202,28 +202,6 @@ describe('handleAuthorize', () => {
expect(callbackPuts).toHaveLength(0)
})
- it.each([
- 'state',
- 'client_id',
- 'redirect_uri',
- 'response_type',
- 'scope',
- 'code_challenge',
- 'code_challenge_method',
- ])('rejects duplicate %s to prevent parameter-pollution code theft', async (param) => {
- const request = new Request(
- `https://oauth.posthog.com/oauth/authorize/?client_id=abc&response_type=code&${param}=first&${param}=second&_region=us`
- )
- const response = await handleAuthorize(request, mockKV)
-
- expect(response.status).toBe(400)
- const data = (await response.json()) as Record<string, unknown>
- expect(data.error).toBe('invalid_request')
- expect(data.error_description).toBe(`Duplicate ${param} parameter is not allowed`)
- // Nothing gets keyed in KV when the request is rejected up front.
- expect(vi.mocked(mockKV.put)).not.toHaveBeenCalled()
- })
-
it('sets security and cache headers on region picker page', async () => {
const request = new Request('https://oauth.posthog.com/oauth/authorize/?client_id=abc&response_type=code')
const response = await handleAuthorize(request, mockKV)
diff --git a/services/oauth-proxy/tests/router.test.ts b/services/oauth-proxy/tests/router.test.ts
index 2efca272d0f2..51843b8611e4 100644
--- a/services/oauth-proxy/tests/router.test.ts
+++ b/services/oauth-proxy/tests/router.test.ts
@@ -2,6 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import worker from '@/index'
+import { createMockKV } from './helpers'
+
const mockEnv = {
AUTH_KV: {} as KVNamespace,
}
@@ -49,6 +51,29 @@ describe('router', () => {
expect(response.headers.get('content-type')).toContain(expectedContentType)
})
+ it.each([
+ 'state',
+ 'client_id',
+ 'redirect_uri',
+ 'response_type',
+ 'scope',
+ 'code_challenge',
+ 'code_challenge_method',
+ ])('rejects duplicate %s on /oauth/authorize before the handler runs', async (param) => {
+ const kv = createMockKV()
+ const request = new Request(
+ `https://oauth.posthog.com/oauth/authorize/?client_id=abc&response_type=code&${param}=first&${param}=second&_region=us`
+ )
+ const response = await worker.fetch(request, { AUTH_KV: kv })
+
+ expect(response.status).toBe(400)
+ const data = (await response.json()) as Record<string, unknown>
+ expect(data.error).toBe('invalid_request')
+ expect(data.error_description).toBe(`Duplicate ${param} parameter is not allowed`)
+ // Rejected at the router before the handler, so nothing is keyed in KV.
+ expect(vi.mocked(kv.put)).not.toHaveBeenCalled()
+ })
+
it('returns 404 for unknown paths', async () => {
const request = new Request('https://oauth.posthog.com/unknown')
const response = await worker.fetch(request, mockEnv)