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): send the registered callback for Pardot OAuth (#97415)

posthog[bot]4aeceaa98675
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index d2546ae20bd5..42a322e3be2d 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -97,6 +97,7 @@ from posthog.models.integration import (
StripeIntegration,
TwilioIntegration,
defer_repository_cache_fields,
+ resolve_aliased_oauth_kind,
)
from posthog.models.user_integration import UserIntegration
from posthog.permissions import (
@@ -625,6 +626,16 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial
def create(self, validated_data: Any) -> Any:
team_id = self.context["team_id"]
+ config_in = validated_data.get("config") or {}
+
+ # A kind that borrows another kind's connected app returns on the owner's callback path, so
+ # the client posts the path's kind. Both kinds derive the same integration id from the same
+ # provider account, so the grant would overwrite the borrowed kind's working integration
+ # with a token its API rejects. Promote the state kind before anything keys on it.
+ state = config_in.get("state")
+ validated_data["kind"] = resolve_aliased_oauth_kind(
+ validated_data["kind"], state if isinstance(state, str) else ""
+ )
kind = validated_data["kind"]
# Setting push identity verification is a security policy change, not a credential upload, so it
@@ -639,7 +650,6 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial
# still be classified as a create and could land `disabled` over the policy an admin had just
# written. Omitting the key entirely stays open to members and is what connecting a channel
# without touching the policy does — that path preserves whatever is already stored.
- config_in = validated_data.get("config") or {}
requested_verification = config_in.get("push_identity_verification")
# Registering/clearing public keys is a security-policy change (it decides which signer is
# trusted), so it carries the same admin bar as the mode. `is not None` covers clearing too.
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index d388cee93c50..92170d525527 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -5855,6 +5855,64 @@ class TestAnthropicIntegration:
assert body["has_more"] is False
+class TestAliasedOauthCallbackKind:
+ @pytest.fixture(autouse=True)
+ def setup_environment(self, db, settings):
+ settings.SALESFORCE_CONSUMER_KEY = "salesforce-client-id"
+ settings.SALESFORCE_CONSUMER_SECRET = "salesforce-client-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
+ )
+ self.instance_url = "https://acme.my.salesforce.com"
+ self.salesforce = Integration.objects.create(
+ team=self.team,
+ kind="salesforce",
+ integration_id=self.instance_url,
+ config={"instance_url": self.instance_url},
+ sensitive_config={"access_token": "CRM_TOKEN", "refresh_token": "CRM_REFRESH"},
+ )
+
+ @pytest.mark.parametrize(
+ "state_kind,expected_kind,expected_salesforce_token",
+ [
+ # pardot borrows the Salesforce app, so its state may rename the callback.
+ ("pardot", "pardot", "CRM_TOKEN"),
+ # hubspot borrows nothing, so the path wins and this stays a Salesforce reconnect.
+ ("hubspot", "salesforce", "NEW_TOKEN"),
+ ],
+ )
+ @patch("posthog.models.integration.oauth.requests.post")
+ def test_state_kind_is_promoted_only_when_the_alias_table_allows_it(
+ self, mock_post, state_kind, expected_kind, expected_salesforce_token, client: HttpClient
+ ):
+ # A client built before the Pardot callback moved posts "salesforce" while it carries a
+ # Pardot grant. Both kinds key on the same instance URL, so that grant would land on the
+ # team's Salesforce row.
+ mock_post.return_value = MagicMock(status_code=200)
+ mock_post.return_value.json.return_value = {
+ "access_token": "NEW_TOKEN",
+ "refresh_token": "NEW_REFRESH",
+ "instance_url": self.instance_url,
+ }
+ client.force_login(self.user)
+
+ response = client.post(
+ f"/api/environments/{self.team.pk}/integrations/",
+ {
+ "kind": "salesforce",
+ "config": {"state": f"token=csrf-tok&kind={state_kind}", "code": "oauth-code"},
+ },
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json()["kind"] == expected_kind
+ self.salesforce.refresh_from_db()
+ assert self.salesforce.sensitive_config["access_token"] == expected_salesforce_token
+
+
class TestSlackPostHogCodeKindDeprecated:
@pytest.fixture(autouse=True)
def setup_environment(self, db):
diff --git a/posthog/models/integration/__init__.py b/posthog/models/integration/__init__.py
index 66615f2f69d7..8e68dd65e319 100644
--- a/posthog/models/integration/__init__.py
+++ b/posthog/models/integration/__init__.py
@@ -80,6 +80,7 @@ from .oauth import (
OauthConfig,
OauthIntegration,
posthog_connect_base_url,
+ resolve_aliased_oauth_kind,
)
from .postgres import (
MISSING_CERT_PATH,
@@ -183,6 +184,7 @@ __all__ = [
"POSTHOG_CONNECT_IDENTITY_SCOPES",
"POSTHOG_CONNECT_GRANTABLE_SCOPES",
"posthog_connect_base_url",
+ "resolve_aliased_oauth_kind",
"OauthIntegration",
"PRIVATE_CHANNEL_WITHOUT_ACCESS",
"SlackIntegrationError",
diff --git a/posthog/models/integration/oauth.py b/posthog/models/integration/oauth.py
index 5a06cf3c48f7..213291e6e056 100644
--- a/posthog/models/integration/oauth.py
+++ b/posthog/models/integration/oauth.py
@@ -151,6 +151,27 @@ def _salesforce_instance_host(instance_url: str | None) -> str | None:
# rather than the hardcoded login host (sandbox orgs reject the prod endpoints).
SALESFORCE_OAUTH_KINDS = ("salesforce", "pardot")
+# Kinds that authorize through another kind's connected app. The provider allows only the callback
+# URL that the app was registered with, so a path built from the borrowing kind is rejected with
+# redirect_uri_mismatch before the user can grant anything.
+OAUTH_REDIRECT_URI_ALIASES: dict[str, str] = {"pardot": "salesforce"}
+
+
+def resolve_aliased_oauth_kind(path_kind: str, state: str) -> str:
+ """Return the kind a callback belongs to, given the kind its callback path names.
+
+ An aliased kind returns on the app owner's path, so the path segment names the wrong
+ integration and `authorize_url` puts the real kind in the state. Only a state kind that the
+ alias table maps back to `path_kind` is promoted, so a caller cannot name an unrelated
+ integration through this — and a caller that wants the aliased kind can already ask for it
+ directly.
+ """
+ state_kind = parse_qs(state).get("kind", [""])[0]
+ if state_kind and OAUTH_REDIRECT_URI_ALIASES.get(state_kind) == path_kind:
+ return state_kind
+ return path_kind
+
+
# PostHog connect. Unlike every other OAuth kind — which points at a fixed third-party provider —
# the `posthog` kind points at *another PostHog project*, in a region chosen by the user at connect
# time. That region may differ from the connecting project's or be the same one (same-region is just
@@ -767,9 +788,10 @@ class OauthIntegration:
@classmethod
def redirect_uri(cls, kind: str) -> str:
# The redirect uri is fixed but should always be https and include the "next" parameter for the frontend to redirect
+ path_kind = OAUTH_REDIRECT_URI_ALIASES.get(kind, kind)
if settings.DEBUG and settings.NGROK_URL:
- return f"{settings.NGROK_URL}/integrations/{kind}/callback"
- return f"{settings.SITE_URL.replace('http://', 'https://')}/integrations/{kind}/callback"
+ return f"{settings.NGROK_URL}/integrations/{path_kind}/callback"
+ return f"{settings.SITE_URL.replace('http://', 'https://')}/integrations/{path_kind}/callback"
@classmethod
def authorize_url(
@@ -790,6 +812,10 @@ class OauthIntegration:
state_payload: dict[str, str] = {"next": next, "token": token}
if team_id is not None:
state_payload["team_id"] = str(team_id)
+ if kind in OAUTH_REDIRECT_URI_ALIASES:
+ # The callback lands on the aliased kind's path, so its URL segment names the wrong
+ # integration. The callback handler reads the real kind from here instead.
+ state_payload["kind"] = kind
scope = oauth_config.scope
if kind == "posthog":
@@ -952,7 +978,7 @@ class OauthIntegration:
if res.status_code != 200 or not access_token:
# Hack to try getting sandbox auth token instead of their salesforce production account
- if kind == "salesforce":
+ if kind in SALESFORCE_OAUTH_KINDS:
oauth_config = cls.oauth_config_for_kind("salesforce-sandbox")
res = requests.post(
oauth_config.token_url,
@@ -965,6 +991,8 @@ class OauthIntegration:
**({"code_verifier": code_verifier} if code_verifier else {}),
},
timeout=10,
+ # Same guard as the first exchange: a 30x must not resend the secret and code.
+ allow_redirects=False,
)
try:
@@ -973,7 +1001,15 @@ class OauthIntegration:
config = {}
if res.status_code != 200 or not config.get("access_token"):
- logger.error(f"Oauth error for {kind}", response=res.text)
+ logger.error(
+ f"Oauth error for {kind}",
+ response=res.text,
+ status_code=res.status_code,
+ client_id=oauth_config.client_id,
+ redirect_uri=OauthIntegration.redirect_uri(kind),
+ code_prefix=str(params.get("code", ""))[:12],
+ exchange_host="sandbox",
+ )
_raise_oauth_validation_error(kind, res)
else:
# Include request context so on-call can compare what we sent against what
diff --git a/posthog/models/test/integration/test_oauth.py b/posthog/models/test/integration/test_oauth.py
index 94757babc697..668b735b9408 100644
--- a/posthog/models/test/integration/test_oauth.py
+++ b/posthog/models/test/integration/test_oauth.py
@@ -1510,6 +1510,47 @@ class TestPardotIntegrationModel(BaseTest):
assert config.scope == "pardot_api refresh_token"
assert config.scope != OauthIntegration.oauth_config_for_kind("salesforce").scope
+ def test_authorize_url_sends_the_registered_salesforce_callback(self):
+ url = OauthIntegration.authorize_url("pardot", token="state_token", next="/projects/test")
+ 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()}
+
+ # This kind borrows the Salesforce connected app, whose allowed callback list holds only the
+ # Salesforce path. A /integrations/pardot/callback redirect_uri is rejected with
+ # redirect_uri_mismatch before the user can grant anything.
+ assert params["redirect_uri"] == "https://localhost:8010/integrations/salesforce/callback"
+ # The callback path can no longer name the kind, so the kind rides in the state instead.
+ assert state["kind"] == "pardot"
+
+ @patch("posthog.models.integration.oauth.requests.post")
+ def test_token_exchange_retries_against_the_sandbox_host(self, mock_post):
+ # An Account Engagement business unit can live on a Salesforce sandbox org, which mints a
+ # code the production token host rejects. Refresh and revoke already follow the org's own
+ # host, so without this retry the connect is the only step that fails for those orgs.
+ production = MagicMock(status_code=400, text='{"error":"invalid_grant"}')
+ production.json.return_value = {"error": "invalid_grant"}
+ sandbox = MagicMock(status_code=200)
+ sandbox.json.return_value = {
+ "access_token": "at",
+ "refresh_token": "rt",
+ "instance_url": "https://acme--sandbox.sandbox.my.salesforce.com",
+ }
+ mock_post.side_effect = [production, sandbox]
+
+ integration = OauthIntegration.integration_from_oauth_response(
+ "pardot",
+ self.team.id,
+ self.user,
+ {"code": "code", "state": "token=state_token"},
+ )
+
+ assert integration.integration_id == "https://acme--sandbox.sandbox.my.salesforce.com"
+ retry = mock_post.call_args_list[1]
+ assert retry.args[0] == "https://test.salesforce.com/services/oauth2/token"
+ assert retry.kwargs["data"]["redirect_uri"] == "https://localhost:8010/integrations/salesforce/callback"
+ # Same guard as the first exchange: a 30x must not resend the client secret and the code.
+ assert retry.kwargs["allow_redirects"] is False
+
def test_pardot_is_an_oauth_kind(self):
# Not being listed makes the authorize + callback endpoints reject the kind and drops
# it out of the scheduled token refresh sweep.