: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(slack_app): check granted Slack scopes alongside rollout flags (#78389)
Vojta Bartoš7245dca4ba4e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 2a9a04ce73ea..4f5a9fddd48f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1165,9 +1165,9 @@ snapshots:components-integrations-slack--slack-full-page-connected-all-scopes--light:hash: v1.k794b7964.0fb31dd9edbb2348ad73cef42960602be6cbe75044a9c2cf46aa6d6646d8b81a.8sYKZtq2DPh0p6Am8XQ2SqFXnu7RKKX-xwhhHQiH9Kgcomponents-integrations-slack--slack-full-page-connected-missing-scopes--dark:- hash: v1.k794b7964.c0e430ead6faea3fa1f8c385890aeb60ad1bb7b40f689c8d4efc1835a9cc03df.PKE6jjGu0stUZ9OWPLtG5Cuo5bi2wYFN8spJwjnIBkg+ hash: v1.k794b7964.a247e90d2db2de4157ae8eda4160326ca3871caa8b25fbd7dac017c3862c1361.wT-fz9r9IRvyJWa61h2zGOHIM__4Ejj_7uoA35YwzZYcomponents-integrations-slack--slack-full-page-connected-missing-scopes--light:- hash: v1.k794b7964.6b4e3c863acc55242757829ec3e5eaed38b26d8b7af143280699987201c0b4de.nsT7VOr5_EtbCurSzIcyixWMhoAoyltvdJqa1Ipv_tA+ hash: v1.k794b7964.36d3c66dbb4003f3f9f1ae43b58594cca7173585a6b93b13617e4e6509b70a21.WnrbnjXsjlke2YiAuEBwM4hMytpWPQauuGOBNlX0dRccomponents-integrations-slack--slack-integration--dark:hash: v1.k794b7964.1bcb0a5391d8290b0bdc18f53b3a3363dad6c03cfce5ffb28bdc4d8b26185f5d._h-SOFA2XkHyVKX9pGcZQItPw6XVxVXbouougXrIqkocomponents-integrations-slack--slack-integration--light:diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 4bfd28bf99bf..24496dc7057d 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -47429,14 +47429,23 @@"SlackIntegrationScope": {"enum": ["app_mentions:read",+ "assistant:write",+ "canvases:write","channels:history",+ "channels:manage","channels:read","chat:write","chat:write.customize",+ "commands",+ "files:read",+ "files:write","groups:history","groups:read",+ "im:history","links:read","links:write",+ "mpim:history",+ "mpim:read","reactions:read","reactions:write","team:read",@@ -47445,20 +47454,6 @@],"type": "string"},- "SlackIntegrationScopeInReview": {- "enum": [- "assistant:write",- "canvases:write",- "channels:manage",- "commands",- "files:read",- "files:write",- "im:history",- "mpim:history",- "mpim:read"- ],- "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 52b7b0547648..8666988049da 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -52,7 +52,6 @@ import {SessionPropertyFilter,SessionRecordingType,SlackIntegrationScope,- SlackIntegrationScopeInReview,StepOrderValue,StickinessFilterType,TrendsFilterType,@@ -61,10 +60,9 @@ import {import { integer, numerical_key, positive_integer } from './type-utils'export { ChartDisplayCategory }-// 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` (always-on) and-// `SLACK_INTEGRATION_SCOPES_IN_REVIEW` (DEV-instance only until Slack approves them).-export { SlackIntegrationScope, SlackIntegrationScopeInReview }+// 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 }/*** PostHog Query Schema definition.diff --git a/frontend/src/scenes/integrations/components/SlackIntegration.stories.tsx b/frontend/src/scenes/integrations/components/SlackIntegration.stories.tsxindex a6452546de70..74daf13e8ec5 100644--- a/frontend/src/scenes/integrations/components/SlackIntegration.stories.tsx+++ b/frontend/src/scenes/integrations/components/SlackIntegration.stories.tsx@@ -3,12 +3,7 @@ import { Meta, StoryObj } from '@storybook/react'import { useStorybookMocks } from '~/mocks/browser'import { useAvailableFeatures } from '~/mocks/features'import { mockIntegration } from '~/test/mocks'-import {- AvailableFeature,- IntegrationType,- SLACK_INTEGRATION_SCOPES,- SLACK_INTEGRATION_SCOPES_IN_REVIEW,-} from '~/types'+import { AvailableFeature, IntegrationType, SLACK_INTEGRATION_SCOPES } from '~/types'import { Slack } from '../definitions/slack'import { SlackIntegration } from './SlackIntegration'@@ -82,14 +77,9 @@ export const SlackFullPageConnect: StoryObj = {export const SlackFullPageConnectedAllScopes: StoryObj = {name: 'Full Page — Connected (all scopes)',- // Storybook runs with ``isDev === true``, so ``useSlackRequiredScopes`` returns the union- // of the always-on and in-review sets. Mirror that here so the green-success state isn't- // immediately undone by missing in-review scopes.render: () =>renderFullPage({- integrations: [- mockSlackIntegrationWithScopes([...SLACK_INTEGRATION_SCOPES, ...SLACK_INTEGRATION_SCOPES_IN_REVIEW]),- ],+ integrations: [mockSlackIntegrationWithScopes([...SLACK_INTEGRATION_SCOPES])],}),}diff --git a/frontend/src/scenes/integrations/components/slackScopes.ts b/frontend/src/scenes/integrations/components/slackScopes.tsindex aec54267a22b..872ff8a7f316 100644--- a/frontend/src/scenes/integrations/components/slackScopes.ts+++ b/frontend/src/scenes/integrations/components/slackScopes.ts@@ -1,29 +1,16 @@-import { useValues } from 'kea'-import { useMemo } from 'react'--import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'--import { Region, SLACK_INTEGRATION_SCOPES, SLACK_INTEGRATION_SCOPES_IN_REVIEW } from '~/types'+import { SLACK_INTEGRATION_SCOPES } from '~/types'/*** Required Slack OAuth scopes for the current PostHog instance.*- * On the DEV instance and local dev the PostHog Slack app manifest lists the in-review- * scopes, so we both request them at install and compare against them here. Anywhere- * else (US / EU / self-hosted) Slack rejects them as ``invalid_scope`` so we stay on- * the always-on list.+ * 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``.** 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[] {- const { preflight, isDev } = useValues(preflightLogic)- return useMemo(- () =>- isDev || preflight?.region === Region.DEV- ? [...SLACK_INTEGRATION_SCOPES, ...SLACK_INTEGRATION_SCOPES_IN_REVIEW]- : [...SLACK_INTEGRATION_SCOPES],- [isDev, preflight?.region]- )+ return [...SLACK_INTEGRATION_SCOPES]}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 85997dc6088e..d397eee0c7ca 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5502,14 +5502,23 @@ export type IntegrationKind = (typeof INTEGRATION_KINDS)[number]// `class SlackIntegrationScope(StrEnum)` in posthog/schema.py.export enum SlackIntegrationScope {APP_MENTIONS_READ = 'app_mentions:read',+ ASSISTANT_WRITE = 'assistant:write',+ CANVASES_WRITE = 'canvases:write',CHANNELS_HISTORY = 'channels:history',+ CHANNELS_MANAGE = 'channels:manage',CHANNELS_READ = 'channels:read',CHAT_WRITE = 'chat:write',CHAT_WRITE_CUSTOMIZE = 'chat:write.customize',+ COMMANDS = 'commands',+ FILES_READ = 'files:read',+ FILES_WRITE = 'files:write',GROUPS_HISTORY = 'groups:history',GROUPS_READ = 'groups:read',+ IM_HISTORY = 'im:history',LINKS_READ = 'links:read',LINKS_WRITE = 'links:write',+ MPIM_HISTORY = 'mpim:history',+ MPIM_READ = 'mpim:read',REACTIONS_READ = 'reactions:read',REACTIONS_WRITE = 'reactions:write',TEAM_READ = 'team:read',@@ -5519,23 +5528,13 @@ export enum SlackIntegrationScope {export const SLACK_INTEGRATION_SCOPES = Object.values(SlackIntegrationScope)-// Scopes still pending Slack app-directory review. Requested only on the internal DEV instance-// (settings.CLOUD_DEPLOYMENT == "DEV", surfaced as `preflight.region === Region.DEV`) where the-// PostHog Slack app manifest already lists them; requesting them anywhere else fails with-// `invalid_scope`. Move entries into SlackIntegrationScope once Slack approves the public app.-export enum SlackIntegrationScopeInReview {- ASSISTANT_WRITE = 'assistant:write',- CANVASES_WRITE = 'canvases:write',- CHANNELS_MANAGE = 'channels:manage',- COMMANDS = 'commands',- FILES_READ = 'files:read',- FILES_WRITE = 'files:write',- IM_HISTORY = 'im:history',- MPIM_HISTORY = 'mpim:history',- MPIM_READ = 'mpim:read',-}--export const SLACK_INTEGRATION_SCOPES_IN_REVIEW = Object.values(SlackIntegrationScopeInReview)+// 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.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.export interface IntegrationType {id: numberdiff --git a/posthog/helpers/slack_scopes.py b/posthog/helpers/slack_scopes.pyindex 5d56076368a4..e132a3023bf8 100644--- a/posthog/helpers/slack_scopes.py+++ b/posthog/helpers/slack_scopes.py@@ -2,6 +2,8 @@# ``products.slack_app`` handlers can share the bot's required scopes without crossing tach# module boundaries.+from collections.abc import Iterable+import structlogfrom posthog.models.integration import Integration, SlackIntegration@@ -11,9 +13,9 @@ logger = structlog.get_logger(__name__)# Installs connected before the full set was requested (#57177) must reconnect before mentions work.# channels:read/groups:read (member_joined_channel onboarding) are deliberately excluded so older# installs degrade gracefully — they skip the welcome message rather than tripping a missing-scopes warning.-# canvases:write/files:write are also excluded: they are still in Slack review-# (SlackIntegrationScopeInReview), so OAuth never grants them on US/EU Cloud — gating mentions on-# them would hard-block every prod install. The artifact delivery path+# canvases:write/files:write are also excluded: they were approved only recently, so every install+# authorized before then lacks them and gating mentions on them would hard-block those workspaces+# until they reconnect. The artifact delivery path# (products/tasks/backend/logic/services/living_artifacts.py) checks them at point of use instead,# behind the slack-app-canvas-file-artifacts feature flag.REQUIRED_SLACK_SCOPES: frozenset[str] = frozenset(@@ -29,10 +31,16 @@ REQUIRED_SLACK_SCOPES: frozenset[str] = frozenset()-def bot_is_ready(integration: Integration) -> bool:- """True when the install has every scope the @PostHog bot needs to answer mentions."""+def has_scopes(integration: Integration, required: Iterable[str]) -> bool:+ """Whether the install granted these bot scopes. Fails closed, so an install whose+ granted set can't be read never enables anything."""try:- return not SlackIntegration(integration).missing_scopes(REQUIRED_SLACK_SCOPES)+ return not SlackIntegration(integration).missing_scopes(required)except Exception:logger.warning("slack_bot_scope_check_failed", integration_id=integration.id, exc_info=True)return False+++def bot_is_ready(integration: Integration) -> bool:+ """True when the install has every scope the @PostHog bot needs to answer mentions."""+ return has_scopes(integration, REQUIRED_SLACK_SCOPES)diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 723acff28536..588653a78fe2 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -58,7 +58,7 @@ from posthog.models.user import Userfrom posthog.models.utils import IntegrityError, generate_random_oauth_access_token, generate_random_oauth_refresh_tokenfrom posthog.plugins.plugin_server_api import reload_integrations_on_workersfrom posthog.rbac.decorators import field_access_control-from posthog.schema_enums import SlackIntegrationScope, SlackIntegrationScopeInReview+from posthog.schema_enums import SlackIntegrationScopefrom posthog.scopes import get_oauth_scopes_supportedfrom posthog.security.url_validation import is_url_allowedfrom posthog.sync import database_sync_to_async@@ -713,19 +713,10 @@ 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.#-# On the internal DEV instance (CLOUD_DEPLOYMENT="DEV") and local development (settings.DEBUG)-# we also request the in-review scopes — the Slack app manifest in those setups can list them.-# US/EU/self-hosted would fail with `invalid_scope` until Slack approves the public Cloud app.-# Evaluated at module import; tests that need a different value should-# `@override_settings(...)` *before* importing this module (or `importlib.reload` it after).-def _build_posthog_slack_scope() -> str:- scopes = [scope.value for scope in SlackIntegrationScope]- if settings.DEBUG or get_instance_region() == "DEV":- scopes.extend(scope.value for scope in SlackIntegrationScopeInReview)- return ",".join(scopes)---POSTHOG_SLACK_SCOPE = _build_posthog_slack_scope()+# 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.+POSTHOG_SLACK_SCOPE = ",".join(scope.value for scope in SlackIntegrationScope)def _salesforce_instance_host(instance_url: str | None) -> str | None:diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex 249b99cece28..8566d1ffae51 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -80,11 +80,15 @@ def update_db_field_value(field, model_id, value):cursor.execute(f"update posthog_integration set {field}='{value}' where id='{model_id}';")-def test_slack_oauth_scope_includes_canvas_scope_for_local_installs():+def test_slack_oauth_requests_the_recently_approved_scopes_on_every_instance():+ # These waited on Slack app-directory review and were only requested on DEV/local. They're+ # approved now, so every instance asks for them — the features behind them (DM assistant,+ # canvas and file artifact delivery, inbox channel creation) are dark without them.from posthog.models.integration import POSTHOG_SLACK_SCOPE- assert "canvases:write" in set(POSTHOG_SLACK_SCOPE.split(","))- assert "files:write" in set(POSTHOG_SLACK_SCOPE.split(","))+ requested = set(POSTHOG_SLACK_SCOPE.split(","))++ assert {"assistant:write", "im:history", "canvases:write", "files:write", "channels:manage"} <= requestedclass TestIntegrationModel(BaseTest):diff --git a/posthog/models/user_integration.py b/posthog/models/user_integration.pyindex 42450a202e38..5993997faa21 100644--- a/posthog/models/user_integration.py+++ b/posthog/models/user_integration.py@@ -41,7 +41,10 @@ class UserIntegration(UUIDModel):Contents for Slack (user identity link):- `integration_id` holds the Slack user id (e.g. "U123ABC"), workspace-scoped- - `config` holds {slack_team_id, slack_team_name, slack_email_at_link, linked_at}+ - `config` holds {slack_team_id, slack_team_name, slack_email_at_link, scope,+ linked_at}; `scope` is the user scopes Slack granted, space-delimited as OIDC+ returns them (the workspace row's `Integration.config["scope"]` is Slack's+ comma-separated bot list, so don't parse the two the same way)- `sensitive_config` holds {user_access_token, user_refresh_token?} — theSlack user-to-server token plus, when the Slack app has`token_rotation_enabled`, a refresh token used to rotate it. Today's@@ -604,6 +607,7 @@ def user_slack_integration_from_identity(slack_email_at_link: str | None,user_access_token: str,user_refresh_token: str | None = None,+ user_scopes: str = "",) -> UserIntegration:"""Create or refresh a Slack ``UserIntegration`` from a Sign-in-with-Slackidentity.@@ -615,11 +619,17 @@ def user_slack_integration_from_identity(Storing both fields now means flipping rotation on later requires noschema or callback-shape change. ``slack_email_at_link`` is stored forsupport diagnostics and is not consulted at resolve time.++ ``user_scopes`` records what Slack granted this link. Nothing gates on it today+ — the OIDC consent screen grants ``OIDC_SCOPES`` all-or-nothing, so the row+ existing already implies them — but it's what tells you, after the fact, which+ scopes an older link was created with."""config: dict[str, Any] = {"slack_team_id": slack_team_id,"slack_team_name": slack_team_name,"slack_email_at_link": slack_email_at_link,+ "scope": user_scopes,"linked_at": int(time.time()),}sensitive_config: dict[str, Any] = {diff --git a/posthog/schema.py b/posthog/schema.pyindex 76ce2b094007..bf539389fd8f 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -238,7 +238,6 @@ from posthog.schema_enums import (SessionTableVersion as SessionTableVersion,SidebarDensity as SidebarDensity,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 1bc8093ee5a3..3fdaa65d075e 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3715,14 +3715,23 @@ class SidebarDensity(StrEnum):class SlackIntegrationScope(StrEnum):APP_MENTIONS_READ = "app_mentions:read"+ ASSISTANT_WRITE = "assistant:write"+ CANVASES_WRITE = "canvases:write"CHANNELS_HISTORY = "channels:history"+ CHANNELS_MANAGE = "channels:manage"CHANNELS_READ = "channels:read"CHAT_WRITE = "chat:write"CHAT_WRITE_CUSTOMIZE = "chat:write.customize"+ COMMANDS = "commands"+ FILES_READ = "files:read"+ FILES_WRITE = "files:write"GROUPS_HISTORY = "groups:history"GROUPS_READ = "groups:read"+ IM_HISTORY = "im:history"LINKS_READ = "links:read"LINKS_WRITE = "links:write"+ MPIM_HISTORY = "mpim:history"+ MPIM_READ = "mpim:read"REACTIONS_READ = "reactions:read"REACTIONS_WRITE = "reactions:write"TEAM_READ = "team:read"@@ -3730,18 +3739,6 @@ class SlackIntegrationScope(StrEnum):USERS_READ_EMAIL = "users:read.email"-class SlackIntegrationScopeInReview(StrEnum):- ASSISTANT_WRITE = "assistant:write"- CANVASES_WRITE = "canvases:write"- CHANNELS_MANAGE = "channels:manage"- COMMANDS = "commands"- FILES_READ = "files:read"- FILES_WRITE = "files:write"- IM_HISTORY = "im:history"- MPIM_HISTORY = "mpim:history"- MPIM_READ = "mpim:read"--class SlashCommandName(StrEnum):FIELD_INIT = "/init"FIELD_REMEMBER = "/remember"diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 659c2f79f4e6..a3ae2df33550 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -59,7 +59,9 @@ from posthog.utils import get_instance_regionfrom products.slack_app.backend import inbox_channel, onboardingfrom products.slack_app.backend.feature_flags import (+ ASSISTANT_REQUIRED_SCOPES,is_slack_app_assistant_enabled,+ is_slack_app_assistant_flag_enabled,is_slack_app_bot_prs_enabled,is_slack_app_oauth_enabled,is_slack_app_untagged_thread_followups_enabled,@@ -1666,7 +1668,7 @@ def _post_assistant_unavailable(slack: SlackIntegration, channel_id: str, threaddef send_assistant_install_welcome(integration: Integration) -> None:"""DM the installing user the moment the app is added, when the assistant is enabled for their team."""- if not is_slack_app_assistant_enabled(integration.team):+ if not is_slack_app_assistant_enabled(integration):returnslack_user_id = ((integration.config or {}).get("authed_user") or {}).get("id")if not slack_user_id:@@ -1677,11 +1679,6 @@ def send_assistant_install_welcome(integration: Integration) -> None:logger.warning("assistant_install_welcome_failed", exc_info=True)-# The DM/agent surface needs the base coding-agent scopes plus the assistant container scopes.-# Kept separate from REQUIRED_SLACK_SCOPES so the mention flow isn't gated on im:history.-_ASSISTANT_REQUIRED_SLACK_SCOPES = REQUIRED_SLACK_SCOPES | frozenset({"assistant:write", "im:history"})--def _handle_assistant_dm_message(event: dict,integration: Integration,@@ -1693,7 +1690,7 @@ def _handle_assistant_dm_message(posthog_user: User,) -> str:slack = SlackIntegration(integration)- missing = slack.missing_scopes(_ASSISTANT_REQUIRED_SLACK_SCOPES)+ missing = slack.missing_scopes(ASSISTANT_REQUIRED_SCOPES)if missing:_notify_missing_slack_scopes(slack, event, missing)return ROUTE_HANDLED_LOCALLY@@ -1760,7 +1757,9 @@ def _route_assistant_event(probe = result.integration if result.integration in result.candidates else result.candidates[0]# Kill-switch first: stay fully dark (no user resolution, no Slack reply) when the flag is off.- if not is_slack_app_assistant_enabled(probe.team):+ # The flag alone, not the full gate — a workspace that opted in but is missing scopes should+ # hear that from `_handle_assistant_dm_message`, not be silently ignored.+ if not is_slack_app_assistant_flag_enabled(probe.team):return ROUTE_HANDLED_LOCALLY# Share the mention path's user resolution + access filter, so the DM only ever sees and runs@@ -2485,7 +2484,7 @@ def _route_team_join(if _us_should_handle_instead(slack_team_id, [SLACK_INTEGRATION_KIND], can_defer_to_other_region, incoming_host):return _proxy_event_and_return_route(request, other_domain)- integration = next((c for c in workspace_result.candidates if is_slack_app_assistant_enabled(c.team)), None)+ integration = next((c for c in workspace_result.candidates if is_slack_app_assistant_enabled(c)), None)if integration is None:return ROUTE_HANDLED_LOCALLYdiff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.pyindex b16e1f262373..eea4e39a9ecb 100644--- a/products/slack_app/backend/feature_flags.py+++ b/products/slack_app/backend/feature_flags.py@@ -2,6 +2,11 @@One module for every Slack-app flag check so rollouts are easy to find and audit.+A flag says a workspace opted into a rollout; it doesn't say the install can make+the Slack API calls the feature needs. So a gate that depends on scopes checks+both, and the scopes it requires are declared here next to its flag. Scopes are+read first — that's a dict lookup, while the flag check is a network call.+All gates share the same evaluation settings, so behaviour is uniform across thesurfaces:@@ -21,6 +26,7 @@ from __future__ import annotationsimport structlogimport posthoganalytics+from posthog.helpers.slack_scopes import REQUIRED_SLACK_SCOPES, has_scopesfrom posthog.models.integration import Integrationfrom posthog.models.team.team import Teamfrom posthog.utils import get_instance_region@@ -39,6 +45,14 @@ SLACK_APP_MODEL_CLASSIFIER_FLAG = "slack-app-model-classifier"UNTAGGED_THREAD_FOLLOWUPS_FLAG = "posthog-slack-app-untagged-thread-followups"+# Linking a Slack identity to a PostHog user resolves the Slack profile and its email.+OAUTH_REQUIRED_SCOPES: frozenset[str] = frozenset({"users:read", "users:read.email"})++# The DM/agent surface needs the base coding-agent scopes plus the assistant container scopes.+# Kept separate from REQUIRED_SLACK_SCOPES so the mention flow isn't gated on im:history.+ASSISTANT_REQUIRED_SCOPES: frozenset[str] = REQUIRED_SLACK_SCOPES | frozenset({"assistant:write", "im:history"})++def _region_properties() -> dict[str, str]:"""The deployment region as a person property, shared by every gate so a``region equals DEV`` rule targets one Cloud region. Falls back to ``dev``@@ -51,6 +65,8 @@ def is_slack_app_oauth_enabled(integration: Integration, slack_team_id: str) ->(offering the invite button, accepting the link callback, listing/startingfrom settings) and frontend (rendering the Slack card in Personalintegrations) decisions. Keyed on the Slack workspace + PostHog org."""+ if not has_scopes(integration, OAUTH_REQUIRED_SCOPES):+ return Falsetry:return bool(posthoganalytics.feature_enabled(@@ -73,7 +89,8 @@ def is_slack_app_oauth_enabled(integration: Integration, slack_team_id: str) ->def is_slack_app_home_enabled(integration: Integration) -> bool:"""Gate for the App Home tab surface and the AI-settings resolver that feeds- Slack-triggered task runs. Keyed on the Slack workspace + PostHog org."""+ Slack-triggered task runs. Publishing a Home view needs no scope of its own, so+ this is the flag alone. Keyed on the Slack workspace + PostHog org."""try:return bool(posthoganalytics.feature_enabled(@@ -95,8 +112,9 @@ def is_slack_app_home_enabled(integration: Integration) -> bool:def is_slack_app_model_classifier_enabled(integration: Integration) -> bool:"""Gate for reading a one-off model choice out of the mention text ("use fable- for this one") and running that task on it. Keyed on the Slack workspace +- PostHog org, matching the other Slack-app gates.+ for this one") and running that task on it. Reads text the bot already receives,+ so this is the flag alone. Keyed on the Slack workspace + PostHog org, matching+ the other Slack-app gates.Independent of ``slack-app-home``: an override applies whether or not theworkspace has opted into the settings tab."""@@ -121,7 +139,9 @@ def is_slack_app_model_classifier_enabled(integration: Integration) -> bool:def is_slack_app_agent_design_enabled(integration: Integration) -> bool:"""Gate for the agent-design plan-block streaming surface on Slack task runs.- Keyed on the Slack workspace + PostHog org, matching ``is_slack_app_home_enabled``."""+ Posts through the ``chat:write`` the mention flow already requires, so this is the+ flag alone. Keyed on the Slack workspace + PostHog org, matching+ ``is_slack_app_home_enabled``."""try:return bool(posthoganalytics.feature_enabled(@@ -142,10 +162,12 @@ def is_slack_app_agent_design_enabled(integration: Integration) -> bool:def is_slack_app_canvas_file_artifacts_enabled(integration: Integration) -> bool:- """Gate for living-artifact delivery that depends on the in-review Slack scopes- (``canvases:write`` for the canvas adapter, ``files:write`` for the file adapter).- Stays off until Slack approves those scopes for the public app; the adapters also- verify the granted scopes at point of use. Keyed on the Slack workspace + PostHog org."""+ """Gate for living-artifact delivery that depends on ``canvases:write`` (the canvas+ adapter) and ``files:write`` (the file adapter). Both are approved but recent, so an+ install authorized earlier won't have them until it reconnects.++ The flag alone: the two adapters need one scope each, so they check theirs at point+ of use and can name the one to grant. Keyed on the Slack workspace + PostHog org."""try:return bool(posthoganalytics.feature_enabled(@@ -193,7 +215,11 @@ def is_slack_app_living_artifacts_enabled(integration: Integration) -> bool:def is_slack_app_untagged_thread_followups_enabled(integration: Integration, slack_team_id: str) -> bool:"""Gate for the untagged-thread followup path: when on, every message in atagged thread is eligible for classification + forward instead of requiring- a fresh ``@PostHog`` mention. Keyed on the Slack workspace + PostHog org."""+ a fresh ``@PostHog`` mention. Keyed on the Slack workspace + PostHog org.++ The flag alone: a followup only reaches this after a mention in the same thread, and+ that path already enforces ``REQUIRED_SLACK_SCOPES`` — which covers reading channel+ history — while telling the user which scopes to grant."""try:return bool(posthoganalytics.feature_enabled(@@ -215,6 +241,8 @@ def is_slack_app_untagged_thread_followups_enabled(integration: Integration, sladef is_slack_app_bot_prs_enabled(team: Team) -> bool:+ """Gate for the workspace's team GitHub install contributing repos alongside the+ mentioner's personal one. A GitHub-side capability, so this is the flag alone."""organization_id = str(team.organization_id)project_id = str(team.id)try:@@ -234,10 +262,14 @@ def is_slack_app_bot_prs_enabled(team: Team) -> bool:return False-def is_slack_app_assistant_enabled(team: Team) -> bool:+def is_slack_app_assistant_flag_enabled(team: Team) -> bool:"""Kill-switch for the DM assistant. Evaluated on the workspace's team (astable key) so the feature can be checked before resolving the DMing user —- i.e. it stays dark when off."""+ i.e. it stays dark when off.++ Kept apart from ``is_slack_app_assistant_enabled`` because the two answers call+ for opposite responses: a workspace outside the rollout gets silence, one that+ opted in but lacks scopes gets told which scopes to grant."""try:return bool(posthoganalytics.feature_enabled(@@ -252,3 +284,11 @@ def is_slack_app_assistant_enabled(team: Team) -> bool:except Exception:logger.exception("assistant_feature_flag_eval_failed")return False+++def is_slack_app_assistant_enabled(integration: Integration) -> bool:+ """Gate for the DM assistant: rolled out to this workspace, and installed with+ the scopes the DM surface calls."""+ if not has_scopes(integration, ASSISTANT_REQUIRED_SCOPES):+ return False+ return is_slack_app_assistant_flag_enabled(integration.team)diff --git a/products/slack_app/backend/services/slack_user_oauth.py b/products/slack_app/backend/services/slack_user_oauth.pyindex 333b97c76dd1..07994330d51e 100644--- a/products/slack_app/backend/services/slack_user_oauth.py+++ b/products/slack_app/backend/services/slack_user_oauth.py@@ -257,6 +257,10 @@ class SlackIdentity(BaseModel):slack_email: str | None = Noneuser_access_token: struser_refresh_token: str | None = None+ # What Slack actually granted, space-delimited. Normally OIDC_SCOPES verbatim —+ # the consent screen grants them together — so this is a record of what an older+ # link was created with rather than something to branch on.+ user_scopes: str = ""def _credentials() -> tuple[str, str]:@@ -346,6 +350,7 @@ def exchange_code(*, code: str, redirect_uri: str) -> SlackIdentity:# `refresh_token` is only present when the Slack app has# `token_rotation_enabled`; falls back to None in today's manifest.user_refresh_token=token_response.get("refresh_token"),+ user_scopes=token_response.get("scope") or "",)diff --git a/products/slack_app/backend/tests/test_feature_flags.py b/products/slack_app/backend/tests/test_feature_flags.pynew file mode 100644index 000000000000..ef49ddc4b186--- /dev/null+++ b/products/slack_app/backend/tests/test_feature_flags.py@@ -0,0 +1,43 @@+import pytest+from unittest.mock import patch++from products.slack_app.backend import feature_flags++SLACK_TEAM_ID = "T12345"++# (gate, scopes the feature calls, trailing args the gate takes)+SCOPED_GATES = [+ (feature_flags.is_slack_app_oauth_enabled, feature_flags.OAUTH_REQUIRED_SCOPES, (SLACK_TEAM_ID,)),+ (feature_flags.is_slack_app_assistant_enabled, feature_flags.ASSISTANT_REQUIRED_SCOPES, ()),+]++IDS = [gate.__name__ for gate, *_ in SCOPED_GATES]+++def _grant(integration, scopes):+ integration.config = {"scope": ",".join(sorted(scopes))}+ integration.save()++[email protected](("gate", "required", "extra_args"), SCOPED_GATES, ids=IDS)+def test_gate_opens_when_the_flag_is_on_and_the_scopes_are_granted(workspace_integration, gate, required, extra_args):+ _grant(workspace_integration, required)++ with patch("posthoganalytics.feature_enabled", return_value=True):+ assert gate(workspace_integration, *extra_args) is True++[email protected](("gate", "required", "extra_args"), SCOPED_GATES, ids=IDS)+def test_gate_stays_closed_when_a_required_scope_is_missing(workspace_integration, gate, required, extra_args):+ _grant(workspace_integration, required - {min(required)})++ with patch("posthoganalytics.feature_enabled", return_value=True):+ assert gate(workspace_integration, *extra_args) is False++[email protected](("gate", "required", "extra_args"), SCOPED_GATES, ids=IDS)+def test_gate_stays_closed_when_the_flag_is_off_despite_full_scopes(workspace_integration, gate, required, extra_args):+ _grant(workspace_integration, required)++ with patch("posthoganalytics.feature_enabled", return_value=False):+ assert gate(workspace_integration, *extra_args) is Falsediff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.pyindex 4f79e9a67eb9..57e7ab40db9a 100644--- a/products/slack_app/backend/tests/test_posthog_code_event_handler.py+++ b/products/slack_app/backend/tests/test_posthog_code_event_handler.py@@ -1255,7 +1255,8 @@ class TestAssistantEvents(TestCase):else UserAndIntegrationsResolution(failure_reason="user_not_found"))resolve = patch("products.slack_app.backend.api.resolve_user_for_workspace", return_value=resolution)- enabled_p = patch("products.slack_app.backend.api.is_slack_app_assistant_enabled", return_value=enabled)+ # The route's kill-switch is the flag alone — missing scopes get a reply, not silence.+ enabled_p = patch("products.slack_app.backend.api.is_slack_app_assistant_flag_enabled", return_value=enabled)usp = patch("products.slack_app.backend.api._us_should_handle_instead", return_value=False)slack = patch("products.slack_app.backend.api.SlackIntegration")return load, resolve, enabled_p, usp, slackdiff --git a/products/slack_app/backend/views/slack_user_link.py b/products/slack_app/backend/views/slack_user_link.pyindex 1a3fd48fa2e8..d0fa25a7deb9 100644--- a/products/slack_app/backend/views/slack_user_link.py+++ b/products/slack_app/backend/views/slack_user_link.py@@ -229,6 +229,7 @@ def slack_user_link_callback(request: HttpRequest) -> HttpResponse:slack_email_at_link=identity.slack_email,user_access_token=identity.user_access_token,user_refresh_token=identity.user_refresh_token,+ user_scopes=identity.user_scopes,)_post_link_success_followup(diff --git a/products/tasks/backend/logic/services/living_artifacts.py b/products/tasks/backend/logic/services/living_artifacts.pyindex b8de8d105c17..b4b751c9f21e 100644--- a/products/tasks/backend/logic/services/living_artifacts.py+++ b/products/tasks/backend/logic/services/living_artifacts.py@@ -24,10 +24,9 @@ from products.tasks.backend.models import TaskArtifact, TaskRunlogger = structlog.get_logger(__name__)-# Both scopes are still in Slack app review (see posthog/helpers/slack_scopes.py), so the canvas-# and file adapters are additionally gated behind the slack-app-canvas-file-artifacts flag: scope-# checks alone would force the feature on for any install whose manifest grants the scopes (DEV-# today, every prod workspace the moment Slack approves them) with no rollout control.+# Both scopes are approved (see posthog/helpers/slack_scopes.py), so the canvas and file adapters+# stay behind the slack-app-canvas-file-artifacts flag: scope checks alone would turn the feature+# on for every install that has them, with no rollout control.SLACK_CANVAS_SCOPE = "canvases:write"SLACK_FILE_SCOPE = "files:write"LIVING_ARTIFACT_TTL_DAYS = "30"