: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
refactor(devex): share stamphog's slack channel lookup and posting (#98981)
Julian Bez6f592e67585d
diff --git a/posthog/team_notifications/__init__.py b/posthog/team_notifications/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/team_notifications/slack.py b/posthog/team_notifications/slack.pynew file mode 100644index 000000000000..c1afa2013dfa--- /dev/null+++ b/posthog/team_notifications/slack.py@@ -0,0 +1,162 @@+"""Find a team's Slack channel by name, and post an automated message into it.++The two pieces every product that posts a routed digest needs, and nothing else. Which channel a+team's message belongs in, what the message says, and what a failed post does to the product's own+records all stay with the product.+"""++from __future__ import annotations++from collections.abc import Mapping+from typing import Literal++import structlog+from slack_sdk.errors import SlackApiError+from slack_sdk.web import SlackResponse++from posthog.dataclasses import frozen+from posthog.models.integration import Integration, SlackIntegration++logger = structlog.get_logger(__name__)++# Slack channel flags that mark a channel as shared beyond this workspace. A caller that maps a team+# name onto a Slack channel by name can land on a shared channel carrying that name, which sends an+# internal message outside the workspace. is_ext_shared and is_pending_ext_shared cover live and+# pending external connections. is_shared also catches org-shared channels.+SHARED_CHANNEL_FLAGS = ("is_ext_shared", "is_pending_ext_shared", "is_shared")+++@frozen+class SlackChannel:+ channel_id: str+ shared: bool+++def is_shared_channel(channel: dict) -> bool:+ return any(channel.get(flag) for flag in SHARED_CHANNEL_FLAGS)+++def fetch_channel_map(integration: Integration) -> dict[str, SlackChannel]:+ """Public channel name -> channel, for one Slack integration.++ Private channels are skipped: listing them needs a real authed Slack user, and this runs from a+ background task with no request user to act as. Public-only is fine for name matching. The+ shared flag rides along rather than filtering here, because a channel a person named by hand is+ allowed to be shared and a name match is not.+ """+ return {+ channel["name"]: SlackChannel(channel_id=channel["id"], shared=is_shared_channel(channel))+ for channel in SlackIntegration(integration).list_public_channels()+ }+++@frozen+class ChannelMatch:+ """One channel lookup, and the reason it found nothing.++ The reason is separate from the channel because the two misses are different problems for+ whoever declared the name: a channel that does not exist is a typo or a rename, and a channel+ the guard refused is a name that would carry the message out of the workspace.+ """++ channel: SlackChannel | None+ reason: Literal["found", "not_found", "shared"]+++def find_channel(+ channels_by_name: Mapping[str, SlackChannel], channel_name: str, *, allow_shared: bool+) -> ChannelMatch:+ """Look one channel up by name. The leading ``#`` is optional, because declarations carry it.++ ``allow_shared`` is for a channel a person picked for their own use. A derived or name-matched+ channel keeps the guard on, because that is the path where a message leaves the workspace+ without anybody choosing it.+ """+ channel = channels_by_name.get(channel_name.removeprefix("#"))+ if channel is None:+ return ChannelMatch(channel=None, reason="not_found")+ if channel.shared and not allow_shared:+ return ChannelMatch(channel=None, reason="shared")+ return ChannelMatch(channel=channel, reason="found")+++def post_message(+ slack: SlackIntegration,+ channel_id: str,+ blocks: list[dict],+ text: str,+ thread_ts: str | None = None,+) -> SlackResponse:+ # No unfurls: the text is written over untrusted content, so a prompt-injected URL must not make+ # Slack's unfurler fetch an attacker's server from inside the workspace.+ return slack.client.chat_postMessage(+ channel=channel_id,+ blocks=blocks,+ text=text,+ thread_ts=thread_ts,+ unfurl_links=False,+ unfurl_media=False,+ )+++def join_channel(slack: SlackIntegration, channel_id: str) -> str | None:+ """Join the channel so the retried post lands. Returns Slack's error code when it refused.++ A channel resolved by name match is one the app was never invited to, which is the normal state+ for a channel nobody set up by hand, so joining is what saves every team a manual ``/invite``.+ Tried rather than gated on the scope: ``conversations.join`` needs ``channels:join``, and+ whether an install granted it is not something the person who set the posting up can see or+ change. Slack answers ``missing_scope`` in under a second, and the caller turns that into an+ error naming the invite.++ ``already_in_channel`` counts as joined: two audiences can resolve to the same channel, so+ another worker may join between this one's failed post and its join, and treating that as a+ refusal would fail a message whose retry would have gone through.+ """+ try:+ slack.client.conversations_join(channel=channel_id)+ except SlackApiError as e:+ error = str(e.response.get("error") or "unknown_error")+ if error == "already_in_channel":+ return None+ logger.warning("team_notifications_slack_join_failed", slack_channel_id=channel_id, error=error)+ return error+ return None+++class SlackPostRefused(Exception):+ """The app is not in the channel and could not join it, so nothing was posted."""+++def post_with_join(+ slack: SlackIntegration,+ channel_id: str,+ blocks: list[dict],+ text: str,+ *,+ channel_name: str | None = None,+) -> str | None:+ """Post to the channel, joining it first when Slack says the app is not a member.++ Returns the message ts. Every Slack error other than ``not_in_channel`` propagates, because that+ is the only one this can act on.+ """+ try:+ response = post_message(slack, channel_id, blocks, text)+ except SlackApiError as e:+ if e.response.get("error") != "not_in_channel":+ raise+ # Retry once behind the join. A refusal names both Slack's reason and the fix: a person+ # reads this message, and neither "invite the app" nor why the join failed is derivable from+ # a raw Slack error code.+ join_error = join_channel(slack, channel_id)+ if join_error is not None:+ channel = channel_name or channel_id+ raise SlackPostRefused(+ f"Couldn't post to #{channel}. PostHog isn't in the channel and couldn't join it: Slack said "+ f"{join_error}. Invite the app with /invite @PostHog."+ ) from e+ response = post_message(slack, channel_id, blocks, text)++ ts = response.get("ts")+ return str(ts) if ts else Nonediff --git a/posthog/team_notifications/test/__init__.py b/posthog/team_notifications/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/team_notifications/test/test_slack.py b/posthog/team_notifications/test/test_slack.pynew file mode 100644index 000000000000..43ab980bda8c--- /dev/null+++ b/posthog/team_notifications/test/test_slack.py@@ -0,0 +1,27 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.team_notifications.slack import SlackChannel, find_channel++_TEAM_CHANNEL = SlackChannel(channel_id="C1", shared=False)+_SHARED_CHANNEL = SlackChannel(channel_id="C2", shared=True)+_CHANNELS = {"team-devex": _TEAM_CHANNEL, "partners": _SHARED_CHANNEL}+++class TestFindChannel(SimpleTestCase):+ @parameterized.expand(+ [+ ("plain_name", "team-devex", False, _TEAM_CHANNEL, "found"),+ ("leading_hash_is_optional", "#team-devex", False, _TEAM_CHANNEL, "found"),+ ("unknown_name", "team-nobody", False, None, "not_found"),+ ("shared_is_refused_by_default", "partners", False, None, "shared"),+ ("shared_is_allowed_when_chosen", "partners", True, _SHARED_CHANNEL, "found"),+ ]+ )+ def test_lookup(+ self, _name: str, channel_name: str, allow_shared: bool, channel: SlackChannel | None, reason: str+ ) -> None:+ match = find_channel(_CHANNELS, channel_name, allow_shared=allow_shared)++ self.assertEqual((match.channel, match.reason), (channel, reason))diff --git a/products/stamphog/backend/logic/channel_resolution.py b/products/stamphog/backend/logic/channel_resolution.pyindex 42b69e6a655b..7456a944cd7e 100644--- a/products/stamphog/backend/logic/channel_resolution.py+++ b/products/stamphog/backend/logic/channel_resolution.py@@ -36,7 +36,8 @@ from posthog_owners.resolver import Purpose, TeamChannel, team_channel, teams_refrom posthog_owners.schema import Producer, TeamEntryfrom posthog.dataclasses import frozen-from posthog.models.integration import Integration, SlackIntegration+from posthog.models.integration import Integration+from posthog.team_notifications.slack import SlackChannel, fetch_channel_map, find_channelfrom ..facade.enums import ChannelResolutionSourcefrom ..models import StamphogRepoConfig@@ -55,14 +56,6 @@ _CHANNEL_PURPOSE: Purpose = "notifications"# Named so a team can keep the daily digest out of its channel while other bots keep posting there._PRODUCER: Producer = "stamphog"-# Slack channel flags that mark a channel as shared beyond this workspace. Routing maps a GitHub-# team slug onto a Slack channel by name, or by a registry entry. A shared channel with that name-# therefore sends internal PR digests outside the workspace, which is a leak. is_ext_shared and-# is_pending_ext_shared cover live and pending external connections. is_shared also catches-# org-shared channels. A repo's own declared digest channel is exempt, because the maintainer chose-# that channel for their own repository.-_SHARED_CHANNEL_FLAGS = ("is_ext_shared", "is_pending_ext_shared", "is_shared")-class RoutingUnavailable(Exception):"""A registry could not be read, so no routing decision this run is safe.@@ -74,12 +67,6 @@ class RoutingUnavailable(Exception):"""-@frozen-class SlackChannel:- channel_id: str- shared: bool--@frozenclass Destination:"""Where one audience's merges from one repository go, and the workspace they go to.@@ -116,10 +103,6 @@ class RoutingContext:channels_by_name: dict[str, SlackChannel]-def _is_shared_channel(channel: dict) -> bool:- return any(channel.get(flag) for flag in _SHARED_CHANNEL_FLAGS)--def _candidate_repo_configs(team_id: int) -> list[StamphogRepoConfig]:"""Every repo the team still uses, in a fixed order.@@ -148,20 +131,6 @@ def _candidate_repo_configs(team_id: int) -> list[StamphogRepoConfig]:)-def _fetch_channel_map(integration: Integration) -> dict[str, SlackChannel]:- """Public channel name -> channel, for one Slack integration.-- Private channels are skipped: listing them needs a real authed Slack user, and this runs from a- background task with no request user to act as. Public-only is fine for name matching. The- shared flag rides along rather than filtering here, because the repo-declared path is allowed- to name a shared channel and the other paths are not.- """- return {- channel["name"]: SlackChannel(channel_id=channel["id"], shared=_is_shared_channel(channel))- for channel in SlackIntegration(integration).list_public_channels()- }--@frozenclass _RepoRouting:"""What one repository declares about routing: its team registry, and its own digest channel."""@@ -211,7 +180,7 @@ def build_routing_context(team_id: int) -> RoutingContext | None:declared_repo_channel[repo_config.repository] = routing.declared_channeltry:- channels_by_name = _fetch_channel_map(integration)+ channels_by_name = fetch_channel_map(integration)except Exception as e:raise RoutingUnavailable(f"could not list Slack channels for team {team_id}: {e}") from e@@ -272,19 +241,18 @@ def _match(context: RoutingContext, channel_name: str, source: ChannelResolutionSource, *, allow_shared: bool) -> Destination | None:name = channel_name.removeprefix("#")- channel = context.channels_by_name.get(name)- if channel is None:+ match = find_channel(context.channels_by_name, name, allow_shared=allow_shared)+ if match.channel is None:+ if match.reason == "shared":+ logger.info("stamphog_routing_shared_channel_skipped", channel_name=name, source=source)# A declared channel that is not there is a dead end, never a reason to retry the slug: the# slug is exactly the wrong name the declaration was written to correct.- if source != ChannelResolutionSource.SLACK_NAME_MATCH:+ elif source != ChannelResolutionSource.SLACK_NAME_MATCH:logger.info("stamphog_routing_declared_channel_not_found", channel_name=name, source=source)return None- if channel.shared and not allow_shared:- logger.info("stamphog_routing_shared_channel_skipped", channel_name=name, source=source)- return Nonereturn Destination(slack_integration_id=context.slack_integration_id,- channel_id=channel.channel_id,+ channel_id=match.channel.channel_id,channel_name=name,source=source,)diff --git a/products/stamphog/backend/logic/slack_digest.py b/products/stamphog/backend/logic/slack_digest.pyindex 62e931c7978b..1c3376d3f0b5 100644--- a/products/stamphog/backend/logic/slack_digest.py+++ b/products/stamphog/backend/logic/slack_digest.py@@ -14,10 +14,9 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGimport structlog-from slack_sdk.errors import SlackApiError-from slack_sdk.web import SlackResponsefrom posthog.models.integration import Integration, SlackIntegration+from posthog.team_notifications.slack import SlackPostRefused, post_message, post_with_joinfrom .digest import as_channel_paragraph@@ -177,25 +176,6 @@ def _build_fallback_text(summary: DigestSummary) -> str:return "\n".join(lines) or "No merged PRs worth a mention."-def _post_message(- slack: SlackIntegration,- destination: Destination,- blocks: list[dict],- text: str,- thread_ts: str | None = None,-) -> SlackResponse:- # No unfurls: the summary text is LLM output over untrusted PR content, so a prompt-injected- # URL must not make Slack's unfurler fetch an attacker's server from inside the workspace.- return slack.client.chat_postMessage(- channel=destination.channel_id,- blocks=blocks,- text=text,- thread_ts=thread_ts,- unfurl_links=False,- unfurl_media=False,- )--def post_digest_details(team_id: int, destination: Destination, summary: DigestSummary, thread_ts: str | None) -> None:"""Post the per-change lines under the lead. Never raises.@@ -213,9 +193,9 @@ def post_digest_details(team_id: int, destination: Destination, summary: DigestSif integration is None:returntry:- _post_message(+ post_message(SlackIntegration(integration),- destination,+ destination.channel_id,_detail_blocks(summary),_build_fallback_text(summary),thread_ts,@@ -226,32 +206,6 @@ def post_digest_details(team_id: int, destination: Destination, summary: DigestSlogger.warning("stamphog_digest_thread_post_failed", slack_channel_id=destination.channel_id, error=str(e))-def _join_channel(slack: SlackIntegration, destination: Destination) -> str | None:- """Join the channel so the retried post lands. Returns Slack's error code when it refused.-- A channel resolved by name match is one the app was never invited to, which is the normal state- for a destination nobody set up by hand, so joining is what saves every team a manual- ``/invite``. Tried- rather than gated on the scope: ``conversations.join`` needs ``channels:join``, and whether an- install granted it is not something the person who set up the digest can see or change. Slack- answers ``missing_scope`` in under a second, and the caller turns that into an error naming the- invite.-- ``already_in_channel`` counts as joined: two audiences can resolve to the same channel, so- another worker may join between this one's failed post and its join, and treating that as a- refusal would fail a digest whose retry would have gone through.- """- try:- slack.client.conversations_join(channel=destination.channel_id)- except SlackApiError as e:- error = str(e.response.get("error") or "unknown_error")- if error == "already_in_channel":- return None- logger.warning("stamphog_digest_join_failed", slack_channel_id=destination.channel_id, error=error)- return error- return None--def post_digest_lead(team_id: int, destination: Destination, summary: DigestSummary) -> str | None:"""Post the channel-level message. Returns its ts, or None.@@ -264,25 +218,14 @@ def post_digest_lead(team_id: int, destination: Destination, summary: DigestSummif integration is None:raise DigestSlackError(f"No slack integration {destination.slack_integration_id} for team {team_id}")- slack = SlackIntegration(integration)- lead_blocks = _lead_blocks(summary)- lead_text = _lead_text(summary)try:- response = _post_message(slack, destination, lead_blocks, lead_text)- except SlackApiError as e:- if e.response.get("error") != "not_in_channel":- raise- # Retry once behind the join. A refusal names both Slack's reason and the fix: the run is what- # a human reads, and neither "invite the app" nor why the join failed is derivable from a- # raw Slack error code.- join_error = _join_channel(slack, destination)- if join_error is not None:- channel = destination.channel_name or destination.channel_id- raise DigestSlackError(- f"Couldn't post to #{channel}. PostHog isn't in the channel and couldn't join it: Slack said "- f"{join_error}. Invite the app with /invite @PostHog."- ) from e- response = _post_message(slack, destination, lead_blocks, lead_text)-- ts = response.get("ts")- return str(ts) if ts else None+ return post_with_join(+ SlackIntegration(integration),+ destination.channel_id,+ _lead_blocks(summary),+ _lead_text(summary),+ channel_name=destination.channel_name,+ )+ except SlackPostRefused as e:+ # The run row is what a human reads, and every digest failure it records is a DigestSlackError.+ raise DigestSlackError(str(e)) from ediff --git a/products/stamphog/backend/tests/conftest.py b/products/stamphog/backend/tests/conftest.pyindex 74105e0b060a..03f3efa7933b 100644--- a/products/stamphog/backend/tests/conftest.py+++ b/products/stamphog/backend/tests/conftest.py@@ -229,7 +229,7 @@ def stamphog_chain() -> Iterator[StamphogChain]:))stack.enter_context(patch("products.stamphog.backend.logic.slack_digest.SlackIntegration", fake_slack))- stack.enter_context(patch("products.stamphog.backend.logic.channel_resolution.SlackIntegration", fake_slack))+ stack.enter_context(patch("posthog.team_notifications.slack.SlackIntegration", fake_slack))stack.enter_context(patch("products.stamphog.backend.logic.digest.build_anthropic_client",diff --git a/products/stamphog/backend/tests/test_digest.py b/products/stamphog/backend/tests/test_digest.pyindex ee3634f55200..bcfbb5934031 100644--- a/products/stamphog/backend/tests/test_digest.py+++ b/products/stamphog/backend/tests/test_digest.py@@ -17,6 +17,7 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.models.integration import Integrationfrom posthog.models.scoping import team_scope+from posthog.team_notifications.slack import SlackChannelfrom products.stamphog.backend.facade.enums import AudienceReason, ChannelResolutionSource, DigestRunStatusfrom products.stamphog.backend.logic.audiences import REPO_AUDIENCE_PREFIX@@ -24,7 +25,6 @@ from products.stamphog.backend.logic.channel_resolution import (Destination,RoutingContext,RoutingUnavailable,- SlackChannel,_candidate_repo_configs,)from products.stamphog.backend.logic.digest import (diff --git a/tools/owners/posthog_owners/schema.py b/tools/owners/posthog_owners/schema.pyindex 25452c90df95..5fcf4da6b560 100644--- a/tools/owners/posthog_owners/schema.py+++ b/tools/owners/posthog_owners/schema.py@@ -27,7 +27,7 @@ _TEAMS_ENTRY_KEYS = {"slack", "notifications"}# Automation that posts to a team's notifications channel and can be silenced on its own. A# producer must be named here to be nameable in `notifications:`. Lint reports a typo where lint# runs; where it does not, an unreadable mapping silences rather than posts (see _validate_teams).-Producer = Literal["stamphog"]+Producer = Literal["stamphog", "visual_review"]PRODUCERS = frozenset(get_args(Producer))_KNOWN_PRODUCERS = ", ".join(sorted(PRODUCERS))diff --git a/tools/owners/tests/test_owners.py b/tools/owners/tests/test_owners.pyindex 64e447c7ed5c..462f715a1ac6 100644--- a/tools/owners/tests/test_owners.py+++ b/tools/owners/tests/test_owners.py@@ -287,6 +287,7 @@ def test_teams_registry_is_root_only(tmp_path: Path) -> None:("teams:\n team-a:\n slack:\n stamphog: false\n", "takes a single channel"),("teams:\n team-a:\n notifications:\n nosuchbot: false\n", "unknown producer 'nosuchbot'"),("teams:\n team-a:\n notifications:\n stamphog: 'no-hash'\n", "'stamphog' must be a string"),+ ("teams:\n team-a:\n notifications:\n visual_review: 'no-hash'\n", "'visual_review' must be a string"),("teams:\n team-a:\n notifications: {}\n", "mapping names no producer"),],)