: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(egress): add Slack API observability (#85221)
Julian Bez31b1a089a67d
diff --git a/.semgrep/rules/devex/slack-api-calls-go-through-egress.py b/.semgrep/rules/devex/slack-api-calls-go-through-egress.pynew file mode 100644index 000000000000..b7a648dc8440--- /dev/null+++ b/.semgrep/rules/devex/slack-api-calls-go-through-egress.py@@ -0,0 +1,37 @@+# ruff: noqa: F841+import requests+from slack_sdk import WebClient++from posthog.egress.slack.client import SlackWebClient+from posthog.egress.slack.transport import slack_request+++def flagged_literal_url(token: str):+ # ruleid: slack-api-calls-go-through-egress+ return requests.post("https://slack.com/api/chat.postMessage", data={"token": token})+++def flagged_sdk_client(token: str):+ # ruleid: slack-api-calls-go-through-egress+ return WebClient(token=token)+++def ok_through_transport(token: str):+ # ok: slack-api-calls-go-through-egress+ return slack_request(+ "POST",+ "https://slack.com/api/chat.postMessage",+ source="test",+ endpoint="chat.postMessage",+ headers={"Authorization": f"Bearer {token}"},+ )+++def ok_egress_client(token: str):+ # ok: slack-api-calls-go-through-egress+ return SlackWebClient(token=token, source="test")+++def ok_webhook():+ # ok: slack-api-calls-go-through-egress+ return requests.post("https://hooks.slack.com/services/example")diff --git a/.semgrep/rules/devex/slack-api-calls-go-through-egress.yaml b/.semgrep/rules/devex/slack-api-calls-go-through-egress.yamlnew file mode 100644index 000000000000..0f30bfdbdd54--- /dev/null+++ b/.semgrep/rules/devex/slack-api-calls-go-through-egress.yaml@@ -0,0 +1,44 @@+rules:+ - id: slack-api-calls-go-through-egress+ message: |+ Outbound Slack Web API calls must go through the recorded egress clients.++ Use `posthog.egress.slack.client.SlackWebClient` (or `SlackAsyncWebClient`) for+ Slack SDK calls and `posthog.egress.slack.transport.slack_request` for direct HTTP.+ Incoming webhooks and interactivity response URLs are outside this rule because their+ secret URL, not a workspace ID, owns the budget. See `posthog/egress/README.md`.++ The direct-HTTP half only catches literal/f-string URLs on the `requests` module, so+ keep URLs inline at the call site. Any `WebClient` / `AsyncWebClient` construction is+ caught regardless of URL shape. Suppress a legitimate exception with+ `# nosemgrep: slack-api-calls-go-through-egress -- <reason>`.+ languages: [python]+ severity: ERROR+ pattern-either:+ - patterns:+ - pattern-either:+ - pattern: requests.$METHOD($URL, ...)+ - pattern: requests.request($METHOD, $URL, ...)+ - metavariable-regex:+ metavariable: $URL+ regex: .*slack\.com/api.*+ - patterns:+ - pattern-inside: |+ from slack_sdk import WebClient+ ...+ - pattern: WebClient(...)+ - patterns:+ - pattern-inside: |+ from slack_sdk.web.async_client import AsyncWebClient+ ...+ - pattern: AsyncWebClient(...)+ paths:+ include:+ - common/**/*.py+ - ee/**/*.py+ - posthog/**/*.py+ - products/**/*.py+ exclude:+ - posthog/egress/**+ - '**/test/**'+ - '**/tests/**'diff --git a/ee/billing/salesforce_enrichment/conversations_signals.py b/ee/billing/salesforce_enrichment/conversations_signals.pyindex e87fd572b093..bd75b032359b 100644--- a/ee/billing/salesforce_enrichment/conversations_signals.py+++ b/ee/billing/salesforce_enrichment/conversations_signals.py@@ -9,12 +9,12 @@ from django.contrib.postgres.aggregates import ArrayAggfrom django.db.models import Case, Count, DateTimeField, Exists, Max, Min, OuterRef, Q, QuerySet, UUIDField, Whenfrom django.db.models.functions import Cast, Coalesce-from slack_sdk import WebClientfrom slack_sdk.errors import SlackApiErrorfrom posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.client.execute import query_with_columnsfrom posthog.clickhouse.query_tagging import tags_context+from posthog.egress.slack.client import SlackWebClient as WebClientfrom posthog.models.comment import Commentfrom posthog.models.organization import OrganizationMembershipfrom posthog.temporal.common.logger import get_logger@@ -52,14 +52,20 @@ def build_support_ticket_url(team_id: int, ticket_number: int) -> str:return f"{settings.SITE_URL.rstrip('/')}/project/{team_id}/support/tickets/{ticket_number}"-def _get_slack_bot_token(slack_team_id: str | None, team_id: int | None) -> str | None:- """Resolve the Slack bot token that can read a channel.+def _get_slack_bot_token(slack_team_id: str | None, team_id: int | None) -> tuple[str, str | None] | None:+ """Resolve the Slack bot token that can read a channel, and the workspace it belongs to.The bot lives in the channel's Slack workspace, so match the config by``slack_team_id`` (unique per workspace) first and fall back to therepresentative PostHog team only when the workspace id is unknown.++ The returned workspace id comes from the resolved config rather than the+ requested ``slack_team_id`` so that a team fallback attributes egress to the+ workspace the token actually belongs to, not to a requested-but-unmatched id."""- configs = TeamConversationsSlackConfig.objects.filter(slack_bot_token__isnull=False).only("slack_bot_token")+ configs = TeamConversationsSlackConfig.objects.filter(slack_bot_token__isnull=False).only(+ "slack_bot_token", "slack_team_id"+ )config = configs.filter(slack_team_id=slack_team_id).first() if slack_team_id else Noneif config is None and team_id is not None:@@ -67,16 +73,22 @@ def _get_slack_bot_token(slack_team_id: str | None, team_id: int | None) -> strif not config or not config.slack_bot_token:return None- return str(config.slack_bot_token)+ return str(config.slack_bot_token), config.slack_team_iddef fetch_slack_channel_user_count(team_id: int, slack_channel_id: str, slack_team_id: str | None = None) -> int | None:"""Fetch the current Slack channel member count using the channel's support bot token."""- bot_token = _get_slack_bot_token(slack_team_id, team_id)- if not bot_token:+ resolved = _get_slack_bot_token(slack_team_id, team_id)+ if not resolved:return None+ bot_token, resolved_slack_team_id = resolved- client = WebClient(token=bot_token)+ client = WebClient(+ token=bot_token,+ source="salesforce_enrichment",+ workspace_id=resolved_slack_team_id,+ app_id="support",+ )cursor: str | None = Noneuser_count = 0diff --git a/ee/billing/test/test_conversations_signals.py b/ee/billing/test/test_conversations_signals.pyindex cd4d68a30d34..bcbf644eefc4 100644--- a/ee/billing/test/test_conversations_signals.py+++ b/ee/billing/test/test_conversations_signals.py@@ -236,7 +236,7 @@ class TestConversationsSlackSignals(SimpleTestCase):@patch("ee.billing.salesforce_enrichment.conversations_signals.WebClient")@patch("ee.billing.salesforce_enrichment.conversations_signals._get_slack_bot_token")def test_fetch_slack_channel_user_count_paginates(self, mock_get_token, mock_web_client):- mock_get_token.return_value = "xoxb-test"+ mock_get_token.return_value = ("xoxb-test", "T123")mock_client = MagicMock()mock_client.conversations_members.side_effect = [{"members": ["U1", "U2"], "response_metadata": {"next_cursor": "next-page"}},@@ -643,9 +643,10 @@ class TestConversationsSlackSignalsDatabase(BaseTest):)# Matches by Slack workspace id, independent of the representative team.- assert _get_slack_bot_token("TWORK", None) == "xoxb-test"- # Falls back to the representative team when the workspace id is absent or unmatched.- assert _get_slack_bot_token(None, self.team.id) == "xoxb-test"- assert _get_slack_bot_token("TUNMATCHED", self.team.id) == "xoxb-test"+ assert _get_slack_bot_token("TWORK", None) == ("xoxb-test", "TWORK")+ # Falls back to the representative team when the workspace id is absent or unmatched,+ # and reports the token's real workspace rather than the requested-but-unmatched id.+ assert _get_slack_bot_token(None, self.team.id) == ("xoxb-test", "TWORK")+ assert _get_slack_bot_token("TUNMATCHED", self.team.id) == ("xoxb-test", "TWORK")# No token when neither path resolves.assert _get_slack_bot_token("TUNMATCHED", None) is Nonediff --git a/posthog/egress/README.md b/posthog/egress/README.mdindex a047c7da0dbb..33ce84361eb6 100644--- a/posthog/egress/README.md+++ b/posthog/egress/README.md@@ -104,6 +104,18 @@ Response handling — what to do on a 403/429 — stays with the caller: `raise_The model-coupled `GitHubIntegrationBase.api_request` layers the installation-token lifecycle (proactive refresh, 401 refresh-retry, rate-limit raising, per-instance `source` attribution) on top — hold an integration, call that; hold a bare token, call `github_request`.Raw `requests` calls against `api.github.com` are blocked by the `github-api-calls-go-through-egress` semgrep rule (`.semgrep/devex-rules/`), so new callers land on one of these two paths by construction.+Slack Web API calls use `SlackWebClient` (and `SlackAsyncWebClient` where needed) from `slack/` so+request volume, method, status, source, and workspace are recorded consistently. Slack applies Web API+limits per method, workspace, and app, with additional special limits such as per-channel message+posting. Installation age and Marketplace status can also change the limits for history methods.+Slack does not return remaining-budget headers, so Slack egress records each HTTP attempt and the+app-and-method-specific `Retry-After` from 429 responses. It does not proactively limit requests.+Callers continue to own reactive retries.++Incoming webhooks and interactivity `response_url` calls are not Slack Web API calls. Their secret URL is+the budget identity, and persisting or labeling by it would expose credentials. Keep their error handling+with the caller rather than assigning them to a shared workspace bucket.+## The one identity ruleEverything keys on the **budget owner in the external API's own id space** — for GitHub the App **installation id**, because that is what GitHub meters.diff --git a/posthog/egress/slack/__init__.py b/posthog/egress/slack/__init__.pynew file mode 100644index 000000000000..c7ab9713d375--- /dev/null+++ b/posthog/egress/slack/__init__.py@@ -0,0 +1,3 @@+from posthog.egress.slack.client import SlackWebClient++__all__ = ["SlackWebClient"]diff --git a/posthog/egress/slack/async_client.py b/posthog/egress/slack/async_client.pynew file mode 100644index 000000000000..54382e21e64f--- /dev/null+++ b/posthog/egress/slack/async_client.py@@ -0,0 +1,61 @@+from typing import Any++from slack_sdk.http_retry.async_handler import AsyncRetryHandler+from slack_sdk.http_retry.request import HttpRequest+from slack_sdk.http_retry.response import HttpResponse+from slack_sdk.http_retry.state import RetryState+from slack_sdk.web.async_client import AsyncWebClient++from posthog.egress.slack.observability import record_slack_api_exception, record_slack_api_response+++class SlackAsyncObservabilityHandler(AsyncRetryHandler):+ def __init__(self, *, source: str, workspace_id: str | None, app_id: str) -> None:+ super().__init__()+ self._source = source+ self._workspace_id = workspace_id or None+ self._app_id = app_id++ async def can_retry_async(+ self,+ *,+ state: RetryState,+ request: HttpRequest,+ response: HttpResponse | None = None,+ error: Exception | None = None,+ ) -> bool:+ endpoint = request.url.rsplit("/", 1)[-1]+ if response is not None:+ record_slack_api_response(+ response,+ source=self._source,+ workspace_id=self._workspace_id,+ app_id=self._app_id,+ method=request.method,+ endpoint=endpoint,+ )+ else:+ record_slack_api_exception(+ source=self._source,+ workspace_id=self._workspace_id,+ method=request.method,+ endpoint=endpoint,+ )+ return False+++class SlackAsyncWebClient(AsyncWebClient):+ def __init__(+ self,+ token: str | None = None,+ *,+ source: str = "unknown",+ workspace_id: str | None = None,+ app_id: str = "unknown",+ **kwargs: Any,+ ) -> None:+ super().__init__(token=token, **kwargs)+ self.retry_handlers.insert(+ 0,+ SlackAsyncObservabilityHandler(source=source, workspace_id=workspace_id, app_id=app_id),+ )diff --git a/posthog/egress/slack/client.py b/posthog/egress/slack/client.pynew file mode 100644index 000000000000..a7c229f48ef7--- /dev/null+++ b/posthog/egress/slack/client.py@@ -0,0 +1,61 @@+from typing import Any++from slack_sdk import WebClient+from slack_sdk.http_retry import RetryHandler+from slack_sdk.http_retry.request import HttpRequest+from slack_sdk.http_retry.response import HttpResponse+from slack_sdk.http_retry.state import RetryState++from posthog.egress.slack.observability import record_slack_api_exception, record_slack_api_response+++class SlackObservabilityHandler(RetryHandler):+ def __init__(self, *, source: str, workspace_id: str | None, app_id: str) -> None:+ super().__init__()+ self._source = source+ self._workspace_id = workspace_id or None+ self._app_id = app_id++ def can_retry(+ self,+ *,+ state: RetryState,+ request: HttpRequest,+ response: HttpResponse | None = None,+ error: Exception | None = None,+ ) -> bool:+ endpoint = request.url.rsplit("/", 1)[-1]+ if response is not None:+ record_slack_api_response(+ response,+ source=self._source,+ workspace_id=self._workspace_id,+ app_id=self._app_id,+ method=request.method,+ endpoint=endpoint,+ )+ else:+ record_slack_api_exception(+ source=self._source,+ workspace_id=self._workspace_id,+ method=request.method,+ endpoint=endpoint,+ )+ return False+++class SlackWebClient(WebClient):+ def __init__(+ self,+ token: str | None = None,+ *,+ source: str = "unknown",+ workspace_id: str | None = None,+ app_id: str = "unknown",+ **kwargs: Any,+ ) -> None:+ super().__init__(token=token, **kwargs)+ self.retry_handlers.insert(+ 0,+ SlackObservabilityHandler(source=source, workspace_id=workspace_id, app_id=app_id),+ )diff --git a/posthog/egress/slack/observability.py b/posthog/egress/slack/observability.pynew file mode 100644index 000000000000..3dcecfd257b5--- /dev/null+++ b/posthog/egress/slack/observability.py@@ -0,0 +1,89 @@+import time+from collections.abc import Mapping+from typing import cast++import requests+from prometheus_client import Counter, Gauge++from posthog.egress.observability.observability import (+ EgressMetrics,+ EgressObservability,+ RateLimitSnapshot,+ register_egress_observability,+)++SLACK_DOMAIN = "slack"+++_metrics = EgressMetrics(+ request_counter=Counter(+ "slack_api_requests",+ "Number of Slack API requests made through a Slack egress client.",+ labelnames=["workspace_id", "method", "endpoint", "status_code", "source"],+ ),+ remaining_gauge=Gauge(+ "slack_api_rate_limit_remaining",+ "Slack API rate limit remaining count when reported by Slack.",+ labelnames=["workspace_id", "resource"],+ ),+ limit_gauge=Gauge(+ "slack_api_rate_limit_limit",+ "Slack API rate limit when reported by Slack.",+ labelnames=["workspace_id", "resource"],+ ),+ reset_gauge=Gauge(+ "slack_api_rate_limit_reset_timestamp_seconds",+ "Slack API retry timestamp after a rate-limited response.",+ labelnames=["workspace_id", "resource"],+ ),+)+++def _header(headers: Mapping[str, object], name: str) -> str | None:+ lowered_name = name.lower()+ value = next((value for key, value in headers.items() if key.lower() == lowered_name), None)+ if isinstance(value, str):+ return value+ if isinstance(value, list) and value and isinstance(value[0], str):+ return value[0]+ return None+++def _parse_slack_rate_limit(response: requests.Response) -> RateLimitSnapshot:+ return RateLimitSnapshot()+++slack_egress = EgressObservability(SLACK_DOMAIN, _metrics, _parse_slack_rate_limit)+register_egress_observability(slack_egress)+++def record_slack_api_response(+ response: object,+ *,+ source: str,+ workspace_id: str | None,+ app_id: str,+ method: str,+ endpoint: str,+) -> None:+ normalized_workspace_id = workspace_id or None+ typed_response = cast(requests.Response, response)+ slack_egress.record_response(+ typed_response,+ source=source,+ scope=normalized_workspace_id,+ method=method,+ endpoint=endpoint,+ )+ retry_after = _header(typed_response.headers, "Retry-After")+ if normalized_workspace_id is None or typed_response.status_code != 429 or retry_after is None:+ return+ try:+ reset_at = time.time() + float(retry_after)+ except ValueError:+ return+ _metrics.reset_gauge.labels(normalized_workspace_id, f"{app_id}:{endpoint}").set(reset_at)+++def record_slack_api_exception(*, source: str, workspace_id: str | None, method: str, endpoint: str) -> None:+ slack_egress.record_exception(source=source, scope=workspace_id or None, method=method, endpoint=endpoint)diff --git a/posthog/egress/slack/transport.py b/posthog/egress/slack/transport.pynew file mode 100644index 000000000000..443d45a26722--- /dev/null+++ b/posthog/egress/slack/transport.py@@ -0,0 +1,83 @@+from typing import Any++import requests++from posthog.egress.limiter.policies import Priority+from posthog.egress.slack.observability import record_slack_api_exception, record_slack_api_response+from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient+++class SlackEgressBudgetExhausted(EgressBudgetExhausted):+ pass+++class SlackClient(EgressClient):+ def __init__(self, app_id: str) -> None:+ self._app_id = app_id++ def _standard_headers(self) -> dict[str, str]:+ return {"Accept": "application/json"}++ def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:+ return True++ def _record_response(+ self,+ response: requests.Response,+ *,+ source: str,+ scope: str | None,+ method: str,+ endpoint: str | None,+ ) -> None:+ record_slack_api_response(+ response,+ source=source,+ workspace_id=scope,+ app_id=self._app_id,+ method=method,+ endpoint=endpoint or "unknown",+ )++ def _record_exception(+ self,+ *,+ source: str,+ scope: str | None,+ method: str,+ url: str,+ endpoint: str | None,+ ) -> None:+ record_slack_api_exception(+ source=source,+ workspace_id=scope,+ method=method,+ endpoint=endpoint or "unknown",+ )++ def _budget_exhausted_error(self, scope: str) -> SlackEgressBudgetExhausted:+ return SlackEgressBudgetExhausted(f"Slack egress budget exhausted for workspace {scope}")+++def slack_request(+ method: str,+ url: str,+ *,+ source: str,+ endpoint: str,+ workspace_id: str | None = None,+ app_id: str = "unknown",+ timeout: float | tuple[float, float] | None = None,+ session: requests.Session | None = None,+ **kwargs: Any,+) -> requests.Response:+ return SlackClient(app_id).request(+ method,+ url,+ source=source,+ scope=workspace_id or None,+ endpoint=endpoint,+ timeout=timeout,+ session=session,+ **kwargs,+ )diff --git a/posthog/egress/test/test_slack_client.py b/posthog/egress/test/test_slack_client.pynew file mode 100644index 000000000000..34a7a21a617a--- /dev/null+++ b/posthog/egress/test/test_slack_client.py@@ -0,0 +1,68 @@+from typing import Any++from unittest.mock import patch++from prometheus_client import REGISTRY+from slack_sdk.http_retry.builtin_handlers import RateLimitErrorRetryHandler+from slack_sdk.http_retry.request import HttpRequest+from slack_sdk.http_retry.response import HttpResponse+from slack_sdk.http_retry.state import RetryState++from posthog.egress.slack.client import SlackWebClient+++class ImmediateRateLimitRetryHandler(RateLimitErrorRetryHandler):+ def prepare_for_next_attempt(+ self,+ *,+ state: RetryState,+ request: HttpRequest,+ response: HttpResponse | None = None,+ error: Exception | None = None,+ ) -> None:+ state.next_attempt_requested = True+ state.increment_current_attempt()+++def _request_count(status_code: str) -> float:+ return (+ REGISTRY.get_sample_value(+ "slack_api_requests_total",+ {+ "workspace_id": "T123",+ "method": "POST",+ "endpoint": "conversations.history",+ "status_code": status_code,+ "source": "test",+ },+ )+ or 0+ )+++def test_slack_web_client_records_each_retry_attempt() -> None:+ client = SlackWebClient(token="xoxb-test", source="test", workspace_id="T123", app_id="posthog")+ client.retry_handlers.append(ImmediateRateLimitRetryHandler(max_retry_count=1))+ responses: list[dict[str, Any]] = [+ {+ "status": 429,+ "headers": {"Retry-After": ["30"]},+ "body": '{"ok": false, "error": "ratelimited"}',+ },+ {"status": 200, "headers": {}, "body": '{"ok": true}'},+ ]+ success_before = _request_count("200")+ rate_limited_before = _request_count("429")++ with patch.object(client, "_perform_urllib_http_request_internal", side_effect=responses):+ assert client.conversations_history(channel="C123")["ok"] is True++ assert _request_count("200") == success_before + 1+ assert _request_count("429") == rate_limited_before + 1+ assert (+ REGISTRY.get_sample_value(+ "slack_api_rate_limit_reset_timestamp_seconds",+ {"workspace_id": "T123", "resource": "posthog:conversations.history"},+ )+ is not None+ )diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex bfea4f6fcf85..bc6f0e07f541 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -42,7 +42,6 @@ from prometheus_client import Counterfrom requests.auth import HTTPBasicAuthfrom rest_framework.exceptions import ValidationErrorfrom rest_framework.request import Request-from slack_sdk import WebClientfrom slack_sdk.errors import SlackApiErrorfrom tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed@@ -50,6 +49,8 @@ from posthog.cache_utils import cache_forfrom posthog.credentials import AWSKeyPairfrom posthog.egress.github.transport import github_requestfrom posthog.egress.limiter.policies import Priority+from posthog.egress.slack.client import SlackWebClient as WebClient+from posthog.egress.slack.observability import record_slack_api_responsefrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.encrypted_fields import FERNET_TOKEN_PREFIX, EncryptedJSONFieldfrom posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationError@@ -1538,6 +1539,16 @@ class OauthIntegration:allow_redirects=False,)+ if kind == "slack":+ record_slack_api_response(+ res,+ source="oauth",+ workspace_id=None,+ app_id="posthog",+ method="POST",+ endpoint="oauth.v2.access",+ )+try:config: dict = res.json()except ValueError:@@ -2162,14 +2173,25 @@ class SlackIntegration:@propertydef client(self) -> WebClient:- return WebClient(self.integration.sensitive_config["access_token"])+ return WebClient(+ self.integration.sensitive_config["access_token"],+ source="integration",+ workspace_id=self.integration.integration_id,+ app_id="posthog",+ )def async_client(self, session: Optional["aiohttp.ClientSession"] = None) -> "AsyncWebClient":# slack_sdk's async client imports aiohttp at module scope; this is a models module,# so a top-level import would put aiohttp on the django.setup() path- from slack_sdk.web.async_client import AsyncWebClient # noqa: PLC0415+ from posthog.egress.slack.async_client import SlackAsyncWebClient # noqa: PLC0415- return AsyncWebClient(self.integration.sensitive_config["access_token"], session=session)+ return SlackAsyncWebClient(+ self.integration.sensitive_config["access_token"],+ source="integration",+ workspace_id=self.integration.integration_id,+ app_id="posthog",+ session=session,+ )def granted_scopes(self) -> frozenset[str]:"""OAuth scopes Slack granted this install, stored on Integration.config["scope"]."""diff --git a/posthog/temporal/ai/slack_app/attachments.py b/posthog/temporal/ai/slack_app/attachments.pyindex 099302015132..7b1912302769 100644--- a/posthog/temporal/ai/slack_app/attachments.py+++ b/posthog/temporal/ai/slack_app/attachments.py@@ -4,9 +4,10 @@ from dataclasses import dataclassfrom typing import Anyfrom urllib.parse import urljoin, urlparse-import requestsimport structlog+from posthog.egress.slack.transport import slack_request+logger = structlog.get_logger(__name__)MAX_SLACK_ATTACHMENTS_PER_MESSAGE = 5@@ -186,8 +187,12 @@ def _download_slack_file(url: str, bot_token: str) -> bytes | None:logger.warning("slack_attachment_download_rejected_host", host=parsed.hostname)return None- response = requests.get(+ response = slack_request(+ "GET",next_url,+ source="slack_app_attachments",+ endpoint="files.download",+ app_id="posthog",headers={"Authorization": f"Bearer {bot_token}"},timeout=SLACK_DOWNLOAD_TIMEOUT_SECONDS,allow_redirects=False,diff --git a/posthog/temporal/tests/ai/slack_app/test_attachments.py b/posthog/temporal/tests/ai/slack_app/test_attachments.pyindex 8da545666d88..be0fac9e4559 100644--- a/posthog/temporal/tests/ai/slack_app/test_attachments.py+++ b/posthog/temporal/tests/ai/slack_app/test_attachments.py@@ -99,7 +99,7 @@ class TestSlackAttachments(SimpleTestCase):response.is_redirect = Falseresponse.status_code = 200response.headers = {"Content-Type": "text/html; charset=utf-8"}- with patch("posthog.temporal.ai.slack_app.attachments.requests.get", return_value=response):+ with patch("posthog.temporal.ai.slack_app.attachments.slack_request", return_value=response):prepared = prepare_slack_file_artifacts([_slack_file()], "xoxb-token")assert prepared.artifacts == []diff --git a/products/conversations/backend/api/slack_oauth.py b/products/conversations/backend/api/slack_oauth.pyindex ba4a03c71549..589c9eaa9acd 100644--- a/products/conversations/backend/api/slack_oauth.py+++ b/products/conversations/backend/api/slack_oauth.py@@ -6,12 +6,12 @@ from django.db import IntegrityError, transactionfrom django.http import HttpRequest, HttpResponse, HttpResponseRedirect, JsonResponsefrom django.views.decorators.csrf import csrf_exempt-import requestsfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.views import APIView+from posthog.egress.slack.transport import slack_requestfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.models.instance_setting import get_instance_settingsfrom posthog.models.organization import OrganizationMembership@@ -170,8 +170,12 @@ def support_slack_oauth_callback(request: HttpRequest) -> HttpResponse:return _error_response(next_path, "support_slack_not_configured", 503)try:- response = requests.post(+ response = slack_request(+ "POST","https://slack.com/api/oauth.v2.access",+ source="conversations_oauth",+ endpoint="oauth.v2.access",+ app_id="support",data={"client_id": client_id,"client_secret": client_secret,diff --git a/products/conversations/backend/api/tests/test_slack_oauth.py b/products/conversations/backend/api/tests/test_slack_oauth.pyindex 40cdea8c3579..d6e21f4c412a 100644--- a/products/conversations/backend/api/tests/test_slack_oauth.py+++ b/products/conversations/backend/api/tests/test_slack_oauth.py@@ -8,7 +8,7 @@ from products.conversations.backend.api.slack_oauth import support_slack_oauth_cclass TestSupportSlackOAuthCallbackThrottle(SimpleTestCase):- @patch("products.conversations.backend.api.slack_oauth.requests.post")+ @patch("products.conversations.backend.api.slack_oauth.slack_request")@patch.object(SupportSlackOAuthCallbackThrottle, "allow_request", return_value=False)def test_throttled_request_returns_429_before_token_exchange(self, _mock_allow, mock_post):request = RequestFactory().get("/api/conversations/v1/slack/callback", {"state": "x", "code": "y"})diff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.pyindex 5902105122fb..f1566bab063a 100644--- a/products/conversations/backend/slack.py+++ b/products/conversations/backend/slack.py@@ -22,13 +22,13 @@ from django.db.models import Fimport structlogimport posthoganalytics-from slack_sdk import WebClientfrom posthog.comment.formatting import (extract_slack_user_ids,slack_to_content_and_rich_content,strip_slack_user_mentions,)+from posthog.egress.slack.client import SlackWebClient as WebClientfrom posthog.event_usage import groups, report_team_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.slack_identity import resolve_posthog_user_for_slack, resolve_slack_user@@ -59,6 +59,7 @@ from .support_slack import (SUPPORT_SLACK_ALLOWED_HOST_SUFFIXES,SUPPORT_SLACK_FILE_READ_SCOPE,get_support_slack_bot_token,+ get_support_slack_workspace_id,supporthog_missing_file_scopes,)@@ -144,7 +145,12 @@ def get_slack_client(team: Team) -> WebClient:"""bot_token = get_support_slack_bot_token(team)if bot_token:- return WebClient(token=bot_token)+ return WebClient(+ token=bot_token,+ source="conversations",+ workspace_id=get_support_slack_workspace_id(team),+ app_id="support",+ )raise ValueError("Support Slack bot token is not configured")diff --git a/products/conversations/backend/support_slack.py b/products/conversations/backend/support_slack.pyindex c7fded776294..bf565f204b79 100644--- a/products/conversations/backend/support_slack.py+++ b/products/conversations/backend/support_slack.py@@ -53,6 +53,11 @@ def get_support_slack_bot_token(team: "Team") -> str:return str(config.slack_bot_token or "")+def get_support_slack_workspace_id(team: "Team") -> str | None:+ config = get_or_create_team_extension(team, TeamConversationsSlackConfig)+ return config.slack_team_id or None++def team_exists_for_slack_workspace(slack_team_id: str) -> bool:"""Whether any team has SupportHog connected to this Slack workspace.diff --git a/products/conversations/backend/support_slack_channels.py b/products/conversations/backend/support_slack_channels.pyindex 13c82210e620..4fd8526f8798 100644--- a/products/conversations/backend/support_slack_channels.py+++ b/products/conversations/backend/support_slack_channels.py@@ -9,9 +9,10 @@ of duplicating WebClient logic.from typing import TYPE_CHECKING, Any, castimport structlog-from slack_sdk import WebClient-from products.conversations.backend.support_slack import get_support_slack_bot_token+from posthog.egress.slack.client import SlackWebClient as WebClient++from products.conversations.backend.support_slack import get_support_slack_bot_token, get_support_slack_workspace_idif TYPE_CHECKING:from posthog.models.team.team import Team@@ -41,7 +42,12 @@ def list_support_bot_channels(team: "Team", *, members_only: bool = False) -> liif not bot_token:raise SupportSlackNotConfigured()- client = WebClient(token=bot_token)+ client = WebClient(+ token=bot_token,+ source="conversations",+ workspace_id=get_support_slack_workspace_id(team),+ app_id="support",+ )channels: list[dict[str, Any]] = []cursor = Nonediff --git a/products/slack_app/backend/services/slack_user_oauth.py b/products/slack_app/backend/services/slack_user_oauth.pyindex 07994330d51e..a12f2a3c9b5c 100644--- a/products/slack_app/backend/services/slack_user_oauth.py+++ b/products/slack_app/backend/services/slack_user_oauth.py@@ -30,9 +30,9 @@ from django.core import signingimport structlogfrom pydantic import BaseModel, ValidationError-from slack_sdk import WebClientfrom slack_sdk.errors import SlackApiError, SlackClientError+from posthog.egress.slack.client import SlackWebClient as WebClientfrom posthog.models.instance_setting import get_instance_settingsfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.user import User@@ -307,7 +307,7 @@ def exchange_code(*, code: str, redirect_uri: str) -> SlackIdentity:"""client_id, client_secret = _credentials()try:- token_response = WebClient().openid_connect_token(+ token_response = WebClient(source="slack_user_oauth", app_id="posthog").openid_connect_token(client_id=client_id,client_secret=client_secret,code=code,@@ -325,7 +325,7 @@ def exchange_code(*, code: str, redirect_uri: str) -> SlackIdentity:raise SlackUserOAuthError("Slack OIDC token response missing access_token")try:- userinfo = WebClient(token=user_token).openid_connect_userInfo()+ userinfo = WebClient(token=user_token, source="slack_user_oauth", app_id="posthog").openid_connect_userInfo()except SlackApiError as exc:error = exc.response.get("error") if exc.response else Nonelogger.warning("slack_app_user_link_oidc_userinfo_failed", error=error)diff --git a/products/slack_app/backend/tests/services/test_slack_user_oauth.py b/products/slack_app/backend/tests/services/test_slack_user_oauth.pyindex 4bacfe87c529..a425a07da67b 100644--- a/products/slack_app/backend/tests/services/test_slack_user_oauth.py+++ b/products/slack_app/backend/tests/services/test_slack_user_oauth.py@@ -319,7 +319,7 @@ class TestExchangeCode:assert identity.user_access_token == "xoxp-user"# userInfo must be asked with the token minted by the code exchange —# a bot or stale token would report the wrong (or no) identity.- slack_client.assert_any_call(token="xoxp-user")+ slack_client.assert_any_call(token="xoxp-user", source="slack_user_oauth", app_id="posthog")def test_token_exchange_api_error_wraps_into_oauth_error(self, slack_client):slack_client.return_value.openid_connect_token.side_effect = SlackApiError(diff --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 138aa6875984..98aad2ac1949 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@@ -14,6 +14,8 @@ from asgiref.sync import async_to_syncfrom requests import Request, Responsefrom tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from posthog.egress.slack.transport import slack_request+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_listfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (@@ -63,7 +65,15 @@ def _wait_with_retry_after(retry_state: RetryCallState) -> float:reraise=True,)def _slack_get(url: str, **kwargs: Any) -> requests.Response:- response = make_tracked_session().get(url, **kwargs)+ response = slack_request(+ "GET",+ url,+ source="warehouse",+ endpoint=url.rsplit("/", 1)[-1],+ app_id="warehouse_source",+ session=make_tracked_session(),+ **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)@@ -82,7 +92,15 @@ def _slack_get(url: str, **kwargs: Any) -> requests.Response:reraise=True,)def _slack_post(url: str, **kwargs: Any) -> requests.Response:- response = make_tracked_session().post(url, **kwargs)+ response = slack_request(+ "POST",+ url,+ source="warehouse",+ endpoint=url.rsplit("/", 1)[-1],+ app_id="warehouse_source",+ session=make_tracked_session(),+ **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)