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(integrations): explain a pending Slack admin approval on the OAuth callback (#97095)

posthog[bot]e34b5e785264
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 55652abf26e3..7f6929f30b9b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9628,6 +9628,10 @@ snapshots:
hash: v1.k794b7964.083ab1c7b52303db3543c12ccc1dee1bcd362b7a2b25d19f52634e25bc4fcfb2.SryekUv5NMLDw0c8j5Odv7nQPa-aqNycfHN-e6wtKm4
scenes-other-credential-review--only-a-connected-application--light:
hash: v1.k794b7964.863a15297cedff0b0558c9a91e10190800012f40172a83d8ba0872cbcc8034de.CFQjit_QDWfWGwtrS4ORtDnk5SexHWF6h53-DLHNyGw
+ scenes-other-integration-landing-page--connect-rejected--dark:
+ hash: v1.k794b7964.744ffc04fe74e99127eee73f8a1c395fe7c56d89447b71465a1797a1ef05b832.2I1sdaQ3oUvbNcUNwdAbHmTjccZ9vnAAUiV5loBZnEo
+ scenes-other-integration-landing-page--connect-rejected--light:
+ hash: v1.k794b7964.4d764e5044145135c98d1fe67537c316b254eee9711589487f1fd1f7ca04e5de.ozA4BOi6p1T7ugqONQH3a-6WLh2Fel6abrgxZdod-8k
scenes-other-integration-landing-page--connected--dark:
hash: v1.k794b7964.1a2abf46a5f43ec0e9bcf1f02115c68f3fab54fc8e8aec6f903e2481689d9a8c.oi6z4uOWfKTWAHVA_UhnCwGg-Zjal3CQ1Se4fDLVOMQ
scenes-other-integration-landing-page--connected--light:
diff --git a/frontend/src/lib/integrations/integrationsLogic.test.ts b/frontend/src/lib/integrations/integrationsLogic.test.ts
index ec9190df98a3..596993d5a8ac 100644
--- a/frontend/src/lib/integrations/integrationsLogic.test.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.test.ts
@@ -213,6 +213,43 @@ describe('integrationsLogic', () => {
})
})
+ // Slack answers `access_denied` when a workspace parks the install as an admin-approval
+ // request, and the user's next move is the connect button on the landing page. A toast is
+ // gone by then, so that page takes the reason in the URL and keeps it on screen; the
+ // settings page has no such banner and still needs the toast.
+ it.each([
+ [
+ 'the integration landing page',
+ '%2Fintegrations%2Fslack',
+ `/project/${MOCK_TEAM_ID}/integrations/slack`,
+ true,
+ ],
+ [
+ 'the settings page',
+ '%2Fproject%2F228502%2Fsettings%2Fproject-integrations',
+ '/project/228502/settings/project-integrations',
+ false,
+ ],
+ ])('carries a rejected connect back to %s', async (_name, encodedNext, expectedPathname, expectBanner) => {
+ const errorSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast')
+
+ await expectLogic(logic, () => {
+ logic.actions.handleOauthCallback('slack' as IntegrationKind, {
+ state: `next=${encodedNext}&token=csrf-tok`,
+ error: 'access_denied',
+ })
+ }).toFinishAllListeners()
+
+ expect(createSpy).not.toHaveBeenCalled()
+ expect(router.values.location.pathname).toBe(expectedPathname)
+ expect(router.values.searchParams.integration_error).toBe(expectBanner ? 'access_denied' : undefined)
+ if (expectBanner) {
+ expect(errorSpy).not.toHaveBeenCalled()
+ } else {
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('admin to approve new apps'))
+ }
+ })
+
it('does not create the integration when the OAuth state token no longer matches the cookie', async () => {
// A stale/expired flow: the cookie minted at authorize time is gone or changed, so the token
// carried in the state can't match. The callback must recover by redirecting back rather than
diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.ts
index 74658e420abc..614350a3f1f1 100644
--- a/frontend/src/lib/integrations/integrationsLogic.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.ts
@@ -8,9 +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 } from 'lib/integrations/oauthCallbackErrors'
+import { describeOAuthCallbackError, INTEGRATION_ERROR_PARAM } from 'lib/integrations/oauthCallbackErrors'
import { preflightLogic } from 'lib/logic/preflightLogic'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { isKeyOf } from 'lib/utils/guards'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { fromParamsGivenUrl } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -42,6 +44,16 @@ 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 {
+ // 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'
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface integrationsLogicValues {
preflight: PreflightStatus | null // preflightLogic
@@ -126,6 +138,13 @@ export interface integrationsLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface integrationsLogicActions {
+ reportIntegrationConnectRejected: (
+ kind: string,
+ error: string
+ ) => {
+ error: string
+ kind: string
+ } // eventUsageLogic
markTaskAsCompleted: (taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]) => {
taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]
} // globalSetupLogic
@@ -768,7 +787,7 @@ export const integrationsLogic = kea<integrationsLogicType>([
path(['lib', 'integrations', 'integrationsLogic']),
connect(() => ({
values: [preflightLogic, ['siteUrlMisconfigured', 'preflight'], teamLogic, ['currentProjectId']],
- actions: [globalSetupLogic, ['markTaskAsCompleted']],
+ actions: [globalSetupLogic, ['markTaskAsCompleted'], eventUsageLogic, ['reportIntegrationConnectRejected']],
})),
actions({
@@ -1060,7 +1079,14 @@ export const integrationsLogic = kea<integrationsLogicType>([
let replaceUrl: string = next || urls.settings('project-integrations')
if (error) {
- lemonToast.error(describeOAuthCallbackError(String(error)))
+ actions.reportIntegrationConnectRejected(resolvedKind, String(error))
+ const url = new URL(replaceUrl, window.location.origin)
+ if (landsOnIntegrationPage(url.pathname)) {
+ url.searchParams.set(INTEGRATION_ERROR_PARAM, String(error))
+ replaceUrl = url.pathname + url.search + url.hash
+ } else {
+ lemonToast.error(describeOAuthCallbackError(String(error), resolvedKind))
+ }
router.actions.replace(replaceUrl)
return
}
diff --git a/frontend/src/lib/integrations/oauthCallbackErrors.test.ts b/frontend/src/lib/integrations/oauthCallbackErrors.test.ts
index 37c36613b088..756d8ac590f3 100644
--- a/frontend/src/lib/integrations/oauthCallbackErrors.test.ts
+++ b/frontend/src/lib/integrations/oauthCallbackErrors.test.ts
@@ -18,6 +18,18 @@ describe('describeOAuthCallbackError', () => {
expect(describeOAuthCallbackError(code)).toBe(expected)
})
+ // Slack sends `access_denied` for an install parked as an admin-approval request too, so the
+ // generic "was canceled … approve access" copy is false twice over for that workspace.
+ it.each([
+ [
+ 'slack',
+ 'PostHog was not added to your Slack workspace. Either the install was declined, or your workspace requires an admin to approve new apps and the request is now waiting for one. Once an admin approves it, come back to this page and click "Add to Slack" again.',
+ ],
+ ['linkedin-ads', 'Authorization was canceled. Please try connecting again and approve access to continue.'],
+ ])('describes access_denied for %s', (kind, expected) => {
+ expect(describeOAuthCallbackError('access_denied', kind)).toBe(expected)
+ })
+
it('falls back to the raw code for unknown errors so support can identify them', () => {
expect(describeOAuthCallbackError('some_unmapped_code')).toBe('Failed due to "some_unmapped_code"')
})
diff --git a/frontend/src/lib/integrations/oauthCallbackErrors.ts b/frontend/src/lib/integrations/oauthCallbackErrors.ts
index eed16a82e52d..975101205ba5 100644
--- a/frontend/src/lib/integrations/oauthCallbackErrors.ts
+++ b/frontend/src/lib/integrations/oauthCallbackErrors.ts
@@ -3,6 +3,11 @@
// integration callback, so without this the user sees cryptic codes like `access_denied` or
// `user_connector_authorize` verbatim. Unknown codes fall back to the raw value so support can
// still identify them.
+// Search param carrying the raw provider error code from the callback to whichever page the user
+// lands on, so the explanation stays on screen instead of vanishing with a toast.
+// pinned: URL search param — the callback redirect and the landing page both read it.
+export const INTEGRATION_ERROR_PARAM = 'integration_error'
+
const OAUTH_CALLBACK_ERROR_MESSAGES: Record<string, string> = {
access_denied: 'Authorization was canceled. Please try connecting again and approve access to continue.',
user_connector_authorize:
@@ -13,6 +18,17 @@ const OAUTH_CALLBACK_ERROR_MESSAGES: Record<string, string> = {
temporarily_unavailable: 'The provider is temporarily unavailable. Please try again in a moment.',
}
-export function describeOAuthCallbackError(error: string): string {
- return OAUTH_CALLBACK_ERROR_MESSAGES[error] ?? `Failed due to "${error}"`
+// Slack answers `access_denied` for two different outcomes: someone declined the install, and a
+// workspace with app approval turned on filing a pending request for an admin to review. The
+// generic copy above claims the first and tells the user to approve access, which they cannot do.
+const OAUTH_CALLBACK_ERROR_MESSAGES_BY_KIND: Record<string, Record<string, string>> = {
+ slack: {
+ access_denied:
+ 'PostHog was not added to your Slack workspace. Either the install was declined, or your workspace requires an admin to approve new apps and the request is now waiting for one. Once an admin approves it, come back to this page and click "Add to Slack" again.',
+ },
+}
+
+export function describeOAuthCallbackError(error: string, kind?: string): string {
+ const kindSpecific = kind ? OAUTH_CALLBACK_ERROR_MESSAGES_BY_KIND[kind]?.[error] : undefined
+ return kindSpecific ?? OAUTH_CALLBACK_ERROR_MESSAGES[error] ?? `Failed due to "${error}"`
}
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 875bffe186f8..c26271e3ee71 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -1798,6 +1798,13 @@ export interface eventUsageLogicActions {
selfDriving: boolean | undefined
surface: IntegrationConnectSurface
}
+ reportIntegrationConnectRejected: (
+ kind: string,
+ error: string
+ ) => {
+ error: string
+ kind: string
+ }
reportInviteMembersButtonClicked: () => {
value: true
}
@@ -2379,6 +2386,7 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
surface,
selfDriving,
}),
+ reportIntegrationConnectRejected: (kind: string, error: string) => ({ kind, error }),
reportPersonalIntegrationConnectClicked: (kind: string) => ({ kind }),
reportGroupPropertyUpdated: (
action: 'added' | 'updated' | 'removed',
@@ -3338,6 +3346,15 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
self_driving: selfDriving,
})
},
+ // Counts connect attempts the provider sent back without a code. `integration_connect_clicked`
+ // only says the user started, so without this the drop-off is invisible outside session
+ // recordings — and `access_denied` in particular hides a workspace waiting on an admin.
+ reportIntegrationConnectRejected: ({ kind, error }) => {
+ posthog.capture('integration_connect_rejected', {
+ integration_kind: kind,
+ error,
+ })
+ },
// Personal integrations are a separate table with their own connect surface, so they get
// their own event: saved insights already count `integration_connect_clicked` unfiltered and
// would silently start including personal links.
diff --git a/frontend/src/scenes/integrations/IntegrationFullPage.stories.tsx b/frontend/src/scenes/integrations/IntegrationFullPage.stories.tsx
index b0a8bb14f68d..d07897a85499 100644
--- a/frontend/src/scenes/integrations/IntegrationFullPage.stories.tsx
+++ b/frontend/src/scenes/integrations/IntegrationFullPage.stories.tsx
@@ -1,8 +1,10 @@
import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_TEAM } from 'lib/api.mock'
import { Meta, StoryObj } from '@storybook/react'
+import { router } from 'kea-router'
import { OrganizationMembershipLevel } from 'lib/constants'
+import { urls } from 'scenes/urls'
import { mswDecorator } from '~/mocks/browser'
import preflightJson from '~/mocks/fixtures/_preflight.json'
@@ -17,6 +19,12 @@ const meta: Meta<typeof IntegrationFullPage> = {
component: IntegrationFullPage,
parameters: { layout: 'fullscreen', viewMode: 'story', mockDate: '2023-01-01' },
decorators: [
+ // Stories share one router across a run, so each one states the URL it renders at rather
+ // than inheriting whatever the previous story left behind.
+ function AtIntegrationUrl(Story, { parameters }) {
+ router.actions.push(urls.integration(Slack.slug), parameters.searchParams ?? {})
+ return <Story />
+ },
mswDecorator({
get: {
// slack_service.available drives whether the "Add to Slack" connect button shows
@@ -43,6 +51,14 @@ export const Connected: Story = {
decorators: [mswDecorator({ get: { '/api/environments/:id/integrations': { results: [mockIntegration] } } })],
}
+// A connect attempt the provider sent back without a code. Slack answers `access_denied` both when
+// someone declines and when the workspace files the install for an admin to approve, so the reason
+// has to sit next to the connect button rather than in a toast the user never reads in time.
+export const ConnectRejected: Story = {
+ decorators: [mswDecorator({ get: { '/api/environments/:id/integrations': { results: [] } } })],
+ parameters: { searchParams: { integration_error: 'access_denied' } },
+}
+
// An instance without Slack configured shows staff the instructions button instead of the connect
// button. That branch ignores ``centered``, so it relies on the page for its centered layout.
export const SlackNotConfigured: Story = {
diff --git a/frontend/src/scenes/integrations/IntegrationFullPage.tsx b/frontend/src/scenes/integrations/IntegrationFullPage.tsx
index a3ae61bb63dc..8318d93cee41 100644
--- a/frontend/src/scenes/integrations/IntegrationFullPage.tsx
+++ b/frontend/src/scenes/integrations/IntegrationFullPage.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
import { IconArrowLeft, IconCheckCircle, IconWarning } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonTextArea, Link, Spinner } from '@posthog/lemon-ui'
@@ -6,6 +7,7 @@ import { LemonBanner, LemonButton, LemonTextArea, Link, Spinner } from '@posthog
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { TeamMembershipLevel } from 'lib/constants'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { describeOAuthCallbackError, INTEGRATION_ERROR_PARAM } from 'lib/integrations/oauthCallbackErrors'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { useSelfDrivingRunState } from 'scenes/onboarding/shared/wizard-sync/hooks'
import { urls } from 'scenes/urls'
@@ -42,6 +44,8 @@ export function IntegrationFullPage({
/>
</div>
+ <ConnectErrorBanner definition={definition} />
+
{integrationsLoading ? (
<Spinner className="text-2xl" />
) : connected ? (
@@ -60,6 +64,26 @@ export function IntegrationFullPage({
)
}
+/**
+ * Explains a connect attempt the provider sent back without a code. The callback handler parks the
+ * raw provider error code in the URL rather than firing a toast, because the user's next step is
+ * the connect button on this page and a toast is gone by the time they read the reason.
+ */
+function ConnectErrorBanner({ definition }: { definition: IntegrationDefinition }): JSX.Element | null {
+ const { searchParams } = useValues(router)
+
+ const error = searchParams[INTEGRATION_ERROR_PARAM]
+ if (!error) {
+ return null
+ }
+
+ return (
+ <LemonBanner type="warning" className="w-full">
+ {describeOAuthCallbackError(String(error), definition.kind)}
+ </LemonBanner>
+ )
+}
+
function ConnectView({
definition,
SettingsSection,