: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(integrations): warn when slack grants fewer scopes than requested (#114500)
posthog[bot]5859e3772234
diff --git a/frontend/src/lib/components/CyclotronJob/integrations/fieldScopes.ts b/frontend/src/lib/components/CyclotronJob/integrations/fieldScopes.tsindex 162126368b57..d553a6f939a7 100644--- a/frontend/src/lib/components/CyclotronJob/integrations/fieldScopes.ts+++ b/frontend/src/lib/components/CyclotronJob/integrations/fieldScopes.ts@@ -1,6 +1,6 @@import { useValues } from 'kea'-import { getMissingScopes } from 'lib/integrations/IntegrationScopesWarning'+import { getMissingScopes } from 'lib/integrations/integrationScopes'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { CyclotronJobInputSchemaType, IntegrationType } from '~/types'diff --git a/frontend/src/lib/integrations/IntegrationScopesWarning.tsx b/frontend/src/lib/integrations/IntegrationScopesWarning.tsxindex 370f496b4291..0899ea7effd1 100644--- a/frontend/src/lib/integrations/IntegrationScopesWarning.tsx+++ b/frontend/src/lib/integrations/IntegrationScopesWarning.tsx@@ -8,44 +8,9 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { IntegrationType } from '~/types'import { useIntegrationManagementRestriction } from './integrationPermissions'+import { getGrantedScopes } from './integrationScopes'import { integrationAuthorizeUrl, reconnectReturnUrl } from './integrationsLogic'-/**- * Extract the granted OAuth scopes from an integration's stored config. Tolerates the- * various shapes different providers persist: ``config.scope`` vs ``config.scopes``,- * space- or comma-separated strings, or a pre-split array. Returns an empty array when- * no recognizable scope list is present (e.g. legacy rows predating the field).- *- * Exported so any caller that needs to decide "is this install missing a scope" (the- * banner below, the OAuth landing-page status hook, etc.) reaches the same verdict.- */-export function getGrantedScopes(integration: IntegrationType): string[] {- const candidates: string[][] = []-- for (const raw of [integration.config?.scope, integration.config?.scopes]) {- if (typeof raw === 'string') {- // Pick the delimiter explicitly. Pushing both comma- and space-split results and- // letting "longest array wins" decide was a heuristic that silently mangled mixed- // delimiters like ``"read write,admin"`` into one of several wrong shapes.- const split = raw.includes(',') ? raw.split(',') : raw.split(' ')- candidates.push(split.map((scope) => scope.trim()).filter(Boolean))- } else if (Array.isArray(raw)) {- candidates.push(raw)- }- }-- return candidates.reduce((a, b) => (a.length > b.length ? a : b), [] as string[])-}--/** Scopes from ``schema.requiredScopes`` that the integration hasn't granted. */-export function getMissingScopes(integration: IntegrationType, requiredScopes: string[]): string[] {- const granted = getGrantedScopes(integration)- if (granted.length === 0) {- return []- }- return requiredScopes.filter((scope) => !granted.includes(scope))-}-export function IntegrationScopesWarning({integration,schema,diff --git a/frontend/src/lib/integrations/integrationScopes.ts b/frontend/src/lib/integrations/integrationScopes.tsnew file mode 100644index 000000000000..01a05569da1b--- /dev/null+++ b/frontend/src/lib/integrations/integrationScopes.ts@@ -0,0 +1,55 @@+import { IntegrationKind, IntegrationType, SLACK_INTEGRATION_SCOPES } from '~/types'++import { getIntegrationNameFromKind } from './utils'++/**+ * Extract the granted OAuth scopes from an integration's stored config. Tolerates the+ * various shapes different providers persist: ``config.scope`` vs ``config.scopes``,+ * space- or comma-separated strings, or a pre-split array. Returns an empty array when+ * no recognizable scope list is present (e.g. legacy rows predating the field).+ *+ * Exported so any caller that needs to decide "is this install missing a scope" (the+ * banner below, the OAuth landing-page status hook, etc.) reaches the same verdict.+ */+export function getGrantedScopes(integration: IntegrationType): string[] {+ const candidates: string[][] = []++ for (const raw of [integration.config?.scope, integration.config?.scopes]) {+ if (typeof raw === 'string') {+ // Pick the delimiter explicitly. Pushing both comma- and space-split results and+ // letting "longest array wins" decide was a heuristic that silently mangled mixed+ // delimiters like ``"read write,admin"`` into one of several wrong shapes.+ const split = raw.includes(',') ? raw.split(',') : raw.split(' ')+ candidates.push(split.map((scope) => scope.trim()).filter(Boolean))+ } else if (Array.isArray(raw)) {+ candidates.push(raw)+ }+ }++ return candidates.reduce((a, b) => (a.length > b.length ? a : b), [] as string[])+}++/** Scopes from ``schema.requiredScopes`` that the integration hasn't granted. */+export function getMissingScopes(integration: IntegrationType, requiredScopes: string[]): string[] {+ const granted = getGrantedScopes(integration)+ if (granted.length === 0) {+ return []+ }+ return requiredScopes.filter((scope) => !granted.includes(scope))+}++/** Scopes PostHog asks for on the authorize URL, for the kinds where the frontend knows the full list. */+export function requestedScopesForKind(kind: IntegrationKind): string[] {+ return kind === 'slack' ? [...SLACK_INTEGRATION_SCOPES] : []+}++export function describeScopeShortfall(kind: IntegrationKind, missingScopes: string[]): string {+ const name = getIntegrationNameFromKind(kind)+ const permissions = missingScopes.length === 1 ? 'permission' : 'permissions'+ // The instructions go before the scope list because the toast clips long messages at its max height.+ return (+ `${name} is connected, but it did not grant ${missingScopes.length} ${permissions}. ` ++ `Reconnecting again will not fix this. Ask a ${name} workspace admin to approve or reinstall the PostHog app, then reconnect. ` ++ `Missing: ${missingScopes.join(', ')}.`+ )+}diff --git a/frontend/src/lib/integrations/integrationsLogic.test.ts b/frontend/src/lib/integrations/integrationsLogic.test.tsindex 3c0c559d2679..ceb0ddf6808a 100644--- a/frontend/src/lib/integrations/integrationsLogic.test.ts+++ b/frontend/src/lib/integrations/integrationsLogic.test.ts@@ -11,7 +11,7 @@ import { teamLogic } from 'scenes/teamLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { IntegrationKind, IntegrationType } from '~/types'+import { IntegrationKind, IntegrationType, SLACK_INTEGRATION_SCOPES } from '~/types'import * as integrationsApi from 'products/integrations/frontend/generated/api'import type {@@ -500,15 +500,17 @@ describe('integrationsLogic', () => {describe('integration create team scoping', () => {let requestedTeamIds: string[]+ let createdConfig: Record<string, unknown>beforeEach(() => {requestedTeamIds = []+ createdConfig = {}document.cookie = 'ph_oauth_state=csrf-tok'useMocks({post: {'/api/environments/:team_id/integrations/': ({ params }) => {requestedTeamIds.push(String(params.team_id))- return [201, { id: 7, kind: 'slack' }]+ return [201, { id: 7, kind: 'slack', config: createdConfig }]},},})@@ -548,6 +550,32 @@ describe('integrationsLogic', () => {)expect(requestedTeamIds).toEqual([String(MOCK_TEAM_ID)])})++ it.each([+ ['every requested scope', SLACK_INTEGRATION_SCOPES.join(','), null],+ [+ 'fewer scopes than requested',+ SLACK_INTEGRATION_SCOPES.filter((scope) => scope !== 'users:read' && scope !== 'files:write').join(+ ','+ ),+ ['files:write', 'users:read'],+ ],+ ['no recorded scopes', undefined, null],+ ])('reports a Slack install that granted %s', async (_name, grantedScope, expectedMissing) => {+ createdConfig = grantedScope === undefined ? {} : { scope: grantedScope }+ const successSpy = jest.spyOn(lemonToast, 'success').mockImplementation(() => 'toast')+ const warningSpy = jest.spyOn(lemonToast, 'warning').mockImplementation(() => 'toast')+ const state = 'next=%2Fproject%2F228502%2Fsettings%2Fproject-integrations&token=csrf-tok'++ await expectLogic(logic, () => {+ logic.actions.handleOauthCallback('slack' as IntegrationKind, { state, code: 'oauth-code' })+ }).toFinishAllListeners()++ expect(warningSpy.mock.calls.map(([message]) => message)).toEqual(+ expectedMissing ? [expect.stringContaining(`: ${expectedMissing.join(', ')}.`)] : []+ )+ expect(successSpy).toHaveBeenCalledTimes(expectedMissing ? 0 : 1)+ })})})})diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.tsindex 1b8ae5f1fe4c..ebe5672e5bab 100644--- a/frontend/src/lib/integrations/integrationsLogic.ts+++ b/frontend/src/lib/integrations/integrationsLogic.ts@@ -8,6 +8,7 @@ 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 { describeScopeShortfall, getMissingScopes, requestedScopesForKind } from 'lib/integrations/integrationScopes'import {describeOAuthCallbackError,INTEGRATION_ERROR_PARAM,@@ -187,6 +188,13 @@ export interface integrationsLogicActions {error: stringkind: string} // eventUsageLogic+ reportIntegrationScopeShortfallShown: (+ kind: string,+ missingScopes: string[]+ ) => {+ kind: string+ missingScopes: string[]+ } // eventUsageLogicmarkTaskAsCompleted: (taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]) => {taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]} // globalSetupLogic@@ -766,7 +774,7 @@ export const integrationsLogic = kea<integrationsLogicType>([globalSetupLogic,['markTaskAsCompleted'],eventUsageLogic,- ['reportIntegrationConnectRejected'],+ ['reportIntegrationConnectRejected', 'reportIntegrationScopeShortfallShown'],teamLogic,['loadCurrentTeamSuccess'],],@@ -1336,7 +1344,15 @@ export const integrationsLogic = kea<integrationsLogicType>([replaceUrl = url.pathname + url.search + url.hashactions.loadIntegrations()- lemonToast.success(`Integration successful.`)+ const missingScopes = getMissingScopes(integration, requestedScopesForKind(integration.kind))+ if (missingScopes.length > 0) {+ actions.reportIntegrationScopeShortfallShown(integration.kind, missingScopes)+ lemonToast.warning(describeScopeShortfall(integration.kind, missingScopes), {+ autoClose: false,+ })+ } else {+ lemonToast.success(`Integration successful.`)+ }}} catch (e) {toastApiError(e)diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex 4f338c528478..6c910a3b8084 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -1416,6 +1416,13 @@ export interface eventUsageLogicActions {kind: stringsurface: IntegrationConnectSurface}+ reportIntegrationScopeShortfallShown: (+ kind: string,+ missingScopes: string[]+ ) => {+ kind: string+ missingScopes: string[]+ }reportInviteMembersButtonClicked: () => {value: true}@@ -1829,6 +1836,7 @@ export const eventUsageLogic = kea<eventUsageLogicType>([responseAgeMs?: number) => ({ surface, discoveryId, installationId, responseAgeMs }),reportIntegrationConnectRejected: (kind: string, error: string) => ({ kind, error }),+ reportIntegrationScopeShortfallShown: (kind: string, missingScopes: string[]) => ({ kind, missingScopes }),// insightsreportDataTableColumnsUpdated: (context_type: string) => ({ context_type }),// insight filters@@ -2364,6 +2372,15 @@ export const eventUsageLogic = kea<eventUsageLogicType>([error,})},+ // A provider can grant fewer scopes than PostHog asked for, e.g. when a workspace admin has to+ // approve the app. The connect still succeeds, so this is the only record of the shortfall.+ reportIntegrationScopeShortfallShown: ({ kind, missingScopes }) => {+ posthog.capture('integration_scope_shortfall_shown', {+ integration_kind: kind,+ missing_scopes: missingScopes,+ missing_scope_count: missingScopes.length,+ })+ },reportTimeToSeeData: async ({ payload }) => {posthog.capture('time to see data', payload)},diff --git a/frontend/src/scenes/integrations/definitions/slack.tsx b/frontend/src/scenes/integrations/definitions/slack.tsxindex 77dabb4a89ce..3d27011a2e42 100644--- a/frontend/src/scenes/integrations/definitions/slack.tsx+++ b/frontend/src/scenes/integrations/definitions/slack.tsx@@ -1,4 +1,5 @@-import { getMissingScopes, IntegrationScopesWarning } from 'lib/integrations/IntegrationScopesWarning'+import { getMissingScopes } from 'lib/integrations/integrationScopes'+import { IntegrationScopesWarning } from 'lib/integrations/IntegrationScopesWarning'import { ICONS } from 'lib/integrations/utils'import { IntegrationType } from '~/types'diff --git a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsxindex 6fc8a0c147c5..3d26437da6e9 100644--- a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx+++ b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx@@ -15,7 +15,7 @@ import {import api from 'lib/api'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { useIntegrationManagementRestriction } from 'lib/integrations/integrationPermissions'-import { getGrantedScopes } from 'lib/integrations/IntegrationScopesWarning'+import { getGrantedScopes } from 'lib/integrations/integrationScopes'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { isSlackMemberTarget, slackChannelDisplayName } from 'lib/integrations/slackChannel'import { SlackChannelPicker } from 'lib/integrations/SlackIntegrationHelpers'diff --git a/products/subscriptions/frontend/components/Subscriptions/utils.tsx b/products/subscriptions/frontend/components/Subscriptions/utils.tsxindex b96ee10aca5c..76a9e98f4fb4 100644--- a/products/subscriptions/frontend/components/Subscriptions/utils.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/utils.tsx@@ -2,7 +2,7 @@ import { IconLetter } from '@posthog/icons'import { LemonSelectOption, LemonSelectOptionLeaf, LemonSelectOptions } from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'-import { getGrantedScopes } from 'lib/integrations/IntegrationScopesWarning'+import { getGrantedScopes } from 'lib/integrations/integrationScopes'import { IconSlack } from 'lib/lemon-ui/icons'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { range } from 'lib/utils/arrays'