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): refresh salesforce sandbox tokens at instance_url (#72487)

Meikel Ratz3cd8623eff17
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 6ab6503fd65f..5fc0ec795ad5 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -9,7 +9,7 @@ from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, Literal, NamedTuple, NoReturn, Optional, Self
-from urllib.parse import parse_qs, urlencode
+from urllib.parse import parse_qs, urlencode, urlparse
from products.workflows.backend.providers import MAILDEV_MOCK_DNS_RECORDS
@@ -490,6 +490,33 @@ def _build_posthog_slack_scope() -> str:
POSTHOG_SLACK_SCOPE = _build_posthog_slack_scope()
+def _salesforce_instance_host(instance_url: str | None) -> str | None:
+ # Every Salesforce-issued instance_url host ends in .salesforce.com: login/test, the
+ # pod hosts (na1.salesforce.com, ...), and My Domain variants like
+ # acme.my.salesforce.com and acme--sandbox.sandbox.my.salesforce.com. Validating at
+ # the point of use means a stray write to integration.config can't cause the shared
+ # SALESFORCE_CONSUMER_SECRET to be POSTed to an attacker origin during a refresh,
+ # even if a future endpoint or admin tool exposes config as writable. Returns
+ # "https://<host>" for a legitimate value, None otherwise (caller falls back to the
+ # hardcoded prod URL).
+ if not instance_url:
+ return None
+ try:
+ parsed = urlparse(instance_url)
+ # port/hostname/username/password are lazily parsed from netloc on access, and
+ # port in particular raises ValueError on a non-numeric or out-of-range value
+ # (e.g. https://host:abc/). Keep every derived-property read inside the try so a
+ # poisoned instance_url can never crash the refresh sweep.
+ if parsed.scheme != "https" or parsed.port is not None or parsed.username or parsed.password:
+ return None
+ host = (parsed.hostname or "").lower()
+ except ValueError:
+ return None
+ if not host.endswith(".salesforce.com"):
+ return None
+ return f"https://{host}"
+
+
class OauthIntegration:
supported_kinds = [
"slack",
@@ -1269,12 +1296,14 @@ class OauthIntegration:
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"
+ # 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 validated instance host so a stray write to config can't redirect the token to
+ # an attacker origin.
+ if self.integration.kind == "salesforce":
+ allowed_host = _salesforce_instance_host(self.integration.config.get("instance_url"))
+ if allowed_host:
+ revoke_url = f"{allowed_host}/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
@@ -1368,8 +1397,20 @@ class OauthIntegration:
timeout=10,
)
else:
+ token_url = oauth_config.token_url
+ # Salesforce sandbox integrations are stored as kind "salesforce" (the sandbox
+ # is only a token-exchange fallback in the OAuth callback), so the static prod
+ # token URL would refuse a sandbox-issued refresh_token. Refresh at the org's
+ # own instance host instead. Validate the host before sending client_secret +
+ # refresh_token so a stray write to config can't exfiltrate the fleet-wide
+ # Salesforce app secret; fall back to the hardcoded prod URL on rejection.
+ if kind == "salesforce":
+ allowed_host = _salesforce_instance_host(self.integration.config.get("instance_url"))
+ if allowed_host:
+ token_url = f"{allowed_host}/services/oauth2/token"
+
return requests.post(
- oauth_config.token_url,
+ token_url,
data={
"client_id": client_id,
"client_secret": client_secret,
@@ -1377,6 +1418,7 @@ class OauthIntegration:
"grant_type": "refresh_token",
},
timeout=10,
+ allow_redirects=False,
)
@staticmethod
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index 7ac9d5500a60..ce7ab48eebe8 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -540,6 +540,7 @@ class TestOauthIntegrationModel(BaseTest):
"refresh_token": "REFRESH",
},
timeout=10,
+ allow_redirects=False,
)
assert integration.config["expires_in"] == 1000
@@ -991,6 +992,78 @@ class TestOauthIntegrationModel(BaseTest):
mock_reload.assert_called_once_with(self.team.id, [integration.id])
+ @patch("posthog.models.integration.reload_integrations_on_workers")
+ @patch("posthog.models.integration.requests.post")
+ def test_salesforce_refresh_uses_instance_url_for_sandbox(self, mock_post, mock_reload):
+ # Sandbox integrations are stored as kind="salesforce" (the sandbox is a token-exchange
+ # fallback in the OAuth callback), so the config's instance_url is the only signal that
+ # the refresh must go to test.salesforce.com or the org's own host rather than the
+ # hardcoded prod token URL. Salesforce rejects a sandbox refresh_token posted to
+ # login.salesforce.com, which shows up to users as "Authentication token could not be
+ # refreshed. Please reconnect." within a few hours of connecting.
+ mock_post.return_value.status_code = 200
+ mock_post.return_value.json.return_value = {
+ "access_token": "REFRESHED_ACCESS_TOKEN",
+ "expires_in": 3600,
+ }
+
+ sandbox_instance_url = "https://ryan-co--sandbox.sandbox.my.salesforce.com"
+ integration = self.create_integration(
+ kind="salesforce",
+ config={"instance_url": sandbox_instance_url},
+ )
+
+ with self.settings(**self.mock_settings):
+ OauthIntegration(integration).refresh_access_token()
+
+ assert integration.errors == ""
+ assert integration.sensitive_config["access_token"] == "REFRESHED_ACCESS_TOKEN"
+
+ called_url = mock_post.call_args.args[0]
+ assert called_url == f"{sandbox_instance_url}/services/oauth2/token"
+
+ @parameterized.expand(
+ [
+ ("attacker_https", "https://attacker.example.com"),
+ ("attacker_lookalike_suffix", "https://salesforce.com.attacker.example"),
+ ("attacker_lookalike_prefix", "https://acmesalesforce.com"),
+ ("http_scheme_downgrade", "http://acme.my.salesforce.com"),
+ ("with_userinfo", "https://user:[email protected]"),
+ ("with_port", "https://acme.my.salesforce.com:8443"),
+ ("invalid_port_raises_valueerror", "https://acme.my.salesforce.com:abc"),
+ ("garbage_value", "not a url"),
+ ("empty_value", ""),
+ ]
+ )
+ @patch("posthog.models.integration.reload_integrations_on_workers")
+ @patch("posthog.models.integration.requests.post")
+ def test_salesforce_refresh_rejects_untrusted_instance_url(self, _name, bad_instance_url, mock_post, mock_reload):
+ # If a future write path (a partial_update action, an admin tool, a data migration)
+ # lets an attacker set instance_url, the refresh must not POST client_secret +
+ # refresh_token to that origin - the client_secret is fleet-wide and its leak forces
+ # rotation and reconnect for every Salesforce integration. Any instance_url that isn't
+ # an https .salesforce.com host falls back to the hardcoded prod token URL, and the
+ # refresh must not follow redirects that would move the secret to another host.
+ mock_post.return_value.status_code = 200
+ mock_post.return_value.json.return_value = {
+ "access_token": "REFRESHED_ACCESS_TOKEN",
+ "expires_in": 3600,
+ }
+
+ integration = self.create_integration(
+ kind="salesforce",
+ config={"instance_url": bad_instance_url},
+ )
+
+ with self.settings(**self.mock_settings):
+ OauthIntegration(integration).refresh_access_token()
+
+ called_url = mock_post.call_args.args[0]
+ assert called_url == "https://login.salesforce.com/services/oauth2/token"
+
+ called_kwargs = mock_post.call_args.kwargs
+ assert called_kwargs["allow_redirects"] is False
+
@patch("posthog.models.integration.reload_integrations_on_workers")
@patch("posthog.models.integration.requests.post")
def test_non_salesforce_refresh_access_token_preserves_none_expires_in(self, mock_post, mock_reload):