: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
feat(integrations): add PKCE to Salesforce OAuth flow (#70054)
Harley Alexander48ab24c25f6c
diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 7127bf63f28c..0272ad140878 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -4,11 +4,12 @@ import jsonimport timeimport base64import hashlib+import secretsfrom collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Any, Literal, NamedTuple, NoReturn, Optional, Self-from urllib.parse import urlencode+from urllib.parse import parse_qs, urlencodefrom products.workflows.backend.providers import MAILDEV_MOCK_DNS_RECORDS@@ -19,6 +20,7 @@ if TYPE_CHECKING:from stripe import StripeClientfrom django.conf import settings+from django.core.cache import cachefrom django.db import models, transactionfrom django.db.models import Qfrom django.dispatch import receiver@@ -365,6 +367,8 @@ class OauthConfig:token_info_graphql_query: str | None = Nonetoken_info_config_fields: list[str] | None = Noneadditional_authorize_params: dict[str, str] | None = None+ # When true, the authorize/token-exchange flow uses PKCE (RFC 7636, S256)+ pkce: bool = False# When set, disconnecting the integration also revokes the grant at the providertoken_revoke_url: str | None = None@@ -455,6 +459,7 @@ class OauthIntegration:scope="full refresh_token",id_path="instance_url",name_path="instance_url",+ pkce=True,)elif kind == "salesforce-sandbox":if not settings.SALESFORCE_CONSUMER_KEY or not settings.SALESFORCE_CONSUMER_SECRET:@@ -469,6 +474,7 @@ class OauthIntegration:scope="full refresh_token",id_path="instance_url",name_path="instance_url",+ pkce=True,)elif kind == "hubspot":if not settings.HUBSPOT_APP_CLIENT_ID or not settings.HUBSPOT_APP_CLIENT_SECRET:@@ -776,6 +782,17 @@ class OauthIntegration:**(oauth_config.additional_authorize_params or {}),}+ if oauth_config.pkce:+ # The verifier is cached against the state token so the token exchange —+ # a separate request via the frontend callback — can retrieve it.+ code_verifier = secrets.token_urlsafe(64)+ code_challenge = (+ base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).rstrip(b"=").decode()+ )+ query_params["code_challenge"] = code_challenge+ query_params["code_challenge_method"] = "S256"+ cache.set(f"oauth_pkce_verifier/{token}", code_verifier, timeout=60 * 5)+return f"{oauth_config.authorize_url}?{urlencode(query_params)}"@classmethod@@ -784,6 +801,18 @@ class OauthIntegration:) -> Integration:oauth_config = cls.oauth_config_for_kind(kind)+ code_verifier: str | None = None+ if oauth_config.pkce:+ state_token = parse_qs(params.get("state", "")).get("token", [""])[0]+ if state_token:+ verifier_cache_key = f"oauth_pkce_verifier/{state_token}"+ code_verifier = cache.get(verifier_cache_key)+ cache.delete(verifier_cache_key) # single-use, per RFC 7636+ # Missing verifier still exchanges without PKCE (Salesforce accepts that until it+ # requires PKCE). Log it so the gap is visible before we enforce PKCE provider-side.+ if not code_verifier:+ logger.warning("oauth_pkce_verifier_missing", kind=kind, has_state_token=bool(state_token))+# Reddit uses HTTP Basic Auth https://github.com/reddit-archive/reddit/wiki/OAuth2 and requires a User-Agent headerif kind == "reddit-ads":res = requests.post(@@ -844,6 +873,7 @@ class OauthIntegration:"code": params["code"],"redirect_uri": redirect_uri,"grant_type": "authorization_code",+ **({"code_verifier": code_verifier} if code_verifier else {}),},timeout=10,)@@ -874,6 +904,7 @@ class OauthIntegration:"code": params["code"],"redirect_uri": OauthIntegration.redirect_uri(kind),"grant_type": "authorization_code",+ **({"code_verifier": code_verifier} if code_verifier else {}),},timeout=10,)diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex 76a2aab35a9b..42f9c92cc802 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -1,7 +1,9 @@import timeimport base64+import hashlibfrom datetime import UTC, datetime, timedeltafrom typing import Optional+from urllib.parse import parse_qsimport pytestfrom freezegun import freeze_time@@ -213,10 +215,35 @@ class TestOauthIntegrationModel(BaseTest):def test_authorize_url(self):with self.settings(**self.mock_settings):url = OauthIntegration.authorize_url("salesforce", token="state_token", next="/projects/test")- assert (- url- == "https://login.salesforce.com/services/oauth2/authorize?client_id=salesforce-client-id&scope=full+refresh_token&redirect_uri=https%3A%2F%2Flocalhost%3A8010%2Fintegrations%2Fsalesforce%2Fcallback&response_type=code&state=next%3D%252Fprojects%252Ftest%26token%3Dstate_token"+ base, _, query = url.partition("?")+ params = {k: v[0] for k, v in parse_qs(query).items()}+ assert base == "https://login.salesforce.com/services/oauth2/authorize"+ assert params == {+ "client_id": "salesforce-client-id",+ "scope": "full refresh_token",+ "redirect_uri": "https://localhost:8010/integrations/salesforce/callback",+ "response_type": "code",+ "state": "next=%2Fprojects%2Ftest&token=state_token",+ "code_challenge": params["code_challenge"],+ "code_challenge_method": "S256",+ }++ 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")+ params = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}+ verifier = cache.get("oauth_pkce_verifier/pkce_state_token")+ assert verifier+ expected_challenge = (+ base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode())+ assert params["code_challenge"] == expected_challenge++ def test_authorize_url_without_pkce_has_no_challenge(self):+ with self.settings(**self.mock_settings):+ url = OauthIntegration.authorize_url("hubspot", token="no_pkce_state_token", next="/projects/test")+ assert "code_challenge" not in url+ assert cache.get("oauth_pkce_verifier/no_pkce_state_token") is Nonedef test_authorize_url_with_additional_authorize_params(self):with self.settings(**self.mock_settings):@@ -262,6 +289,36 @@ class TestOauthIntegrationModel(BaseTest):"id_token": None,}+ @patch("posthog.models.integration.requests.post")+ def test_integration_from_oauth_response_sends_pkce_verifier(self, mock_post):+ with self.settings(**self.mock_settings):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {+ "access_token": "FAKES_ACCESS_TOKEN",+ "instance_url": "https://fake.salesforce.com",+ "expires_in": 3600,+ }++ # authorize_url caches the verifier; the exchange must send that exact value and consume it+ url = OauthIntegration.authorize_url("salesforce", token="exchange_state_token", next="/projects/test")+ challenge = parse_qs(url.partition("?")[2])["code_challenge"][0]+ verifier = cache.get("oauth_pkce_verifier/exchange_state_token")++ OauthIntegration.integration_from_oauth_response(+ "salesforce",+ self.team.id,+ self.user,+ {"code": "code", "state": "next=%2Fprojects%2Ftest&token=exchange_state_token"},+ )++ sent = mock_post.call_args.kwargs["data"]+ assert sent["code_verifier"] == verifier+ assert (+ base64.urlsafe_b64encode(hashlib.sha256(sent["code_verifier"].encode()).digest()).rstrip(b"=").decode()+ == challenge+ )+ assert cache.get("oauth_pkce_verifier/exchange_state_token") is None+@parameterized.expand([(