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.

fix(slack_app): migrate user-link sign-in to Slack OpenID Connect (#73900)

Vojta Bartošf0ce9a060b7f
diff --git a/docs/internal/slack-local-setup-guide.md b/docs/internal/slack-local-setup-guide.md
index ec31ce327430..e285d2cbd3a8 100644
--- a/docs/internal/slack-local-setup-guide.md
+++ b/docs/internal/slack-local-setup-guide.md
@@ -118,8 +118,9 @@ oauth_config:
- users:read
- users:read.email
user:
- - identity.basic
- - identity.email
+ - openid
+ - email
+ - profile
settings:
event_subscriptions:
request_url: https://<you>-posthog.ngrok.dev/slack/event-callback
@@ -142,9 +143,9 @@ Django must be up at that moment.
> otherwise) and the coding agent doesn't use it.
> The `app_home` block + `app_home_opened` bot event power the App Home tab; the
-> sign-in-with-Slack flow needs `user` scopes `identity.basic` + `identity.email` and the second
-> redirect URL (`/complete/slack-link/`). Drop those if you don't want either feature locally —
-> they're behind the `slack-app-home` and `slack-app-oauth` flags.
+> Sign in with Slack (OpenID Connect) flow needs `user` scopes `openid` + `email` + `profile` and
+> the second redirect URL (`/complete/slack-link/`). Drop those if you don't want either feature
+> locally — they're behind the `slack-app-home` and `slack-app-oauth` flags.
## Step 3 — backend credentials and `SITE_URL`
diff --git a/products/slack_app/backend/services/slack_user_oauth.py b/products/slack_app/backend/services/slack_user_oauth.py
index 85baf17063e5..333b97c76dd1 100644
--- a/products/slack_app/backend/services/slack_user_oauth.py
+++ b/products/slack_app/backend/services/slack_user_oauth.py
@@ -6,18 +6,19 @@ Single home for the whole user-link feature surface:
(``resolve_slack_user`` etc.) before falling back to email matching.
* Signed-state Pydantic models (``InviteToken``, ``CallbackState``) that
flow through Slack's OAuth redirects.
-* The Sign-in-with-Slack OAuth dance: authorize URL builder, code exchange,
- ``users.identity`` call, kept thin and pure so the view layer can compose
- it with login state / templates / follow-up messages.
+* The Sign-in-with-Slack (OpenID Connect) dance: authorize URL builder,
+ code exchange, ``openid.connect.userInfo`` call, kept thin and pure so
+ the view layer can compose it with login state / templates / follow-up
+ messages.
* Block Kit invite-message poster the resolver uses when email matching
fails and the user has a recovery affordance to offer.
Distinct from the workspace install flow in
``posthog.models.integration.OauthIntegration``: that one mints workspace-
level bot tokens and persists them as an ``Integration`` row. This one runs
-the user-token flow (``user_scope=identity.basic,identity.email``) and
-stores the resulting credential on a ``UserIntegration(kind="slack")`` row
-in symmetry with the GitHub personal integration.
+Slack's OIDC sign-in flow (``scope=openid email profile``) and stores the
+resulting credential on a ``UserIntegration(kind="slack")`` row in symmetry
+with the GitHub personal integration.
"""
from typing import Any
@@ -27,11 +28,10 @@ from uuid import UUID
from django.conf import settings
from django.core import signing
-import requests
import structlog
from pydantic import BaseModel, ValidationError
from slack_sdk import WebClient
-from slack_sdk.errors import SlackApiError
+from slack_sdk.errors import SlackApiError, SlackClientError
from posthog.models.instance_setting import get_instance_settings
from posthog.models.organization import OrganizationMembership
@@ -224,18 +224,17 @@ def build_invite_url(
# ---------------------------------------------------------------------------
-# Sign-in-with-Slack OAuth flow
+# Sign-in-with-Slack (OpenID Connect) flow
# ---------------------------------------------------------------------------
-SLACK_AUTHORIZE_URL = "https://slack.com/oauth/v2/authorize"
-SLACK_TOKEN_URL = "https://slack.com/api/oauth.v2.access"
+SLACK_AUTHORIZE_URL = "https://slack.com/openid/connect/authorize"
-# `identity.basic` returns `{user: {id, name}, team: {id}}` — the bare
-# minimum we need to bind a Slack user to a PostHog user. `identity.email`
-# powers the support diagnostics field stored alongside the link. The user
-# token issued for these scopes is persisted on the UserIntegration row in
-# symmetry with the GitHub personal flow.
-USER_IDENTITY_SCOPES = "identity.basic,identity.email"
+# `openid` identifies the user (`https://slack.com/user_id` + `team_id`
+# claims) — the bare minimum we need to bind a Slack user to a PostHog user.
+# `email` powers the support diagnostics field stored alongside the link;
+# `profile` adds the team name. The legacy `identity.*` user scopes these
+# replace are rejected by Slack Marketplace review.
+OIDC_SCOPES = "openid email profile"
class SlackUserOAuthError(Exception):
@@ -244,7 +243,7 @@ class SlackUserOAuthError(Exception):
class SlackIdentity(BaseModel):
- """Result of ``oauth.v2.access`` + ``users.identity`` for the user flow.
+ """Result of ``openid.connect.token`` + ``openid.connect.userInfo``.
``user_refresh_token`` is only populated when the Slack app has
``token_rotation_enabled``; with rotation off (today) Slack omits the
@@ -273,15 +272,16 @@ def _credentials() -> tuple[str, str]:
def build_authorize_url(*, redirect_uri: str, state: str) -> str:
- """The full Slack URL the user is redirected to. ``user_scope`` is the
- Sign-in-with-Slack lever — bot scopes stay empty so the user doesn't see
- a permissions prompt for things the bot already has.
+ """The full Slack OIDC URL the user is redirected to. Only identity
+ scopes are requested — bot scopes belong to the separate workspace
+ install flow, so the user doesn't see a permissions prompt for things
+ the bot already has.
"""
client_id, _ = _credentials()
params = {
"client_id": client_id,
- "user_scope": USER_IDENTITY_SCOPES,
- "scope": "",
+ "scope": OIDC_SCOPES,
+ "response_type": "code",
"redirect_uri": redirect_uri,
"state": state,
}
@@ -289,70 +289,63 @@ def build_authorize_url(*, redirect_uri: str, state: str) -> str:
def exchange_code(*, code: str, redirect_uri: str) -> SlackIdentity:
- """Trade the auth code for a user token, then call ``users.identity`` to
- learn who that token belongs to. The token is returned on ``SlackIdentity``
- so the caller can persist it alongside the link.
+ """Trade the auth code for a user token at ``openid.connect.token``, then
+ call ``openid.connect.userInfo`` to learn who that token belongs to. The
+ token is returned on ``SlackIdentity`` so the caller can persist it
+ alongside the link.
+
+ ``userInfo`` is used instead of decoding the ``id_token`` JWT — the
+ claims are the same, and asking Slack directly over the server-to-server
+ channel we just authenticated on avoids carrying JWT-verification code.
``redirect_uri`` must match the one used on ``build_authorize_url``
exactly; Slack rejects the exchange otherwise.
"""
client_id, client_secret = _credentials()
try:
- response = requests.post(
- SLACK_TOKEN_URL,
- data={
- "client_id": client_id,
- "client_secret": client_secret,
- "code": code,
- "redirect_uri": redirect_uri,
- },
- timeout=10,
+ token_response = WebClient().openid_connect_token(
+ client_id=client_id,
+ client_secret=client_secret,
+ code=code,
+ redirect_uri=redirect_uri,
)
- except requests.RequestException as exc:
- raise SlackUserOAuthError("Slack OAuth request failed") from exc
-
- try:
- payload = response.json()
- except ValueError as exc:
- raise SlackUserOAuthError("Slack OAuth returned non-JSON response") from exc
-
- if not payload.get("ok"):
- logger.warning("slack_app_user_link_oauth_exchange_failed", error=payload.get("error"))
- raise SlackUserOAuthError(f"Slack OAuth exchange failed: {payload.get('error')}")
+ except SlackApiError as exc:
+ error = exc.response.get("error") if exc.response else None
+ logger.warning("slack_app_user_link_oidc_token_failed", error=error)
+ raise SlackUserOAuthError(f"Slack openid.connect.token failed: {error}") from exc
+ except (SlackClientError, OSError) as exc:
+ raise SlackUserOAuthError("Slack OIDC token request failed") from exc
- authed_user = payload.get("authed_user") or {}
- user_token = authed_user.get("access_token")
+ user_token = token_response.get("access_token")
if not user_token:
- raise SlackUserOAuthError("Slack OAuth response missing authed_user.access_token")
+ raise SlackUserOAuthError("Slack OIDC token response missing access_token")
- # `authed_user.id` and `team.id` from `oauth.v2.access` are authoritative,
- # but we still call `users.identity` to pick up the email + team name in
- # the same request the user already authorized. Slack returns these
- # under the user-token scope, not the bot token, so we have to use the
- # token we just received.
try:
- identity_response = WebClient(token=user_token).users_identity()
+ userinfo = WebClient(token=user_token).openid_connect_userInfo()
except SlackApiError as exc:
error = exc.response.get("error") if exc.response else None
- logger.warning("slack_app_user_link_users_identity_failed", error=error)
- raise SlackUserOAuthError(f"Slack users.identity failed: {error}") from exc
-
- user_info = identity_response.get("user") or {}
- team_info = identity_response.get("team") or {}
- slack_user_id = user_info.get("id") or authed_user.get("id")
- slack_team_id = team_info.get("id") or (payload.get("team") or {}).get("id")
+ logger.warning("slack_app_user_link_oidc_userinfo_failed", error=error)
+ raise SlackUserOAuthError(f"Slack openid.connect.userInfo failed: {error}") from exc
+ except (SlackClientError, OSError) as exc:
+ raise SlackUserOAuthError("Slack OIDC userInfo request failed") from exc
+
+ # Slack namespaces its non-standard OIDC claims under the
+ # `https://slack.com/` prefix; `email` and `name` follow the standard
+ # claim names and are only present when their scopes were granted.
+ slack_user_id = userinfo.get("https://slack.com/user_id")
+ slack_team_id = userinfo.get("https://slack.com/team_id")
if not slack_user_id or not slack_team_id:
- raise SlackUserOAuthError("Slack identity response missing user.id or team.id")
+ raise SlackUserOAuthError("Slack userInfo response missing user or team id")
return SlackIdentity(
slack_user_id=slack_user_id,
slack_team_id=slack_team_id,
- slack_team_name=team_info.get("name") or (payload.get("team") or {}).get("name"),
- slack_email=user_info.get("email"),
+ slack_team_name=userinfo.get("https://slack.com/team_name"),
+ slack_email=userinfo.get("email"),
user_access_token=user_token,
# `refresh_token` is only present when the Slack app has
# `token_rotation_enabled`; falls back to None in today's manifest.
- user_refresh_token=authed_user.get("refresh_token"),
+ user_refresh_token=token_response.get("refresh_token"),
)
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.py
index 99f36c5778e7..4bacfe87c529 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
@@ -12,6 +12,8 @@ from uuid import uuid4
import pytest
from unittest.mock import MagicMock, patch
+from slack_sdk.errors import SlackApiError
+
from posthog.models.integration import SlackIntegration
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.user import User
@@ -21,7 +23,9 @@ from products.slack_app.backend.api import resolve_slack_user
from products.slack_app.backend.services.slack_user_oauth import (
CallbackState,
InviteToken,
+ SlackUserOAuthError,
build_invite_url,
+ exchange_code,
find_linked_posthog_user,
)
from products.slack_app.backend.tests.conftest import SLACK_TEAM_ID, SLACK_USER_ID
@@ -281,6 +285,57 @@ class TestResolveSlackUserWithLink:
mock_post_invite.assert_not_called()
+class TestExchangeCode:
+ OIDC_CLAIMS = {
+ "https://slack.com/user_id": SLACK_USER_ID,
+ "https://slack.com/team_id": SLACK_TEAM_ID,
+ "https://slack.com/team_name": "My Workspace",
+ "email": "[email protected]",
+ }
+
+ @pytest.fixture(autouse=True)
+ def credentials(self):
+ with patch(
+ "products.slack_app.backend.services.slack_user_oauth.get_instance_settings",
+ return_value={"SLACK_APP_CLIENT_ID": "cid", "SLACK_APP_CLIENT_SECRET": "csecret"},
+ ):
+ yield
+
+ @pytest.fixture
+ def slack_client(self):
+ with patch("products.slack_app.backend.services.slack_user_oauth.WebClient") as mock_cls:
+ client = mock_cls.return_value
+ client.openid_connect_token.return_value = {"access_token": "xoxp-user", "refresh_token": None}
+ client.openid_connect_userInfo.return_value = dict(self.OIDC_CLAIMS)
+ yield mock_cls
+
+ def test_maps_oidc_claims_to_identity(self, slack_client):
+ identity = exchange_code(code="abc", redirect_uri="https://ph.example/complete/slack-link/")
+
+ assert identity.slack_user_id == SLACK_USER_ID
+ assert identity.slack_team_id == SLACK_TEAM_ID
+ assert identity.slack_team_name == "My Workspace"
+ assert identity.slack_email == "[email protected]"
+ 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")
+
+ def test_token_exchange_api_error_wraps_into_oauth_error(self, slack_client):
+ slack_client.return_value.openid_connect_token.side_effect = SlackApiError(
+ "bad code", {"ok": False, "error": "invalid_code"}
+ )
+ with pytest.raises(SlackUserOAuthError, match="invalid_code"):
+ exchange_code(code="abc", redirect_uri="https://ph.example/complete/slack-link/")
+
+ @pytest.mark.parametrize("missing_claim", ["https://slack.com/user_id", "https://slack.com/team_id"])
+ def test_missing_identity_claims_raise_oauth_error(self, slack_client, missing_claim):
+ claims = {key: value for key, value in self.OIDC_CLAIMS.items() if key != missing_claim}
+ slack_client.return_value.openid_connect_userInfo.return_value = claims
+ with pytest.raises(SlackUserOAuthError, match="missing user or team id"):
+ exchange_code(code="abc", redirect_uri="https://ph.example/complete/slack-link/")
+
+
@pytest.mark.django_db(transaction=False)
class TestInviteToken:
def test_round_trips(self):
diff --git a/products/slack_app/backend/tests/views/test_slack_user_link.py b/products/slack_app/backend/tests/views/test_slack_user_link.py
index 9bdfaa598c77..d5478fcfe471 100644
--- a/products/slack_app/backend/tests/views/test_slack_user_link.py
+++ b/products/slack_app/backend/tests/views/test_slack_user_link.py
@@ -73,7 +73,7 @@ class TestAuthorizeView:
response = client.get(f"/complete/slack-link/start/?state={token}")
self._assert_settings_redirect_error(response, "flag_off")
- def test_flag_on_redirects_to_slack_with_user_scope(self, logged_in_client, workspace_integration):
+ def test_flag_on_redirects_to_slack_oidc_authorize(self, logged_in_client, workspace_integration):
client, _ = logged_in_client
token = InviteToken(
slack_user_id=SLACK_USER_ID,
@@ -92,10 +92,13 @@ class TestAuthorizeView:
response = client.get(f"/complete/slack-link/start/?state={token}")
assert response.status_code == 302
location = response["Location"]
- assert location.startswith("https://slack.com/oauth/v2/authorize?")
- # The whole point: user_scope is requested, bot scopes stay empty.
- assert "user_scope=identity.basic" in location
- assert "scope=&" in location or location.endswith("scope=")
+ # The whole point: the OIDC authorize endpoint with the openid scope
+ # set — the legacy `/oauth/v2/authorize` + `user_scope=identity.*`
+ # shape is rejected by Slack Marketplace review.
+ assert location.startswith("https://slack.com/openid/connect/authorize?")
+ assert "scope=openid+email+profile" in location
+ assert "response_type=code" in location
+ assert "user_scope" not in location
def test_unauthenticated_user_is_bounced_through_login(self, db):
# `db` fixture: PostHog's `login_required` consults `User.objects.exists()`
diff --git a/products/slack_app/backend/views/slack_user_link.py b/products/slack_app/backend/views/slack_user_link.py
index b5431719e72a..1a3fd48fa2e8 100644
--- a/products/slack_app/backend/views/slack_user_link.py
+++ b/products/slack_app/backend/views/slack_user_link.py
@@ -14,8 +14,9 @@ install routes the SPA owns.
* ``GET /complete/slack-link/``
Slack redirects here after the user authorizes. We exchange the code for a
- user token, call ``users.identity`` to learn the Slack user id + team, and
- upsert a ``UserIntegration(kind="slack")`` row pinning the Slack identity
+ user token, call ``openid.connect.userInfo`` to learn the Slack user id
+ + team, and upsert a ``UserIntegration(kind="slack")`` row pinning the
+ Slack identity
to the currently-logged-in PostHog user. On success we DM the user back in
the original Slack thread (if we have channel + thread context) and bounce
the browser tab back to Personal integrations with a success query param —