: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
fix(workflows): require a channel filter to activate a slack-message trigger (#87865)
Harley Alexanderc02dde18e4b5
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex eb61bf5f348e..1926ee1f2d1f 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -768,6 +768,38 @@ def _normalize_slack_channel_filters(filters: dict) -> None:prop["value"] = [item.split("|")[0] if isinstance(item, str) else item for item in value]+# Exact is the only operator that names channels. Channel ids are opaque (C0...), so+# substring and regex matching can't narrow meaningfully and patterns like ".*" or "C"+# match every channel; presence operators match every message and carry the operator+# string as their value, so a value check alone can't catch them; negations exclude+# channels rather than pick any. The property compiler treats a missing operator as exact.+_CHANNEL_RESTRICTING_OPERATORS = frozenset({"exact"})+++def _has_slack_channel_filter(filters: dict) -> bool:+ """Whether the filters restrict the trigger to at least one Slack channel.++ The builder always writes this filter ("Please pick a Slack channel"), but the table's+ enable action, the raw API, and MCP authoring all reach activation without the builder,+ and a live slack-message trigger with no channel filter fires on every message in every+ channel the bot was ever invited to.+ """+ properties = filters.get("properties")+ if not isinstance(properties, list):+ return False+ for prop in properties:+ if not isinstance(prop, dict) or prop.get("key") != "channel":+ continue+ if (prop.get("operator") or "exact") not in _CHANNEL_RESTRICTING_OPERATORS:+ continue+ value = prop.get("value")+ if isinstance(value, str) and value.strip():+ return True+ if isinstance(value, list) and any(isinstance(item, str) and item.strip() for item in value):+ return True+ return False++def _existing_email_from_by_action(instance: "HogFlow") -> dict[str, list[dict]]:"""Stored email sender overrides keyed by action id, live and draft variants both kept.@@ -1305,6 +1337,12 @@ class HogFlowActionSerializer(serializers.Serializer):filters.pop("events", None)filters.pop("actions", None)_normalize_slack_channel_filters(filters)+ if not is_draft and not _has_slack_channel_filter(filters):+ raise serializers.ValidationError(+ {+ "filters": "Pick a Slack channel for this trigger. Without one it runs on every message in every channel the Slack bot is in."+ }+ )# Left on the default "events" source: the internal event is event-shaped, so# property filters compile against event.properties.* with no special casing.serializer = HogFunctionFiltersSerializer(data=filters, context=self.context)diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex 4b944db128ff..bdfe698a10bc 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -2369,6 +2369,70 @@ class TestHogFlowAPI(APIBaseTest):stored = response.json()["trigger"]["filters"]["properties"][0]["value"]assert stored == ["C0ALERTS"]+ @staticmethod+ def _slack_trigger_action(properties: list[dict]) -> dict:+ return {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {"type": "slack-message", "filters": {"properties": properties}},+ }++ @parameterized.expand(+ [+ ("no_properties", []),+ ("no_channel_entry", [{"key": "bot_id", "value": "is_not_set", "operator": "is_not_set", "type": "event"}]),+ ("blank_channel_value", [{"key": "channel", "value": [""], "operator": "exact", "type": "event"}]),+ # Presence operators store the operator string as the value, so the value looks+ # non-empty while the compiled filter matches every channel.+ ("is_set_channel", [{"key": "channel", "value": "is_set", "operator": "is_set", "type": "event"}]),+ ("negated_channel", [{"key": "channel", "value": ["C0ALERTS"], "operator": "is_not", "type": "event"}]),+ # Channel ids are opaque, so a pattern can only widen; ".*" matches every channel.+ ("regex_channel", [{"key": "channel", "value": [".*"], "operator": "regex", "type": "event"}]),+ ]+ )+ def test_hog_flow_slack_trigger_requires_a_channel_filter_to_activate(self, _name, properties):+ # Only the builder UI asks for a channel; without this server-side check, a flow+ # activated via the raw API or MCP fires on every message in every channel the+ # Slack bot is in.+ hog_flow = {+ "name": "Test Slack Flow",+ "status": "active",+ "actions": [self._slack_trigger_action(properties)],+ }++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert response.status_code == 400, response.json()+ assert "channel" in response.json()["detail"].lower()++ def test_hog_flow_slack_trigger_channel_gap_is_caught_at_enable(self):+ # The workflows table's Enable button patches status alone, skipping the builder's+ # channel validation, so activation-time re-validation is what has to catch it.+ draft = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows",+ {"name": "Test Slack Flow", "status": "draft", "actions": [self._slack_trigger_action([])]},+ )+ assert draft.status_code == 201, draft.json()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{draft.json()['id']}", {"status": "active"}+ )++ assert response.status_code == 400, response.json()+ assert "channel" in response.json()["detail"].lower()++ def test_hog_flow_slack_trigger_draft_saves_without_a_channel(self):+ # The builder saves mid-edit drafts before a channel is picked; only activation+ # fails closed.+ hog_flow = {+ "name": "Test Slack Flow",+ "status": "draft",+ "actions": [self._slack_trigger_action([])],+ }++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert response.status_code == 201, response.json()+def test_hog_flow_data_warehouse_table_trigger_forces_exit_only_at_end(self):# Other exit conditions re-evaluate trigger/conversion filters that may reference person# data, so warehouse-triggered flows are coerced to exit_only_at_end regardless of input.