Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(integrations): revoke Salesforce OAuth grant on disconnect (#70044)

Harley Alexandera9c86ccb9e7a
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index ad46cb7c5bd8..0b22ac7629d2 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -969,6 +969,15 @@ class IntegrationViewSet(
stripe_integration.clear_posthog_secrets()
except Exception as e:
capture_exception(e)
+ if instance.kind in OauthIntegration.supported_kinds:
+ # Disconnecting should sever the grant at the provider too, not just delete our copy
+ # of the tokens — otherwise the provider keeps treating the app as authorized.
+ try:
+ OauthIntegration(instance).revoke_token()
+ except NotImplementedError:
+ pass # kind not configured on this instance
+ except Exception as e:
+ capture_exception(e)
if instance.kind == "github" and instance.integration_id:
# Team integrations own the installation; personal ones are subordinate. When the
# last team integration for an installation is removed, tear it down everywhere:
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index e298cdcba082..9856ae0ccbaf 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -14,6 +14,7 @@ from django.test import override_settings
from django.test.client import Client as HttpClient
from django.utils import timezone
+import requests
from parameterized import parameterized
from rest_framework import status
@@ -3380,6 +3381,121 @@ class TestStripeIntegration:
assert not Integration.objects.filter(team_id=self.team.pk, kind="stripe").exists()
+class TestOauthIntegrationRevokeOnDisconnect:
+ @pytest.fixture(autouse=True)
+ def setup_integration(self, db, settings):
+ settings.SALESFORCE_CONSUMER_KEY = "sf-key"
+ settings.SALESFORCE_CONSUMER_SECRET = "sf-secret"
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
+ )
+
+ def _create_salesforce_integration(
+ self,
+ sensitive_config: dict | None = None,
+ instance_url: str = "https://example.my.salesforce.com",
+ ) -> Integration:
+ return Integration.objects.create(
+ team=self.team,
+ kind="salesforce",
+ config={"instance_url": instance_url},
+ sensitive_config=(
+ {"access_token": "sf-access", "refresh_token": "sf-refresh"}
+ if sensitive_config is None
+ else sensitive_config
+ ),
+ integration_id=instance_url,
+ created_by=self.user,
+ )
+
+ @patch("posthog.models.integration.requests.post")
+ def test_destroy_salesforce_revokes_token_at_provider(self, mock_post, client: HttpClient):
+ integration = self._create_salesforce_integration()
+
+ client.force_login(self.user)
+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not Integration.objects.filter(id=integration.id).exists()
+ mock_post.assert_called_once_with(
+ "https://example.my.salesforce.com/services/oauth2/revoke",
+ data={"token": "sf-refresh"},
+ timeout=10,
+ allow_redirects=False,
+ )
+
+ @patch("posthog.models.integration.requests.post")
+ def test_destroy_sandbox_salesforce_revokes_at_sandbox_host(self, mock_post, client: HttpClient):
+ # Sandbox integrations are stored as kind "salesforce" with a sandbox instance_url; revoking
+ # must hit that host, not login.salesforce.com, or the sandbox grant is never invalidated.
+ integration = self._create_salesforce_integration(
+ instance_url="https://example--sandbox.sandbox.my.salesforce.com"
+ )
+
+ client.force_login(self.user)
+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not Integration.objects.filter(id=integration.id).exists()
+ mock_post.assert_called_once_with(
+ "https://example--sandbox.sandbox.my.salesforce.com/services/oauth2/revoke",
+ data={"token": "sf-refresh"},
+ timeout=10,
+ allow_redirects=False,
+ )
+
+ @patch("posthog.models.integration.requests.post")
+ def test_destroy_still_deletes_when_revoke_fails(self, mock_post, client: HttpClient):
+ client.force_login(self.user)
+
+ raising = self._create_salesforce_integration()
+ mock_post.side_effect = Exception("Salesforce is down")
+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{raising.id}/")
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not Integration.objects.filter(id=raising.id).exists()
+
+ rejected = self._create_salesforce_integration()
+ mock_post.side_effect = None
+ rejecting_response = MagicMock(status_code=400)
+ rejecting_response.raise_for_status.side_effect = requests.HTTPError(
+ "400 Client Error", response=rejecting_response
+ )
+ mock_post.return_value = rejecting_response
+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{rejected.id}/")
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not Integration.objects.filter(id=rejected.id).exists()
+
+ @patch("posthog.models.integration.requests.post")
+ def test_destroy_without_tokens_skips_revoke(self, mock_post, client: HttpClient):
+ integration = self._create_salesforce_integration(sensitive_config={})
+
+ client.force_login(self.user)
+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not Integration.objects.filter(id=integration.id).exists()
+ mock_post.assert_not_called()
+
+ @patch("posthog.models.integration.requests.post")
+ def test_destroy_kind_without_revoke_url_skips_revoke(self, mock_post, client: HttpClient):
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ config={"authed_user": {"id": "U123"}},
+ sensitive_config={"access_token": "xoxb-test"},
+ created_by=self.user,
+ )
+
+ client.force_login(self.user)
+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not Integration.objects.filter(id=integration.id).exists()
+ mock_post.assert_not_called()
+
+
class TestStripeIntegrationOAuthTokens:
@pytest.fixture(autouse=True)
def setup(self, db):
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index fd5a62807632..7127bf63f28c 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -365,6 +365,8 @@ class OauthConfig:
token_info_graphql_query: str | None = None
token_info_config_fields: list[str] | None = None
additional_authorize_params: dict[str, str] | None = None
+ # When set, disconnecting the integration also revokes the grant at the provider
+ token_revoke_url: str | None = None
# Slack accepts comma-separated scopes on the OAuth authorize URL. The canonical list is the
@@ -447,6 +449,7 @@ class OauthIntegration:
return OauthConfig(
authorize_url="https://login.salesforce.com/services/oauth2/authorize",
token_url="https://login.salesforce.com/services/oauth2/token",
+ token_revoke_url="https://login.salesforce.com/services/oauth2/revoke",
client_id=settings.SALESFORCE_CONSUMER_KEY,
client_secret=settings.SALESFORCE_CONSUMER_SECRET,
scope="full refresh_token",
@@ -460,6 +463,7 @@ class OauthIntegration:
return OauthConfig(
authorize_url="https://test.salesforce.com/services/oauth2/authorize",
token_url="https://test.salesforce.com/services/oauth2/token",
+ token_revoke_url="https://test.salesforce.com/services/oauth2/revoke",
client_id=settings.SALESFORCE_CONSUMER_KEY,
client_secret=settings.SALESFORCE_CONSUMER_SECRET,
scope="full refresh_token",
@@ -1086,6 +1090,43 @@ class OauthIntegration:
return integration
+ def revoke_token(self) -> None:
+ """Revoke the OAuth grant at the provider, for kinds with a revoke endpoint.
+
+ Revoking the refresh token also invalidates its access tokens (per RFC 7009 and
+ Salesforce's revoke semantics), so the provider no longer considers PostHog authorized
+ after a disconnect. Callers treat this as best-effort — the local deletion proceeds
+ regardless.
+ """
+ oauth_config = self.oauth_config_for_kind(self.integration.kind)
+ if not oauth_config.token_revoke_url:
+ return
+
+ token = self.integration.sensitive_config.get("refresh_token") or self.integration.sensitive_config.get(
+ "access_token"
+ )
+ if not token:
+ return
+
+ revoke_url = oauth_config.token_revoke_url
+ # Salesforce sandbox integrations are stored as kind "salesforce" (the sandbox is only a
+ # token-exchange fallback), so the static prod revoke URL would miss them. Revoke at the
+ # org's own instance host instead - it serves oauth2/revoke and matches prod or sandbox.
+ instance_url = self.integration.config.get("instance_url")
+ if self.integration.kind == "salesforce" and instance_url:
+ revoke_url = f"{instance_url.rstrip('/')}/services/oauth2/revoke"
+
+ # allow_redirects=False so a misconfigured/compromised provider can't 30x us into
+ # resending the token to another host. raise_for_status surfaces a provider rejection
+ # to the caller's capture_exception instead of it passing silently as a revoke.
+ response = requests.post(
+ revoke_url,
+ data={"token": token},
+ timeout=10,
+ allow_redirects=False,
+ )
+ response.raise_for_status()
+
def access_token_expired(self, time_threshold: timedelta | None = None) -> bool:
# Not all integrations have refresh tokens or expiries, so we just return False if we can't check