: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(data-warehouse): keep an OAuth connect failure on screen in the source wizard (#101373)
Tom Owers4b6cfe63847a
diff --git a/frontend/src/lib/integrations/integrationsLogic.test.ts b/frontend/src/lib/integrations/integrationsLogic.test.tsindex ea1d015f9352..a5034014b474 100644--- a/frontend/src/lib/integrations/integrationsLogic.test.ts+++ b/frontend/src/lib/integrations/integrationsLogic.test.ts@@ -267,6 +267,32 @@ describe('integrationsLogic', () => {document.cookie = 'ph_oauth_state=; expires=Thu, 01 Jan 1970 00:00:00 GMT'})+ // The data warehouse source wizard shows the reason beside its connect button, so both a+ // provider rejection and an expired state reach it in the URL rather than as a toast that+ // is gone before the user retries.+ it.each([+ ['a rejected connect', { error: 'access_denied' }, 'access_denied'],+ ['an expired state', { code: 'oauth-code' }, 'posthog_state_expired'],+ ])('carries %s back to the source wizard', async (_name, extraParams, expectedError) => {+ const errorSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast')+ document.cookie = 'ph_oauth_state=a-different-token'++ await expectLogic(logic, () => {+ logic.actions.handleOauthCallback('meta-ads' as IntegrationKind, {+ state: 'next=%2Fdata-warehouse%2Fnew-source%3Fkind%3Dmeta-ads&token=csrf-tok',+ ...extraParams,+ })+ }).toFinishAllListeners()++ expect(createSpy).not.toHaveBeenCalled()+ expect(router.values.location.pathname).toBe(`/project/${MOCK_TEAM_ID}/data-warehouse/new-source`)+ expect(router.values.searchParams.integration_error).toBe(expectedError)+ expect(router.values.searchParams.kind).toBe('meta-ads')+ expect(errorSpy).not.toHaveBeenCalled()++ document.cookie = 'ph_oauth_state=; expires=Thu, 01 Jan 1970 00:00:00 GMT'+ })+describe('integration create team scoping', () => {let requestedTeamIds: string[]diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.tsindex 30d8933c2550..ae77ac7042f0 100644--- a/frontend/src/lib/integrations/integrationsLogic.ts+++ b/frontend/src/lib/integrations/integrationsLogic.ts@@ -8,7 +8,11 @@ import api, { ApiError, getCookie } from 'lib/api'import { globalSetupLogic } from 'lib/components/ProductSetup'import { buildGithubDisconnectDescription } from 'lib/integrations/githubDisconnectCopy'import { describeGithubSetupError, GITHUB_INSTALL_PENDING_MESSAGE } from 'lib/integrations/githubSetupErrors'-import { describeOAuthCallbackError, INTEGRATION_ERROR_PARAM } from 'lib/integrations/oauthCallbackErrors'+import {+ describeOAuthCallbackError,+ INTEGRATION_ERROR_PARAM,+ OAUTH_STATE_EXPIRED,+} from 'lib/integrations/oauthCallbackErrors'import { preflightLogic } from 'lib/logic/preflightLogic'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { isKeyOf } from 'lib/utils/guards'@@ -45,14 +49,18 @@ function toastApiError(e: unknown): void {lemonToast.error(detail || 'Something went wrong. Please try again.')}-// The integration landing page (`/integrations/:slug`) can keep a failed connect on screen as a-// banner beside the connect button, so it takes the reason in the URL instead of a toast that is-// gone by the time the user reads it. Everywhere else the toast is the only carrier.-function landsOnIntegrationPage(pathname: string): boolean {+// The integration landing page (`/integrations/:slug`) and the data warehouse source wizard can+// both keep a failed connect on screen as a banner beside the connect button, so they take the+// reason in the URL instead of a toast that is gone by the time the user reads it. Everywhere+// else the toast is the only carrier.+function landsOnErrorAwarePage(pathname: string): boolean {// Callers build ``next`` either from ``urls.integration(slug)`` or from the browser pathname,// so the project prefix is there in some flows and not others.const segments = removeProjectIdIfPresent(pathname).split('/').filter(Boolean)- return segments.length === 2 && segments[0] === 'integrations'+ if (segments.length === 2 && segments[0] === 'integrations') {+ return true+ }+ return segments.length === 2 && segments[0] === 'data-warehouse' && segments[1] === 'new-source'}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -1003,7 +1011,7 @@ export const integrationsLogic = kea<integrationsLogicType>([if (error) {actions.reportIntegrationConnectRejected(resolvedKind, String(error))const url = new URL(replaceUrl, window.location.origin)- if (landsOnIntegrationPage(url.pathname)) {+ if (landsOnErrorAwarePage(url.pathname)) {url.searchParams.set(INTEGRATION_ERROR_PARAM, String(error))replaceUrl = url.pathname + url.search + url.hash} else {@@ -1044,8 +1052,14 @@ export const integrationsLogic = kea<integrationsLogicType>([// match. That's recoverable by simply retrying, so say so instead of surfacing the generic// "Something went wrong" that a thrown error would fall back to.if (token !== getCookie('ph_oauth_state')) {- lemonToast.error('This connection attempt expired before it could finish. Please try connecting again.')- router.actions.replace(replaceUrl)+ const url = new URL(replaceUrl, window.location.origin)+ if (landsOnErrorAwarePage(url.pathname)) {+ url.searchParams.set(INTEGRATION_ERROR_PARAM, OAUTH_STATE_EXPIRED)+ router.actions.replace(url.pathname + url.search + url.hash)+ } else {+ lemonToast.error(describeOAuthCallbackError(OAUTH_STATE_EXPIRED, resolvedKind))+ router.actions.replace(replaceUrl)+ }return}diff --git a/frontend/src/lib/integrations/oauthCallbackErrors.ts b/frontend/src/lib/integrations/oauthCallbackErrors.tsindex 975101205ba5..fcb0c985c73b 100644--- a/frontend/src/lib/integrations/oauthCallbackErrors.ts+++ b/frontend/src/lib/integrations/oauthCallbackErrors.ts@@ -8,7 +8,15 @@// pinned: URL search param — the callback redirect and the landing page both read it.export const INTEGRATION_ERROR_PARAM = 'integration_error'+// Not a provider code: PostHog's own CSRF state cookie outlived the authorization round-trip, so+// the callback can't be verified. It rides the same param as the provider codes to reach whichever+// page the user lands on.+// pinned: URL search param value — the callback redirect and the landing page both read it.+export const OAUTH_STATE_EXPIRED = 'posthog_state_expired'+const OAUTH_CALLBACK_ERROR_MESSAGES: Record<string, string> = {+ [OAUTH_STATE_EXPIRED]:+ 'This connection attempt expired before it could finish. Start it again and approve access without waiting in between.',access_denied: 'Authorization was canceled. Please try connecting again and approve access to continue.',user_connector_authorize:'Authorization was not completed. Please try connecting again and approve access to continue.',diff --git a/products/data_warehouse/frontend/shared/components/forms/IntegrationChoice.tsx b/products/data_warehouse/frontend/shared/components/forms/IntegrationChoice.tsxindex e4a4488dd879..f679113788b1 100644--- a/products/data_warehouse/frontend/shared/components/forms/IntegrationChoice.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/IntegrationChoice.tsx@@ -5,6 +5,8 @@ import {IntegrationChoice,IntegrationConfigureProps,} from 'lib/components/CyclotronJob/integrations/IntegrationChoice'+import { describeOAuthCallbackError, INTEGRATION_ERROR_PARAM } from 'lib/integrations/oauthCallbackErrors'+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { urls } from 'scenes/urls'import { SourceConfigResponseApi } from 'products/warehouse_sources/frontend/generated/api.schemas'@@ -21,9 +23,13 @@ export function SourceIntegrationChoice({...props}: SourceIntegrationChoiceProps): JSX.Element {const { saveFormStateBeforeRedirect } = useActions(sourceWizardLogic)- const { location } = useValues(router)+ const { location, searchParams } = useValues(router)const sourceKind = sourceConfig.name.toLowerCase()+ // A failed authorization sends the user back here, where the connect button is. The callback+ // carries the reason in the URL rather than a toast, which would be gone before they retry.+ const oauthError = searchParams[INTEGRATION_ERROR_PARAM]+// In onboarding the wizard is embedded in the page. A full-page OAuth redirect to the// standalone new-source scene would drop the user out of the onboarding flow, so when we're// on an onboarding route we return to the current onboarding URL with the source kind instead.@@ -40,11 +46,16 @@ export function SourceIntegrationChoice({}return (- <IntegrationChoice- {...props}- integration={integration ?? sourceKind}- redirectUrl={redirectUrl}- beforeRedirect={saveFormStateBeforeRedirect}- />+ <div className="flex flex-col gap-2">+ {oauthError && (+ <LemonBanner type="error">{describeOAuthCallbackError(String(oauthError), sourceKind)}</LemonBanner>+ )}+ <IntegrationChoice+ {...props}+ integration={integration ?? sourceKind}+ redirectUrl={redirectUrl}+ beforeRedirect={saveFormStateBeforeRedirect}+ />+ </div>)}