Skip to content

: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.

chore(slack-app): distinguish failure paths in Slack email lookup (#64509)

Vojta Bartošf649625c3075
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 7c39eec8f682..5098d4f5f881 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -18,6 +18,7 @@ from django.views.decorators.csrf import csrf_exempt
import requests
import structlog
import posthoganalytics
+from slack_sdk.errors import SlackApiError
from slack_sdk.http_retry.builtin_handlers import RateLimitErrorRetryHandler
from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy
@@ -1257,26 +1258,69 @@ def _notify_missing_slack_scopes(
_post_slack_user_feedback(slack, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)
+# Slack ``users.info`` error codes that mean the stored bot token can no longer talk to
+# Slack on this workspace's behalf. Surfaced as ``token_broken=True`` on the failure log
+# so support can distinguish "needs reconnect" from other API failures at a glance.
+_SLACK_AUTH_FAILURE_CODES = frozenset(
+ {"token_revoked", "invalid_auth", "not_authed", "account_inactive", "token_expired"}
+)
+
+
def get_slack_email_for_user(probe_integration: Integration, slack_user_id: str) -> str | None:
- """Best-effort lookup of the Slack user's email via ``users.info``,
- cache-first then a fresh hit on miss. Returns ``None`` when Slack doesn't
- expose an email for the user (profile email hidden) or the lookup fails.
+ """Best-effort lookup of the Slack user's email via ``users.info``, cache-first then
+ a fresh hit on miss. Returns ``None`` when Slack doesn't expose an email for the
+ user (profile email hidden) or the lookup fails.
+
+ Every termination path emits a distinct structured log so a silent ``None`` can
+ still be diagnosed from logs alone — historically the failure modes collapsed
+ onto a downstream ``user_not_found`` warning that hid the actual cause.
"""
slack_client = SlackIntegration(probe_integration)
try:
user_info = get_slack_user_info(slack_client, probe_integration, slack_user_id)
slack_email = user_info.get("user", {}).get("profile", {}).get("email")
+ if slack_email:
+ return slack_email
+
+ fresh = normalize_slack_response(slack_client.client.users_info(user=slack_user_id))
+ if not fresh:
+ logger.warning(
+ "slack_app_resolve_user_email_empty_response",
+ integration_id=probe_integration.id,
+ slack_user_id=slack_user_id,
+ )
+ return None
+
+ persist_slack_user_info(probe_integration, slack_user_id, fresh)
+ slack_email = fresh.get("user", {}).get("profile", {}).get("email")
if not slack_email:
- fresh = normalize_slack_response(slack_client.client.users_info(user=slack_user_id))
- if fresh:
- persist_slack_user_info(probe_integration, slack_user_id, fresh)
- slack_email = fresh.get("user", {}).get("profile", {}).get("email")
- return slack_email or None
+ logger.warning(
+ "slack_app_resolve_user_email_missing_in_profile",
+ integration_id=probe_integration.id,
+ slack_user_id=slack_user_id,
+ ok=fresh.get("ok"),
+ )
+ return None
+ return slack_email
+ except SlackApiError as exc:
+ error_code = exc.response.get("error") if exc.response else None
+ token_broken = isinstance(error_code, str) and error_code in _SLACK_AUTH_FAILURE_CODES
+ logger.warning(
+ "slack_app_resolve_user_email_failed",
+ integration_id=probe_integration.id,
+ slack_user_id=slack_user_id,
+ error_code=error_code,
+ token_broken=token_broken,
+ exc_info=True,
+ )
+ return None
except Exception:
logger.warning(
"slack_app_resolve_user_email_failed",
integration_id=probe_integration.id,
slack_user_id=slack_user_id,
+ error_code=None,
+ token_broken=False,
exc_info=True,
)
return None
diff --git a/products/slack_app/backend/tests/test_get_slack_email_for_user.py b/products/slack_app/backend/tests/test_get_slack_email_for_user.py
new file mode 100644
index 000000000000..d4fc240884fa
--- /dev/null
+++ b/products/slack_app/backend/tests/test_get_slack_email_for_user.py
@@ -0,0 +1,139 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from slack_sdk.errors import SlackApiError
+
+from posthog.models.integration import Integration
+from posthog.models.organization import Organization
+from posthog.models.team.team import Team
+
+from products.slack_app.backend.api import get_slack_email_for_user
+from products.slack_app.backend.models import SlackUserProfileCache
+
+
+def integration(db):
+ organization = Organization.objects.create(name="Test Org")
+ team = Team.objects.create(organization=organization, name="Test Team")
+ return Integration.objects.create(
+ team=team,
+ kind="slack",
+ integration_id="T12345",
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+
+
+def _make_slack_response(payload):
+ response = MagicMock()
+ response.data = payload
+ return response
+
+
+def _slack_api_error(error_code):
+ return SlackApiError(message=f"slack returned {error_code}", response={"ok": False, "error": error_code})
+
+
+class TestGetSlackEmailForUser:
+ @patch("posthog.models.integration.WebClient")
+ def test_returns_email_when_present_in_fresh_response(self, mock_webclient_class, integration):
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.users_info.return_value = _make_slack_response(
+ {"ok": True, "user": {"id": "U1", "profile": {"email": "[email protected]"}}}
+ )
+
+ email = get_slack_email_for_user(integration, "U1")
+
+ assert email == "[email protected]"
+ assert SlackUserProfileCache.objects.filter(integration=integration, slack_user_id="U1").exists()
+
+ @patch("posthog.models.integration.WebClient")
+ def test_logs_empty_response_when_users_info_returns_blank(self, mock_webclient_class, integration, caplog):
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ # Both the cache-miss call inside ``get_slack_user_info`` and the explicit fresh
+ # retry return an unusable response. ``normalize_slack_response`` collapses both
+ # to ``{}``, so we should emit the dedicated empty-response log and bail.
+ mock_client.users_info.return_value = _make_slack_response(None)
+
+ with caplog.at_level("WARNING"):
+ email = get_slack_email_for_user(integration, "U1")
+
+ assert email is None
+ assert any("slack_app_resolve_user_email_empty_response" in record.message for record in caplog.records)
+
+ @patch("posthog.models.integration.WebClient")
+ def test_logs_missing_email_when_profile_has_no_email(self, mock_webclient_class, integration, caplog):
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ # Bot token works but lacks ``users:read.email``, or the user's email is hidden:
+ # Slack returns ``ok=true`` with a profile that has no ``email`` field.
+ mock_client.users_info.return_value = _make_slack_response(
+ {"ok": True, "user": {"id": "U1", "profile": {"display_name": "Dev"}}}
+ )
+
+ with caplog.at_level("WARNING"):
+ email = get_slack_email_for_user(integration, "U1")
+
+ assert email is None
+ assert any("slack_app_resolve_user_email_missing_in_profile" in record.message for record in caplog.records)
+
+ @pytest.mark.parametrize(
+ "error_code",
+ [
+ "token_revoked",
+ "invalid_auth",
+ "not_authed",
+ "account_inactive",
+ "token_expired",
+ ],
+ )
+ @patch("posthog.models.integration.WebClient")
+ def test_auth_error_logs_token_broken_flag(self, mock_webclient_class, integration, error_code, caplog):
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.users_info.side_effect = _slack_api_error(error_code)
+
+ with caplog.at_level("WARNING"):
+ email = get_slack_email_for_user(integration, "U1")
+
+ assert email is None
+ # No DB write — the integration row is untouched. Reconnect signal lives on the log line.
+ integration.refresh_from_db()
+ assert integration.errors == ""
+ failed = [r for r in caplog.records if "slack_app_resolve_user_email_failed" in r.message]
+ assert failed, "expected slack_app_resolve_user_email_failed to be logged"
+ assert any(f"'error_code': '{error_code}'" in r.message for r in failed)
+ assert any("'token_broken': True" in r.message for r in failed)
+
+ @patch("posthog.models.integration.WebClient")
+ def test_non_auth_slack_error_does_not_flag_token_broken(self, mock_webclient_class, integration, caplog):
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.users_info.side_effect = _slack_api_error("user_not_found")
+
+ with caplog.at_level("WARNING"):
+ email = get_slack_email_for_user(integration, "U1")
+
+ assert email is None
+ failed = [r for r in caplog.records if "slack_app_resolve_user_email_failed" in r.message]
+ assert failed
+ assert all("'token_broken': False" in r.message for r in failed)
+ assert any("'error_code': 'user_not_found'" in r.message for r in failed)
+
+ @patch("posthog.models.integration.WebClient")
+ def test_generic_exception_logs_without_error_code(self, mock_webclient_class, integration, caplog):
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.users_info.side_effect = RuntimeError("boom")
+
+ with caplog.at_level("WARNING"):
+ email = get_slack_email_for_user(integration, "U1")
+
+ assert email is None
+ failed = [r for r in caplog.records if "slack_app_resolve_user_email_failed" in r.message]
+ assert failed
+ # Non-Slack exceptions carry ``error_code=None`` and ``token_broken=False`` so a
+ # log filter for "needs reconnect" cleanly excludes them.
+ assert all("'error_code': None" in r.message for r in failed)
+ assert all("'token_broken': False" in r.message for r in failed)