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): use sandbox developer secret for stripe sandbox installs (#56849)

Matt Brookere3e77098df16
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 22d03c48c409..08a40b49c2b4 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -13,6 +13,7 @@ from django.core.cache import cache
from django.test.client import Client as HttpClient
from django.utils import timezone
+from parameterized import parameterized
from rest_framework import status
from posthog.api.integration import IntegrationViewSet
@@ -1841,6 +1842,91 @@ class TestStripeIntegrationOAuthTokens:
assert call.kwargs["params"]["scope"] == {"type": "account"}
assert call.kwargs["options"] == {"stripe_account": "acct_789"}
+ @parameterized.expand(
+ [
+ ("write_uses_sandbox_when_flag_set", "write_posthog_secrets", {"is_sandbox": True}, "sk_test_sandbox"),
+ ("clear_uses_sandbox_when_flag_set", "clear_posthog_secrets", {"is_sandbox": True}, "sk_test_sandbox"),
+ ("write_uses_live_when_flag_missing", "write_posthog_secrets", {}, "sk_live"),
+ ]
+ )
+ @patch("posthog.models.integration.StripeClient")
+ @patch("posthog.models.integration.settings")
+ def test_stripe_client_secret_selection(
+ self, _name, method_name, config, expected_key, mock_settings, MockStripeClient
+ ):
+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
+ mock_settings.STRIPE_APP_SECRET_KEY = "sk_live"
+ mock_settings.STRIPE_APP_SANDBOX_SECRET_KEY = "sk_test_sandbox"
+ MockStripeClient.return_value = MagicMock()
+
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="stripe",
+ config=config,
+ sensitive_config={},
+ integration_id=f"acct_{_name}",
+ created_by=self.user,
+ )
+ stripe_int = StripeIntegration(integration)
+ if method_name == "write_posthog_secrets":
+ stripe_int.write_posthog_secrets(self.team.pk, self.user)
+ else:
+ stripe_int.clear_posthog_secrets()
+
+ MockStripeClient.assert_called_once_with(expected_key)
+
+ @patch("posthog.models.integration.capture_exception")
+ @patch("posthog.models.integration.StripeClient")
+ @patch("posthog.models.integration.settings")
+ def test_write_posthog_secrets_skips_when_sandbox_keys_missing(self, mock_settings, MockStripeClient, mock_capture):
+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
+ mock_settings.STRIPE_APP_CLIENT_ID = "ca_live"
+ mock_settings.STRIPE_APP_SECRET_KEY = "sk_live"
+ mock_settings.STRIPE_APP_SANDBOX_CLIENT_ID = None
+ mock_settings.STRIPE_APP_SANDBOX_SECRET_KEY = None
+ MockStripeClient.return_value = MagicMock()
+
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="stripe",
+ config={"is_sandbox": True},
+ sensitive_config={},
+ integration_id="acct_sandbox_missing_write",
+ created_by=self.user,
+ )
+ stripe_int = StripeIntegration(integration)
+ stripe_int.write_posthog_secrets(self.team.pk, self.user)
+
+ MockStripeClient.assert_not_called()
+ mock_capture.assert_called_once()
+ captured_exc = mock_capture.call_args.args[0]
+ assert isinstance(captured_exc, NotImplementedError)
+
+ @patch("posthog.models.integration.capture_exception")
+ @patch("posthog.models.integration.StripeClient")
+ @patch("posthog.models.integration.settings")
+ def test_clear_posthog_secrets_skips_and_revokes_tokens_when_sandbox_keys_missing(
+ self, mock_settings, MockStripeClient, mock_capture
+ ):
+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id
+ mock_settings.STRIPE_APP_CLIENT_ID = "ca_live"
+ mock_settings.STRIPE_APP_SECRET_KEY = "sk_live"
+ mock_settings.STRIPE_APP_SANDBOX_CLIENT_ID = None
+ mock_settings.STRIPE_APP_SANDBOX_SECRET_KEY = None
+ MockStripeClient.return_value = MagicMock()
+
+ integration, access_token, refresh_token = self._create_integration_with_tokens()
+ integration.config = {"is_sandbox": True}
+ integration.save()
+
+ stripe_int = StripeIntegration(integration)
+ stripe_int.clear_posthog_secrets()
+
+ MockStripeClient.assert_not_called()
+ mock_capture.assert_called_once()
+ assert not OAuthAccessToken.objects.filter(pk=access_token.pk).exists()
+ assert not OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists()
+
def _make_github_branches_response(names: list[str], has_next: bool = False) -> MagicMock:
"""Build a mock requests.Response for the GitHub branches API."""
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 3d89a3d2605d..991dd66c2830 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -741,6 +741,16 @@ class OauthIntegration:
"grant_type": "authorization_code",
},
)
+ if res.status_code == 200:
+ # Use the sandbox config for downstream API calls (account name lookup)
+ # and persist the flag so refresh / write_posthog_secrets / clear_posthog_secrets
+ # pick the sandbox secret without retrying.
+ oauth_config = sandbox_oauth_config
+ stripe_is_sandbox = True
+ else:
+ stripe_is_sandbox = False
+ else:
+ stripe_is_sandbox = False
else:
redirect_uri = OauthIntegration.redirect_uri(kind)
res = requests.post(
@@ -947,6 +957,12 @@ class OauthIntegration:
# Default to 1 hour for Salesforce if not provided (conservative)
config["expires_in"] = 3600
+ if kind == "stripe":
+ # Persisted so downstream Stripe API calls (refresh_access_token,
+ # StripeIntegration.write_posthog_secrets / clear_posthog_secrets)
+ # pick the right developer secret without error-driven retries.
+ config["is_sandbox"] = stripe_is_sandbox
+
config["refreshed_at"] = int(time.time())
integration, created = Integration.objects.update_or_create(
@@ -992,7 +1008,8 @@ class OauthIntegration:
"""
Refresh the access token for the integration if necessary
"""
- oauth_config = self.oauth_config_for_kind(self.integration.kind)
+ is_sandbox = _stripe_integration_is_sandbox(self.integration)
+ oauth_config = self.oauth_config_for_kind(self.integration.kind, is_sandbox=is_sandbox)
# Clear out previous token refreshing errors, as they'll be re-set below if another error occurs
self.integration.errors = ""
@@ -3381,6 +3398,16 @@ class AzureBlobIntegration:
return None
+def _stripe_integration_is_sandbox(integration: Integration) -> bool:
+ """True when this is a Stripe integration provisioned via the sandbox channel.
+
+ Strict identity check on the config flag - a malformed string write (e.g. "false")
+ fails closed to live rather than escalating to sandbox-secret usage. Returns
+ False for non-stripe integrations so non-Stripe call sites can pass through.
+ """
+ return integration.kind == "stripe" and integration.config.get("is_sandbox") is True
+
+
class StripeIntegration:
integration: Integration
@@ -3411,6 +3438,28 @@ class StripeIntegration:
raise ValueError(f"Expected stripe integration, got {integration.kind}")
self.integration = integration
+ @property
+ def is_sandbox(self) -> bool:
+ return _stripe_integration_is_sandbox(self.integration)
+
+ def _stripe_client(self) -> StripeClient | None:
+ # Sandbox accounts are issued by a separate Stripe app (live vs sandbox), so the
+ # Apps Secret Store and account-scoped API calls must authenticate with the matching
+ # developer secret. Returns None when the required env vars are missing so callers
+ # can skip Stripe API calls without raising past their per-secret error handling.
+ try:
+ oauth_config = OauthIntegration.oauth_config_for_kind("stripe", is_sandbox=self.is_sandbox)
+ except NotImplementedError as e:
+ capture_exception(
+ e,
+ {
+ "stripe_user_id": self.integration.integration_id,
+ "is_sandbox": self.is_sandbox,
+ },
+ )
+ return None
+ return StripeClient(oauth_config.client_secret)
+
def write_posthog_secrets(self, team_id: int, created_by: "User") -> None:
"""Write PostHog OAuth tokens to Stripe's Secret Store so the Stripe App can call PostHog APIs."""
@@ -3452,7 +3501,9 @@ class StripeIntegration:
"posthog_oauth_client_id": oauth_app.client_id,
}
- client = StripeClient(settings.STRIPE_APP_SECRET_KEY)
+ client = self._stripe_client()
+ if client is None:
+ return
for name, payload in secrets.items():
try:
@@ -3465,12 +3516,13 @@ class StripeIntegration:
options={"stripe_account": stripe_user_id},
)
except Exception as e:
- capture_exception(e)
- logger.warning(
- "Failed to write secret to Stripe",
- secret_name=name,
- stripe_user_id=stripe_user_id,
- error=str(e),
+ capture_exception(
+ e,
+ {
+ "secret_name": name,
+ "stripe_user_id": stripe_user_id,
+ "is_sandbox": self.is_sandbox,
+ },
)
def clear_posthog_secrets(self) -> None:
@@ -3479,7 +3531,10 @@ class StripeIntegration:
if not stripe_user_id:
raise ValueError("Missing stripe_user_id on integration")
- client = StripeClient(settings.STRIPE_APP_SECRET_KEY)
+ client = self._stripe_client()
+ if client is None:
+ self._destroy_posthog_oauth_tokens()
+ return
for name in (
"posthog_region",
@@ -3497,12 +3552,13 @@ class StripeIntegration:
options={"stripe_account": stripe_user_id},
)
except Exception as e:
- capture_exception(e)
- logger.warning(
- "Failed to clear secret from Stripe",
- secret_name=name,
- stripe_user_id=stripe_user_id,
- error=str(e),
+ capture_exception(
+ e,
+ {
+ "secret_name": name,
+ "stripe_user_id": stripe_user_id,
+ "is_sandbox": self.is_sandbox,
+ },
)
self._destroy_posthog_oauth_tokens()
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index 3e6b8db002b4..8981159472f7 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -810,6 +810,80 @@ class TestOauthIntegrationModel(BaseTest):
mock_reload.assert_called_once_with(self.team.id, [integration.id])
+ @patch("posthog.models.integration.requests.post")
+ def test_stripe_oauth_persists_is_sandbox_false_for_live_install(self, mock_post):
+ mock_post.return_value.status_code = 200
+ mock_post.return_value.json.return_value = {
+ "access_token": "FAKE_ACCESS",
+ "refresh_token": "FAKE_REFRESH",
+ "stripe_user_id": "acct_live_1",
+ "account_name": "Live Account",
+ "expires_in": 3600,
+ }
+
+ with self.settings(
+ STRIPE_APP_CLIENT_ID="ca_live_clientid",
+ STRIPE_APP_SECRET_KEY="sk_live_secret",
+ ):
+ integration = OauthIntegration.integration_from_oauth_response(
+ "stripe",
+ self.team.id,
+ self.user,
+ {"code": "ac_live_code"},
+ )
+
+ assert integration.config.get("is_sandbox") is False
+
+ @patch("posthog.models.integration.requests.post")
+ def test_stripe_oauth_persists_is_sandbox_true_after_sandbox_fallback(self, mock_post):
+ first_response = MagicMock(
+ status_code=400,
+ text='{"error":"invalid_grant","error_description":"Authorization code provided does not belong to you"}',
+ )
+ first_response.json.return_value = {"error": "invalid_grant"}
+ second_response = MagicMock(status_code=200)
+ second_response.json.return_value = {
+ "access_token": "FAKE_SANDBOX_ACCESS",
+ "refresh_token": "FAKE_SANDBOX_REFRESH",
+ "stripe_user_id": "acct_sandbox_1",
+ "account_name": "Sandbox Account",
+ "expires_in": 3600,
+ }
+ mock_post.side_effect = [first_response, second_response]
+
+ with self.settings(
+ STRIPE_APP_CLIENT_ID="ca_live_clientid",
+ STRIPE_APP_SANDBOX_CLIENT_ID="ca_sandbox_clientid",
+ STRIPE_APP_SECRET_KEY="sk_live_secret",
+ STRIPE_APP_SANDBOX_SECRET_KEY="sk_test_sandbox_secret",
+ ):
+ integration = OauthIntegration.integration_from_oauth_response(
+ "stripe",
+ self.team.id,
+ self.user,
+ {"code": "ac_sandbox_code"},
+ )
+
+ assert integration.config.get("is_sandbox") is True
+
+ @patch("posthog.models.integration.reload_integrations_on_workers")
+ @patch("posthog.models.integration.requests.post")
+ def test_stripe_refresh_access_token_uses_sandbox_secret_when_flag_set(self, mock_post, mock_reload):
+ mock_post.return_value.status_code = 200
+ mock_post.return_value.json.return_value = {"access_token": "REFRESHED", "expires_in": 1000}
+
+ integration = self.create_integration(kind="stripe", config={"expires_in": 1000, "is_sandbox": True})
+
+ with self.settings(
+ STRIPE_APP_CLIENT_ID="ca_live_clientid",
+ STRIPE_APP_SANDBOX_CLIENT_ID="ca_sandbox_clientid",
+ STRIPE_APP_SECRET_KEY="sk_live_secret",
+ STRIPE_APP_SANDBOX_SECRET_KEY="sk_test_sandbox_secret",
+ ):
+ OauthIntegration(integration).refresh_access_token()
+
+ assert mock_post.call_args.kwargs["auth"].username == "sk_test_sandbox_secret"
+
class TestGoogleCloudIntegrationModel(BaseTest):
mock_keyfile = {