: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(data-warehouse): connect Slack source with your own Slack app (#72870)
Tom Owers5808dad02463
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/slack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/slack.pyindex 7a48a4e9aef8..dbd722cb6046 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/slack.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/slack.py@@ -4,6 +4,15 @@from products.warehouse_sources.backend.temporal.data_imports.sources.common import config+class SlackJoinPublicChannelsConfig(config.Config):+ enabled: bool = config.value(converter=config.str_to_bool, default=True)++@config.configclass SlackSourceConfig(config.Config):- slack_integration_id: int = config.value(converter=config.str_to_int)+ slack_access_token: str | None = None+ # Back-compat: legacy sources created before bring-your-own point at PostHog's shared Slack app+ # via this Integration id. New sources can't set it (the connect form only offers the token).+ slack_integration_id: int | None = config.value(converter=config.str_to_optional_int, default_factory=lambda: None)+ join_public_channels: SlackJoinPublicChannelsConfig | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/slack/slack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/slack/slack.pyindex 00e794550e20..4f1feb1a477d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/slack/slack.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/slack/slack.py@@ -1,3 +1,4 @@+import hashlibimport datetimeimport dataclassesfrom collections.abc import AsyncIterable, Callable, Iterable, Iterator@@ -72,6 +73,25 @@ def _slack_get(url: str, **kwargs: Any) -> requests.Response:return response+@retry(+ retry=retry_if_exception_type(+ (SlackRetryableError, requests.exceptions.ConnectionError, requests.exceptions.Timeout)+ ),+ stop=stop_after_attempt(5),+ wait=_wait_with_retry_after,+ reraise=True,+)+def _slack_post(url: str, **kwargs: Any) -> requests.Response:+ response = make_tracked_session().post(url, **kwargs)+ if response.status_code == 429:+ retry_after = int(response.headers.get("Retry-After", 1))+ logger.warning("Slack API rate limited", url=url, retry_after=retry_after)+ raise SlackRetryableError("Slack: rate limited", retry_after=retry_after)+ if response.status_code >= 500:+ raise SlackRetryableError(f"Slack: server error {response.status_code}")+ return response++class SlackCursorPaginator(BasePaginator):def update_state(self, response: Response, data: list[Any] | None = None) -> None:res = response.json()@@ -184,14 +204,46 @@ def _fetch_all_channels(access_token: str, authed_user: str | None = None) -> li_CHANNELS_CACHE_TTL_SECONDS = 300-def _channels_cache_key(integration_id: int) -> str:- # Keyed on the Integration row PK (unique per PostHog team × Slack workspace), matching+def _channels_cache_key(cache_id: str) -> str:+ # Keyed on a stable per-workspace identity — the Integration row PK for the legacy OAuth path,+ # or a hash of the bring-your-own bot token for the manual path (see `manual_cache_id`). Mirrors# the convention used by the HogFunctions Slack channel-list cache in posthog.api.integration.- return f"@dwh/slack/{integration_id}/channels"+ return f"@dwh/slack/{cache_id}/channels"+++def manual_cache_id(access_token: str) -> str:+ """Stable channel-cache identity for a bring-your-own bot token.++ The manual auth path has no Integration row to key the cache on, so we derive a short,+ non-reversible id from the token. It only scopes a 5-minute channel-list cache, so a token+ rotation harmlessly starts a fresh cache entry rather than serving another workspace's data.+ """+ return hashlib.sha256(access_token.encode()).hexdigest()[:16]+++def auth_test_user_id(access_token: str) -> str | None:+ """Return the user id `auth.test` reports for a token, or None if the call fails.++ Used by the manual auth path to scope private-channel discovery. For a bot token this is the+ bot's own user id; `users.conversations` then returns the private channels the bot is a member+ of. A failed/invalid token yields None (discovery falls back to unscoped), and credential+ validation surfaces the error separately.+ """+ url = "https://slack.com/api/auth.test"+ headers = {"Authorization": f"Bearer {access_token}"}+ try:+ response = _slack_get(url, headers=headers, timeout=10)+ response.raise_for_status()+ data = response.json()+ if data.get("ok"):+ return data.get("user_id")+ except Exception:+ logger.warning("Slack auth.test failed while resolving authed user", exc_info=True)+ return Nonedef _fetch_all_channels_cached(- integration_id: int,+ cache_id: str,access_token: str,authed_user: str | None = None,force_refresh: bool = False,@@ -206,7 +258,7 @@ def _fetch_all_channels_cached(stays in cache until the new one is written, so concurrent readers don't pile upon a missing key."""- cache_key = _channels_cache_key(integration_id)+ cache_key = _channels_cache_key(cache_id)if not force_refresh:cached = cache.get(cache_key)if cached is not None:@@ -294,7 +346,7 @@ def _fetch_thread_replies(def get_channels(- integration_id: int,+ cache_id: str,access_token: str,authed_user: str | None = None,force_refresh: bool = False,@@ -302,10 +354,50 @@ def get_channels("""Return channel id + name pairs for all accessible channels."""return [{"id": ch["id"], "name": ch["name"]}- for ch in _fetch_all_channels_cached(integration_id, access_token, authed_user, force_refresh=force_refresh)+ for ch in _fetch_all_channels_cached(cache_id, access_token, authed_user, force_refresh=force_refresh)]+# conversations.join errors that mean "nothing to do for this channel" rather than a real failure.+_SKIP_JOIN_ERRORS = {"already_in_channel", "is_archived", "method_not_supported_for_channel_type"}+++def _join_public_channels(access_token: str, channels: list[dict[str, Any]]) -> int:+ """Join every public channel the bot isn't already in, so their message events reach the webhook.++ ``conversations.join`` only works for public channels — private channels must be invited manually.+ Joins are idempotent (``already_in_channel`` is a no-op) and archived channels are skipped. A+ missing ``channels:join`` scope is surfaced immediately, since it means auto-join can never work.+ Returns the number of channels newly joined.+ """+ url = "https://slack.com/api/conversations.join"+ headers = {"Authorization": f"Bearer {access_token}"}+ joined = 0+ for ch in channels:+ if ch.get("is_private") or ch.get("is_archived") or ch.get("is_member"):+ continue+ response = _slack_post(url, headers=headers, data={"channel": ch["id"]}, timeout=10)+ response.raise_for_status()+ data = response.json()+ if data.get("ok"):+ joined += 1+ continue+ error = data.get("error", "unknown_error")+ if error == "missing_scope":+ raise Exception("missing_scope: your Slack app needs the channels:join scope to auto-join public channels.")+ if error not in _SKIP_JOIN_ERRORS:+ logger.warning("Slack conversations.join failed", channel_id=ch.get("id"), error=error)+ if joined:+ logger.info("Slack auto-joined public channels", joined=joined)+ return joined+++def join_public_channels(access_token: str, cache_id: str, authed_user: str | None = None) -> int:+ """Auto-join all public channels the bot isn't in yet (see ``_join_public_channels``)."""+ channels = _fetch_all_channels_cached(cache_id, access_token, authed_user)+ return _join_public_channels(access_token, channels)++def _add_timestamp(msg: dict[str, Any]) -> dict[str, Any]:ts = msg.get("ts")if ts:@@ -388,7 +480,7 @@ def _webhook_table_transformer(table: pa.Table) -> pa.Table:def slack_source(access_token: str,- integration_id: int,+ cache_id: str,endpoint: str,team_id: int,job_id: str,@@ -409,7 +501,7 @@ def slack_source(# public+private types are mixed, so we walk public and private separately and# scope private channels to the installer (matches get_schemas behavior).endpoint_config = ENDPOINTS[endpoint]- items = lambda: iter(_fetch_all_channels_cached(integration_id, access_token, authed_user))+ items = lambda: iter(_fetch_all_channels_cached(cache_id, access_token, authed_user))elif endpoint in ENDPOINTS:# $users — served via the generic REST frameworkendpoint_config = ENDPOINTS[endpoint]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/slack/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/slack/source.pyindex 1435d5828dcd..eaf9d5da714d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/slack/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/slack/source.py@@ -11,7 +11,7 @@ from posthog.schema import (SourceConfig,SourceFieldInputConfig,SourceFieldInputConfigType,- SourceFieldOauthConfig,+ SourceFieldSwitchGroupConfig,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (@@ -37,7 +37,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.temporal.data_imports.sources.slack.settings import ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.slack.slack import (SlackResumeConfig,+ auth_test_user_id,get_channels,+ join_public_channels,+ manual_cache_id,slack_source,validate_credentials as validate_slack_credentials,)@@ -73,6 +76,33 @@ class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], Webhookdef _get_authed_user_id(integration: "Integration") -> str | None:return (integration.config or {}).get("authed_user", {}).get("id")+ def _resolve_access_token(self, config: SlackSourceConfig, team_id: int) -> tuple[str, str | None, str]:+ """Resolve credentials, preferring the bring-your-own bot token.++ Returns ``(access_token, authed_user_id, cache_id)``. ``authed_user_id`` scopes private-channel+ discovery to a single user; ``cache_id`` keys the per-workspace channel-list cache.++ - A ``slack_access_token`` means the customer's own Slack app. The token is stored on the+ source itself, so it stays within Slack's API terms for internal apps. ``auth.test`` gives+ the token's own user id and a hash of the token keys the cache. This is the only path new+ sources can configure.+ - Otherwise the source predates bring-your-own and still points at PostHog's shared app+ (legacy OAuth): credentials live on the linked Integration row. Pasting a token converts+ such a source in place — the token takes precedence and the stale integration id is ignored.+ """+ if config.slack_access_token:+ access_token = config.slack_access_token+ return access_token, auth_test_user_id(access_token), manual_cache_id(access_token)++ if not config.slack_integration_id:+ raise ValueError("Slack access token not found")++ integration = self.get_oauth_integration(config.slack_integration_id, team_id)+ oauth_token = integration.access_token+ if not oauth_token:+ raise ValueError("Slack access token not found")+ return oauth_token, self._get_authed_user_id(integration), str(integration.id)+def create_webhook(self, config: SlackSourceConfig, webhook_url: str, team_id: int) -> WebhookCreationResult:return WebhookCreationResult(success=False,@@ -90,48 +120,109 @@ class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], Webhookreturn SourceConfig(name=SchemaExternalDataSourceType.SLACK,category=DataWarehouseSourceCategory.COMMUNICATION,- caption="Connect your Slack workspace to sync channels, users, and messages.",+ caption="""Sync Slack channels, users, and messages into PostHog by connecting your own Slack app.++You create a Slack app in your workspace and paste its bot token here. Using your own app keeps message syncing within Slack's API terms — [read the docs](https://posthog.com/docs/cdp/sources/slack) for the full walkthrough.++**1. Create the app**++Open [Slack apps](https://api.slack.com/apps?new_app=1), click **From a manifest**, pick your workspace, and paste this manifest:++```json+{+ "display_information": {+ "name": "PostHog data warehouse",+ "description": "Sync Slack channels, users, and messages to PostHog data warehouse"+ },+ "oauth_config": {+ "scopes": {+ "bot": [+ "channels:read",+ "channels:join",+ "groups:read",+ "channels:history",+ "groups:history",+ "users:read",+ "users:read.email",+ "reactions:read"+ ]+ }+ },+ "settings": {+ "org_deploy_enabled": false,+ "socket_mode_enabled": false,+ "token_rotation_enabled": false+ }+}+```++**2. Install and copy the token**++Click **Install App > Install to Workspace** and authorize. Copy the **Bot User OAuth Token** (starts with `xoxb-`) and paste it below.++**3. Invite the bot**++Invite the bot to any channel whose messages you want to sync (`/invite @PostHog data warehouse`). After the source is created, follow the webhook steps to start receiving messages.""",iconPath="/static/services/slack.png",+ docsUrl="https://posthog.com/docs/cdp/sources/slack",releaseStatus=ReleaseStatus.GA,fields=cast(list[FieldType],[- SourceFieldOauthConfig(- name="slack_integration_id",- label="Slack workspace",+ SourceFieldInputConfig(+ name="slack_access_token",+ label="Bot User OAuth Token",+ type=SourceFieldInputConfigType.PASSWORD,required=True,- kind="slack",- requiredScopes="channels:read groups:read channels:history groups:history users:read users:read.email reactions:read",- )+ placeholder="xoxb-...",+ caption="Found under **Settings > Install App** in the Slack app you created from the manifest above.",+ secret=True,+ ),+ SourceFieldSwitchGroupConfig(+ name="join_public_channels",+ label="Automatically join public channels",+ caption="On by default: the bot joins every public channel so their new messages sync without inviting it to each one. Turn it off to pick channels manually. Private channels always need a manual invite. Uses the `channels:join` scope, which the manifest above already includes.",+ default=True,+ fields=cast(list[FieldType], []),+ ),],),webhookManualOnly=True,- webhookSetupCaption="""Use the manifest below to create a Slack app with the webhook URL and event subscriptions already configured.+ webhookSetupCaption="""Slack delivers new messages to PostHog through your Slack app's Event Subscriptions.++If you connected with your own Slack app (recommended), open that same app and add the Event Subscriptions below. Otherwise create a new app from the manifest.++1. Open your app (or [create one from a manifest](https://api.slack.com/apps?new_app=1))+2. Go to **Event Subscriptions**, toggle it on, and set the **Request URL** to the webhook URL shown below+3. Under **Subscribe to bot events**, add `message.channels` and `message.groups`, then **Save Changes** and reinstall if prompted+4. Open **Basic Information > App Credentials**, copy the **Signing Secret**, and paste it in the form below-1. Open [Slack apps](https://api.slack.com/apps?new_app=1) and click **From a manifest**-2. Pick your workspace and click **Next**-3. Paste the manifest below into the editor, click **Next**, then **Create**-4. In the left sidebar, click **Install App**, then **Install to Workspace**, and authorize-5. Open **Basic information > App credentials**, copy the **Signing secret**, and paste it in the form below+Prefer a manifest? Paste this when creating the app — it wires the request URL and events for you:```json{"display_information": {"name": "PostHog data warehouse",- "description": "Sync Slack messages and channels to PostHog data warehouse"+ "description": "Sync Slack channels, users, and messages to PostHog data warehouse"},"oauth_config": {"scopes": {- "user": [+ "bot": [+ "channels:read",+ "channels:join",+ "groups:read","channels:history",- "groups:history"+ "groups:history",+ "users:read",+ "users:read.email",+ "reactions:read"]}},"settings": {"event_subscriptions": {"request_url": "{webhook_url}",- "user_events": [+ "bot_events": ["message.channels","message.groups"]@@ -194,13 +285,13 @@ class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], Webhookfor name, endpoint_config in ENDPOINTS.items()]- integration = self.get_oauth_integration(config.slack_integration_id, team_id)- access_token = integration.access_token- if not access_token:- raise ValueError("Slack access token not found")-- authed_user = self._get_authed_user_id(integration)- channels = get_channels(integration.id, access_token, authed_user, force_refresh=force_refresh)+ access_token, authed_user, cache_id = self._resolve_access_token(config, team_id)+ # Only the bring-your-own path can auto-join — the legacy shared app lacks channels:join.+ # Joining is idempotent and only touches public channels the bot isn't in, so running it on+ # each discovery/refresh also picks up channels created since the last pass.+ if config.slack_access_token and config.join_public_channels and config.join_public_channels.enabled:+ join_public_channels(access_token, cache_id, authed_user)+ channels = get_channels(cache_id, access_token, authed_user, force_refresh=force_refresh)for ch in channels:if ch["id"] in ENDPOINTS:continue@@ -226,11 +317,7 @@ class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], Webhookself, config: SlackSourceConfig, team_id: int, schema_name: Optional[str] = None) -> tuple[bool, str | None]:try:- integration = self.get_oauth_integration(config.slack_integration_id, team_id)- access_token = integration.access_token-- if not access_token:- return False, "Slack access token not found"+ access_token, _authed_user, _cache_id = self._resolve_access_token(config, team_id)if validate_slack_credentials(access_token):return True, None@@ -248,11 +335,7 @@ class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], Webhookresumable_source_manager: ResumableSourceManager[SlackResumeConfig],inputs: SourceInputs,) -> SourceResponse:- integration = self.get_oauth_integration(config.slack_integration_id, inputs.team_id)- access_token = integration.access_token-- if not access_token:- raise ValueError(f"Slack access token not found for job {inputs.job_id}")+ access_token, authed_user, cache_id = self._resolve_access_token(config, inputs.team_id)# For channel schemas, the schema name is the channel ID itselfchannel_id = inputs.schema_name if inputs.schema_name not in ENDPOINTS else None@@ -261,7 +344,7 @@ class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], Webhookreturn slack_source(access_token=access_token,- integration_id=integration.id,+ cache_id=cache_id,endpoint=inputs.schema_name,team_id=inputs.team_id,job_id=inputs.job_id,@@ -273,5 +356,5 @@ class SlackSource(ResumableSource[SlackSourceConfig, SlackResumeConfig], Webhookincremental_field=inputs.incremental_field,channel_id=channel_id,webhook_source_manager=webhook_source_manager,- authed_user=self._get_authed_user_id(integration),+ authed_user=authed_user,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/slack/test_slack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/slack/test_slack.pyindex 195495df96bf..a8301dc96882 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/slack/test_slack.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/slack/test_slack.py@@ -15,6 +15,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.slack.slac_fetch_all_channels,_fetch_all_channels_cached,_fetch_channels_by_type,+ _join_public_channels,+ auth_test_user_id,+ manual_cache_id,slack_source,)@@ -278,8 +281,8 @@ class TestFetchAllChannelsCached:"products.warehouse_sources.backend.temporal.data_imports.sources.slack.slack._fetch_all_channels",return_value=[{"id": "C1", "name": "general"}],) as mock_fetch:- first = _fetch_all_channels_cached(integration_id=42, access_token="token", authed_user="U_INSTALLER")- second = _fetch_all_channels_cached(integration_id=42, access_token="token", authed_user="U_INSTALLER")+ first = _fetch_all_channels_cached(cache_id="42", access_token="token", authed_user="U_INSTALLER")+ second = _fetch_all_channels_cached(cache_id="42", access_token="token", authed_user="U_INSTALLER")assert first == second == [{"id": "C1", "name": "general"}]assert mock_fetch.call_count == 1@@ -289,8 +292,8 @@ class TestFetchAllChannelsCached:"products.warehouse_sources.backend.temporal.data_imports.sources.slack.slack._fetch_all_channels",side_effect=[[{"id": "A1", "name": "a"}], [{"id": "B1", "name": "b"}]],) as mock_fetch:- a = _fetch_all_channels_cached(integration_id=1, access_token="token", authed_user="U1")- b = _fetch_all_channels_cached(integration_id=2, access_token="token", authed_user="U1")+ a = _fetch_all_channels_cached(cache_id="1", access_token="token", authed_user="U1")+ b = _fetch_all_channels_cached(cache_id="2", access_token="token", authed_user="U1")assert a == [{"id": "A1", "name": "a"}]assert b == [{"id": "B1", "name": "b"}]@@ -301,11 +304,11 @@ class TestFetchAllChannelsCached:"products.warehouse_sources.backend.temporal.data_imports.sources.slack.slack._fetch_all_channels",side_effect=[[{"id": "C1", "name": "general"}], [{"id": "C2", "name": "renamed"}]],) as mock_fetch:- first = _fetch_all_channels_cached(integration_id=42, access_token="token", authed_user="U_INSTALLER")+ first = _fetch_all_channels_cached(cache_id="42", access_token="token", authed_user="U_INSTALLER")second = _fetch_all_channels_cached(- integration_id=42, access_token="token", authed_user="U_INSTALLER", force_refresh=True+ cache_id="42", access_token="token", authed_user="U_INSTALLER", force_refresh=True)- third = _fetch_all_channels_cached(integration_id=42, access_token="token", authed_user="U_INSTALLER")+ third = _fetch_all_channels_cached(cache_id="42", access_token="token", authed_user="U_INSTALLER")assert first == [{"id": "C1", "name": "general"}]assert second == [{"id": "C2", "name": "renamed"}]@@ -320,7 +323,7 @@ class TestFetchAllChannelsCached:"products.warehouse_sources.backend.temporal.data_imports.sources.slack.slack._fetch_all_channels",return_value=[{"id": "C1", "name": "general"}],):- _fetch_all_channels_cached(integration_id=42, access_token="token", authed_user="U_INSTALLER")+ _fetch_all_channels_cached(cache_id="42", access_token="token", authed_user="U_INSTALLER")with patch("products.warehouse_sources.backend.temporal.data_imports.sources.slack.slack._fetch_all_channels",@@ -328,7 +331,7 @@ class TestFetchAllChannelsCached:):try:_fetch_all_channels_cached(- integration_id=42, access_token="token", authed_user="U_INSTALLER", force_refresh=True+ cache_id="42", access_token="token", authed_user="U_INSTALLER", force_refresh=True)except RuntimeError:pass@@ -337,7 +340,7 @@ class TestFetchAllChannelsCached:"products.warehouse_sources.backend.temporal.data_imports.sources.slack.slack._fetch_all_channels",return_value=[{"id": "WRONG", "name": "should_not_be_called"}],) as mock_fetch:- after = _fetch_all_channels_cached(integration_id=42, access_token="token", authed_user="U_INSTALLER")+ after = _fetch_all_channels_cached(cache_id="42", access_token="token", authed_user="U_INSTALLER")assert after == [{"id": "C1", "name": "general"}]assert mock_fetch.call_count == 0@@ -352,6 +355,7 @@ class TestSlackSourceGetSchemasForceRefresh:def _build_mocks(self) -> tuple[Any, Any]:config = MagicMock()+ config.slack_access_token = Noneconfig.slack_integration_id = 42integration = MagicMock()@@ -424,7 +428,7 @@ class TestSlackSourceChannelsEndpoint:def _build_source(self, authed_user: str | None) -> Any:return slack_source(access_token="token",- integration_id=42,+ cache_id="42",endpoint="$channels",team_id=1,job_id="job-1",@@ -468,7 +472,7 @@ class TestSlackSourceChannelMessagesWebhookOnly:def _build_channel_source(self, webhook_manager: Any) -> Any:return slack_source(access_token="token",- integration_id=42,+ cache_id="42",endpoint="C123",team_id=1,job_id="job-1",@@ -506,3 +510,231 @@ class TestSlackSourceChannelMessagesWebhookOnly:assert items == expected_itemsassert manager.get_items.called == expect_get_items_calledmock_backfill.assert_not_called()+++class TestResolveAccessToken:+ _SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.slack.source"++ def test_token_uses_pasted_token_without_an_integration(self) -> None:+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.slack import (+ SlackSourceConfig,+ )+ from products.warehouse_sources.backend.temporal.data_imports.sources.slack.source import SlackSource++ config = SlackSourceConfig.from_dict({"slack_access_token": "xoxb-abc"})+ source = SlackSource()++ with (+ patch(f"{self._SOURCE_MODULE}.auth_test_user_id", return_value="UBOT") as mock_auth_test,+ patch.object(source, "get_oauth_integration") as mock_get_integration,+ ):+ access_token, authed_user, cache_id = source._resolve_access_token(config, team_id=1)++ assert access_token == "xoxb-abc"+ assert authed_user == "UBOT"+ assert cache_id == manual_cache_id("xoxb-abc")+ # The bring-your-own path must never touch an Integration row — that's what keeps it+ # off the shared PostHog app.+ mock_get_integration.assert_not_called()+ mock_auth_test.assert_called_once_with("xoxb-abc")++ def test_legacy_source_resolves_via_linked_integration(self) -> None:+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.slack import (+ SlackSourceConfig,+ )+ from products.warehouse_sources.backend.temporal.data_imports.sources.slack.source import SlackSource++ config = SlackSourceConfig.from_dict({"slack_integration_id": 42})+ source = SlackSource()++ integration = MagicMock()+ integration.id = 42+ integration.access_token = "token"+ integration.config = {"authed_user": {"id": "U_INSTALLER"}}++ with patch.object(source, "get_oauth_integration", return_value=integration) as mock_get_integration:+ access_token, authed_user, cache_id = source._resolve_access_token(config, team_id=1)++ assert (access_token, authed_user, cache_id) == ("token", "U_INSTALLER", "42")+ mock_get_integration.assert_called_once_with(42, 1)++ def test_token_takes_precedence_over_a_legacy_integration(self) -> None:+ # Converting a legacy source in place: once a bot token is pasted, the stale integration id+ # is ignored and no Integration lookup happens.+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.slack import (+ SlackSourceConfig,+ )+ from products.warehouse_sources.backend.temporal.data_imports.sources.slack.source import SlackSource++ config = SlackSourceConfig.from_dict({"slack_access_token": "xoxb-new", "slack_integration_id": 42})+ source = SlackSource()++ with (+ patch(f"{self._SOURCE_MODULE}.auth_test_user_id", return_value="UBOT"),+ patch.object(source, "get_oauth_integration") as mock_get_integration,+ ):+ access_token, _authed_user, _cache_id = source._resolve_access_token(config, team_id=1)++ assert access_token == "xoxb-new"+ mock_get_integration.assert_not_called()++ def test_no_credentials_raises(self) -> None:+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.slack import (+ SlackSourceConfig,+ )+ from products.warehouse_sources.backend.temporal.data_imports.sources.slack.source import SlackSource++ config = SlackSourceConfig.from_dict({})+ source = SlackSource()++ try:+ source._resolve_access_token(config, team_id=1)+ raise AssertionError("expected ValueError for missing credentials")+ except ValueError as e:+ assert "access token not found" in str(e)+++class TestAuthTestUserId:+ @parameterized.expand(+ [+ ("ok_returns_user_id", {"ok": True, "user_id": "U1"}, "U1"),+ ("not_ok_returns_none", {"ok": False, "error": "invalid_auth"}, None),+ ("ok_without_user_id_returns_none", {"ok": True}, None),+ ]+ )+ def test_parses_response(self, _name: str, payload: dict[str, Any], expected: str | None) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.slack.slack._slack_get",+ return_value=_make_response(payload),+ ):+ assert auth_test_user_id("token") == expected++ def test_network_error_returns_none(self) -> None:+ # A failed auth.test must not blow up discovery — it falls back to unscoped private-channel+ # listing rather than crashing the sync.+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.slack.slack._slack_get",+ side_effect=RuntimeError("boom"),+ ):+ assert auth_test_user_id("token") is None+++class TestJoinPublicChannels:+ _POST = "products.warehouse_sources.backend.temporal.data_imports.sources.slack.slack._slack_post"++ def test_only_public_non_member_channels_are_joined(self) -> None:+ channels: list[dict[str, Any]] = [+ {"id": "C_PUB_NEW"}, # public, not a member -> join+ {"id": "C_PUB_MEMBER", "is_member": True}, # already in -> skip+ {"id": "C_PRIVATE", "is_private": True}, # private -> skip (can't self-join)+ {"id": "C_ARCHIVED", "is_archived": True}, # archived -> skip+ ]+ with patch(self._POST, return_value=_make_response({"ok": True})) as mock_post:+ joined = _join_public_channels("xoxb", channels)++ assert joined == 1+ assert mock_post.call_count == 1+ assert mock_post.call_args.kwargs["data"] == {"channel": "C_PUB_NEW"}++ def test_already_in_channel_is_not_counted_or_raised(self) -> None:+ # A race where the bot joined between listing and the join call must be a silent no-op.+ channels = [{"id": "C1"}]+ with patch(self._POST, return_value=_make_response({"ok": False, "error": "already_in_channel"})):+ assert _join_public_channels("xoxb", channels) == 0++ def test_missing_scope_raises(self) -> None:+ # Auto-join silently doing nothing would be worse than failing — surface the missing scope.+ channels = [{"id": "C1"}]+ with patch(self._POST, return_value=_make_response({"ok": False, "error": "missing_scope"})):+ try:+ _join_public_channels("xoxb", channels)+ raise AssertionError("expected an error for missing channels:join scope")+ except Exception as e:+ assert "channels:join" in str(e)+++class TestGetSchemasAutoJoin:+ _SRC = "products.warehouse_sources.backend.temporal.data_imports.sources.slack.source"++ def setup_method(self) -> None:+ django_cache.clear()++ def teardown_method(self) -> None:+ django_cache.clear()++ @parameterized.expand(+ [+ ("toggle_on_joins", True, "xoxb-token", True),+ ("toggle_off_skips", False, "xoxb-token", False),+ ("legacy_source_never_joins", True, None, False),+ ]+ )+ def test_join_is_gated_on_toggle_and_byo_token(+ self, _name: str, enabled: bool, token: str | None, expect_join: bool+ ) -> None:+ from products.warehouse_sources.backend.temporal.data_imports.sources.slack.source import SlackSource++ config = MagicMock()+ config.slack_access_token = token+ config.slack_integration_id = 42 if token is None else None+ config.join_public_channels.enabled = enabled++ integration = MagicMock()+ integration.id = 42+ integration.access_token = "legacy-token"+ integration.config = {"authed_user": {"id": "U_INSTALLER"}}++ source = SlackSource()+ with (+ patch(f"{self._SRC}.auth_test_user_id", return_value="UBOT"),+ patch.object(source, "get_oauth_integration", return_value=integration),+ patch(f"{self._SRC}.join_public_channels") as mock_join,+ patch(f"{self._SRC}.get_channels", return_value=[]),+ ):+ source.get_schemas(config, team_id=1)++ assert mock_join.called == expect_join++ def test_byo_source_joins_by_default(self) -> None:+ # The toggle defaults on: a bring-your-own source that doesn't set it explicitly still+ # auto-joins. (Legacy OAuth sources are held off by the token gate — covered above.)+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.slack import (+ SlackSourceConfig,+ )+ from products.warehouse_sources.backend.temporal.data_imports.sources.slack.source import SlackSource++ config = SlackSourceConfig.from_dict({"slack_access_token": "xoxb-token"})+ assert config.join_public_channels is not None+ assert config.join_public_channels.enabled is True++ source = SlackSource()+ with (+ patch(f"{self._SRC}.auth_test_user_id", return_value="UBOT"),+ patch(f"{self._SRC}.join_public_channels") as mock_join,+ patch(f"{self._SRC}.get_channels", return_value=[]),+ ):+ source.get_schemas(config, team_id=1)++ mock_join.assert_called_once()++ def test_toggle_can_be_explicitly_disabled(self) -> None:+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.slack import (+ SlackSourceConfig,+ )+ from products.warehouse_sources.backend.temporal.data_imports.sources.slack.source import SlackSource++ config = SlackSourceConfig.from_dict(+ {"slack_access_token": "xoxb-token", "join_public_channels": {"enabled": False}}+ )+ assert config.join_public_channels is not None+ assert config.join_public_channels.enabled is False++ source = SlackSource()+ with (+ patch(f"{self._SRC}.auth_test_user_id", return_value="UBOT"),+ patch(f"{self._SRC}.join_public_channels") as mock_join,+ patch(f"{self._SRC}.get_channels", return_value=[]),+ ):+ source.get_schemas(config, team_id=1)++ mock_join.assert_not_called()