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.

feat(slack): link Slack users to PostHog accounts via OAuth (#65239)

Vojta Bartoš10bcbc5a2f40
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 396cb8548327..13f8e23cef3b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1577,9 +1577,9 @@ snapshots:
components-search--product-recents-and-starred--light:
hash: v1.k794b7964.d1758a403c58affafb18200426a1ff62fc908a3cf7b69198d4b96cf0e5fc4d79.GfvoSqPZoq687NsU1Tpx5Q8Xfl6moWo1_8rdXcNlhFM
components-search--searching--dark:
- hash: v1.k794b7964.2b6565645158a1c2b48cdda980298e6564fbb38cd76cb8230a0ff1cc726a6c73.O6ohcLvjdauxqx9m1PA4MXuHqGkca2NCzdfXpKQtyAU
+ hash: v1.k794b7964.4f7b2f3eda81eb88cc9fa021da92a591a68a6a6964d841535e78768cc19e0a26.7UE1gQqLlC2yE6qkzB6WkVinYuPPk4c3fVtOekkCFrs
components-search--searching--light:
- hash: v1.k794b7964.03b211d4ef749cff4115a5fd03754d0e12a073f95f4181967b5b88f4fdfb88de.-VoIleDr1-4soYmj9g6HASQTd9zm1IUlbjfEEl6J9Mc
+ hash: v1.k794b7964.efad9bbfe6f1e48a3ca25d04269641c70f1d2862fca813c5bf1c71a3b26ba0e9.5ATF6iN-uqQQjQYbid_fWC05MT6vkaiK7UWBe4oUHyc
components-sentencelist--full-sentence--dark:
hash: v1.k794b7964.2bc693d15a56feae37ff7691155712fee3f9c0590cf5fac3f52911ee5a0cbfeb.w4Q-a1Ll26AC29zPLkyqCUoPWfXbCI71OjbaxNRU2Oc
components-sentencelist--full-sentence--light:
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 4ab8ee996d91..b859db4f701b 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -3661,6 +3661,53 @@ export interface UserGitHubLinkStartResponseApi {
connect_flow: string
}
+export interface UserSlackLinkableWorkspaceItemApi {
+ /** PostHog team/project id owning the Slack workspace install. */
+ posthog_team_id: number
+ /** PostHog team/project name, for display in a picker. */
+ posthog_team_name: string
+ /** PostHog organization name owning the team, for picker disambiguation. */
+ posthog_organization_name: string
+ /** Slack workspace (team) id. */
+ slack_team_id: string
+ /**
+ * Slack workspace display name as known by PostHog.
+ * @nullable
+ */
+ slack_team_name?: string | null
+}
+
+export interface UserSlackLinkableWorkspaceListResponseApi {
+ /** Slack workspaces the user could link to but hasn't yet. */
+ results: UserSlackLinkableWorkspaceItemApi[]
+}
+
+/**
+ * Settings-initiated link can target a specific PostHog team + Slack workspace.
+ *
+ * Both are optional — when omitted we fall back to the user's ``current_team``
+ * and that team's first Slack ``Integration`` (mirrors ``github_start`` for
+ * the simple case). The frontend passes both explicitly once it has the
+ * linkable-workspace list and the user has picked a workspace.
+ */
+export interface UserSlackLinkStartRequestApi {
+ /**
+ * Optional team/project id to link against; defaults to the user's current team.
+ * @nullable
+ */
+ team_id?: number | null
+ /**
+ * Specific Slack workspace id to link against, scoped to the team. Disambiguates when one team has multiple Slack integrations (rare).
+ * @nullable
+ */
+ slack_team_id?: string | null
+}
+
+export interface UserSlackLinkStartResponseApi {
+ /** URL to open in the browser to start the Sign-in-with-Slack flow. */
+ install_url: string
+}
+
/**
* A cookie-auth login session shown on the user's 'Web sessions' screen.
*/
@@ -4035,6 +4082,10 @@ export type UsersListParams = {
}
export type UsersIntegrationsListParams = {
+ /**
+ * Integration kind to list. Defaults to `github` for back-compat with mobile and the Code SDK, which call this endpoint without a query param and expect GitHub-shaped items.
+ */
+ kind?: UsersIntegrationsListKind
/**
* Number of results to return per page.
*/
@@ -4045,6 +4096,13 @@ export type UsersIntegrationsListParams = {
offset?: number
}
+export type UsersIntegrationsListKind = (typeof UsersIntegrationsListKind)[keyof typeof UsersIntegrationsListKind]
+
+export const UsersIntegrationsListKind = {
+ Github: 'github',
+ Slack: 'slack',
+} as const
+
export type UsersIntegrationsGithubBranchesRetrieveParams = {
/**
* Maximum number of branches to return
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 1b014bf883c6..49dccb9c7b99 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -81,6 +81,9 @@ import type {
UserPushTokenItemApi,
UserPushTokenRegisterRequestApi,
UserPushTokenUnregisterRequestApi,
+ UserSlackLinkStartRequestApi,
+ UserSlackLinkStartResponseApi,
+ UserSlackLinkableWorkspaceListResponseApi,
UsersIntegrationsGithubBranchesRetrieveParams,
UsersIntegrationsGithubReposRetrieveParams,
UsersIntegrationsListParams,
@@ -3182,8 +3185,21 @@ export const getUsersIntegrationsListUrl = (uuid: string, params?: UsersIntegrat
}
/**
- * `/api/users/@me/integrations/` — manage the user's personal GitHub integrations.
- * @summary List personal GitHub integrations
+ * Return the authenticated user's personal integrations of a given
+ * ``kind`` (``github`` or ``slack``).
+ *
+ * The response shape varies per kind because the underlying ``UserIntegration``
+ * rows carry different identity fields — GitHub rows expose
+ * ``installation_id`` / ``account`` / ``uses_shared_installation``; Slack
+ * rows expose ``slack_user_id`` / ``slack_team_id`` / ``slack_team_name``.
+ * Kind-specific destroy and start actions remain split so their distinct
+ * semantics (e.g. Slack's lack of "uninstall on last reference") stay
+ * explicit at the URL layer.
+ *
+ * Default of ``kind=github`` is load-bearing: mobile (``apps/mobile/...``)
+ * and the Code SDK (``packages/api-client/...``) both call this endpoint
+ * without a query param today and rely on receiving GitHub rows.
+ * @summary List the user's personal integrations of a given kind
*/
export const usersIntegrationsList = async (
uuid: string,
@@ -3354,6 +3370,84 @@ export const usersIntegrationsGithubStartCreate = async (
})
}
+export const getUsersIntegrationsSlackDestroyUrl = (uuid: string, slackUserId: string) => {
+ return `/api/users/${uuid}/integrations/slack/${slackUserId}/`
+}
+
+/**
+ * Remove a Slack identity link by Slack user id. Idempotent and
+ * flag-agnostic — users must always be able to unlink even after the
+ * feature flag is turned off.
+ * @summary Unlink a Slack identity
+ */
+export const usersIntegrationsSlackDestroy = async (
+ uuid: string,
+ slackUserId: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getUsersIntegrationsSlackDestroyUrl(uuid, slackUserId), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getUsersIntegrationsSlackLinkableWorkspacesRetrieveUrl = (uuid: string) => {
+ return `/api/users/${uuid}/integrations/slack/linkable_workspaces/`
+}
+
+/**
+ * Return Slack workspaces in the user's organizations that they have
+ * not yet linked. The settings UI uses this list to decide whether to
+ * show a "Link my Slack account" button (non-empty list) and what to
+ * offer in the picker when several are connectable.
+ * @summary List Slack workspaces this user could link to
+ */
+export const usersIntegrationsSlackLinkableWorkspacesRetrieve = async (
+ uuid: string,
+ options?: RequestInit
+): Promise<UserSlackLinkableWorkspaceListResponseApi> => {
+ return apiMutator<UserSlackLinkableWorkspaceListResponseApi>(
+ getUsersIntegrationsSlackLinkableWorkspacesRetrieveUrl(uuid),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getUsersIntegrationsSlackStartCreateUrl = (uuid: string) => {
+ return `/api/users/${uuid}/integrations/slack/start/`
+}
+
+/**
+ * Mint a Sign-in-with-Slack invite URL initiated from settings, without
+ * Slack-DM context. The returned URL takes the user through PostHog login
+ * (already satisfied here), then to Slack OAuth, then back to our callback
+ * which writes the ``UserIntegration`` row.
+ *
+ * Without body params, falls back to the user's ``current_team`` and that
+ * team's first Slack ``Integration`` — works when there's exactly one
+ * linkable workspace. With ``team_id`` + ``slack_team_id``, links against
+ * the exact pair (what the frontend uses when a picker is shown).
+ *
+ * Refuses if the target team has no matching Slack workspace, if the
+ * feature flag is off for the workspace, or if the user is already linked
+ * to it.
+ * @summary Start Slack identity link from settings
+ */
+export const usersIntegrationsSlackStartCreate = async (
+ uuid: string,
+ userSlackLinkStartRequestApi?: UserSlackLinkStartRequestApi,
+ options?: RequestInit
+): Promise<UserSlackLinkStartResponseApi> => {
+ return apiMutator<UserSlackLinkStartResponseApi>(getUsersIntegrationsSlackStartCreateUrl(uuid), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(userSlackLinkStartRequestApi),
+ })
+}
+
export const getUsersLoginSessionsListUrl = (uuid: string, params?: UsersLoginSessionsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index bf6c81d47533..ddc8e34e5c89 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -10043,6 +10043,39 @@ export const UsersIntegrationsGithubStartCreateBody = /* @__PURE__ */ zod.object
.describe('Optional client hint (e.g. posthog_code) for return routing after OAuth.'),
})
+/**
+ * Mint a Sign-in-with-Slack invite URL initiated from settings, without
+ * Slack-DM context. The returned URL takes the user through PostHog login
+ * (already satisfied here), then to Slack OAuth, then back to our callback
+ * which writes the ``UserIntegration`` row.
+ *
+ * Without body params, falls back to the user's ``current_team`` and that
+ * team's first Slack ``Integration`` — works when there's exactly one
+ * linkable workspace. With ``team_id`` + ``slack_team_id``, links against
+ * the exact pair (what the frontend uses when a picker is shown).
+ *
+ * Refuses if the target team has no matching Slack workspace, if the
+ * feature flag is off for the workspace, or if the user is already linked
+ * to it.
+ * @summary Start Slack identity link from settings
+ */
+export const UsersIntegrationsSlackStartCreateBody = /* @__PURE__ */ zod
+ .object({
+ team_id: zod
+ .number()
+ .nullish()
+ .describe("Optional team\/project id to link against; defaults to the user's current team."),
+ slack_team_id: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Specific Slack workspace id to link against, scoped to the team. Disambiguates when one team has multiple Slack integrations (rare).'
+ ),
+ })
+ .describe(
+ "Settings-initiated link can target a specific PostHog team + Slack workspace.\n\nBoth are optional — when omitted we fall back to the user's ``current_team``\nand that team's first Slack ``Integration`` (mirrors ``github_start`` for\nthe simple case). The frontend passes both explicitly once it has the\nlinkable-workspace list and the user has picked a workspace."
+ )
+
/**
* Mark the current user as having exited onboarding with a non-delegated reason.
* Idempotent: the skip timestamp is only set on the first successful call.
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 7792d9ee4faa..02cd851c346f 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -222,6 +222,7 @@ export const FEATURE_FLAGS = {
SETTINGS_SESSION_TABLE_VERSION: 'settings-session-table-version', // owner: #team-analytics-platform
SETTINGS_SESSIONS_V2_JOIN: 'settings-sessions-v2-join', // owner: @robbie-c #team-web-analytics
SETTINGS_WEB_ANALYTICS_PRE_AGGREGATED_TABLES: 'web-analytics-pre-aggregated-tables', // owner: @lricoy #team-web-analytics
+ SLACK_APP_OAUTH: 'slack-app-oauth', // owner: @VojtechBartos #team-platform-features
SLOPE_GRAPH_INSIGHT: 'slope-graph-insight', // owner: @pauldambra #team-product-analytics
STARTUP_PROGRAM_INTENT: 'startup-program-intent', // owner: @pawel-cebula #team-billing
SURVEYS_ACTIONS: 'surveys-actions', // owner: #team-surveys
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 62affb2c1271..b2a4cf4cda27 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -159,7 +159,7 @@ import { MCPHintsSetting } from './user/MCPHintsSetting'
import { OptOutCapture } from './user/OptOutCapture'
import { PasskeySettings } from './user/PasskeySettings'
import { PersonalAPIKeys } from './user/PersonalAPIKeys'
-import { PersonalIntegrations } from './user/PersonalIntegrations'
+import { PersonalGitHubIntegrations, PersonalSlackIntegrations } from './user/PersonalIntegrations'
import { RealtimeNotificationPreferences } from './user/RealtimeNotificationPreferences'
import { Reminders } from './user/Reminders'
import { SidebarAutoSuggestSetting } from './user/SidebarProductSettings'
@@ -1971,13 +1971,22 @@ export const SETTINGS_MAP: SettingSection[] = [
title: 'Personal integrations',
settings: [
{
- id: 'personal-integrations',
- title: 'Personal integrations',
+ id: 'personal-integrations-github',
+ title: 'GitHub',
description:
'Your personal GitHub integrations for repo access, code attribution, and pull request authorship. You can connect multiple GitHub accounts or organizations.',
- component: <PersonalIntegrations />,
+ component: <PersonalGitHubIntegrations />,
keywords: ['github', 'integration', 'repos', 'identity', 'link', 'code', 'personal'],
},
+ {
+ id: 'personal-integrations-slack',
+ title: 'Slack',
+ description:
+ 'Bind your Slack identity to this PostHog account so @PostHog mentions route to you even when your Slack email and PostHog email differ.',
+ component: <PersonalSlackIntegrations />,
+ keywords: ['slack', 'integration', 'identity', 'link', 'mention', 'personal'],
+ flag: 'SLACK_APP_OAUTH',
+ },
],
},
{
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 76dca3ba4803..b6f92cc72da3 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -208,7 +208,8 @@ export type SettingId =
| 'person-display-name'
| 'person-last-seen-at'
| 'personal-api-keys'
- | 'personal-integrations'
+ | 'personal-integrations-github'
+ | 'personal-integrations-slack'
| 'persons-join-mode'
| 'reminders'
| 'persons-on-events'
diff --git a/frontend/src/scenes/settings/user/PersonalIntegrations.tsx b/frontend/src/scenes/settings/user/PersonalIntegrations.tsx
index 47a6cb8b8e31..973342940703 100644
--- a/frontend/src/scenes/settings/user/PersonalIntegrations.tsx
+++ b/frontend/src/scenes/settings/user/PersonalIntegrations.tsx
@@ -6,8 +6,14 @@ import { LemonBanner, LemonButton, LemonDialog, LemonSkeleton } from '@posthog/l
import { TZLabel } from 'lib/components/TZLabel'
import { GitHubRepoSummary } from 'lib/integrations/GitHubRepoSummary'
import { userGithubIntegrationLogic } from 'lib/integrations/userGithubIntegrationLogic'
+import { IconSlack } from 'lib/lemon-ui/icons'
-import { personalIntegrationsLogic, PersonalGitHubIntegration } from './personalIntegrationsLogic'
+import {
+ LinkableSlackWorkspace,
+ personalIntegrationsLogic,
+ PersonalGitHubIntegration,
+ PersonalSlackIntegration,
+} from './personalIntegrationsLogic'
function GitHubInstallationRow({ integration }: { integration: PersonalGitHubIntegration }): JSX.Element {
const { disconnectGitHub } = useActions(personalIntegrationsLogic)
@@ -71,7 +77,7 @@ function GitHubInstallationRow({ integration }: { integration: PersonalGitHubInt
</div>
<div className="mt-1">
<GitHubRepoSummary
- repoNames={repositories.map((r) => r.name)}
+ repoNames={repositories.map((r: { name: string }) => r.name)}
loading={repositoriesLoading}
installationId={installationId}
accountType={accountType}
@@ -93,7 +99,67 @@ function GitHubInstallationRow({ integration }: { integration: PersonalGitHubInt
)
}
-export function PersonalIntegrations(): JSX.Element {
+function SlackLinkRow({ integration }: { integration: PersonalSlackIntegration }): JSX.Element {
+ const { disconnectSlack } = useActions(personalIntegrationsLogic)
+
+ const handleUnlink = (): void => {
+ LemonDialog.open({
+ title: `Unlink ${integration.slack_team_name || 'this Slack workspace'}?`,
+ description: (
+ <p>
+ PostHog will go back to matching you by email. If your Slack email doesn't match any PostHog account
+ in the organization, mentions won't route to you until you link again.
+ </p>
+ ),
+ primaryButton: {
+ children: 'Unlink',
+ status: 'danger',
+ onClick: () => disconnectSlack(integration.slack_user_id),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+
+ return (
+ <div className="flex items-center gap-4 px-4 py-3">
+ <div className="shrink-0">
+ <div className="flex h-10 w-10 items-center justify-center rounded-md border bg-surface-secondary text-2xl">
+ <IconSlack />
+ </div>
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="font-semibold">{integration.slack_team_name || 'Slack workspace'}</span>
+ <span className="text-xs text-muted bg-surface-secondary px-1.5 py-0.5 rounded font-mono">
+ {integration.slack_user_id}
+ </span>
+ </div>
+ <div className="mt-0.5 text-xs text-secondary">
+ {integration.created_at ? (
+ <>
+ Linked <TZLabel time={integration.created_at} className="align-baseline" />
+ </>
+ ) : (
+ 'Linked'
+ )}
+ {integration.slack_email_at_link ? ` · ${integration.slack_email_at_link}` : ''}
+ </div>
+ </div>
+ <div className="flex shrink-0 items-center">
+ <LemonButton
+ size="small"
+ type="secondary"
+ status="danger"
+ icon={<IconTrash />}
+ onClick={handleUnlink}
+ tooltip="Unlink this Slack account"
+ />
+ </div>
+ </div>
+ )
+}
+
+export function PersonalGitHubIntegrations(): JSX.Element {
const { integrations, integrationsLoading } = useValues(personalIntegrationsLogic)
const { connectGitHub } = useActions(personalIntegrationsLogic)
@@ -106,33 +172,132 @@ export function PersonalIntegrations(): JSX.Element {
}
return (
- <div className="deprecated-space-y-3">
- <div className="divide-y rounded border bg-surface-primary">
- {integrations.length === 0 ? (
- <div className="px-4 py-6 text-center text-sm text-secondary">
- <IconGithub className="text-3xl mb-2 opacity-40" />
- <p className="mb-1">No GitHub installations connected yet</p>
- <p className="text-xs text-muted text-balance">
- Connect to let PostHog access your repos, attribute commits, open pull requests, and assign
- issues as you. You can add multiple installations for different accounts or organizations.
- </p>
- </div>
- ) : (
- integrations.map((integration) => (
- <GitHubInstallationRow key={integration.installation_id} integration={integration} />
- ))
- )}
+ <div className="divide-y rounded border bg-surface-primary">
+ {integrations.length === 0 ? (
+ <div className="px-4 py-6 text-center text-sm text-secondary">
+ <IconGithub className="text-3xl mb-2 opacity-40" />
+ <p className="mb-1">No GitHub installations connected yet</p>
+ <p className="text-xs text-muted text-balance">
+ Connect to let PostHog access your repos, attribute commits, open pull requests, and assign
+ issues as you. You can add multiple installations for different accounts or organizations.
+ </p>
+ </div>
+ ) : (
+ integrations.map((integration: PersonalGitHubIntegration) => (
+ <GitHubInstallationRow key={integration.installation_id} integration={integration} />
+ ))
+ )}
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3">
+ <LemonButton type="secondary" size="small" icon={<IconPlus />} onClick={connectGitHub}>
+ {integrations.length === 0 ? 'Connect GitHub' : 'Add account/organization'}
+ </LemonButton>
+ <span className="text-xs text-secondary text-balance">
+ Heads up: if GitHub's <strong>Save</strong> button is disabled at the end of the flow, flip between{' '}
+ <strong>All repositories</strong> and <strong>Only select repositories</strong> to proceed.
+ </span>
+ </div>
+ </div>
+ )
+}
+
+function openSlackWorkspacePicker(
+ workspaces: LinkableSlackWorkspace[],
+ connectSlack: (payload: { workspace: LinkableSlackWorkspace }) => void
+): void {
+ LemonDialog.open({
+ title: 'Pick a Slack workspace to link',
+ description: (
+ <div className="deprecated-space-y-2">
+ <p className="text-sm text-secondary">
+ Your organizations are connected to multiple Slack workspaces. Pick the one you want to bind your
+ PostHog identity to.
+ </p>
+ <div className="divide-y rounded border">
+ {workspaces.map((workspace) => (
+ <LemonButton
+ key={`${workspace.posthog_team_id}:${workspace.slack_team_id}`}
+ fullWidth
+ type="tertiary"
+ icon={<IconSlack />}
+ sideIcon={<IconPlus />}
+ onClick={() => connectSlack({ workspace })}
+ >
+ <div className="flex flex-col min-w-0">
+ <span className="font-semibold truncate">
+ {workspace.slack_team_name || workspace.slack_team_id}
+ </span>
+ <span className="text-xs text-secondary truncate">
+ {workspace.posthog_organization_name} · {workspace.posthog_team_name}
+ </span>
+ </div>
+ </LemonButton>
+ ))}
+ </div>
+ </div>
+ ),
+ primaryButton: null,
+ secondaryButton: { children: 'Cancel' },
+ })
+}
+
+export function PersonalSlackIntegrations(): JSX.Element {
+ const {
+ slackIntegrations,
+ slackIntegrationsLoading,
+ slackConnectLoading,
+ linkableSlackWorkspaces,
+ linkableSlackWorkspacesLoading,
+ } = useValues(personalIntegrationsLogic)
+ const { connectSlack } = useActions(personalIntegrationsLogic)
+
+ const hasLinkableWorkspaces = linkableSlackWorkspaces.length > 0
+ const onConnect = (): void => {
+ if (linkableSlackWorkspaces.length > 1) {
+ openSlackWorkspacePicker(linkableSlackWorkspaces, connectSlack)
+ } else if (linkableSlackWorkspaces.length === 1) {
+ connectSlack({ workspace: linkableSlackWorkspaces[0] })
+ }
+ }
+
+ return (
+ <div className="divide-y rounded border bg-surface-primary">
+ {slackIntegrationsLoading && slackIntegrations.length === 0 ? (
+ <LemonSkeleton className="h-16 w-full" />
+ ) : slackIntegrations.length === 0 ? (
+ <div className="px-4 py-6 text-center text-sm text-secondary">
+ <IconSlack className="text-3xl mb-2 opacity-40" />
+ <p className="mb-1">No Slack account linked</p>
+ <p className="text-xs text-muted text-balance">
+ Link your Slack identity so @PostHog mentions route to you even when your Slack email and
+ PostHog email don't match.
+ </p>
+ </div>
+ ) : (
+ slackIntegrations.map((integration: PersonalSlackIntegration) => (
+ <SlackLinkRow key={integration.id} integration={integration} />
+ ))
+ )}
+ {/* Button is hidden when there are no linkable workspaces left — every workspace
+ accessible via the user's orgs has already been linked, or none are connected at
+ all. Server still defends with a 400 if the user gets here some other way. */}
+ {(linkableSlackWorkspacesLoading || hasLinkableWorkspaces) && (
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3">
- <LemonButton type="secondary" size="small" icon={<IconPlus />} onClick={connectGitHub}>
- {integrations.length === 0 ? 'Connect GitHub' : 'Add account/organization'}
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconPlus />}
+ onClick={onConnect}
+ loading={slackConnectLoading || linkableSlackWorkspacesLoading}
+ disabledReason={!hasLinkableWorkspaces ? 'Loading…' : undefined}
+ >
+ {slackIntegrations.length === 0 ? 'Link my Slack account' : 'Link another workspace'}
</LemonButton>
<span className="text-xs text-secondary text-balance">
- Heads up: if GitHub's <strong>Save</strong> button is disabled at the end of the flow, flip
- between <strong>All repositories</strong> and <strong>Only select repositories</strong> to
- proceed.
+ You'll be redirected to Slack to authorize this PostHog account. The link binds your Slack user
+ id to your PostHog account — no Slack token is kept after the redirect.
</span>
</div>
- </div>
+ )}
</div>
)
}
diff --git a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
index 32c7e7a1bfe0..d0860c589e2e 100644
--- a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
+++ b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts
@@ -1,15 +1,25 @@
-import { actions, connect, events, kea, listeners, path } from 'kea'
+import { actions, connect, events, kea, listeners, path, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import {
+ usersIntegrationsGithubDestroy,
+ usersIntegrationsGithubStartCreate,
+ usersIntegrationsSlackDestroy,
+ usersIntegrationsSlackLinkableWorkspacesRetrieve,
+ usersIntegrationsSlackStartCreate,
+} from '~/generated/core/api'
import type { personalIntegrationsLogicType } from './personalIntegrationsLogicType'
export interface PersonalGitHubIntegration {
- kind: string
+ kind: 'github'
installation_id: string | null
repository_selection: string | null
account: { type: string; name: string } | null
@@ -17,10 +27,38 @@ export interface PersonalGitHubIntegration {
created_at: string | null
}
-interface GithubStartResponse {
- install_url: string
+export interface PersonalSlackIntegration {
+ id: string
+ kind: 'slack'
+ slack_user_id: string
+ slack_team_id: string
+ slack_team_name: string | null
+ slack_email_at_link: string | null
+ created_at: string | null
+}
+
+export interface LinkableSlackWorkspace {
+ posthog_team_id: number
+ posthog_team_name: string
+ posthog_organization_name: string
+ slack_team_id: string
+ slack_team_name: string | null
}
+const SLACK_LINK_ERROR_MESSAGES: Record<string, string> = {
+ access_denied: 'Slack authorization was canceled.',
+ invalid_state: 'The Slack link request expired or could not be verified. Please try again.',
+ workspace_not_found: 'The Slack workspace is no longer connected to PostHog.',
+ flag_off: "Slack identity linking isn't enabled for this organization.",
+ exchange_failed: 'Slack rejected the authorization. Please try again.',
+ team_mismatch: 'You signed in to a different Slack workspace than the one that started this flow.',
+ org_mismatch: "You aren't a member of the PostHog organization connected to this Slack workspace.",
+ session_mismatch:
+ 'This Slack link was started in a different PostHog session. Please start the link again from settings.',
+ not_configured: 'Slack is not configured for this PostHog instance.',
+}
+const SLACK_LINK_ERROR_FALLBACK = 'Could not connect Slack. Please try again.'
+
/** Key for stashing the ``connect_from`` URL param across the GitHub install roundtrip.
*
* The install flow leaves posthog.com for github.com and comes back, which drops the query
@@ -56,11 +94,13 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
integrationsLogic,
['loadIntegrations as loadProjectIntegrations', 'loadIntegrationsSuccess as projectIntegrationsLoaded'],
],
+ values: [featureFlagLogic, ['featureFlags']],
})),
actions({
connectGitHub: true,
disconnectGitHub: (installationId: string) => ({ installationId }),
+ disconnectSlack: (slackUserId: string) => ({ slackUserId }),
}),
loaders(() => ({
@@ -68,6 +108,11 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
[] as PersonalGitHubIntegration[],
{
loadIntegrations: async () => {
+ // The list endpoint returns a flat `{results: [...]}` payload,
+ // but drf-spectacular auto-wraps `list()` viewset methods in a
+ // paginated schema, so the generated helper would mis-type the
+ // response — call `api.get` directly until the backend serializer
+ // is decorated to bypass pagination.
const response = await api.get<{ results: PersonalGitHubIntegration[] }>(
'api/users/@me/integrations/'
)
@@ -75,19 +120,97 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
},
},
],
+ slackIntegrations: [
+ [] as PersonalSlackIntegration[],
+ {
+ loadSlackIntegrations: async () => {
+ const response = await api.get<{ results: PersonalSlackIntegration[] }>(
+ 'api/users/@me/integrations/?kind=slack'
+ )
+ return response.results
+ },
+ },
+ ],
+ linkableSlackWorkspaces: [
+ [] as LinkableSlackWorkspace[],
+ {
+ loadLinkableSlackWorkspaces: async () => {
+ const response = await usersIntegrationsSlackLinkableWorkspacesRetrieve('@me')
+ return response.results as LinkableSlackWorkspace[]
+ },
+ },
+ ],
+ slackConnect: [
+ false as boolean,
+ {
+ connectSlack: async (payload: { workspace?: LinkableSlackWorkspace } = {}) => {
+ try {
+ const body = payload.workspace
+ ? {
+ team_id: payload.workspace.posthog_team_id,
+ slack_team_id: payload.workspace.slack_team_id,
+ }
+ : {}
+ const response = await usersIntegrationsSlackStartCreate('@me', body)
+ window.location.href = response.install_url
+ return true
+ } catch (error: unknown) {
+ // DRF errors come through as ApiError with `.detail` (string|null),
+ // `.data` (the parsed body — often `{detail: '…'}` or an array of strings),
+ // and `.message`. Read `detail` first, then fall back to `data.detail`
+ // / first array entry, then the error message itself. Without this, a
+ // ValidationError like "You're already linked to this Slack workspace."
+ // surfaces only as the generic fallback because `detail` is null on
+ // non-`detail`-shaped DRF bodies.
+ const message =
+ error instanceof Error
+ ? (error as any).detail ||
+ (error as any).data?.detail ||
+ (Array.isArray((error as any).data) ? (error as any).data[0] : undefined) ||
+ error.message
+ : undefined
+ lemonToast.error(message || 'Could not start Slack linking.')
+ return false
+ }
+ },
+ },
+ ],
})),
+ selectors({
+ // Gating selector for the new section. Read once in the component so the
+ // backend endpoints are still queryable for users who linked before the
+ // flag flipped off — only the *new connect / discoverability* surface
+ // is hidden, not the unlink path.
+ slackLinkEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags): boolean => !!featureFlags[FEATURE_FLAGS.SLACK_APP_OAUTH],
+ ],
+ }),
+
listeners(({ actions }) => ({
projectIntegrationsLoaded: () => {
// When a project-level integration is added/removed, the backend may
// auto-create a user-level integration. Reload to pick it up.
actions.loadIntegrations()
},
+ disconnectSlack: async ({ slackUserId }) => {
+ try {
+ await usersIntegrationsSlackDestroy('@me', slackUserId)
+ lemonToast.success('Unlinked your Slack account')
+ actions.loadSlackIntegrations()
+ // Refresh linkable so the just-unlinked workspace re-appears
+ // in the connect picker without a page reload.
+ actions.loadLinkableSlackWorkspaces()
+ } catch {
+ lemonToast.error('Could not unlink your Slack account.')
+ }
+ },
connectGitHub: async () => {
try {
const connectFrom = readConnectFromStorage()
- const body = connectFrom === 'posthog_code' ? { connect_from: 'posthog_code' as const } : {}
- const response = await api.create<GithubStartResponse>('api/users/@me/integrations/github/start/', body)
+ const body = connectFrom === 'posthog_code' ? { connect_from: 'posthog_code' } : {}
+ const response = await usersIntegrationsGithubStartCreate('@me', body)
window.location.href = response.install_url
} catch (error: unknown) {
const message = error instanceof Error && 'detail' in error ? (error as any).detail : undefined
@@ -96,7 +219,7 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
},
disconnectGitHub: async ({ installationId }) => {
try {
- await api.delete(`api/users/@me/integrations/github/${installationId}/`)
+ await usersIntegrationsGithubDestroy('@me', installationId)
lemonToast.success('Disconnected GitHub installation')
actions.loadIntegrations()
actions.loadProjectIntegrations()
@@ -109,6 +232,8 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
events(({ actions }) => ({
afterMount: () => {
actions.loadIntegrations()
+ actions.loadSlackIntegrations()
+ actions.loadLinkableSlackWorkspaces()
const params = new URLSearchParams(window.location.search)
// Stash ``connect_from`` so the post-roundtrip success toast can surface a
@@ -142,6 +267,13 @@ export const personalIntegrationsLogic = kea<personalIntegrationsLogicType>([
: 'Could not connect GitHub. Please try again.'
lemonToast.error(message)
}
+
+ if (params.has('slack_link_success')) {
+ lemonToast.success('Slack connected.')
+ } else if (params.has('slack_link_error')) {
+ const reason = params.get('slack_link_error') ?? ''
+ lemonToast.error(SLACK_LINK_ERROR_MESSAGES[reason] ?? SLACK_LINK_ERROR_FALLBACK)
+ }
},
})),
])
diff --git a/posthog/api/test/test_user_integration.py b/posthog/api/test/test_user_integration.py
index 51fc2aeb6572..6f89e722514d 100644
--- a/posthog/api/test/test_user_integration.py
+++ b/posthog/api/test/test_user_integration.py
@@ -1,4 +1,5 @@
import time
+from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -970,3 +971,251 @@ class TestGithubUserFromCode(APIBaseTest):
self.assertEqual(result.refresh_token, "ghr_user_refresh")
self.assertEqual(result.access_token_expires_in, 28800)
self.assertEqual(result.refresh_token_expires_in, 15897600)
+
+
+def _create_slack_user_integration(
+ user: User,
+ *,
+ slack_user_id: str = "U999",
+ slack_team_id: str = "T12345",
+ slack_team_name: str | None = "Test Workspace",
+ slack_email_at_link: str | None = "[email protected]",
+) -> UserIntegration:
+ return UserIntegration.objects.create(
+ user=user,
+ kind=UserIntegration.IntegrationKind.SLACK,
+ integration_id=slack_user_id,
+ config={
+ "slack_team_id": slack_team_id,
+ "slack_team_name": slack_team_name,
+ "slack_email_at_link": slack_email_at_link,
+ "linked_at": int(time.time()),
+ },
+ sensitive_config={},
+ )
+
+
+class TestUserIntegrationKindParam(APIBaseTest):
+ """Back-compat + dispatch behavior of the unified list endpoint."""
+
+ def test_default_kind_returns_github_rows(self):
+ # Mobile + Code SDK call this URL without a query param and rely on
+ # receiving GitHub-shaped items. Don't change the default lightly.
+ _create_user_integration(self.user) # github
+ response = self.client.get("/api/users/@me/integrations/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ results = response.json()["results"]
+ self.assertEqual(len(results), 1)
+ self.assertEqual(results[0]["installation_id"], "12345")
+
+ def test_explicit_github_kind_matches_default(self):
+ _create_user_integration(self.user)
+ default_response = self.client.get("/api/users/@me/integrations/")
+ explicit_response = self.client.get("/api/users/@me/integrations/?kind=github")
+ self.assertEqual(default_response.json(), explicit_response.json())
+
+ def test_unsupported_kind_returns_400(self):
+ response = self.client.get("/api/users/@me/integrations/?kind=bitbucket")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+
+class TestUserIntegrationSlackEndpoints(APIBaseTest):
+ def test_slack_list_returns_empty_when_no_links(self):
+ response = self.client.get("/api/users/@me/integrations/?kind=slack")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["results"], [])
+
+ def test_slack_list_returns_user_link_with_full_payload(self):
+ _create_slack_user_integration(self.user)
+ response = self.client.get("/api/users/@me/integrations/?kind=slack")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ results = response.json()["results"]
+ self.assertEqual(len(results), 1)
+ row = results[0]
+ self.assertEqual(row["kind"], "slack")
+ self.assertEqual(row["slack_user_id"], "U999")
+ self.assertEqual(row["slack_team_id"], "T12345")
+ self.assertEqual(row["slack_team_name"], "Test Workspace")
+ self.assertEqual(row["slack_email_at_link"], "[email protected]")
+
+ def test_slack_list_does_not_include_github_rows(self):
+ _create_user_integration(self.user)
+ _create_slack_user_integration(self.user)
+ response = self.client.get("/api/users/@me/integrations/?kind=slack")
+ results = response.json()["results"]
+ self.assertEqual(len(results), 1)
+ self.assertEqual(results[0]["kind"], "slack")
+
+ def test_slack_list_scoped_to_requesting_user(self):
+ other = User.objects.create(email="[email protected]", distinct_id="other-1")
+ _create_slack_user_integration(other, slack_user_id="U-OTHER")
+ response = self.client.get("/api/users/@me/integrations/?kind=slack")
+ self.assertEqual(response.json()["results"], [])
+
+ def test_slack_destroy_removes_row(self):
+ _create_slack_user_integration(self.user, slack_user_id="U999")
+ response = self.client.delete("/api/users/@me/integrations/slack/U999/")
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ self.assertFalse(
+ UserIntegration.objects.filter(
+ user=self.user, kind=UserIntegration.IntegrationKind.SLACK, integration_id="U999"
+ ).exists()
+ )
+
+ def test_slack_destroy_404_when_link_missing(self):
+ response = self.client.delete("/api/users/@me/integrations/slack/U-NOPE/")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_slack_destroy_cannot_remove_other_users_link(self):
+ other = User.objects.create(email="[email protected]", distinct_id="other-2")
+ _create_slack_user_integration(other, slack_user_id="U-OTHER")
+ # The requesting user has no row with this slack_user_id, so we get 404,
+ # not 403 — the route refuses to acknowledge another user's rows.
+ response = self.client.delete("/api/users/@me/integrations/slack/U-OTHER/")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ self.assertTrue(
+ UserIntegration.objects.filter(
+ user=other, kind=UserIntegration.IntegrationKind.SLACK, integration_id="U-OTHER"
+ ).exists()
+ )
+
+ def _enable_flag(self) -> Any:
+ return patch("posthog.api.user_integration.slack_oauth_link_enabled", return_value=True)
+
+ def _seed_workspace_integration(self) -> Integration:
+ return Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T12345",
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+
+ def test_slack_start_returns_install_url_when_workspace_connected(self):
+ self._seed_workspace_integration()
+ with self._enable_flag():
+ response = self.client.post("/api/users/@me/integrations/slack/start/", data={}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ install_url = response.json()["install_url"]
+ # Routes through the same backend authorize entry — settings is just
+ # another invite origin, not a separate OAuth flow.
+ self.assertIn("/complete/slack-link/start/?state=", install_url)
+
+ def test_slack_start_fails_when_no_workspace_integration(self):
+ with self._enable_flag():
+ response = self.client.post("/api/users/@me/integrations/slack/start/", data={}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("no Slack workspace", response.json()["detail"])
+
+ def test_slack_start_fails_when_already_linked(self):
+ self._seed_workspace_integration()
+ _create_slack_user_integration(self.user, slack_team_id="T12345")
+ with self._enable_flag():
+ response = self.client.post("/api/users/@me/integrations/slack/start/", data={}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("already linked", response.json()["detail"])
+
+ def test_slack_start_403_when_flag_off(self):
+ self._seed_workspace_integration()
+ with patch("posthog.api.user_integration.slack_oauth_link_enabled", return_value=False):
+ response = self.client.post("/api/users/@me/integrations/slack/start/", data={}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_slack_linkable_empty_when_no_workspaces_connected(self):
+ with self._enable_flag():
+ response = self.client.get("/api/users/@me/integrations/slack/linkable_workspaces/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["results"], [])
+
+ def test_slack_linkable_returns_workspaces_user_can_still_link(self):
+ self._seed_workspace_integration()
+ with self._enable_flag():
+ response = self.client.get("/api/users/@me/integrations/slack/linkable_workspaces/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ results = response.json()["results"]
+ self.assertEqual(len(results), 1)
+ self.assertEqual(results[0]["slack_team_id"], "T12345")
+ self.assertEqual(results[0]["posthog_team_id"], self.team.id)
+
+ def test_slack_linkable_excludes_workspaces_user_already_linked(self):
+ self._seed_workspace_integration()
+ _create_slack_user_integration(self.user, slack_team_id="T12345")
+ with self._enable_flag():
+ response = self.client.get("/api/users/@me/integrations/slack/linkable_workspaces/")
+ # The screenshot bug: user has linked the only workspace, so the
+ # picker has nothing to offer. Frontend uses the empty list to hide
+ # the "Link another workspace" button instead of letting the user
+ # attempt a duplicate link the backend would reject.
+ self.assertEqual(response.json()["results"], [])
+
+ def test_slack_linkable_skips_workspaces_with_flag_off(self):
+ self._seed_workspace_integration()
+ with patch("posthog.api.user_integration.slack_oauth_link_enabled", return_value=False):
+ response = self.client.get("/api/users/@me/integrations/slack/linkable_workspaces/")
+ self.assertEqual(response.json()["results"], [])
+
+ def test_slack_linkable_excludes_private_project_user_cannot_access(self):
+ # The endpoint scopes candidates by organization, but org membership
+ # alone is not access — an access-control-enabled project the user
+ # has no role in must not surface its Slack workspace metadata
+ # (workspace id, team name) in the picker. Without the per-team
+ # ``effective_membership_level`` filter, an org member could call this
+ # endpoint and enumerate Slack installs (plus project + organization
+ # names) for every private project in their orgs.
+ from posthog.constants import AvailableFeature
+ from posthog.models.organization import Organization, OrganizationMembership
+ from posthog.models.team import Team
+
+ from ee.models.rbac.access_control import AccessControl
+
+ ac_org = Organization.objects.create(name="AC Org")
+ # ``pre_save`` on Organization resets ``available_product_features`` on
+ # insert; set it after the initial save to opt the org into per-team
+ # access-control checks.
+ ac_org.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ ac_org.save()
+ private_team = Team.objects.create(organization=ac_org, name="Private Team")
+ AccessControl.objects.create(
+ team=private_team,
+ resource="project",
+ resource_id=str(private_team.id),
+ organization_member=None,
+ role=None,
+ access_level="none",
+ )
+ OrganizationMembership.objects.create(organization=ac_org, user=self.user)
+ Integration.objects.create(
+ team=private_team,
+ kind="slack",
+ integration_id="T-PRIVATE",
+ sensitive_config={"access_token": "xoxb-private"},
+ )
+
+ with self._enable_flag():
+ response = self.client.get("/api/users/@me/integrations/slack/linkable_workspaces/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ results = response.json()["results"]
+ self.assertNotIn("T-PRIVATE", [r["slack_team_id"] for r in results])
+
+ def test_slack_start_with_explicit_slack_team_id_links_against_picked_workspace(self):
+ self._seed_workspace_integration()
+ with self._enable_flag():
+ response = self.client.post(
+ "/api/users/@me/integrations/slack/start/",
+ data={"team_id": self.team.id, "slack_team_id": "T12345"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIn("/complete/slack-link/start/?state=", response.json()["install_url"])
+
+ def test_slack_start_with_explicit_unknown_slack_team_id_is_400(self):
+ self._seed_workspace_integration()
+ with self._enable_flag():
+ response = self.client.post(
+ "/api/users/@me/integrations/slack/start/",
+ data={"team_id": self.team.id, "slack_team_id": "T-NOPE"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.py
index 52511c8d354e..45f1356895ea 100644
--- a/posthog/api/user_integration.py
+++ b/posthog/api/user_integration.py
@@ -18,7 +18,8 @@ from django.core.cache import cache
import requests
import structlog
-from drf_spectacular.utils import OpenApiResponse, extend_schema
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
from rest_framework import exceptions, serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
@@ -46,6 +47,10 @@ from posthog.models.user import User
from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
from posthog.permissions import APIScopePermission
from posthog.rate_limit import UserAuthenticationThrottle
+from posthog.user_permissions import UserPermissions
+
+from products.slack_app.backend.feature_flags import slack_oauth_link_enabled
+from products.slack_app.backend.services.slack_user_oauth import build_invite_url
logger = structlog.get_logger(__name__)
@@ -112,13 +117,92 @@ class UserGitHubLinkStartResponseSerializer(serializers.Serializer):
)
+class UserSlackIntegrationItemSerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="PostHog UserIntegration row id.")
+ kind = serializers.CharField(help_text="Integration kind; always `slack` for this API.")
+ slack_user_id = serializers.CharField(help_text="Slack user id this PostHog account is linked to.")
+ slack_team_id = serializers.CharField(help_text="Slack workspace (team) id the link belongs to.")
+ slack_team_name = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Slack workspace display name as of link time.",
+ )
+ slack_email_at_link = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Slack email at the time of linking. Stored for support; not consulted at resolve time.",
+ )
+ created_at = serializers.DateTimeField(help_text="When this link was first created.")
+
+
+class UserSlackIntegrationListResponseSerializer(serializers.Serializer):
+ results = UserSlackIntegrationItemSerializer(
+ many=True,
+ help_text="Slack identity links for the authenticated user.",
+ )
+
+
+class UserSlackLinkStartRequestSerializer(serializers.Serializer):
+ """Settings-initiated link can target a specific PostHog team + Slack workspace.
+
+ Both are optional — when omitted we fall back to the user's ``current_team``
+ and that team's first Slack ``Integration`` (mirrors ``github_start`` for
+ the simple case). The frontend passes both explicitly once it has the
+ linkable-workspace list and the user has picked a workspace.
+ """
+
+ team_id = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ help_text="Optional team/project id to link against; defaults to the user's current team.",
+ )
+ slack_team_id = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Specific Slack workspace id to link against, scoped to the team. Disambiguates when one team has multiple Slack integrations (rare).",
+ )
+
+
+class UserSlackLinkStartResponseSerializer(serializers.Serializer):
+ install_url = serializers.CharField(
+ help_text="URL to open in the browser to start the Sign-in-with-Slack flow.",
+ )
+
+
+class UserSlackLinkableWorkspaceItemSerializer(serializers.Serializer):
+ posthog_team_id = serializers.IntegerField(help_text="PostHog team/project id owning the Slack workspace install.")
+ posthog_team_name = serializers.CharField(help_text="PostHog team/project name, for display in a picker.")
+ posthog_organization_name = serializers.CharField(
+ help_text="PostHog organization name owning the team, for picker disambiguation.",
+ )
+ slack_team_id = serializers.CharField(help_text="Slack workspace (team) id.")
+ slack_team_name = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Slack workspace display name as known by PostHog.",
+ )
+
+
+class UserSlackLinkableWorkspaceListResponseSerializer(serializers.Serializer):
+ results = UserSlackLinkableWorkspaceItemSerializer(
+ many=True,
+ help_text="Slack workspaces the user could link to but hasn't yet.",
+ )
+
+
@extend_schema(extensions={"x-product": "core"})
class UserIntegrationViewSet(viewsets.GenericViewSet):
"""`/api/users/@me/integrations/` — manage the user's personal GitHub integrations."""
scope_object = "user"
required_scopes: list[str] | None = None
- scope_object_read_actions = ["list", "retrieve", "github_repos", "github_branches"]
+ scope_object_read_actions = [
+ "list",
+ "retrieve",
+ "github_repos",
+ "github_branches",
+ "slack_linkable",
+ ]
scope_object_write_actions = [
"create",
"update",
@@ -128,6 +212,8 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
"github_start",
"github_destroy",
"github_repos_refresh",
+ "slack_start",
+ "slack_destroy",
]
authentication_classes = [OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication]
@@ -166,21 +252,59 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
return installation_ids
@extend_schema(
- summary="List personal GitHub integrations",
+ summary="List the user's personal integrations of a given kind",
+ parameters=[
+ OpenApiParameter(
+ name="kind",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ enum=["github", "slack"],
+ description="Integration kind to list. Defaults to `github` for back-compat with mobile and the Code SDK, which call this endpoint without a query param and expect GitHub-shaped items.",
+ ),
+ ],
responses={200: UserGitHubIntegrationListResponseSerializer},
)
def list(self, request: Request, **_kwargs) -> Response:
+ """Return the authenticated user's personal integrations of a given
+ ``kind`` (``github`` or ``slack``).
+
+ The response shape varies per kind because the underlying ``UserIntegration``
+ rows carry different identity fields — GitHub rows expose
+ ``installation_id`` / ``account`` / ``uses_shared_installation``; Slack
+ rows expose ``slack_user_id`` / ``slack_team_id`` / ``slack_team_name``.
+ Kind-specific destroy and start actions remain split so their distinct
+ semantics (e.g. Slack's lack of "uninstall on last reference") stay
+ explicit at the URL layer.
+
+ Default of ``kind=github`` is load-bearing: mobile (``apps/mobile/...``)
+ and the Code SDK (``packages/api-client/...``) both call this endpoint
+ without a query param today and rely on receiving GitHub rows.
+ """
user = self._get_user()
- integrations = UserIntegration.objects.filter(user=user, kind="github").order_by("created_at")
- team_installation_ids = self._team_github_installation_ids(user)
- return Response(
- {
- "results": [
+ kind = request.query_params.get("kind") or "github"
+ if kind not in {"github", "slack"}:
+ raise exceptions.ValidationError(f"Unsupported integration kind: {kind!r}")
+
+ # Single query and single pass — each row picks its own serializer
+ # off `integration.kind`. Today the query is filtered to one kind so
+ # the loop only sees that one shape, but the per-row dispatch keeps
+ # the door open for dropping the kind default and returning github
+ # + slack rows side-by-side in one response.
+ integrations = UserIntegration.objects.filter(user=user, kind=kind).order_by("created_at")
+ # Only compute the github-specific cross-team installation set when
+ # there could be github rows in the response; for `kind=slack` this
+ # would be an unused DB roundtrip on every settings page load.
+ team_installation_ids: set[str] = self._team_github_installation_ids(user) if kind == "github" else set()
+ results: list[dict[str, Any]] = []
+ for integration in integrations:
+ if integration.kind == "github":
+ results.append(
_serialize_github_integration(integration, team_integration_installation_ids=team_installation_ids)
- for integration in integrations
- ],
- }
- )
+ )
+ elif integration.kind == "slack":
+ results.append(_serialize_slack_integration(integration))
+ return Response({"results": results})
@extend_schema(
summary="Disconnect a personal GitHub integration",
@@ -360,6 +484,150 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
}
)
+ @extend_schema(
+ summary="List Slack workspaces this user could link to",
+ responses={200: UserSlackLinkableWorkspaceListResponseSerializer},
+ )
+ @action(methods=["GET"], detail=False, url_path="slack/linkable_workspaces")
+ def slack_linkable(self, request: Request, **_kwargs) -> Response:
+ """Return Slack workspaces in the user's organizations that they have
+ not yet linked. The settings UI uses this list to decide whether to
+ show a "Link my Slack account" button (non-empty list) and what to
+ offer in the picker when several are connectable.
+ """
+ user = self._get_user()
+ org_ids = set(user.organization_memberships.values_list("organization_id", flat=True))
+ if not org_ids:
+ return Response({"results": []})
+
+ already_linked_slack_team_ids = set(
+ UserIntegration.objects.filter(
+ user=user,
+ kind=UserIntegration.IntegrationKind.SLACK,
+ ).values_list("config__slack_team_id", flat=True)
+ )
+
+ candidates = (
+ Integration.objects.filter(kind="slack", team__organization_id__in=org_ids)
+ .exclude(integration_id__in=already_linked_slack_team_ids)
+ .select_related("team", "team__organization")
+ )
+
+ # Skip projects the user can't actually access (private project, no role
+ # via access-control, etc.). Without the per-team check, an org member
+ # would see Slack workspace IDs + project names for every project in
+ # their orgs — including private ones their `effective_membership_level`
+ # is `None` for. Using per-team `effective_membership_level` rather than
+ # `user.teams` mirrors `resolve_user_for_workspace` and dodges the
+ # `Organization.first()`-feature-flags quirk that gates `user.teams`.
+ permissions = UserPermissions(user=user)
+
+ results: list[dict[str, Any]] = []
+ for integration in candidates:
+ if permissions.team(integration.team).effective_membership_level is None:
+ continue
+ # Feature-flag check per workspace so an org that hasn't rolled out
+ # the flag yet doesn't show up in another org's picker.
+ if not slack_oauth_link_enabled(integration, integration.integration_id):
+ continue
+ # `(config or {}).get("team", {})` doesn't defend against an explicit
+ # ``config["team"] = None`` — dict.get returns the literal None
+ # rather than the default — so we coerce defensively before the
+ # second `.get("name")`.
+ team_block = (integration.config or {}).get("team") or {}
+ results.append(
+ {
+ "posthog_team_id": integration.team_id,
+ "posthog_team_name": integration.team.name,
+ "posthog_organization_name": integration.team.organization.name,
+ "slack_team_id": integration.integration_id,
+ "slack_team_name": team_block.get("name"),
+ }
+ )
+ return Response({"results": results})
+
+ @extend_schema(
+ summary="Start Slack identity link from settings",
+ request=UserSlackLinkStartRequestSerializer,
+ responses={200: UserSlackLinkStartResponseSerializer},
+ )
+ @action(methods=["POST"], detail=False, url_path="slack/start", throttle_classes=[UserAuthenticationThrottle])
+ def slack_start(self, request: Request, **_kwargs) -> Response:
+ """Mint a Sign-in-with-Slack invite URL initiated from settings, without
+ Slack-DM context. The returned URL takes the user through PostHog login
+ (already satisfied here), then to Slack OAuth, then back to our callback
+ which writes the ``UserIntegration`` row.
+
+ Without body params, falls back to the user's ``current_team`` and that
+ team's first Slack ``Integration`` — works when there's exactly one
+ linkable workspace. With ``team_id`` + ``slack_team_id``, links against
+ the exact pair (what the frontend uses when a picker is shown).
+
+ Refuses if the target team has no matching Slack workspace, if the
+ feature flag is off for the workspace, or if the user is already linked
+ to it.
+ """
+ user = self._get_user()
+ team = _resolve_team_for_github_start(user, request)
+ if team is None:
+ raise exceptions.ValidationError("No team available for this user.")
+
+ # If the caller specifies a Slack workspace explicitly, honor it (this
+ # is the picker path). Otherwise pick the first Slack integration on
+ # the resolved team (the simple "Link my Slack account" path).
+ body: Any = request.data if isinstance(request.data, dict) else {}
+ slack_team_id_hint = body.get("slack_team_id")
+ workspace_query = Integration.objects.filter(team=team, kind="slack")
+ if slack_team_id_hint:
+ workspace_query = workspace_query.filter(integration_id=slack_team_id_hint)
+ workspace = workspace_query.first()
+ if workspace is None:
+ raise exceptions.ValidationError(
+ "This project has no Slack workspace connected. Ask an admin to install the Slack app first."
+ )
+
+ if not slack_oauth_link_enabled(workspace, workspace.integration_id):
+ raise exceptions.PermissionDenied("Slack identity linking is not enabled for this organization.")
+
+ if UserIntegration.objects.filter(
+ user=user,
+ kind=UserIntegration.IntegrationKind.SLACK,
+ config__slack_team_id=workspace.integration_id,
+ ).exists():
+ raise exceptions.ValidationError("You're already linked to this Slack workspace.")
+
+ install_url = build_invite_url(
+ slack_user_id=None,
+ slack_team_id=workspace.integration_id,
+ posthog_team_id=team.id,
+ channel=None,
+ thread_ts=None,
+ )
+ return Response({"install_url": install_url})
+
+ @extend_schema(
+ summary="Unlink a Slack identity",
+ responses={204: OpenApiResponse(description="Slack link removed.")},
+ )
+ # Restrict the slack_user_id capture to Slack's real id format ("U..." for
+ # human users, "W..." for Enterprise Grid). A looser regex would shadow
+ # sibling actions like ``slack/start`` and return 405 on their POSTs.
+ @action(methods=["DELETE"], detail=False, url_path=r"slack/(?P<slack_user_id>[UW][A-Z0-9]+)")
+ def slack_destroy(self, request: Request, slack_user_id: str, **_kwargs) -> Response:
+ """Remove a Slack identity link by Slack user id. Idempotent and
+ flag-agnostic — users must always be able to unlink even after the
+ feature flag is turned off."""
+ user = self._get_user()
+ integration = UserIntegration.objects.filter(
+ user=user,
+ kind=UserIntegration.IntegrationKind.SLACK,
+ integration_id=slack_user_id,
+ ).first()
+ if integration is None:
+ raise exceptions.NotFound("No Slack link found for this Slack user id.")
+ integration.delete()
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
def _resolve_team_for_github_start(user: User, request: Request):
"""Resolve which team to use for team-level GitHub install discovery.
@@ -488,3 +756,17 @@ def _serialize_github_integration(
"uses_shared_installation": integration.integration_id in team_integration_installation_ids,
"created_at": integration.created_at,
}
+
+
+def _serialize_slack_integration(integration: UserIntegration) -> dict[str, Any]:
+ """Build the response payload for a single Slack UserIntegration row."""
+ config = integration.config or {}
+ return {
+ "id": integration.id,
+ "kind": "slack",
+ "slack_user_id": integration.integration_id,
+ "slack_team_id": config.get("slack_team_id"),
+ "slack_team_name": config.get("slack_team_name"),
+ "slack_email_at_link": config.get("slack_email_at_link"),
+ "created_at": integration.created_at,
+ }
diff --git a/posthog/migrations/1235_userintegration_slack_kind.py b/posthog/migrations/1235_userintegration_slack_kind.py
new file mode 100644
index 000000000000..bde019de6113
--- /dev/null
+++ b/posthog/migrations/1235_userintegration_slack_kind.py
@@ -0,0 +1,16 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("posthog", "1234_oauthapplication_optional_scopes_and_more")]
+
+ operations = [
+ migrations.AlterField(
+ model_name="userintegration",
+ name="kind",
+ field=models.CharField(
+ choices=[("github", "Github"), ("slack", "Slack")],
+ max_length=32,
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/1236_userintegration_kind_extid_idx.py b/posthog/migrations/1236_userintegration_kind_extid_idx.py
new file mode 100644
index 000000000000..f790f36d2f8a
--- /dev/null
+++ b/posthog/migrations/1236_userintegration_kind_extid_idx.py
@@ -0,0 +1,17 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # CREATE INDEX CONCURRENTLY cannot run inside a transaction, and PostHog policy keeps
+ # concurrent index builds in their own migration away from regular DDL.
+ atomic = False
+ dependencies = [("posthog", "1235_userintegration_slack_kind")]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="userintegration",
+ index=models.Index(fields=["kind", "integration_id"], name="user_integration_kind_extid"),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 074e368e6c8e..3441c8c01c06 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1234_oauthapplication_optional_scopes_and_more
+1236_userintegration_kind_extid_idx
diff --git a/posthog/models/user_integration.py b/posthog/models/user_integration.py
index 1d1bc1298b2f..edc6d63bbba7 100644
--- a/posthog/models/user_integration.py
+++ b/posthog/models/user_integration.py
@@ -35,10 +35,38 @@ class UserIntegration(UUIDModel):
- `integration_id` holds the GitHub App installation_id
- `config` holds installation metadata + user identity (login, id)
- `sensitive_config` holds installation access token + user-to-server tokens
+
+ Contents for Slack (user identity link):
+ - `integration_id` holds the Slack user id (e.g. "U123ABC"), workspace-scoped
+ - `config` holds {slack_team_id, slack_team_name, slack_email_at_link, linked_at}
+ - `sensitive_config` holds {user_access_token, user_refresh_token?} — the
+ Slack user-to-server token plus, when the Slack app has
+ `token_rotation_enabled`, a refresh token used to rotate it. Today's
+ manifest has rotation off, so `user_refresh_token` is absent and
+ `user_access_token` is long-lived; the capture is defensive so flipping
+ rotation on later requires no schema or callback-shape change.
+
+ Cardinality (Slack):
+ - One PostHog user → many rows, one per Slack workspace they've linked
+ (Slack assigns a distinct user id per workspace, so the rows have
+ different `integration_id` values).
+ - One Slack identity (workspace × Slack user id) → may have multiple
+ PostHog rows when the same Slack account is linked to more than one
+ PostHog account (e.g. personal + work). The inbound resolver picks
+ the most-recently-linked accessible row and warns when it sees more
+ than one match — see `find_linked_posthog_user`.
+
+ The `unique_together = ("user", "kind", "integration_id")` constraint only
+ forbids the same PostHog user linking the same Slack workspace identity
+ twice (which would have to be a re-OAuth that `update_or_create` already
+ folds into an in-place refresh). It does NOT forbid two PostHog users
+ sharing a Slack identity — that's a deliberate allowance the resolver
+ handles deterministically.
"""
class IntegrationKind(models.TextChoices):
GITHUB = "github"
+ SLACK = "slack"
user = models.ForeignKey(
"posthog.User",
@@ -58,6 +86,9 @@ class UserIntegration(UUIDModel):
class Meta:
db_table = "posthog_user_integration"
unique_together = [("user", "kind", "integration_id")]
+ indexes = [
+ models.Index(fields=["kind", "integration_id"], name="user_integration_kind_extid"),
+ ]
class ReauthorizationRequired(Exception):
@@ -352,3 +383,47 @@ def user_github_integration_from_installation(
},
)
return integration
+
+
+def user_slack_integration_from_identity(
+ user: "User",
+ *,
+ slack_user_id: str,
+ slack_team_id: str,
+ slack_team_name: str | None,
+ slack_email_at_link: str | None,
+ user_access_token: str,
+ user_refresh_token: str | None = None,
+) -> UserIntegration:
+ """Create or refresh a Slack ``UserIntegration`` from a Sign-in-with-Slack
+ identity.
+
+ Persists the Slack user-to-server token in ``sensitive_config`` in symmetry
+ with the GitHub personal integration. ``user_refresh_token`` is captured
+ defensively — Slack only returns it when the app has
+ `token_rotation_enabled`, which today is off, so it's typically ``None``.
+ Storing both fields now means flipping rotation on later requires no
+ schema or callback-shape change. ``slack_email_at_link`` is stored for
+ support diagnostics and is not consulted at resolve time.
+ """
+ config: dict[str, Any] = {
+ "slack_team_id": slack_team_id,
+ "slack_team_name": slack_team_name,
+ "slack_email_at_link": slack_email_at_link,
+ "linked_at": int(time.time()),
+ }
+ sensitive_config: dict[str, Any] = {
+ "user_access_token": user_access_token,
+ }
+ if user_refresh_token is not None:
+ sensitive_config["user_refresh_token"] = user_refresh_token
+ integration, _created = UserIntegration.objects.update_or_create(
+ user=user,
+ kind=UserIntegration.IntegrationKind.SLACK,
+ integration_id=slack_user_id,
+ defaults={
+ "config": config,
+ "sensitive_config": sensitive_config,
+ },
+ )
+ return integration
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.py
index 202cbf12a06f..b2fb44c49e07 100644
--- a/posthog/temporal/ai/slack_app/activities/task_creation.py
+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py
@@ -572,7 +572,10 @@ def forward_posthog_code_followup_activity(
actual=slack_user_id,
)
return True
- actor_name = resolved.user.get_full_name() or resolved.slack_email
+ # `slack_email` is None on the linked-user resolver path; fall through
+ # to the user's PostHog email rather than interpolating literal "None: "
+ # into the LLM-forwarded prefix when both name and slack_email are absent.
+ actor_name = resolved.user.get_full_name() or resolved.slack_email or resolved.user.email
followup_user_text_prefix = f"{actor_name}: "
logger.info(
"posthog_code_followup_cross_user_authorized",
diff --git a/posthog/urls.py b/posthog/urls.py
index b6dc1da920fd..d7d8af602371 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -60,6 +60,7 @@ from products.slack_app.backend.api import (
posthog_code_interactivity_handler,
slack_workspace_claims_view,
)
+from products.slack_app.backend.views import slack_user_link_authorize, slack_user_link_callback
from products.surveys.backend.api.survey import public_survey_page
from products.tasks.backend.facade.agent_proxy import agent_proxy_callback
from products.user_interviews.backend.presentation.webhooks import (
@@ -451,6 +452,10 @@ urlpatterns = [
# GitHub account linking (identity-only, separate from the login pipeline).
# Must precede `social_django.urls` so the latter's `complete/<str:backend>/` doesn't swallow it.
path("complete/github-link/", github_link_complete, name="github_link_complete"),
+ # Slack user-identity linking — mirrors the GitHub per-user pattern above,
+ # and likewise must precede `social_django.urls` for the same reason.
+ path("complete/slack-link/start/", slack_user_link_authorize, name="slack_link_start"),
+ path("complete/slack-link/", slack_user_link_callback, name="slack_link_complete"),
path("", include("social_django.urls", namespace="social")),
path("uploaded_media/<str:image_uuid>", uploaded_media.download),
opt_slash_path("slack/interactivity-callback", posthog_code_interactivity_handler),
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 6155248c52f3..9e79a5357c36 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -52,6 +52,7 @@ from posthog.user_permissions import UserPermissions
from posthog.utils import get_instance_region
from products.slack_app.backend import inbox_channel, onboarding
+from products.slack_app.backend.feature_flags import slack_oauth_link_enabled
from products.slack_app.backend.models import SlackChannel, SlackThreadTaskMapping
from products.slack_app.backend.services import inbox_interactivity
from products.slack_app.backend.services.integration_resolver import (
@@ -67,6 +68,11 @@ from products.slack_app.backend.services.slack_user_info import (
normalize_slack_response,
persist_slack_user_info,
)
+from products.slack_app.backend.services.slack_user_oauth import (
+ build_invite_url,
+ find_linked_posthog_user,
+ post_link_invite_message,
+)
from products.slack_app.backend.slack_link_unfurl import handle_posthog_link_unfurl
logger = structlog.get_logger(__name__)
@@ -158,7 +164,10 @@ def _clear_pending_repo_picker(*, integration_id: int, channel: str, thread_ts:
@dataclass
class SlackUserContext:
user: User
- slack_email: str
+ # `None` on the linked-user path: the OAuth link binds slack_user_id to a
+ # PostHog user without ever consulting Slack's email, so no value is
+ # available. The email-matching path still always populates this.
+ slack_email: str | None
@dataclass
@@ -264,13 +273,56 @@ def resolve_slack_user(
) -> SlackUserContext | None:
"""Resolve a Slack user to a PostHog user. Posts an ephemeral error message and returns None on failure (unless post_feedback is False)."""
try:
- slack_user_info = get_slack_user_info(slack, integration, slack_user_id)
- slack_email = slack_user_info.get("user", {}).get("profile", {}).get("email")
- if not slack_email:
- fresh_user_info = normalize_slack_response(slack.client.users_info(user=slack_user_id))
- if fresh_user_info:
- persist_slack_user_info(integration, slack_user_id, fresh_user_info)
- slack_email = fresh_user_info.get("user", {}).get("profile", {}).get("email")
+ slack_team_id = integration.integration_id
+
+ # Linked-user path: when the user has bound their Slack identity to a
+ # PostHog account via the OAuth link flow, we resolve directly without
+ # paying for users.info / email matching. Falls through to the email
+ # path on miss so this stays additive — a workspace with no links
+ # behaves exactly like before.
+ #
+ # The link lookup runs FIRST (two cheap indexed queries) and the flag
+ # check only fires when a row is found, and on the email-mismatch
+ # failure branch below to decide whether to offer the invite button.
+ # Both checks are local-evaluation only (`only_evaluate_locally=True`),
+ # so calling twice on the rare both-branches path is essentially free.
+ linked_user = find_linked_posthog_user(
+ slack_user_id=slack_user_id,
+ slack_team_id=slack_team_id,
+ candidate_org_ids={integration.team.organization_id},
+ )
+
+ if linked_user is not None and slack_oauth_link_enabled(integration, slack_team_id):
+ user_permissions = UserPermissions(user=linked_user, team=integration.team)
+ if user_permissions.current_team.effective_membership_level is None:
+ logger.warning(
+ "slack_app_linked_user_no_team_access",
+ user_id=linked_user.id,
+ team_id=integration.team_id,
+ slack_user_id=slack_user_id,
+ )
+ if post_feedback:
+ _post_slack_user_feedback(
+ slack,
+ channel,
+ slack_user_id,
+ thread_ts,
+ (
+ "Sorry, you don't have access to the PostHog project connected to this Slack workspace. "
+ "Please ask an admin of your PostHog organization to grant you access."
+ ),
+ )
+ return None
+ return SlackUserContext(user=linked_user, slack_email=None)
+
+ slack_email = get_slack_email_for_user(integration, slack_user_id)
+ if settings.DEBUG:
+ # Local dev: match the seeded test fixture user regardless of what
+ # Slack returns. Applied here rather than in the shared helper so
+ # other callers (e.g. `resolve_posthog_user_from_event` from the
+ # channel-approval path) can still drive the helper with stubbed
+ # Slack responses in tests.
+ slack_email = "[email protected]"
if not slack_email:
logger.exception("slack_app_no_user_email", slack_user_id=slack_user_id)
@@ -289,10 +341,6 @@ def resolve_slack_user(
)
return None
- if settings.DEBUG:
- # When running locally - match the local user
- slack_email = "[email protected]"
-
# Trust model: Slack signature validation proves the payload is authentic.
# The email comes from Slack's `users.info` API via `users:read.email` scope, not from
# user-supplied input. Slack verifies emails at workspace sign-up, and admins control
@@ -307,6 +355,15 @@ def resolve_slack_user(
if not membership or not membership.user:
organization_name = integration.team.organization.name
if post_feedback:
+ # Two messages by design, with distinct audiences:
+ #
+ # * The text reply goes into the thread (`prefer_thread_message=True`)
+ # so other channel members can see why the bot stayed silent on
+ # this mention. Without it, the channel reads as if the mention
+ # was simply ignored.
+ # * The invite-button message is ephemeral — only the affected
+ # user sees the recovery affordance. Posting the button into
+ # the public thread would be noise for everyone else.
_post_slack_user_feedback(
slack,
channel,
@@ -318,6 +375,22 @@ def resolve_slack_user(
),
prefer_thread_message=True,
)
+ if slack_oauth_link_enabled(integration, slack_team_id):
+ invite_url = build_invite_url(
+ slack_user_id=slack_user_id,
+ slack_team_id=slack_team_id,
+ posthog_team_id=integration.team_id,
+ channel=channel,
+ thread_ts=thread_ts,
+ )
+ post_link_invite_message(
+ slack_client=slack.client,
+ channel=channel,
+ slack_user_id=slack_user_id,
+ thread_ts=thread_ts,
+ slack_email=slack_email,
+ invite_url=invite_url,
+ )
return None
posthog_user = membership.user
@@ -1212,13 +1285,27 @@ def resolve_posthog_user_from_event(
``slack_email`` may be passed by callers that already have it (e.g.
``resolve_user_and_integrations``) so we don't repeat the cache lookup.
"""
+ org_ids = {c.team.organization_id for c in candidate_integrations}
+ if not org_ids:
+ return None
+
+ # Linked-user path: short-circuit the email match when the user has bound
+ # their Slack identity to a PostHog account. The cheap indexed lookup
+ # runs first; the feature-flag gate only fires when a row is found so
+ # workspaces with no linked users don't pay for the flag evaluation.
+ slack_team_id = probe_integration.integration_id
+ linked_user = find_linked_posthog_user(
+ slack_user_id=slack_user_id,
+ slack_team_id=slack_team_id,
+ candidate_org_ids=org_ids,
+ )
+ if linked_user is not None and slack_oauth_link_enabled(probe_integration, slack_team_id):
+ return linked_user
+
if slack_email is None:
slack_email = get_slack_email_for_user(probe_integration, slack_user_id)
if not slack_email:
return None
- org_ids = {c.team.organization_id for c in candidate_integrations}
- if not org_ids:
- return None
try:
membership = (
OrganizationMembership.objects.filter(organization_id__in=org_ids, user__email__iexact=slack_email)
@@ -1287,9 +1374,29 @@ def _post_user_resolution_failure_reply(
text = user_resolution_failure_reply(failure_reason, slack_email=slack_email)
if text is None:
return
- _post_slack_user_feedback(
- SlackIntegration(probe), channel, slack_user_id, thread_ts, text, prefer_thread_message=True
- )
+ slack_client = SlackIntegration(probe)
+ # The text reply lands in the thread so the rest of the channel knows why
+ # the bot stayed silent. The invite button is a separate ephemeral, visible
+ # only to the affected user — both messages have distinct audiences and
+ # neither is redundant. Only `user_not_found` is link-recoverable;
+ # `no_team_access` means the user *is* known but lacks project access.
+ _post_slack_user_feedback(slack_client, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)
+ if failure_reason == "user_not_found" and slack_oauth_link_enabled(probe, probe.integration_id):
+ invite_url = build_invite_url(
+ slack_user_id=slack_user_id,
+ slack_team_id=probe.integration_id,
+ posthog_team_id=probe.team_id,
+ channel=channel,
+ thread_ts=thread_ts,
+ )
+ post_link_invite_message(
+ slack_client=slack_client.client,
+ channel=channel,
+ slack_user_id=slack_user_id,
+ thread_ts=thread_ts,
+ slack_email=slack_email,
+ invite_url=invite_url,
+ )
def _start_posthog_code_workflow(
diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.py
new file mode 100644
index 000000000000..67bdb176fdef
--- /dev/null
+++ b/products/slack_app/backend/feature_flags.py
@@ -0,0 +1,55 @@
+"""Feature-flag checks for the Slack app backend.
+
+One module per flag-check function, so flag rollouts are easy to find and
+audit. Every check here is fail-closed: a flaky ``posthoganalytics.feature_enabled``
+call must not silently enable a feature for everyone.
+"""
+
+import structlog
+import posthoganalytics
+
+from posthog.models.integration import Integration
+from posthog.utils import get_instance_region
+
+logger = structlog.get_logger(__name__)
+
+
+SLACK_APP_OAUTH_FLAG = "slack-app-oauth"
+
+
+def slack_oauth_link_enabled(integration: Integration, slack_team_id: str) -> bool:
+ """Gate for the Slack user-identity OAuth link feature, covering both
+ backend (offering the invite button, accepting the link callback,
+ listing/starting from settings) and frontend (rendering the Slack card
+ in Personal integrations) decisions.
+
+ Evaluated against the workspace's PostHog organization so we can roll
+ out org-by-org, with the deployment region carried as a person property
+ so a flag rule like ``region equals US`` targets a single Cloud region.
+
+ Fail-closed on any error: a flaky feature-flag check must not silently
+ enable the feature for everyone.
+ """
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ SLACK_APP_OAUTH_FLAG,
+ f"slack_workspace:{slack_team_id}",
+ groups={"organization": str(integration.team.organization_id)},
+ person_properties={"region": get_instance_region() or "unknown"},
+ # Hot path: every inbound Slack event (every @mention, link_shared,
+ # message-in-watched-channel) hits this. Local evaluation avoids a
+ # synchronous HTTPS call to PostHog's `decide` endpoint that would
+ # compete with Slack's 3s webhook ack deadline. The org-level rules
+ # and region person-property all evaluate fine locally.
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ logger.exception(
+ "slack_app_user_link_feature_flag_check_failed",
+ slack_team_id=slack_team_id,
+ integration_id=integration.id,
+ )
+ return False
diff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.py
index 2470aa381c3b..a13732af6e8d 100644
--- a/products/slack_app/backend/services/integration_resolver.py
+++ b/products/slack_app/backend/services/integration_resolver.py
@@ -1,7 +1,6 @@
from dataclasses import dataclass, field
from typing import Literal
-from django.conf import settings
from django.db.models import Q
import structlog
@@ -235,23 +234,19 @@ def resolve_user_for_workspace(
)
return UserAndIntegrationsResolution(failure_reason="user_not_found")
- # Look the Slack email up once and pass it through so the user resolver
- # doesn't repeat the cache hit and so the routing layer can mention it in
- # the user-facing failure reply.
probe = workspace_result.candidates[0]
- slack_email = get_slack_email_for_user(probe, slack_user_id)
-
- if settings.DEBUG:
- # When running locally - match the local user
- slack_email = "[email protected]"
+ # Pass slack_email=None so the linked-user path short-circuits before
+ # users.info; the resolver fetches lazily on the email-fallback branch.
+ # Re-fetch on the failure branches below is a cache hit.
posthog_user = resolve_posthog_user_from_event(
slack_user_id=slack_user_id,
probe_integration=probe,
candidate_integrations=workspace_result.candidates,
- slack_email=slack_email,
+ slack_email=None,
)
if posthog_user is None:
+ slack_email = get_slack_email_for_user(probe, slack_user_id)
logger.warning(
"slack_app_no_integration_found",
reason="user_not_found",
@@ -275,6 +270,9 @@ def resolve_user_for_workspace(
]
accessible_team_ids = {c.team_id for c in accessible_candidates}
if not accessible_candidates:
+ # Fetch slack_email lazily for the failure reply (cached after the
+ # earlier resolve_posthog_user_from_event call, so this is free).
+ slack_email = get_slack_email_for_user(probe, slack_user_id)
logger.warning(
"slack_app_no_integration_found",
reason="no_team_access",
diff --git a/products/slack_app/backend/services/slack_user_oauth.py b/products/slack_app/backend/services/slack_user_oauth.py
new file mode 100644
index 000000000000..85baf17063e5
--- /dev/null
+++ b/products/slack_app/backend/services/slack_user_oauth.py
@@ -0,0 +1,427 @@
+"""Slack user-identity OAuth + linked-user resolution.
+
+Single home for the whole user-link feature surface:
+
+* Feature flag check + linked-user lookup, used by inbound event resolvers
+ (``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.
+* 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.
+"""
+
+from typing import Any
+from urllib.parse import urlencode
+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 posthog.models.instance_setting import get_instance_settings
+from posthog.models.organization import OrganizationMembership
+from posthog.models.user import User
+from posthog.models.user_integration import UserIntegration
+
+logger = structlog.get_logger(__name__)
+
+
+def find_linked_posthog_user(
+ *,
+ slack_user_id: str,
+ slack_team_id: str,
+ candidate_org_ids: set[UUID],
+) -> User | None:
+ """Return the PostHog ``User`` linked to this Slack identity, scoped to the
+ organizations connected to this workspace.
+
+ Multiple PostHog users may legitimately link to the same Slack identity
+ (e.g. one Slack account → personal + work PostHog accounts). When more
+ than one matching row passes the org-scope check, we return the
+ **most-recently-linked** one — they just authenticated, presumably with
+ intent — and emit a warn-log so the rare collision is visible in prod.
+
+ Returns ``None`` when no link exists or none of the linked users are
+ members of a connected org. Caller still owns the access-level
+ (``effective_membership_level``) check on the resolved user.
+ """
+ if not slack_user_id or not slack_team_id or not candidate_org_ids:
+ return None
+ # Split the lookup into two queries — the JSON match on `UserIntegration`
+ # followed by an org-membership check — instead of a single cross-table
+ # join. The chained `user__organization_memberships__organization_id__in`
+ # lookup gets rejected by Django when one of the joined models lives on
+ # a different database (which `User` does in PostHog's deployment), so a
+ # straight-line equivalent keeps the query portable across routers.
+ try:
+ links = list(
+ UserIntegration.objects.filter(
+ kind=UserIntegration.IntegrationKind.SLACK,
+ integration_id=slack_user_id,
+ config__slack_team_id=slack_team_id,
+ )
+ .select_related("user")
+ .order_by("-created_at")
+ )
+ if not links:
+ return None
+ # Org-scope filter as a set lookup so we keep the per-row iteration
+ # below in stable most-recent-first order without a second per-row query.
+ user_ids = [link.user_id for link in links if link.user is not None]
+ accessible_user_ids = set(
+ OrganizationMembership.objects.filter(
+ user_id__in=user_ids, organization_id__in=candidate_org_ids
+ ).values_list("user_id", flat=True)
+ )
+ if not accessible_user_ids:
+ return None
+ if len(links) > 1:
+ # Telemetry for the multi-link ambiguity case. Picking
+ # most-recent is deliberate but it's worth seeing how often
+ # this fires — if it's common, the linking flow needs harder
+ # guard rails (or a DB-level partial unique constraint).
+ logger.warning(
+ "slack_app_user_link_multiple_matches",
+ slack_user_id=slack_user_id,
+ slack_team_id=slack_team_id,
+ link_count=len(links),
+ accessible_count=len(accessible_user_ids),
+ )
+ for link in links:
+ if link.user_id in accessible_user_ids:
+ return link.user
+ return None
+ except Exception:
+ logger.warning(
+ "slack_app_user_link_lookup_failed",
+ slack_user_id=slack_user_id,
+ slack_team_id=slack_team_id,
+ exc_info=True,
+ )
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Signed-state Pydantic models
+# ---------------------------------------------------------------------------
+
+# Short-lived invite tokens carry the Slack-side context (user id, workspace,
+# thread) to the PostHog authorize view; longer would let the same Slack DM
+# be replayed by anyone who scrapes it from a forwarded message.
+INVITE_TOKEN_SALT = "slack_user_link_invite"
+INVITE_TOKEN_MAX_AGE_SECONDS = 15 * 60
+
+# Distinct salt from the invite token: an invite leaked from a Slack DM must
+# not be replayable as a callback state.
+CALLBACK_STATE_SALT = "slack_user_link_oauth"
+CALLBACK_STATE_MAX_AGE_SECONDS = 15 * 60
+
+
+class InviteToken(BaseModel):
+ """Slack-side invite payload signed into the URL on the "Link my PostHog
+ account" button. Decoded by the authorize view to learn which workspace
+ to link against and how to get the user back to the right Slack thread
+ after the OAuth dance.
+
+ ``slack_user_id`` is only present on Slack-DM-initiated invites (we knew
+ who triggered the matching failure). Settings-initiated invites omit it
+ because the user hasn't authenticated to Slack yet — we'll learn their
+ identity only from the OAuth callback.
+ """
+
+ slack_team_id: str
+ posthog_team_id: int
+ slack_user_id: str | None = None
+ channel: str | None = None
+ thread_ts: str | None = None
+
+ def encode(self) -> str:
+ return signing.dumps(self.model_dump(exclude_none=True), salt=INVITE_TOKEN_SALT, compress=True)
+
+ @classmethod
+ def decode(cls, token: str) -> "InviteToken | None":
+ """Return ``None`` on bad signature, expiry, or schema mismatch so
+ callers can render a friendly error instead of throwing."""
+ try:
+ payload = signing.loads(token, salt=INVITE_TOKEN_SALT, max_age=INVITE_TOKEN_MAX_AGE_SECONDS)
+ except (signing.BadSignature, signing.SignatureExpired):
+ return None
+ if not isinstance(payload, dict):
+ return None
+ try:
+ return cls.model_validate(payload)
+ except ValidationError:
+ return None
+
+
+class CallbackState(BaseModel):
+ """State we round-trip through Slack's authorize endpoint. Carries the
+ invite context plus the PostHog user who started the flow, so the
+ callback can attribute the link to the right account even if the user
+ swaps browsers mid-flow.
+ """
+
+ slack_team_id: str
+ posthog_team_id: int
+ posthog_user_id: int
+ slack_user_id: str | None = None
+ channel: str | None = None
+ thread_ts: str | None = None
+
+ def encode(self) -> str:
+ return signing.dumps(self.model_dump(exclude_none=True), salt=CALLBACK_STATE_SALT, compress=True)
+
+ @classmethod
+ def decode(cls, token: str) -> "CallbackState | None":
+ try:
+ payload = signing.loads(token, salt=CALLBACK_STATE_SALT, max_age=CALLBACK_STATE_MAX_AGE_SECONDS)
+ except (signing.BadSignature, signing.SignatureExpired):
+ return None
+ if not isinstance(payload, dict):
+ return None
+ try:
+ return cls.model_validate(payload)
+ except ValidationError:
+ return None
+
+
+def build_invite_url(
+ *,
+ slack_user_id: str | None,
+ slack_team_id: str,
+ posthog_team_id: int,
+ channel: str | None,
+ thread_ts: str | None,
+) -> str:
+ """Full https URL the Slack button opens. Routes through PostHog's
+ ``SITE_URL`` so a workspace in a region different from the one that
+ received the event still lands on the right instance after the proxy.
+ """
+ token = InviteToken(
+ slack_team_id=slack_team_id,
+ posthog_team_id=posthog_team_id,
+ slack_user_id=slack_user_id,
+ channel=channel,
+ thread_ts=thread_ts,
+ ).encode()
+ base = settings.SITE_URL.rstrip("/")
+ return f"{base}/complete/slack-link/start/?{urlencode({'state': token})}"
+
+
+# ---------------------------------------------------------------------------
+# Sign-in-with-Slack OAuth flow
+# ---------------------------------------------------------------------------
+
+SLACK_AUTHORIZE_URL = "https://slack.com/oauth/v2/authorize"
+SLACK_TOKEN_URL = "https://slack.com/api/oauth.v2.access"
+
+# `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"
+
+
+class SlackUserOAuthError(Exception):
+ """Raised when the OAuth exchange or identity fetch fails. The view
+ catches this and redirects back to settings with an error param."""
+
+
+class SlackIdentity(BaseModel):
+ """Result of ``oauth.v2.access`` + ``users.identity`` for the user flow.
+
+ ``user_refresh_token`` is only populated when the Slack app has
+ ``token_rotation_enabled``; with rotation off (today) Slack omits the
+ field from the OAuth response. Capturing it defensively means the
+ callback shape doesn't change the day rotation gets flipped on.
+ """
+
+ slack_user_id: str
+ slack_team_id: str
+ slack_team_name: str | None = None
+ slack_email: str | None = None
+ user_access_token: str
+ user_refresh_token: str | None = None
+
+
+def _credentials() -> tuple[str, str]:
+ """Resolve Slack app credentials at call time so dev/test overrides via
+ instance settings work the same way the workspace install flow does.
+ """
+ from_settings = get_instance_settings(["SLACK_APP_CLIENT_ID", "SLACK_APP_CLIENT_SECRET"])
+ client_id = from_settings.get("SLACK_APP_CLIENT_ID") or ""
+ client_secret = from_settings.get("SLACK_APP_CLIENT_SECRET") or ""
+ if not client_id or not client_secret:
+ raise SlackUserOAuthError("Slack app credentials not configured")
+ return client_id, client_secret
+
+
+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.
+ """
+ client_id, _ = _credentials()
+ params = {
+ "client_id": client_id,
+ "user_scope": USER_IDENTITY_SCOPES,
+ "scope": "",
+ "redirect_uri": redirect_uri,
+ "state": state,
+ }
+ return f"{SLACK_AUTHORIZE_URL}?{urlencode(params)}"
+
+
+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.
+
+ ``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,
+ )
+ 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')}")
+
+ authed_user = payload.get("authed_user") or {}
+ user_token = authed_user.get("access_token")
+ if not user_token:
+ raise SlackUserOAuthError("Slack OAuth response missing authed_user.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()
+ 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")
+ if not slack_user_id or not slack_team_id:
+ raise SlackUserOAuthError("Slack identity response missing user.id 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"),
+ 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"),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Slack-side invite message
+# ---------------------------------------------------------------------------
+
+
+def post_link_invite_message(
+ *,
+ slack_client: WebClient,
+ channel: str,
+ slack_user_id: str,
+ thread_ts: str | None,
+ slack_email: str | None,
+ invite_url: str,
+) -> None:
+ """Post an ephemeral Block Kit message inviting the user to link their
+ PostHog account. Visible only to ``slack_user_id``.
+
+ The wording is intentionally minimal — a separate public thread reply
+ already diagnoses the matching failure for the rest of the channel, and
+ this message's only job is to surface the one-click recovery affordance
+ to the affected user. Repeating the diagnosis here would just clutter
+ their view.
+
+ Slack's ``url``-bearing buttons require no interactivity handler — clicks
+ open the link in the user's browser and the OAuth dance proceeds without
+ another round-trip to PostHog. Failures here are logged and swallowed:
+ the public text reply has already informed the channel about the
+ matching failure, so a button-post failure must not double-up a second
+ visible error.
+ """
+ # `slack_email` is intentionally not interpolated into the body — the
+ # public thread reply already names the address PostHog tried to match.
+ del slack_email
+ fallback_text = "Link your PostHog account to fix this for future mentions."
+ blocks: list[dict[str, Any]] = [
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": f"👉 {fallback_text}",
+ },
+ },
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": "Link my PostHog account"},
+ "style": "primary",
+ "url": invite_url,
+ }
+ ],
+ },
+ ]
+ try:
+ slack_client.chat_postEphemeral(
+ channel=channel,
+ user=slack_user_id,
+ thread_ts=thread_ts,
+ text=fallback_text,
+ blocks=blocks,
+ )
+ except Exception:
+ logger.warning(
+ "slack_app_user_link_invite_post_failed",
+ channel=channel,
+ slack_user_id=slack_user_id,
+ exc_info=True,
+ )
diff --git a/products/slack_app/backend/tests/conftest.py b/products/slack_app/backend/tests/conftest.py
index b57421ae7a6e..ae61b3c97cfc 100644
--- a/products/slack_app/backend/tests/conftest.py
+++ b/products/slack_app/backend/tests/conftest.py
@@ -1,23 +1,41 @@
"""Shared fixtures for slack_app backend tests.
-The resolver's ``load_integrations`` now eagerly runs Slack ``auth.test`` on
-cache miss (see ``services/slack_auth.check_integrations_auth_and_filter``).
-Without intervention, every test that constructs an ``Integration`` row but
-doesn't patch the Slack SDK ends up making the resolver try a real Slack call
-with a fake token, which fails, drops the candidate, and breaks downstream
-routing assertions in ways that have nothing to do with what the test is
-actually checking.
-
-This conftest neutralizes that for the whole package: by default, the
-auth-state filter is a pass-through. Tests that actually want to exercise
-the filter (``test_slack_auth.py``, ``TestLoadIntegrationsAuthStateFilter``)
-opt back in by overriding the fixture or asserting against the real flow
-behind a local patch.
+Combines two unrelated concerns that both want module-level conftest scope:
+
+1) ``_bypass_slack_auth_filter`` (autouse): the resolver's ``load_integrations``
+ now eagerly runs Slack ``auth.test`` on cache miss (see
+ ``services/slack_auth.check_integrations_auth_and_filter``). Without
+ intervention, every test that constructs an ``Integration`` row but doesn't
+ patch the Slack SDK ends up making the resolver try a real Slack call with
+ a fake token, which fails, drops the candidate, and breaks downstream
+ routing assertions in ways that have nothing to do with what the test is
+ actually checking. This fixture turns the filter into a pass-through for
+ the whole package; tests that actually want to exercise the filter
+ (``test_slack_auth.py``, ``TestLoadIntegrationsAuthStateFilter``) opt back
+ in by patching at the module the resolver imports from.
+
+2) User-link fixtures (``org_team_user``, ``workspace_integration``,
+ ``link_user``): scoped to the user-OAuth-link feature. Tests under
+ ``tests/services/`` and ``tests/views/`` both consume them via pytest's
+ conftest autodiscovery, so the same fixture identity flows across the two
+ files that exercise the inbound resolver and the OAuth callback views.
"""
+from typing import Any
+
import pytest
from unittest.mock import patch
+from posthog.models.integration import Integration
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.team.team import Team
+from posthog.models.user import User
+from posthog.models.user_integration import user_slack_integration_from_identity
+
+SLACK_TEAM_ID = "T12345"
+SLACK_USER_ID = "U999"
+SLACK_USER_ACCESS_TOKEN = "xoxp-user-test"
+
@pytest.fixture(autouse=True)
def _bypass_slack_auth_filter():
@@ -45,3 +63,47 @@ def _bypass_slack_auth_filter():
side_effect=lambda candidates, **_: candidates,
):
yield
+
+
+def org_team_user(db):
+ org = Organization.objects.create(name="Test Org")
+ team = Team.objects.create(organization=org, name="Test Team")
+ user = User.objects.create(email="[email protected]", distinct_id="user-1")
+ OrganizationMembership.objects.create(user=user, organization=org)
+ return org, team, user
+
+
+def workspace_integration(org_team_user):
+ _, team, _ = org_team_user
+ return Integration.objects.create(
+ team=team,
+ kind="slack",
+ integration_id=SLACK_TEAM_ID,
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+
+
+def link_user():
+ """Returns a callable that creates a Slack ``UserIntegration`` link with
+ sensible defaults so individual tests can stay focused on the slack_user_id
+ / team_id / org-scoping behavior they actually want to exercise.
+ """
+
+ def _link(user, **overrides):
+ # `dict[str, Any]` so the optional `slack_team_name` / `slack_email_at_link`
+ # entries (which carry `None`) don't narrow the union value type and break
+ # the keyword-arg type check on `user_slack_integration_from_identity`.
+ defaults: dict[str, Any] = {
+ "slack_user_id": SLACK_USER_ID,
+ "slack_team_id": SLACK_TEAM_ID,
+ "slack_team_name": None,
+ "slack_email_at_link": None,
+ "user_access_token": SLACK_USER_ACCESS_TOKEN,
+ }
+ defaults.update(overrides)
+ return user_slack_integration_from_identity(user, **defaults)
+
+ return _link
diff --git a/products/slack_app/backend/tests/services/__init__.py b/products/slack_app/backend/tests/services/__init__.py
index e69de29bb2d1..f9ce6811f29a 100644
--- a/products/slack_app/backend/tests/services/__init__.py
+++ b/products/slack_app/backend/tests/services/__init__.py
@@ -0,0 +1 @@
+"""Tests for ``products.slack_app.backend.services.*`` modules."""
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
new file mode 100644
index 000000000000..3009c83333ff
--- /dev/null
+++ b/products/slack_app/backend/tests/services/test_slack_user_oauth.py
@@ -0,0 +1,333 @@
+"""Tests for ``products.slack_app.backend.services.slack_user_oauth``.
+
+Covers the linked-user resolver, the Pydantic state models that flow through
+Slack's OAuth redirects, and the ``resolve_slack_user`` integration in
+``products.slack_app.backend.api`` that consumes them. Shared fixtures
+(``org_team_user``, ``workspace_integration``, ``link_user``) come from
+``conftest.py`` one level up.
+"""
+
+from uuid import uuid4
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.models.integration import SlackIntegration
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.user import User
+from posthog.models.user_integration import UserIntegration
+
+from products.slack_app.backend.api import resolve_slack_user
+from products.slack_app.backend.services.slack_user_oauth import (
+ CallbackState,
+ InviteToken,
+ build_invite_url,
+ find_linked_posthog_user,
+)
+from products.slack_app.backend.tests.conftest import SLACK_TEAM_ID, SLACK_USER_ID
+
+
+class TestFindLinkedPosthogUser:
+ def test_returns_linked_user_when_scoped_org_matches(self, org_team_user, link_user):
+ org, _, user = org_team_user
+ link_user(user, slack_team_name="Test Workspace", slack_email_at_link="[email protected]")
+ found = find_linked_posthog_user(
+ slack_user_id=SLACK_USER_ID, slack_team_id=SLACK_TEAM_ID, candidate_org_ids={org.id}
+ )
+ assert found is not None
+ assert found.id == user.id
+
+ def test_returns_none_when_team_id_does_not_match(self, org_team_user, link_user):
+ org, _, user = org_team_user
+ link_user(user)
+ assert (
+ find_linked_posthog_user(slack_user_id=SLACK_USER_ID, slack_team_id="T-OTHER", candidate_org_ids={org.id})
+ is None
+ )
+
+ def test_returns_none_when_user_is_in_different_org(self, org_team_user, link_user):
+ _, _, user = org_team_user
+ link_user(user)
+ other_org = Organization.objects.create(name="Unrelated")
+ assert (
+ find_linked_posthog_user(
+ slack_user_id=SLACK_USER_ID, slack_team_id=SLACK_TEAM_ID, candidate_org_ids={other_org.id}
+ )
+ is None
+ )
+
+ def test_returns_none_when_no_link_exists(self, org_team_user):
+ org, _, _ = org_team_user
+ assert (
+ find_linked_posthog_user(
+ slack_user_id=SLACK_USER_ID, slack_team_id=SLACK_TEAM_ID, candidate_org_ids={org.id}
+ )
+ is None
+ )
+
+ def test_empty_inputs_return_none(self):
+ # Use a sentinel UUID for the non-empty-set arg since the function
+ # signature is `set[UUID]`; the value is never looked up because the
+ # early-return guards on empty slack_user_id / slack_team_id fire first.
+ sentinel_org_id = uuid4()
+ assert (
+ find_linked_posthog_user(slack_user_id="", slack_team_id=SLACK_TEAM_ID, candidate_org_ids={sentinel_org_id})
+ is None
+ )
+ assert (
+ find_linked_posthog_user(slack_user_id=SLACK_USER_ID, slack_team_id="", candidate_org_ids={sentinel_org_id})
+ is None
+ )
+ assert (
+ find_linked_posthog_user(slack_user_id=SLACK_USER_ID, slack_team_id=SLACK_TEAM_ID, candidate_org_ids=set())
+ is None
+ )
+
+ def test_multiple_linked_users_returns_most_recent_accessible(self, org_team_user, link_user):
+ org, _, first_user = org_team_user
+ # Two PostHog accounts in the same org, both linked to the same Slack identity.
+ # The DB allows this; the resolver tiebreaks deterministically on
+ # `-created_at` (most recently linked wins).
+ second_user = User.objects.create(email="[email protected]", distinct_id="user-2")
+ OrganizationMembership.objects.create(user=second_user, organization=org)
+ link_user(first_user)
+ link_user(second_user)
+
+ found = find_linked_posthog_user(
+ slack_user_id=SLACK_USER_ID, slack_team_id=SLACK_TEAM_ID, candidate_org_ids={org.id}
+ )
+ assert found is not None
+ assert found.id == second_user.id
+
+ def test_most_recent_link_skipped_when_user_lacks_org_membership(self, org_team_user, link_user):
+ org, _, first_user = org_team_user
+ # `first_user` is in `org`; `second_user` is in `unrelated_org`. With
+ # candidate_org_ids={org.id}, only `first_user` qualifies even though
+ # `second_user` linked more recently. Resolver must walk past the
+ # most-recent link rather than refusing to match.
+ unrelated_org = Organization.objects.create(name="Unrelated")
+ second_user = User.objects.create(email="[email protected]", distinct_id="user-2")
+ OrganizationMembership.objects.create(user=second_user, organization=unrelated_org)
+ link_user(first_user)
+ link_user(second_user)
+
+ found = find_linked_posthog_user(
+ slack_user_id=SLACK_USER_ID, slack_team_id=SLACK_TEAM_ID, candidate_org_ids={org.id}
+ )
+ assert found is not None
+ assert found.id == first_user.id
+
+
+class TestUserSlackIntegrationFromIdentity:
+ """Tests for the model factory that the OAuth callback hands off to.
+
+ Lives with the service tests because the factory is tightly coupled to
+ the OAuth-flow output shape (``SlackIdentity`` fields → ``UserIntegration``
+ row), even though the function itself is defined under ``posthog.models``.
+ """
+
+ def test_creates_row_with_stored_user_token(self, org_team_user, link_user):
+ _, _, user = org_team_user
+ integration = link_user(
+ user,
+ slack_team_name="Workspace",
+ slack_email_at_link="[email protected]",
+ user_access_token="xoxp-fresh",
+ )
+ assert integration.kind == UserIntegration.IntegrationKind.SLACK
+ assert integration.integration_id == SLACK_USER_ID
+ assert integration.config["slack_team_id"] == SLACK_TEAM_ID
+ assert integration.config["slack_team_name"] == "Workspace"
+ assert integration.config["slack_email_at_link"] == "[email protected]"
+ # Token persisted in symmetry with the GitHub personal flow — future
+ # "act as user" scopes can reuse it without a fresh OAuth consent.
+ assert integration.sensitive_config == {"user_access_token": "xoxp-fresh"}
+
+ def test_update_refreshes_token_in_place(self, org_team_user, link_user):
+ _, _, user = org_team_user
+ first = link_user(user, slack_team_name="Old name", user_access_token="xoxp-1")
+ second = link_user(
+ user,
+ slack_team_name="New name",
+ slack_email_at_link="[email protected]",
+ user_access_token="xoxp-2",
+ )
+ assert first.id == second.id
+ assert second.config["slack_team_name"] == "New name"
+ assert second.sensitive_config == {"user_access_token": "xoxp-2"}
+
+
+class TestResolveSlackUserWithLink:
+ """Integration of ``api.resolve_slack_user`` with the linked-user lookup.
+
+ Lives here rather than in ``tests/test_resolve_slack_user.py`` because the
+ behavior under test is owned by the user-link service — the resolver just
+ delegates the lookup to it.
+ """
+
+ @patch("posthog.models.integration.WebClient")
+ @patch("products.slack_app.backend.api.slack_oauth_link_enabled")
+ def test_flag_off_falls_through_to_email_path_unchanged(
+ self, mock_flag, mock_webclient_class, org_team_user, workspace_integration, link_user
+ ):
+ _, _, user = org_team_user
+ # Even with a link row present, flag-off behavior must not consult it.
+ link_user(user)
+ mock_flag.return_value = False
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.users_info.return_value = {"user": {"profile": {"email": "[email protected]"}}}
+
+ result = resolve_slack_user(
+ SlackIntegration(workspace_integration), workspace_integration, SLACK_USER_ID, "C001", "1234.5"
+ )
+
+ assert result is not None
+ # users.info IS called — confirms email path ran.
+ assert mock_client.users_info.called
+ assert result.slack_email == "[email protected]"
+
+ @patch("posthog.models.integration.WebClient")
+ @patch("products.slack_app.backend.api.slack_oauth_link_enabled")
+ def test_flag_on_with_link_short_circuits_email_lookup(
+ self, mock_flag, mock_webclient_class, org_team_user, workspace_integration, link_user
+ ):
+ _, _, user = org_team_user
+ link_user(user)
+ mock_flag.return_value = True
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+
+ result = resolve_slack_user(
+ SlackIntegration(workspace_integration), workspace_integration, SLACK_USER_ID, "C001", "1234.5"
+ )
+
+ assert result is not None
+ assert result.user.id == user.id
+ # The whole point: no Slack API hit when a link exists.
+ mock_client.users_info.assert_not_called()
+ # And the contract: slack_email is None on the linked path.
+ assert result.slack_email is None
+
+ # `test_flag_on_with_link_but_no_team_access_returns_none` lives at
+ # `tests/test_zz_resolve_slack_user_with_link_no_access.py` — see that
+ # file's module docstring for why it can't live next to its siblings here.
+
+ @patch("posthog.models.integration.WebClient")
+ @patch("products.slack_app.backend.api.post_link_invite_message")
+ @patch("products.slack_app.backend.api.slack_oauth_link_enabled")
+ def test_flag_on_with_no_link_and_no_membership_posts_invite(
+ self,
+ mock_flag,
+ mock_post_invite,
+ mock_webclient_class,
+ org_team_user,
+ workspace_integration,
+ ):
+ mock_flag.return_value = True
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.users_info.return_value = {"user": {"profile": {"email": "[email protected]"}}}
+
+ with patch("products.slack_app.backend.api.settings") as mock_settings:
+ mock_settings.DEBUG = False
+ result = resolve_slack_user(
+ SlackIntegration(workspace_integration),
+ workspace_integration,
+ SLACK_USER_ID,
+ "C001",
+ "1234.5",
+ )
+
+ assert result is None
+ # Two messages by design: a public thread reply explaining the failure
+ # to the rest of the channel, plus an ephemeral button visible only
+ # to the affected user. Confirming both fire — neither is redundant
+ # because their audiences differ.
+ assert mock_client.chat_postMessage.called or mock_client.chat_postEphemeral.called
+ mock_post_invite.assert_called_once()
+ invite_kwargs = mock_post_invite.call_args.kwargs
+ assert invite_kwargs["slack_user_id"] == SLACK_USER_ID
+ assert invite_kwargs["slack_email"] == "[email protected]"
+ assert invite_kwargs["invite_url"].startswith("http")
+
+ @patch("posthog.models.integration.WebClient")
+ @patch("products.slack_app.backend.api.post_link_invite_message")
+ @patch("products.slack_app.backend.api.slack_oauth_link_enabled")
+ def test_flag_off_with_no_membership_does_not_post_invite(
+ self,
+ mock_flag,
+ mock_post_invite,
+ mock_webclient_class,
+ org_team_user,
+ workspace_integration,
+ ):
+ mock_flag.return_value = False
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.users_info.return_value = {"user": {"profile": {"email": "[email protected]"}}}
+
+ with patch("products.slack_app.backend.api.settings") as mock_settings:
+ mock_settings.DEBUG = False
+ result = resolve_slack_user(
+ SlackIntegration(workspace_integration),
+ workspace_integration,
+ SLACK_USER_ID,
+ "C001",
+ "1234.5",
+ )
+
+ assert result is None
+ mock_post_invite.assert_not_called()
+
+
[email protected]_db(transaction=False)
+class TestInviteToken:
+ def test_round_trips(self):
+ original = InviteToken(
+ slack_user_id=SLACK_USER_ID,
+ slack_team_id=SLACK_TEAM_ID,
+ posthog_team_id=42,
+ channel="C001",
+ thread_ts="1.2",
+ )
+ decoded = InviteToken.decode(original.encode())
+ assert decoded == original
+
+ def test_settings_initiated_invite_omits_slack_user_id(self):
+ original = InviteToken(slack_team_id=SLACK_TEAM_ID, posthog_team_id=42)
+ decoded = InviteToken.decode(original.encode())
+ assert decoded is not None
+ assert decoded.slack_user_id is None
+ assert decoded.channel is None
+
+ def test_rejects_tampered_token(self):
+ token = InviteToken(slack_team_id=SLACK_TEAM_ID, posthog_team_id=42).encode()
+ assert InviteToken.decode(token + "x") is None
+
+ def test_rejects_callback_state_signed_with_other_salt(self):
+ # A callback state must not satisfy the invite check (cross-salt).
+ callback_state = CallbackState(slack_team_id="T1", posthog_team_id=1, posthog_user_id=99).encode()
+ assert InviteToken.decode(callback_state) is None
+
+ def test_invite_url_contains_signed_state(self):
+ url = build_invite_url(
+ slack_user_id=SLACK_USER_ID,
+ slack_team_id=SLACK_TEAM_ID,
+ posthog_team_id=42,
+ channel=None,
+ thread_ts=None,
+ )
+ assert "/complete/slack-link/start/?state=" in url
+
+
+class TestCallbackState:
+ def test_round_trips(self):
+ original = CallbackState(slack_team_id="T1", posthog_team_id=1, posthog_user_id=99, slack_user_id="U1")
+ decoded = CallbackState.decode(original.encode())
+ assert decoded == original
+
+ def test_rejects_invite_token(self):
+ # Cross-salt protection in the other direction too.
+ invite = InviteToken(slack_team_id="T1", posthog_team_id=1).encode()
+ assert CallbackState.decode(invite) is None
diff --git a/products/slack_app/backend/tests/test_zz_resolve_slack_user_with_link_no_access.py b/products/slack_app/backend/tests/test_zz_resolve_slack_user_with_link_no_access.py
new file mode 100644
index 000000000000..d3c240eb39f3
--- /dev/null
+++ b/products/slack_app/backend/tests/test_zz_resolve_slack_user_with_link_no_access.py
@@ -0,0 +1,53 @@
+"""Access-denied branch of ``resolve_slack_user`` when a Slack user is linked
+to a PostHog account that has no access to the workspace's project.
+
+Lives in its own top-level test file (rather than next to the other linked-user
+resolver tests in ``tests/services/test_slack_user_oauth.py``) so it sorts
+alphabetically AFTER the caplog-driven tests in ``test_get_slack_email_for_user.py``
+and ``test_guess_repository.py``. Earlier placement caused those tests' caplog
+assertions to silently miss logs from ``products.slack_app.backend.api``: once
+this test's data-setup signals emit through the structlog ``BoundLogger``, the
+project-wide ``cache_logger_on_first_use=True`` config caches the logger before
+caplog hooks in for the later tests, and they observe ``caplog.records == []``.
+
+If a future caller reorders test files (e.g. via a new ``pytest-ordering`` plugin
+or a forced random seed), the same caplog pollution may resurface — keep the
+``zz_`` prefix.
+"""
+
+from unittest.mock import MagicMock, patch
+
+from posthog.models.integration import SlackIntegration
+
+from products.slack_app.backend.api import resolve_slack_user
+from products.slack_app.backend.tests.conftest import SLACK_USER_ID
+
+
+class TestResolveSlackUserAccessDenied:
+ @patch("posthog.models.integration.WebClient")
+ @patch("products.slack_app.backend.api.UserPermissions")
+ @patch("products.slack_app.backend.api.slack_oauth_link_enabled")
+ def test_flag_on_with_link_but_no_team_access_returns_none(
+ self,
+ mock_flag,
+ mock_permissions_class,
+ mock_webclient_class,
+ org_team_user,
+ workspace_integration,
+ link_user,
+ ):
+ _, _, user = org_team_user
+ link_user(user)
+ mock_flag.return_value = True
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_permissions = MagicMock()
+ mock_permissions.current_team.effective_membership_level = None
+ mock_permissions_class.return_value = mock_permissions
+
+ result = resolve_slack_user(
+ SlackIntegration(workspace_integration), workspace_integration, SLACK_USER_ID, "C001", "1234.5"
+ )
+ assert result is None
+ # User feedback is posted — access-denied message lands in Slack.
+ assert mock_client.chat_postEphemeral.called or mock_client.chat_postMessage.called
diff --git a/products/slack_app/backend/tests/views/__init__.py b/products/slack_app/backend/tests/views/__init__.py
new file mode 100644
index 000000000000..7e12026d2c99
--- /dev/null
+++ b/products/slack_app/backend/tests/views/__init__.py
@@ -0,0 +1 @@
+"""Tests for ``products.slack_app.backend.views.*`` modules."""
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
new file mode 100644
index 000000000000..e1b67e75e678
--- /dev/null
+++ b/products/slack_app/backend/tests/views/test_slack_user_link.py
@@ -0,0 +1,263 @@
+"""Tests for ``products.slack_app.backend.views.slack_user_link``.
+
+Covers the two backend views in the user-link OAuth ceremony: the authorize
+entrypoint (``GET /complete/slack-link/start/``) and the OAuth callback
+(``GET /complete/slack-link/``). Shared fixtures (``org_team_user``,
+``workspace_integration``, ``link_user``) come from ``conftest.py`` two
+levels up.
+"""
+
+import pytest
+from unittest.mock import patch
+
+from django.test import Client
+
+from posthog.models.user import User
+from posthog.models.user_integration import UserIntegration
+
+from products.slack_app.backend.services.slack_user_oauth import (
+ CallbackState,
+ InviteToken,
+ SlackIdentity,
+ SlackUserOAuthError,
+)
+from products.slack_app.backend.tests.conftest import SLACK_TEAM_ID, SLACK_USER_ACCESS_TOKEN, SLACK_USER_ID
+
+
+class TestAuthorizeView:
+ @pytest.fixture
+ def logged_in_client(self, org_team_user):
+ _, _, user = org_team_user
+ client = Client()
+ client.force_login(user)
+ return client, user
+
+ # All failure paths in the authorize view round-trip the user back to
+ # Personal integrations with a `slack_link_error=<reason>` query param —
+ # mirrors `personal_finish.github_link_complete`. The frontend toast
+ # handler in `personalIntegrationsLogic.afterMount` renders the toast.
+
+ def _assert_settings_redirect_error(self, response, expected_reason: str) -> None:
+ assert response.status_code == 302
+ assert response["Location"].startswith("/settings/user-personal-integrations?")
+ assert f"slack_link_error={expected_reason}" in response["Location"]
+
+ def test_missing_state_redirects_with_invalid_state_error(self, logged_in_client):
+ client, _ = logged_in_client
+ response = client.get("/complete/slack-link/start/")
+ self._assert_settings_redirect_error(response, "invalid_state")
+
+ def test_bad_state_redirects_with_invalid_state_error(self, logged_in_client):
+ client, _ = logged_in_client
+ response = client.get("/complete/slack-link/start/?state=garbage")
+ self._assert_settings_redirect_error(response, "invalid_state")
+
+ def test_unknown_workspace_redirects_with_workspace_not_found(self, logged_in_client, org_team_user):
+ client, _ = logged_in_client
+ token = InviteToken(
+ slack_user_id=SLACK_USER_ID,
+ slack_team_id="T-DOES-NOT-EXIST",
+ posthog_team_id=999_999,
+ ).encode()
+ response = client.get(f"/complete/slack-link/start/?state={token}")
+ self._assert_settings_redirect_error(response, "workspace_not_found")
+
+ def test_flag_off_redirects_with_flag_off_error(self, logged_in_client, workspace_integration):
+ client, _ = logged_in_client
+ token = InviteToken(
+ slack_user_id=SLACK_USER_ID,
+ slack_team_id=SLACK_TEAM_ID,
+ posthog_team_id=workspace_integration.team_id,
+ ).encode()
+ with patch("products.slack_app.backend.views.slack_user_link.slack_oauth_link_enabled", return_value=False):
+ 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):
+ client, _ = logged_in_client
+ token = InviteToken(
+ slack_user_id=SLACK_USER_ID,
+ slack_team_id=SLACK_TEAM_ID,
+ posthog_team_id=workspace_integration.team_id,
+ channel="C001",
+ thread_ts="1.2",
+ ).encode()
+ with (
+ patch("products.slack_app.backend.views.slack_user_link.slack_oauth_link_enabled", return_value=True),
+ patch(
+ "products.slack_app.backend.services.slack_user_oauth.get_instance_settings",
+ return_value={"SLACK_APP_CLIENT_ID": "cid", "SLACK_APP_CLIENT_SECRET": "csecret"},
+ ),
+ ):
+ 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=")
+
+ def test_unauthenticated_user_is_bounced_through_login(self, db):
+ # `db` fixture: PostHog's `login_required` consults `User.objects.exists()`
+ # before deciding what to do for anonymous traffic, so an empty test DB
+ # is the minimum requirement even though this case never touches the
+ # view body.
+ client = Client()
+ response = client.get("/complete/slack-link/start/?state=anything")
+ assert response.status_code in (302, 303)
+
+
+class TestCallbackView:
+ @pytest.fixture
+ def logged_in_client(self, org_team_user):
+ _, _, user = org_team_user
+ client = Client()
+ client.force_login(user)
+ return client, user
+
+ def _state_for(self, user, posthog_team_id, *, slack_team_id=SLACK_TEAM_ID, slack_user_id=SLACK_USER_ID):
+ return CallbackState(
+ slack_user_id=slack_user_id,
+ slack_team_id=slack_team_id,
+ posthog_team_id=posthog_team_id,
+ posthog_user_id=user.id,
+ channel="C001",
+ thread_ts="1.2",
+ ).encode()
+
+ def _identity(self, **overrides) -> SlackIdentity:
+ defaults: dict = {
+ "slack_user_id": SLACK_USER_ID,
+ "slack_team_id": SLACK_TEAM_ID,
+ "slack_team_name": "My Workspace",
+ "slack_email": "[email protected]",
+ "user_access_token": SLACK_USER_ACCESS_TOKEN,
+ }
+ defaults.update(overrides)
+ return SlackIdentity(**defaults)
+
+ # All callback paths — success and error — round-trip to Personal
+ # integrations with `slack_link_success=1` or `slack_link_error=<reason>`
+ # so the frontend toast handler surfaces the result next to the linked
+ # row that just appeared (or didn't).
+
+ def _assert_settings_redirect_error(self, response, expected_reason: str) -> None:
+ assert response.status_code == 302
+ assert response["Location"].startswith("/settings/user-personal-integrations?")
+ assert f"slack_link_error={expected_reason}" in response["Location"]
+
+ def _assert_settings_redirect_success(self, response) -> None:
+ assert response.status_code == 302
+ assert response["Location"].startswith("/settings/user-personal-integrations?")
+ assert "slack_link_success=1" in response["Location"]
+
+ def test_missing_code_redirects_with_invalid_state(self, logged_in_client, workspace_integration):
+ client, user = logged_in_client
+ state = self._state_for(user, workspace_integration.team_id)
+ response = client.get(f"/complete/slack-link/?state={state}")
+ self._assert_settings_redirect_error(response, "invalid_state")
+
+ def test_slack_error_param_is_passed_through(self, logged_in_client, workspace_integration):
+ client, _ = logged_in_client
+ response = client.get("/complete/slack-link/?error=access_denied&state=x")
+ # Slack's error code propagates verbatim so the frontend toast can
+ # render the friendly "Slack authorization was canceled." copy.
+ self._assert_settings_redirect_error(response, "access_denied")
+
+ def test_happy_path_creates_link_and_redirects_to_settings(self, logged_in_client, workspace_integration):
+ client, user = logged_in_client
+ state = self._state_for(user, workspace_integration.team_id)
+
+ with (
+ patch("products.slack_app.backend.views.slack_user_link.slack_oauth_link_enabled", return_value=True),
+ patch("products.slack_app.backend.views.slack_user_link.exchange_code", return_value=self._identity()),
+ patch("posthog.models.integration.WebClient"),
+ ):
+ response = client.get(f"/complete/slack-link/?code=abc&state={state}")
+
+ self._assert_settings_redirect_success(response)
+ link = UserIntegration.objects.get(user=user, kind=UserIntegration.IntegrationKind.SLACK)
+ assert link.integration_id == SLACK_USER_ID
+ assert link.config["slack_team_id"] == SLACK_TEAM_ID
+ assert link.config["slack_team_name"] == "My Workspace"
+ assert link.config["slack_email_at_link"] == "[email protected]"
+ # The user access token IS persisted (mirrors the GitHub personal flow).
+ assert link.sensitive_config == {"user_access_token": SLACK_USER_ACCESS_TOKEN}
+
+ def test_team_mismatch_refuses_to_link(self, logged_in_client, workspace_integration):
+ client, user = logged_in_client
+ state = self._state_for(user, workspace_integration.team_id)
+
+ with (
+ patch("products.slack_app.backend.views.slack_user_link.slack_oauth_link_enabled", return_value=True),
+ patch(
+ "products.slack_app.backend.views.slack_user_link.exchange_code",
+ return_value=self._identity(slack_team_id="T-DIFFERENT", slack_team_name=None, slack_email=None),
+ ),
+ ):
+ response = client.get(f"/complete/slack-link/?code=abc&state={state}")
+
+ self._assert_settings_redirect_error(response, "team_mismatch")
+ # No row should have been written.
+ assert not UserIntegration.objects.filter(user=user, kind=UserIntegration.IntegrationKind.SLACK).exists()
+
+ def test_oauth_exchange_failure_redirects_with_exchange_failed(self, logged_in_client, workspace_integration):
+ client, user = logged_in_client
+ state = self._state_for(user, workspace_integration.team_id)
+
+ with (
+ patch("products.slack_app.backend.views.slack_user_link.slack_oauth_link_enabled", return_value=True),
+ patch(
+ "products.slack_app.backend.views.slack_user_link.exchange_code",
+ side_effect=SlackUserOAuthError("invalid_code"),
+ ),
+ ):
+ response = client.get(f"/complete/slack-link/?code=abc&state={state}")
+
+ self._assert_settings_redirect_error(response, "exchange_failed")
+ assert not UserIntegration.objects.filter(user=user).exists()
+
+ def test_session_mismatch_refuses_to_link(self, org_team_user, workspace_integration):
+ # CSRF guard: the attacker starts the OAuth dance themselves so
+ # `state.posthog_user_id` points at the attacker, but the callback
+ # fires in a *different* PostHog user's browser session (the victim,
+ # who clicked a forwarded URL). The link MUST NOT be written against
+ # the victim's account. Without this check, the attacker's Slack id
+ # would be bound to the victim and every future @mention from the
+ # attacker would route to them.
+ _, _, victim = org_team_user
+ attacker = User.objects.create(email="[email protected]", distinct_id="attacker-1")
+ client = Client()
+ client.force_login(victim)
+ # State carries the *attacker's* posthog_user_id (the flow's initiator),
+ # but the callback is hitting the victim's session.
+ state = self._state_for(attacker, workspace_integration.team_id)
+
+ with (
+ patch("products.slack_app.backend.views.slack_user_link.slack_oauth_link_enabled", return_value=True),
+ patch("products.slack_app.backend.views.slack_user_link.exchange_code", return_value=self._identity()),
+ ):
+ response = client.get(f"/complete/slack-link/?code=abc&state={state}")
+
+ self._assert_settings_redirect_error(response, "session_mismatch")
+ # No row written against either user.
+ assert not UserIntegration.objects.filter(kind=UserIntegration.IntegrationKind.SLACK).exists()
+
+ def test_org_mismatch_refuses_to_link(self, workspace_integration, db):
+ # A user logged into PostHog but NOT a member of the workspace's org —
+ # e.g. someone who got hold of a forwarded invite URL. The OAuth dance
+ # itself can complete (they have a valid session, Slack auth works),
+ # but we refuse the write so orphan rows can't accumulate.
+ outsider = User.objects.create(email="[email protected]", distinct_id="outsider-1")
+ client = Client()
+ client.force_login(outsider)
+ state = self._state_for(outsider, workspace_integration.team_id)
+
+ with (
+ patch("products.slack_app.backend.views.slack_user_link.slack_oauth_link_enabled", return_value=True),
+ patch("products.slack_app.backend.views.slack_user_link.exchange_code", return_value=self._identity()),
+ ):
+ response = client.get(f"/complete/slack-link/?code=abc&state={state}")
+
+ self._assert_settings_redirect_error(response, "org_mismatch")
+ assert not UserIntegration.objects.filter(user=outsider).exists()
diff --git a/products/slack_app/backend/views/__init__.py b/products/slack_app/backend/views/__init__.py
new file mode 100644
index 000000000000..411061c62d64
--- /dev/null
+++ b/products/slack_app/backend/views/__init__.py
@@ -0,0 +1,10 @@
+"""HTTP view entry points for the Slack app.
+
+Re-exports the public view callables so callers can ``from
+products.slack_app.backend.views import <name>`` without reaching into the
+per-flow submodule. New view modules should be re-exported here too.
+"""
+
+from products.slack_app.backend.views.slack_user_link import slack_user_link_authorize, slack_user_link_callback
+
+__all__ = ["slack_user_link_authorize", "slack_user_link_callback"]
diff --git a/products/slack_app/backend/views/slack_user_link.py b/products/slack_app/backend/views/slack_user_link.py
new file mode 100644
index 000000000000..832d8ae52d80
--- /dev/null
+++ b/products/slack_app/backend/views/slack_user_link.py
@@ -0,0 +1,271 @@
+"""Backend OAuth views for the Slack user-identity link flow.
+
+Two endpoints, both pure-backend (no SPA route). Mirrors the GitHub user-link
+convention documented in ``posthog/api/github_callback/README.md``: per-user
+OAuth callbacks live under ``/complete/<kind>-link/`` so the
+``/integrations/<kind>/callback`` namespace stays reserved for the workspace
+install routes the SPA owns.
+
+* ``GET /complete/slack-link/start/``
+ Entry point the user lands on from the Slack DM button or settings page.
+ Login-gated, so an unauthenticated visitor is bounced through PostHog
+ login and returns here with the invite token still in the URL. Validates
+ the invite, then redirects to Slack to start the OAuth dance.
+
+* ``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
+ 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 —
+ matching how the GitHub link flow finishes.
+
+The whole feature is gated by ``slack-app-oauth``; with the flag off both
+views redirect to the settings page with ``?slack_link_error=flag_off`` so
+the user sees a clear toast instead of a 404.
+"""
+
+from typing import Any, cast
+from urllib.parse import urlencode
+
+from django.conf import settings
+from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
+from django.shortcuts import redirect
+from django.views.decorators.http import require_GET
+
+import structlog
+
+from posthog.api.github_callback.redirects import PERSONAL_INTEGRATIONS_SETTINGS_PATH
+from posthog.models.integration import Integration, SlackIntegration
+from posthog.models.organization import OrganizationMembership
+from posthog.models.user import User
+from posthog.models.user_integration import user_slack_integration_from_identity
+from posthog.views import login_required
+
+from products.slack_app.backend.feature_flags import slack_oauth_link_enabled
+from products.slack_app.backend.services.slack_user_oauth import (
+ CallbackState,
+ InviteToken,
+ SlackUserOAuthError,
+ build_authorize_url,
+ exchange_code,
+)
+
+logger = structlog.get_logger(__name__)
+
+# `PERSONAL_INTEGRATIONS_SETTINGS_PATH` is imported from the github_callback
+# module so a future rename of the settings URL updates both providers'
+# redirect targets in one move; the query-param convention
+# (`<kind>_link_success=1` / `<kind>_link_error=<reason>`) is shared too.
+
+
+def _callback_redirect_uri() -> str:
+ base = settings.SITE_URL.rstrip("/")
+ return f"{base}/complete/slack-link/"
+
+
+def _settings_redirect(*, error: str | None = None) -> HttpResponseRedirect:
+ """Bounce back to Personal integrations with a result query param.
+
+ Success and error paths share the same destination; the difference is
+ only the query param the frontend's ``afterMount`` reads to fire the
+ success or error toast.
+ """
+ param = {"slack_link_error": error} if error else {"slack_link_success": "1"}
+ return redirect(f"{PERSONAL_INTEGRATIONS_SETTINGS_PATH}?{urlencode(param)}")
+
+
+def _load_workspace_integration(posthog_team_id: int, slack_team_id: str) -> Integration | None:
+ return (
+ Integration.objects.filter(team_id=posthog_team_id, kind="slack", integration_id=slack_team_id)
+ .select_related("team", "team__organization")
+ .first()
+ )
+
+
+@require_GET
+@login_required
+def slack_user_link_authorize(request: HttpRequest) -> HttpResponse:
+ """Validate the invite, then redirect to Slack OAuth.
+
+ The user is necessarily authenticated by the time this runs (the
+ ``login_required`` decorator handles the bounce). Bad / expired invites
+ bounce back to the settings page with an error param instead of
+ rendering a dead-end HTML page — the toast handler in
+ ``personalIntegrationsLogic`` explains what went wrong in context.
+ """
+ invite = InviteToken.decode(request.GET.get("state", ""))
+ if invite is None:
+ return _settings_redirect(error="invalid_state")
+
+ workspace_integration = _load_workspace_integration(invite.posthog_team_id, invite.slack_team_id)
+ if workspace_integration is None:
+ return _settings_redirect(error="workspace_not_found")
+
+ if not slack_oauth_link_enabled(workspace_integration, invite.slack_team_id):
+ return _settings_redirect(error="flag_off")
+
+ callback_state = CallbackState(
+ slack_team_id=invite.slack_team_id,
+ posthog_team_id=invite.posthog_team_id,
+ posthog_user_id=request.user.id,
+ slack_user_id=invite.slack_user_id,
+ channel=invite.channel,
+ thread_ts=invite.thread_ts,
+ ).encode()
+
+ try:
+ authorize_url = build_authorize_url(redirect_uri=_callback_redirect_uri(), state=callback_state)
+ except SlackUserOAuthError:
+ logger.exception("slack_app_user_link_authorize_misconfigured")
+ return _settings_redirect(error="not_configured")
+
+ return HttpResponseRedirect(authorize_url)
+
+
+@require_GET
+@login_required
+def slack_user_link_callback(request: HttpRequest) -> HttpResponse:
+ """Receive Slack's redirect, exchange the code, persist the link, and
+ bounce back to Personal integrations.
+
+ Re-checks login + feature flag at this end so a stale tab can't bypass
+ either guard. The session-mismatch check below binds the callback to the
+ PostHog user who started the flow (``state.posthog_user_id``) — without
+ it, a leaked invite URL + Slack ``code`` (15-min lifetime) opened in a
+ different user's browser would write the attacker's Slack identity to
+ the victim's PostHog account.
+ """
+ slack_error = request.GET.get("error")
+ if slack_error:
+ # Pass Slack's error code straight through — the frontend toast
+ # handler renders known codes (`access_denied`, …) with friendly
+ # copy and falls back to a generic message for anything else.
+ return _settings_redirect(error=slack_error)
+
+ code = request.GET.get("code", "")
+ state = CallbackState.decode(request.GET.get("state", ""))
+ if not code or state is None:
+ return _settings_redirect(error="invalid_state")
+
+ workspace_integration = _load_workspace_integration(state.posthog_team_id, state.slack_team_id)
+ if workspace_integration is None:
+ return _settings_redirect(error="workspace_not_found")
+ if not slack_oauth_link_enabled(workspace_integration, state.slack_team_id):
+ return _settings_redirect(error="flag_off")
+
+ try:
+ identity = exchange_code(code=code, redirect_uri=_callback_redirect_uri())
+ except SlackUserOAuthError as exc:
+ logger.warning("slack_app_user_link_callback_exchange_failed", error=str(exc))
+ return _settings_redirect(error="exchange_failed")
+
+ # Hard-bind to the workspace from the original invite: if the user
+ # authorized in a different Slack workspace tab, refuse rather than
+ # silently linking them to the wrong workspace.
+ if identity.slack_team_id != state.slack_team_id:
+ logger.warning(
+ "slack_app_user_link_callback_team_mismatch",
+ expected=state.slack_team_id,
+ actual=identity.slack_team_id,
+ )
+ return _settings_redirect(error="team_mismatch")
+
+ # `state.slack_user_id` is informational — if the user clicks an invite
+ # meant for a different person but authorizes as themselves, that's fine
+ # (they're linking their own identity). We log the divergence so support
+ # can spot a forwarded-button case.
+ if state.slack_user_id is not None and identity.slack_user_id != state.slack_user_id:
+ logger.info(
+ "slack_app_user_link_callback_user_diverged_from_invite",
+ invite_user=state.slack_user_id,
+ authed_user=identity.slack_user_id,
+ )
+
+ # `request.user` is `User | AnonymousUser` to mypy even though
+ # `@login_required` rules out the anonymous case at runtime; cast so the
+ # factory's `user: User` signature is satisfied without an `assert`.
+ posthog_user = cast(User, request.user)
+
+ # CSRF guard: bind the link write to the same PostHog user who initiated
+ # the flow. Without this, an attacker who completes their own OAuth dance
+ # could send the resulting `?code=…&state=…` URL to a victim and have the
+ # victim's browser write the *attacker's* Slack identity into the *victim's*
+ # PostHog account — every subsequent @mention from the attacker would then
+ # resolve as the victim. `org_mismatch` below catches cross-org cases but
+ # not the same-org colleague case, so this check is the actual boundary.
+ if state.posthog_user_id != posthog_user.id:
+ logger.warning(
+ "slack_app_user_link_callback_session_mismatch",
+ state_posthog_user_id=state.posthog_user_id,
+ request_posthog_user_id=posthog_user.id,
+ )
+ return _settings_redirect(error="session_mismatch")
+
+ # Refuse to write a link row for a PostHog user who isn't a member of
+ # the workspace's org. The org-scope filter in `find_linked_posthog_user`
+ # would already skip such rows at resolve time, but writing them anyway
+ # would let anyone who got hold of a signed invite URL (forwarded DM,
+ # screenshot, etc.) seed orphan rows on the workspace.
+ if not OrganizationMembership.objects.filter(
+ user_id=posthog_user.id,
+ organization_id=workspace_integration.team.organization_id,
+ ).exists():
+ logger.warning(
+ "slack_app_user_link_callback_org_mismatch",
+ posthog_user_id=posthog_user.id,
+ posthog_team_id=workspace_integration.team_id,
+ organization_id=workspace_integration.team.organization_id,
+ )
+ return _settings_redirect(error="org_mismatch")
+
+ user_slack_integration_from_identity(
+ posthog_user,
+ slack_user_id=identity.slack_user_id,
+ slack_team_id=identity.slack_team_id,
+ slack_team_name=identity.slack_team_name,
+ slack_email_at_link=identity.slack_email,
+ user_access_token=identity.user_access_token,
+ user_refresh_token=identity.user_refresh_token,
+ )
+
+ _post_link_success_followup(
+ workspace_integration=workspace_integration,
+ slack_user_id=identity.slack_user_id,
+ channel=state.channel,
+ thread_ts=state.thread_ts,
+ )
+
+ return _settings_redirect()
+
+
+def _post_link_success_followup(
+ *,
+ workspace_integration: Integration,
+ slack_user_id: str,
+ channel: Any,
+ thread_ts: Any,
+) -> None:
+ """Best-effort follow-up DM/thread message confirming the link. The user
+ has already been bounced back to the settings page in their browser, so
+ a Slack post failure is not surfaced — it's a nice-to-have for context,
+ not a correctness requirement.
+ """
+ if not isinstance(channel, str) or not channel:
+ return
+ try:
+ client = SlackIntegration(workspace_integration).client
+ client.chat_postEphemeral(
+ channel=channel,
+ user=slack_user_id,
+ thread_ts=thread_ts if isinstance(thread_ts, str) else None,
+ text="✅ Your PostHog account is now linked. Mention me again and I'll route to you correctly.",
+ )
+ except Exception:
+ logger.info(
+ "slack_app_user_link_success_followup_failed",
+ channel=channel,
+ slack_user_id=slack_user_id,
+ exc_info=True,
+ )
diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yaml
index 204443cd82c0..117b28627b23 100644
--- a/services/mcp/definitions/core.yaml
+++ b/services/mcp/definitions/core.yaml
@@ -720,6 +720,15 @@ tools:
users-integrations-list:
operation: users_integrations_list
enabled: false
+ users-integrations-slack-destroy:
+ operation: users_integrations_slack_destroy
+ enabled: false
+ users-integrations-slack-linkable-workspaces-retrieve:
+ operation: users_integrations_slack_linkable_workspaces_retrieve
+ enabled: false
+ users-integrations-slack-start-create:
+ operation: users_integrations_slack_start_create
+ enabled: false
users-list:
operation: users_list
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 175394a7f926..d74ccbe8e983 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -50385,6 +50385,53 @@ export namespace Schemas {
token: string;
}
+ /**
+ * Settings-initiated link can target a specific PostHog team + Slack workspace.
+ *
+ * Both are optional — when omitted we fall back to the user's ``current_team``
+ * and that team's first Slack ``Integration`` (mirrors ``github_start`` for
+ * the simple case). The frontend passes both explicitly once it has the
+ * linkable-workspace list and the user has picked a workspace.
+ */
+ export interface UserSlackLinkStartRequest {
+ /**
+ * Optional team/project id to link against; defaults to the user's current team.
+ * @nullable
+ */
+ team_id?: number | null;
+ /**
+ * Specific Slack workspace id to link against, scoped to the team. Disambiguates when one team has multiple Slack integrations (rare).
+ * @nullable
+ */
+ slack_team_id?: string | null;
+ }
+
+ export interface UserSlackLinkStartResponse {
+ /** URL to open in the browser to start the Sign-in-with-Slack flow. */
+ install_url: string;
+ }
+
+ export interface UserSlackLinkableWorkspaceItem {
+ /** PostHog team/project id owning the Slack workspace install. */
+ posthog_team_id: number;
+ /** PostHog team/project name, for display in a picker. */
+ posthog_team_name: string;
+ /** PostHog organization name owning the team, for picker disambiguation. */
+ posthog_organization_name: string;
+ /** Slack workspace (team) id. */
+ slack_team_id: string;
+ /**
+ * Slack workspace display name as known by PostHog.
+ * @nullable
+ */
+ slack_team_name?: string | null;
+ }
+
+ export interface UserSlackLinkableWorkspaceListResponse {
+ /** Slack workspaces the user could link to but hasn't yet. */
+ results: UserSlackLinkableWorkspaceItem[];
+ }
+
export interface UtmEvent {
/** UTM campaign value from pageview events */
utm_campaign: string;
@@ -63714,6 +63761,10 @@ export namespace Schemas {
};
export type UsersIntegrationsListParams = {
+ /**
+ * Integration kind to list. Defaults to `github` for back-compat with mobile and the Code SDK, which call this endpoint without a query param and expect GitHub-shaped items.
+ */
+ kind?: UsersIntegrationsListKind;
/**
* Number of results to return per page.
*/
@@ -63724,6 +63775,14 @@ export namespace Schemas {
offset?: number;
};
+ export type UsersIntegrationsListKind = typeof UsersIntegrationsListKind[keyof typeof UsersIntegrationsListKind];
+
+
+ export const UsersIntegrationsListKind = {
+ Github: 'github',
+ Slack: 'slack',
+ } as const;
+
export type UsersIntegrationsGithubBranchesRetrieveParams = {
/**
* Maximum number of branches to return