:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(integrations): land OAuth integration on the initiating project (#73901)
posthog[bot]a843418186fd
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 1326eedeb9ac..5fb6363e57cf 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -6256,8 +6256,8 @@ const api = {async get(id: IntegrationType['id']): Promise<IntegrationType> {return await new ApiRequest().integration(id).get()},- async create(data: Partial<IntegrationType> | FormData): Promise<IntegrationType> {- return await new ApiRequest().integrations().create({ data })+ async create(data: Partial<IntegrationType> | FormData, teamId?: TeamType['id']): Promise<IntegrationType> {+ return await new ApiRequest().integrations(teamId).create({ data })},async delete(integrationId: IntegrationType['id']): Promise<IntegrationType> {return await new ApiRequest().integration(integrationId).delete()diff --git a/frontend/src/lib/integrations/integrationsLogic.test.ts b/frontend/src/lib/integrations/integrationsLogic.test.tsindex fb485865604b..c01657322318 100644--- a/frontend/src/lib/integrations/integrationsLogic.test.ts+++ b/frontend/src/lib/integrations/integrationsLogic.test.ts@@ -1,3 +1,5 @@+import { MOCK_TEAM_ID } from 'lib/api.mock'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'@@ -65,4 +67,53 @@ describe('integrationsLogic — handleOauthCallback', () => {stripe_user_id: 'acct_456',})})++ describe('integration create team scoping', () => {+ let requestedTeamIds: string[]++ beforeEach(() => {+ requestedTeamIds = []+ document.cookie = 'ph_oauth_state=csrf-tok'+ useMocks({+ post: {+ '/api/environments/:team_id/integrations/': ({ params }) => {+ requestedTeamIds.push(String(params.team_id))+ return [201, { id: 7, kind: 'slack' }]+ },+ },+ })+ })++ afterEach(() => {+ document.cookie = 'ph_oauth_state=; expires=Thu, 01 Jan 1970 00:00:00 GMT'+ })++ it('creates the integration against the team carried in the OAuth state', async () => {+ // The callback is a full-page round-trip on a non-project-scoped URL, so the SPA's+ // current team is the user's default team here (MOCK_TEAM_ID) — not team 228502,+ // which the state says initiated the flow.+ const state = 'next=%2Fproject%2F228502%2Fsettings%2Fproject-integrations&token=csrf-tok&team_id=228502'++ await expectLogic(logic, () => {+ logic.actions.handleOauthCallback('slack' as IntegrationKind, { state, code: 'oauth-code' })+ }).toFinishAllListeners()++ expect(createSpy).toHaveBeenCalledWith({ kind: 'slack', config: { state, code: 'oauth-code' } }, 228502)+ expect(requestedTeamIds).toEqual(['228502'])+ expect(router.values.location.pathname).toBe('/project/228502/settings/project-integrations')+ expect(router.values.searchParams.integration_id).toBe(7)+ })++ it('falls back to the current team when the OAuth state carries no team_id', async () => {+ // In-flight flows started before team_id was added to the state keep the old behavior.+ const state = 'next=%2Fproject%2F228502%2Fsettings%2Fproject-integrations&token=csrf-tok'++ await expectLogic(logic, () => {+ logic.actions.handleOauthCallback('slack' as IntegrationKind, { state, code: 'oauth-code' })+ }).toFinishAllListeners()++ expect(createSpy).toHaveBeenCalledWith({ kind: 'slack', config: { state, code: 'oauth-code' } }, undefined)+ expect(requestedTeamIds).toEqual([String(MOCK_TEAM_ID)])+ })+ })})diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.tsindex f83221a6de25..2b09b1cfdf55 100644--- a/frontend/src/lib/integrations/integrationsLogic.ts+++ b/frontend/src/lib/integrations/integrationsLogic.ts@@ -868,7 +868,7 @@ export const integrationsLogic = kea<integrationsLogicType>([},handleOauthCallback: async ({ kind, searchParams }) => {const { state, code, error, stripe_user_id, account_id, user_id } = searchParams- const { next, token, source, server_id } = fromParamsGivenUrl(state)+ const { next, token, source, server_id, team_id } = fromParamsGivenUrl(state)const resolvedKind = kindlet replaceUrl: string = next || urls.settings('project-integrations')@@ -913,10 +913,19 @@ export const integrationsLogic = kea<integrationsLogicType>([replaceUrl += `${replaceUrl.includes('?') ? '&' : '?'}code=${encodeURIComponent(code)}&server_id=${encodeURIComponent(server_id)}&state_token=${encodeURIComponent(token)}`lemonToast.success('Authorization successful.')} else {- const integration = await api.integrations.create({- kind: resolvedKind,- config: { state, code },- })+ // The callback URL is not project-scoped, so after this full-page round-trip+ // the SPA may have re-resolved to the user's default team. Target the team+ // that started the flow (carried through the OAuth state) so the integration+ // lands on the project the user actually chose.+ const parsedTeamId = Number(team_id)+ const initiatingTeamId = Number.isFinite(parsedTeamId) ? parsedTeamId : undefined+ const integration = await api.integrations.create(+ {+ kind: resolvedKind,+ config: { state, code },+ },+ initiatingTeamId+ )// Add the integration ID to the replaceUrl so that the landing page can use itconst url = new URL(replaceUrl, window.location.origin)diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex db7ff868cafd..fb39fdfc234d 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -1096,7 +1096,7 @@ class IntegrationViewSet(if kind in OauthIntegration.supported_kinds:try:- auth_url = OauthIntegration.authorize_url(kind, next=next, token=token)+ auth_url = OauthIntegration.authorize_url(kind, next=next, token=token, team_id=self.team_id)response = redirect(auth_url)# nosemgrep: python.django.security.audit.secure-cookies.django-secure-set-cookie (OAuth state, short-lived, needed for cross-site redirect)response.set_cookie("ph_oauth_state", token, max_age=60 * 5)diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 12612279d4f7..c0f14c11202c 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -1088,10 +1088,15 @@ class OauthIntegration:return f"{settings.SITE_URL.replace('http://', 'https://')}/integrations/{kind}/callback"@classmethod- def authorize_url(cls, kind: str, token: str, next: str = "") -> str:+ def authorize_url(cls, kind: str, token: str, next: str = "", team_id: int | None = None) -> str:oauth_config = cls.oauth_config_for_kind(kind)+ # Carry the initiating team through the OAuth round-trip. The fixed callback URL is not+ # project-scoped, so without this the SPA re-resolves to the user's default team on+ # reload and the integration lands on the wrong project.state_payload: dict[str, str] = {"next": next, "token": token}+ if team_id is not None:+ state_payload["team_id"] = str(team_id)if kind == "tiktok-ads":# TikTok uses different parameter namesdiff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex 446f9354847b..7d5b80000687 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -249,6 +249,21 @@ class TestOauthIntegrationModel(BaseTest):"code_challenge_method": "S256",}+ def test_authorize_url_carries_initiating_team_id_in_state(self):+ with self.settings(**self.mock_settings):+ url = OauthIntegration.authorize_url(+ "salesforce", token="state_token", next="/projects/test", team_id=228502+ )+ params = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}+ state = {k: v[0] for k, v in parse_qs(params["state"]).items()}+ assert state["team_id"] == "228502"++ def test_authorize_url_omits_team_id_when_not_provided(self):+ with self.settings(**self.mock_settings):+ url = OauthIntegration.authorize_url("salesforce", token="state_token", next="/projects/test")+ params = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}+ assert "team_id" not in parse_qs(params["state"])+def test_authorize_url_pkce_challenge_matches_cached_verifier(self):with self.settings(**self.mock_settings):url = OauthIntegration.authorize_url("salesforce", token="pkce_state_token", next="/projects/test")