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(oauth): send the state parameter to the API unchanged (#79891)

Michael Matlokafe8fb9552a09
diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
index 8d68fd7721e1..44646f047c40 100644
--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
@@ -1,11 +1,13 @@
import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+import { decodeParams } from 'kea-router'
+
import { userLogic } from 'scenes/userLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import { oauthAuthorizeLogic } from './oauthAuthorizeLogic'
+import { describeOAuthError, oauthAuthorizeLogic } from './oauthAuthorizeLogic'
describe('oauthAuthorizeLogic', () => {
let logic: ReturnType<typeof oauthAuthorizeLogic.build>
@@ -292,4 +294,108 @@ describe('oauthAuthorizeLogic', () => {
expect(logic.values.selectedOrganization).toBe(expectedOrg)
expect(logic.values.oauthAuthorization.scoped_teams).toEqual(expectedTeams)
})
+
+ // Opaque client-owned params must reach the API byte-for-byte, whatever they look like.
+ describe('OAuth parameter passthrough', () => {
+ const JSON_STATE = '{"flow_id":"5a8f3d48-c841-4375-b06d-5c828c86282d","provider":"posthog"}'
+
+ let sentBody: Record<string, any>
+
+ beforeEach(() => {
+ sentBody = {}
+ useMocks({
+ post: {
+ '/oauth/authorize/': async ({ request }) => {
+ sentBody = (await request.json()) as Record<string, any>
+ // No `redirect_to`, so the logic does not navigate the test page away.
+ return {}
+ },
+ },
+ })
+ })
+
+ const authorizeWithSearch = async (search: string): Promise<Record<string, any>> => {
+ // `replaceState` rather than `router.actions.push`: push rebuilds the search string
+ // from kea-router's decoded values, so it cannot reproduce a raw inbound URL.
+ window.history.replaceState({}, '', `/oauth/authorize${search}`)
+ await logic.asyncActions.cancel().catch(() => undefined)
+ return sentBody
+ }
+
+ it('sends a JSON state as the verbatim string the client provided', async () => {
+ const search = `?client_id=abc&state=${encodeURIComponent(JSON_STATE)}`
+ // This is what kea-router hands to `searchParams` — the value we must not send.
+ expect(decodeParams(search, '?').state).toEqual({
+ flow_id: '5a8f3d48-c841-4375-b06d-5c828c86282d',
+ provider: 'posthog',
+ })
+
+ const body = await authorizeWithSearch(search)
+ expect(body.state).toBe(JSON_STATE)
+ expect(body.client_id).toBe('abc')
+ })
+
+ it.each([
+ ['a boolean-like state', 'true'],
+ ['a numeric state with a leading zero', '0123'],
+ ['an array-like state', '[1,2]'],
+ ])('sends %s unchanged', async (_name, state) => {
+ const body = await authorizeWithSearch(`?state=${encodeURIComponent(state)}`)
+ expect(body.state).toBe(state)
+ })
+
+ it('sends null for a parameter the client omitted', async () => {
+ const body = await authorizeWithSearch('?client_id=abc')
+ expect(body.state).toBeNull()
+ expect(body.nonce).toBeNull()
+ })
+ })
+
+ describe('describeOAuthError', () => {
+ it('names the parameter that the serializer rejected', () => {
+ expect(describeOAuthError({ state: ['Not a valid string.'] })).toBe(
+ 'The application sent an incorrect authorization request. ' +
+ 'The parameter "state" is not correct: Not a valid string.'
+ )
+ })
+
+ it('describes every rejected parameter', () => {
+ expect(describeOAuthError({ state: ['Not a valid string.'], scope: ['Unknown scope.'] })).toBe(
+ 'The application sent an incorrect authorization request. ' +
+ 'The parameter "state" is not correct: Not a valid string. ' +
+ 'The parameter "scope" is not correct: Unknown scope.'
+ )
+ })
+
+ it('uses a non-field error as its own sentence', () => {
+ expect(describeOAuthError({ non_field_errors: ['The request expired.'] })).toBe(
+ 'The application sent an incorrect authorization request. The request expired.'
+ )
+ })
+
+ // `/oauth/authorize/` also fails with the RFC 6749 envelope (views.py:1274). Its keys
+ // are not parameter names, and `ApiError.message` would show the code, not the prose.
+ it('prefers the description over the code in an OAuth error envelope', () => {
+ expect(
+ describeOAuthError({
+ error: 'access_denied',
+ error_description: 'This organization has disabled AI data processing.',
+ })
+ ).toBe('This organization has disabled AI data processing.')
+ })
+
+ it.each([
+ ['no body', undefined],
+ ['a null body', null],
+ ['a plain string body', 'Bad Request'],
+ ['an array body', ['Bad Request']],
+ ['a body without messages', { state: [] }],
+ // Would otherwise read as a parameter named "error".
+ ['an envelope with no description', { error: 'invalid_client' }],
+ // DRF always sends a list, so a bare string is not a field error.
+ ['a non-list field value', { state: 'Not a valid string.' }],
+ ])('returns null for %s, so the caller falls back', (_name, data) => {
+ expect(describeOAuthError(data)).toBeNull()
+ })
+ })
})
diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
index 24f7a5f45e45..5456e57fcfff 100644
--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
@@ -110,20 +110,58 @@ const isNativeProtocol = (url: string): boolean => {
type OAuthAuthorizeResult = { redirectTo: string; isNative: boolean }
+// `/oauth/authorize/` fails in two shapes, and `ApiError` reads neither usefully: the RFC 6749
+// §4.1.2.1 envelope `{ error, error_description }`, where it surfaces the machine code rather
+// than the prose, and DRF serializer errors `{ "<field>": ["<message>"] }`, where it finds no
+// key at all and falls back to the transport text ("Non-OK response [POST ...] (status 400: )").
+export const describeOAuthError = (data: unknown): string | null => {
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
+ return null
+ }
+ const body = data as Record<string, unknown>
+
+ if (typeof body.error_description === 'string' && body.error_description) {
+ return body.error_description
+ }
+
+ const sentences: string[] = []
+ for (const [field, value] of Object.entries(body)) {
+ // DRF always reports field errors as a list, which is what tells them apart from the
+ // envelope above — `{ error: 'access_denied' }` is not a parameter named "error".
+ if (!Array.isArray(value)) {
+ continue
+ }
+ const messages = value.filter((message): message is string => typeof message === 'string' && !!message)
+ if (!messages.length) {
+ continue
+ }
+ const text = messages.join(' ')
+ sentences.push(field === 'non_field_errors' ? text : `The parameter "${field}" is not correct: ${text}`)
+ }
+ if (!sentences.length) {
+ return null
+ }
+ return ['The application sent an incorrect authorization request.', ...sentences].join(' ')
+}
+
const oauthAuthorize = async (
values: OAuthAuthorizationFormValues & { allow: boolean; scopes: string[] }
): Promise<OAuthAuthorizeResult | null> => {
+ // Not kea-router's `searchParams`: it JSON-parses object-like values and coerces numbers
+ // and booleans, and its own `location.search` is re-encoded from those. RFC 6749 A.5 allows
+ // any printable ASCII in `state`, so a raw-JSON state must reach the API byte-for-byte.
+ const params = new URLSearchParams(window.location.search)
try {
const response = await api.create('/oauth/authorize/', {
- client_id: router.values.searchParams['client_id'],
- redirect_uri: router.values.searchParams['redirect_uri'],
- response_type: router.values.searchParams['response_type'],
- state: router.values.searchParams['state'],
+ client_id: params.get('client_id'),
+ redirect_uri: params.get('redirect_uri'),
+ response_type: params.get('response_type'),
+ state: params.get('state'),
scope: values.scopes.join(' '),
- code_challenge: router.values.searchParams['code_challenge'],
- code_challenge_method: router.values.searchParams['code_challenge_method'],
- nonce: router.values.searchParams['nonce'],
- claims: router.values.searchParams['claims'],
+ code_challenge: params.get('code_challenge'),
+ code_challenge_method: params.get('code_challenge_method'),
+ nonce: params.get('nonce'),
+ claims: params.get('claims'),
scoped_organizations: values.access_type === 'organizations' ? values.scoped_organizations : [],
scoped_teams: values.access_type === 'teams' ? values.scoped_teams : [],
access_level:
@@ -139,7 +177,11 @@ const oauthAuthorize = async (
}
return null
} catch (error: any) {
- const detail = error?.detail || error?.message || 'Something went wrong while authorizing the application'
+ const detail =
+ error?.detail ||
+ describeOAuthError(error?.data) ||
+ error?.message ||
+ 'PostHog could not authorize the application.'
lemonToast.error(detail)
throw error
}
@@ -826,6 +868,9 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
redirectDomain: [
(s) => [s.oauthApplication],
(): string => {
+ // Stays on kea-router: a redirect_uri is always a URL, which `parseValue` leaves
+ // alone, and only the request payload needs verbatim bytes. Reading
+ // `window.location` here would break under Storybook's in-memory history.
const redirectUri = router.values.searchParams['redirect_uri'] as string
if (!redirectUri) {
return ''