: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
feat(integrations): request in-review slack scopes on dev and local only (#128322)
Vojta Bartoš81e86ffb53a0
diff --git a/frontend/bin/build-schema-json.mjs b/frontend/bin/build-schema-json.mjsindex 66da58149907..2a621a613b73 100644--- a/frontend/bin/build-schema-json.mjs+++ b/frontend/bin/build-schema-json.mjs@@ -11,11 +11,25 @@ const config = {tsconfig: 'tsconfig.json',discriminatorType: 'open-api',skipTypeCheck: true,+ extraTags: ['schemaEnum'],}const output_path = 'src/queries/schema.json'const schema = tsj.createGenerator(config).createSchema(config.type)++// The generator writes a one-member enum as `const`, which Python gets as a `Literal` root model.+// Tag a TS enum `@schemaEnum` to keep its `enum` list, so Python gets a `StrEnum` at any size.+for (const definition of Object.values(schema.definitions ?? {})) {+ if (definition.schemaEnum !== undefined) {+ if ('const' in definition) {+ definition.enum = [definition.const]+ delete definition.const+ }+ delete definition.schemaEnum+ }+}+const stringify = config.sortProps ? stableStringify : JSON.stringifyconst schemaString = config.minify ? stringify(schema) : stringify(schema, null, 2)diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a91213d604b5..981a1512fae8 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1737,13 +1737,13 @@ snapshots:components-integrations-slack--slack-full-page-connect--light:hash: v1.k794b7964.43f9ed59c7ada1816c3868080fbed403f9d77b62366cdc4537779e3541e9326b.wItDTj0Z5U5FlAltTgn5YnNgC444wkCDR8yhBDf5KIocomponents-integrations-slack--slack-full-page-connected-all-scopes--dark:- hash: v1.k794b7964.f23aecf6ced3a0a5187194cc3e7b7d2908be00cd1cef463aee61c0335c61d1a1.Cpd3UrvoUfWC8OCXv54mEs7LmMrhOCylorsVY3w3pP0+ hash: v1.k794b7964.5f07a7ca81ea242d0f1324a2e2ea6b5687057f1d2f88231f8c7ac0d3f959aa7b.PHPt53fppsCs3u7f48A50CiP6VAqRrxwr6uL2lhxCM4components-integrations-slack--slack-full-page-connected-all-scopes--light:- hash: v1.k794b7964.0fb31dd9edbb2348ad73cef42960602be6cbe75044a9c2cf46aa6d6646d8b81a.8sYKZtq2DPh0p6Am8XQ2SqFXnu7RKKX-xwhhHQiH9Kg+ hash: v1.k794b7964.9acd9bfe35e19620c3b30279f484e40a019d6894f63ef92adc97b2bbdd4b188c.ChJjan_VyyddbM8VvsA5RIDOgr1BHLpidjzSE9O1qfocomponents-integrations-slack--slack-full-page-connected-missing-scopes--dark:- hash: v1.k794b7964.a247e90d2db2de4157ae8eda4160326ca3871caa8b25fbd7dac017c3862c1361.wT-fz9r9IRvyJWa61h2zGOHIM__4Ejj_7uoA35YwzZY+ hash: v1.k794b7964.57080295e3db711682eef4f811c2fabbf0351dd38a797086b3897cd109ec65ce.Zu-d4K9TvGeKyWNJ81HLY9kT6wkFkCpQq3KUd5Exvyccomponents-integrations-slack--slack-full-page-connected-missing-scopes--light:- hash: v1.k794b7964.36d3c66dbb4003f3f9f1ae43b58594cca7173585a6b93b13617e4e6509b70a21.WnrbnjXsjlke2YiAuEBwM4hMytpWPQauuGOBNlX0dRc+ hash: v1.k794b7964.55d53fef0a8690fd054e3a2f2b439790923928607c3e96ce8e84ceb8bfecb361.g2PwsLL0Ski-DPKuNdhEA5Km3UChJVQWPFr0sQG9z1Ucomponents-integrations-slack--slack-integration--dark:hash: v1.k794b7964.1bcb0a5391d8290b0bdc18f53b3a3363dad6c03cfce5ffb28bdc4d8b26185f5d._h-SOFA2XkHyVKX9pGcZQItPw6XVxVXbouougXrIqkocomponents-integrations-slack--slack-integration--light:diff --git a/frontend/src/lib/integrations/integrationScopes.ts b/frontend/src/lib/integrations/integrationScopes.tsindex 01a05569da1b..8402dd077ec9 100644--- a/frontend/src/lib/integrations/integrationScopes.ts+++ b/frontend/src/lib/integrations/integrationScopes.ts@@ -1,4 +1,4 @@-import { IntegrationKind, IntegrationType, SLACK_INTEGRATION_SCOPES } from '~/types'+import { IntegrationKind, IntegrationType, PreflightStatus, Region, slackRequestedScopes } from '~/types'import { getIntegrationNameFromKind } from './utils'@@ -38,9 +38,14 @@ export function getMissingScopes(integration: IntegrationType, requiredScopes: sreturn requiredScopes.filter((scope) => !granted.includes(scope))}+/** Whether this instance asks Slack for the scopes in ``SlackIntegrationScopeInReview``. Mirrors ``posthog_slack_scope``. */+export function requestsSlackInReviewScopes(preflight: PreflightStatus | null | undefined): boolean {+ return !!preflight?.is_debug || preflight?.region === Region.DEV+}+/** 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 requestedScopesForKind(kind: IntegrationKind, preflight: PreflightStatus | null | undefined): string[] {+ return kind === 'slack' ? slackRequestedScopes(requestsSlackInReviewScopes(preflight)) : []}export function describeScopeShortfall(kind: IntegrationKind, missingScopes: string[]): string {diff --git a/frontend/src/lib/integrations/integrationsLogic.test.ts b/frontend/src/lib/integrations/integrationsLogic.test.tsindex a7e810f1d833..225944fb8e24 100644--- a/frontend/src/lib/integrations/integrationsLogic.test.ts+++ b/frontend/src/lib/integrations/integrationsLogic.test.ts@@ -7,11 +7,19 @@ import { expectLogic } from 'kea-test-utils'import { LemonDialog, lemonToast } from '@posthog/lemon-ui'import apiReal, { ApiError } from 'lib/api'+import { preflightLogic } from 'lib/logic/preflightLogic'import { teamLogic } from 'scenes/teamLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { IntegrationKind, IntegrationType, SLACK_INTEGRATION_SCOPES } from '~/types'+import {+ IntegrationKind,+ IntegrationType,+ PreflightStatus,+ Region,+ SLACK_INTEGRATION_SCOPES,+ SLACK_INTEGRATION_SCOPES_IN_REVIEW,+} from '~/types'import * as integrationsApi from 'products/integrations/frontend/generated/api'import type {@@ -580,31 +588,45 @@ describe('integrationsLogic', () => {expect(requestedTeamIds).toEqual([String(MOCK_TEAM_ID)])})+ const approvedScopes = SLACK_INTEGRATION_SCOPES.join(',')+ const allScopes = [...SLACK_INTEGRATION_SCOPES, ...SLACK_INTEGRATION_SCOPES_IN_REVIEW].join(',')it.each([- ['every requested scope', SLACK_INTEGRATION_SCOPES.join(','), null],+ ['US', 'every requested scope', approvedScopes, null],[+ 'US','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)- })+ ['US', 'no recorded scopes', undefined, null],+ ['DEV', 'every requested scope', allScopes, null],+ ['DEV', 'only the approved scopes', approvedScopes, [...SLACK_INTEGRATION_SCOPES_IN_REVIEW]],+ ])(+ 'reports a Slack install on %s that granted %s',+ async (region, _name, grantedScope, expectedMissing) => {+ preflightLogic.mount()+ preflightLogic.actions.loadPreflightSuccess({+ ...preflightLogic.values.preflight,+ is_debug: false,+ region: region as Region,+ } as PreflightStatus)+ 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 7e40cc3183b4..66cab074e540 100644--- a/frontend/src/lib/integrations/integrationsLogic.ts+++ b/frontend/src/lib/integrations/integrationsLogic.ts@@ -1393,7 +1393,10 @@ export const integrationsLogic = kea<integrationsLogicType>([replaceUrl = url.pathname + url.search + url.hashactions.loadIntegrations()- const missingScopes = getMissingScopes(integration, requestedScopesForKind(integration.kind))+ const missingScopes = getMissingScopes(+ integration,+ requestedScopesForKind(integration.kind, values.preflight)+ )if (missingScopes.length > 0) {actions.reportIntegrationScopeShortfallShown(integration.kind, missingScopes)lemonToast.warning(describeScopeShortfall(integration.kind, missingScopes), {diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex c1a17c68861f..90c4e1bfa1e8 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -54206,6 +54206,10 @@],"type": "string"},+ "SlackIntegrationScopeInReview": {+ "enum": ["canvases:read", "channels:join"],+ "type": "string"+ },"SlashCommandName": {"enum": ["/init", "/remember", "/usage", "/feedback", "/ticket"],"type": "string"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex de5fbefffaba..6277fc90852e 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -60,6 +60,7 @@ import {SessionPropertyFilter,SessionRecordingType,SlackIntegrationScope,+ SlackIntegrationScopeInReview,StepOrderValue,} from '~/types'@@ -67,9 +68,9 @@ import { BIVisualizationNode } from './schema-business-intelligence'import { integer, numerical_key, positive_integer } from './type-utils'export { ChartDisplayCategory }-// Re-exported so the codegen picks it up and emits a matching `StrEnum` in posthog/schema.py.-// The runtime const lives in `~/types` as `SLACK_INTEGRATION_SCOPES`.-export { SlackIntegrationScope }+// Re-exported so the codegen picks them up and emits matching `StrEnum`s in posthog/schema.py.+// The runtime consts live in `~/types` as `SLACK_INTEGRATION_SCOPES` and `SLACK_INTEGRATION_SCOPES_IN_REVIEW`.+export { SlackIntegrationScope, SlackIntegrationScopeInReview }/*** PostHog Query Schema definition.diff --git a/frontend/src/scenes/integrations/components/slackScopes.ts b/frontend/src/scenes/integrations/components/slackScopes.tsindex 872ff8a7f316..b38900c4837e 100644--- a/frontend/src/scenes/integrations/components/slackScopes.ts+++ b/frontend/src/scenes/integrations/components/slackScopes.ts@@ -1,16 +1,21 @@-import { SLACK_INTEGRATION_SCOPES } from '~/types'+import { useValues } from 'kea'++import { requestsSlackInReviewScopes } from 'lib/integrations/integrationScopes'+import { preflightLogic } from 'lib/logic/preflightLogic'++import { slackRequestedScopes } from '~/types'/*** Required Slack OAuth scopes for the current PostHog instance.*- * Every scope PostHog requests is approved for the public app, so this is the same list- * on every instance. If a future scope has to wait on Slack review, this is where the- * DEV-only union goes back — see the note by ``SlackIntegrationScope`` in ``~/types``.+ * The DEV instance and local development also require the scopes that wait on Slack review,+ * because they request them at install. See the note by ``SlackIntegrationScopeInReview`` in ``~/types``.** Used by both the settings-side ``SlackIntegration`` connect/manage UI and the OAuth* landing page's status hook so the two surfaces always agree on what "fully scoped"* means.*/export function useSlackRequiredScopes(): string[] {- return [...SLACK_INTEGRATION_SCOPES]+ const { preflight } = useValues(preflightLogic)+ return slackRequestedScopes(requestsSlackInReviewScopes(preflight))}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 5c2b81e33afe..5b72274e7760 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5714,13 +5714,21 @@ export enum SlackIntegrationScope {export const SLACK_INTEGRATION_SCOPES = Object.values(SlackIntegrationScope)-// Nothing is pending Slack app-directory review right now, so there is no in-review list.-// To stage a scope that Slack hasn't approved yet, reintroduce a `SlackIntegrationScopeInReview`-// enum here holding only the pending entries, re-export it from schema-general.ts, and have-// `POSTHOG_SLACK_SCOPE` (posthog/models/integration/oauth.py) and `useSlackRequiredScopes` append it on-// DEV/local only — requesting an unapproved scope anywhere else fails with `invalid_scope`.-// The enum cannot be left empty between rounds: JSON Schema rejects a zero-length `enum`, so-// `hogli build:schema` fails on it.+// Scopes that wait on Slack app review. Only DEV and local development request them, because the+// US and EU apps reject them with `invalid_scope`. Move a scope to SlackIntegrationScope when Slack approves it.+/** @schemaEnum */+export enum SlackIntegrationScopeInReview {+ CANVASES_READ = 'canvases:read',+ CHANNELS_JOIN = 'channels:join',+}++export const SLACK_INTEGRATION_SCOPES_IN_REVIEW = Object.values(SlackIntegrationScopeInReview)++export function slackRequestedScopes(includeInReview: boolean): string[] {+ return includeInReview+ ? [...SLACK_INTEGRATION_SCOPES, ...SLACK_INTEGRATION_SCOPES_IN_REVIEW]+ : [...SLACK_INTEGRATION_SCOPES]+}export interface IntegrationType {id: numberdiff --git a/posthog/models/integration/oauth.py b/posthog/models/integration/oauth.pyindex e9c8b6456318..cd947b9fcb20 100644--- a/posthog/models/integration/oauth.py+++ b/posthog/models/integration/oauth.py@@ -26,7 +26,7 @@ from posthog.egress.slack.observability import record_slack_api_responsefrom posthog.integrations.contracts import IntegrationRecordfrom posthog.models.user import Userfrom posthog.plugins.plugin_server_api import reload_integrations_on_workers-from posthog.schema_enums import SlackIntegrationScope+from posthog.schema_enums import SlackIntegrationScope, SlackIntegrationScopeInReviewfrom posthog.scopes import get_oauth_scopes_supportedfrom . import apple_ads, common, model, refresh_tracking@@ -198,12 +198,17 @@ class OauthConfig:# StrEnum declared in posthog/schema.py (generated from the SlackIntegrationScope enum in# frontend/src/types.ts via `hogli build:schema`), so widening it on either side stays in sync.#-# Every scope here is approved for the public Cloud app, so the same list is requested on every-# instance. Staging a scope Slack hasn't approved needs a DEV/local-only branch again — see the-# note by SlackIntegrationScope in frontend/src/types.ts.+# Every scope here is approved for the public Cloud app, so every instance requests it.POSTHOG_SLACK_SCOPE = ",".join(scope.value for scope in SlackIntegrationScope)+def posthog_slack_scope() -> str:+ # See SlackIntegrationScopeInReview in frontend/src/types.ts for why only DEV and local request these.+ if settings.DEBUG or settings.CLOUD_DEPLOYMENT == "DEV":+ return ",".join([POSTHOG_SLACK_SCOPE, *(scope.value for scope in SlackIntegrationScopeInReview)])+ return POSTHOG_SLACK_SCOPE++def _apple_ads_acl_accounts(access_token: str) -> list[dict[str, Any]]:"""Ad accounts an Apple Ads access token can read, flattened one row per account.@@ -669,7 +674,7 @@ class OauthIntegration:return OauthConfig(authorize_url="https://slack.com/oauth/v2/authorize",token_url="https://slack.com/api/oauth.v2.access",- scope=POSTHOG_SLACK_SCOPE,+ scope=posthog_slack_scope(),id_path="team.id",name_path="team.name",)diff --git a/posthog/models/test/integration/test_oauth.py b/posthog/models/test/integration/test_oauth.pyindex 0cffd02bd36e..d9af436539bd 100644--- a/posthog/models/test/integration/test_oauth.py+++ b/posthog/models/test/integration/test_oauth.py@@ -39,6 +39,8 @@ from posthog.models.integration import (oauth_refresh_terminal_counter,refresh_backoff_active,)+from posthog.models.integration.oauth import posthog_slack_scope+from posthog.schema_enums import SlackIntegrationScope, SlackIntegrationScopeInReviewdef get_db_field_value(field, model_id):@@ -58,6 +60,26 @@ def test_slack_oauth_requests_the_recently_approved_scopes_on_every_instance():assert {"assistant:write", "im:history", "canvases:write", "files:write", "channels:manage"} <= requested+ "debug, cloud_deployment, requests_in_review",+ [+ (False, "US", False),+ (False, "EU", False),+ (False, None, False),+ (False, "DEV", True),+ (True, None, True),+ ],+)+def test_slack_oauth_requests_in_review_scopes_only_on_dev_and_local(+ debug: bool, cloud_deployment: str | None, requests_in_review: bool+) -> None:+ with override_settings(DEBUG=debug, CLOUD_DEPLOYMENT=cloud_deployment):+ requested = set(posthog_slack_scope().split(","))++ assert {scope.value for scope in SlackIntegrationScope} <= requested+ assert ({scope.value for scope in SlackIntegrationScopeInReview} <= requested) is requests_in_review++class TestOauthIntegrationModel(BaseTest):mock_settings = {"SALESFORCE_CONSUMER_KEY": "salesforce-client-id",diff --git a/posthog/schema.py b/posthog/schema.pyindex 262a71ee479b..fb700c04776b 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -297,6 +297,7 @@ from posthog.schema_enums import (SessionTableVersion as SessionTableVersion,Shelf as Shelf,SlackIntegrationScope as SlackIntegrationScope,+ SlackIntegrationScopeInReview as SlackIntegrationScopeInReview,SlashCommandName as SlashCommandName,SliceContent as SliceContent,SnapchatAdsConversionFields as SnapchatAdsConversionFields,diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex b703a8eac0d7..3d710f63cad7 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3058,6 +3058,11 @@ class SlackIntegrationScope(StrEnum):USERS_READ_EMAIL = "users:read.email"+class SlackIntegrationScopeInReview(StrEnum):+ CANVASES_READ = "canvases:read"+ CHANNELS_JOIN = "channels:join"++class SlashCommandName(StrEnum):FIELD_INIT = "/init"FIELD_REMEMBER = "/remember"