: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
fix(integrations): narrow stripe app oauth scopes to the five it calls (#83368)
Matt Brookerfa818301bf0c
diff --git a/ee/partners/stripe/api/provisioning/constants.py b/ee/partners/stripe/api/provisioning/constants.pyindex 78731b51933e..0a9e09f86ca5 100644--- a/ee/partners/stripe/api/provisioning/constants.py+++ b/ee/partners/stripe/api/provisioning/constants.py@@ -4,8 +4,6 @@ from __future__ import annotationsimport re-from posthog.models.integration import StripeIntegration-SUPPORTED_VERSIONS = ["0.1d"]MAX_TIMESTAMP_DRIFT_SECONDS = 300@@ -21,7 +19,26 @@ ACCESS_TOKEN_EXPIRY_SECONDS = 365 * 24 * 3600# Default scopes for a Stripe-issued token when the auth code requested none.# This namespace enforces no scope ceiling; a code that names scopes gets those.-STRIPE_CONTRACTED_SCOPES: list[str] = StripeIntegration.SCOPES.split()+# Listed explicitly rather than aliasing StripeIntegration.SCOPES: that list bounds a+# credential shared across a merchant's Stripe account, while these back a provisioned+# user's own PAT. Narrowing one must not silently narrow the other.+STRIPE_CONTRACTED_SCOPES: list[str] = [+ "customer_journey:read",+ "query:read",+ "conversation:read",+ "conversation:write",+ "experiment:read",+ "feature_flag:read",+ "insight:read",+ "organization:read",+ "person:read",+ "project:read",+ "ticket:read",+ "ticket:write",+ "user:read",+ "hog_flow:read",+ "hog_flow:write",+]# Mirrors PersonalAPIKey.label's CharField(max_length=40) - keep in sync if that ever changes.PROVISIONED_PAT_LABEL_MAX_LENGTH = 40diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex 0fe7d7b5eb47..3203e653c6c8 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -16,6 +16,7 @@ from django.utils import timezoneimport structlogfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import extend_schema, extend_schema_serializer+from prometheus_client import Counterfrom rest_framework import mixins, serializers, status, viewsetsfrom rest_framework.exceptions import APIException, PermissionDenied, ValidationErrorfrom rest_framework.permissions import IsAuthenticated@@ -114,6 +115,16 @@ from products.workflows.backend.services.integration_usage import get_active_hoglogger = structlog.get_logger(__name__)+# The published app uses Connect-OAuth, which never signs its callback, so every real install+# lands unsigned and that alone says nothing. What is alertable is volume: this path can link a+# Stripe account to whichever project the browser is signed into, so a spike is the abuse signal.+# The label exists so the split moves if Stripe ever starts signing these.+stripe_marketplace_install_counter = Counter(+ "stripe_marketplace_install",+ "Stripe marketplace install callbacks, by whether an install signature was present and valid",+ labelnames=["signature_state"],+)+GITHUB_REPOSITORY_NAME_RE = re.compile(r"[A-Za-z0-9_.\-]+")@@ -862,6 +873,21 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial"Stripe install signature could not be verified.",code="stripe_install_signature_invalid",)+ stripe_marketplace_install_counter.labels(signature_state="verified").inc()+ logger.info(+ "stripe.marketplace_install_signature_verified",+ team_id=team_id,+ stripe_user_id=stripe_user_id,+ user_id=request.user.id,+ )+ else:+ stripe_marketplace_install_counter.labels(signature_state="absent").inc()+ logger.info(+ "stripe.marketplace_install_no_signature",+ team_id=team_id,+ stripe_user_id=stripe_user_id,+ user_id=request.user.id,+ )conflicting = (Integration.objects.filter(team_id=team_id, kind="stripe")diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex c67e07c05b5a..bf936ec33481 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -16,9 +16,11 @@ from django.utils import timezoneimport requestsfrom parameterized import parameterized+from prometheus_client import REGISTRYfrom rest_framework import statusfrom rest_framework.exceptions import ValidationErrorfrom slack_sdk.errors import SlackApiError+from structlog.testing import capture_logsfrom posthog.api.github_callback.personal_state import usable_personal_github_tokenfrom posthog.api.github_callback.state import store_unified_authorize_state@@ -4073,6 +4075,84 @@ class TestStripeIntegration:assert response.status_code == status.HTTP_201_CREATEDmock_oauth_response.assert_called_once()+ @pytest.mark.parametrize(+ "include_install_signature,expected_event,expected_level,expected_label",+ [+ (False, "stripe.marketplace_install_no_signature", "info", "absent"),+ (True, "stripe.marketplace_install_signature_verified", "info", "verified"),+ ],+ )+ @patch("posthog.api.integration.StripeIntegration")+ @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")+ def test_marketplace_callback_logs_signature_state(+ self,+ mock_oauth_response,+ MockStripeIntegration,+ include_install_signature,+ expected_event,+ expected_level,+ expected_label,+ stripe_settings,+ client: HttpClient,+ ):+ mock_oauth_response.return_value = self._create_stripe_integration()+ MockStripeIntegration.return_value = MagicMock()++ config: dict = {+ "code": "oauth_code_123",+ "stripe_user_id": "acct_123",+ "account_id": "acct_123",+ "user_id": "usr_abc",+ }+ if include_install_signature:+ config["install_signature"] = self._make_install_signature(+ state="", user_id="usr_abc", account_id="acct_123"+ )++ counter_labels = {"signature_state": expected_label}+ before = REGISTRY.get_sample_value("stripe_marketplace_install_total", counter_labels) or 0.0++ client.force_login(self.user)+ with capture_logs() as logs:+ response = client.post(+ f"/api/environments/{self.team.pk}/integrations",+ {"kind": "stripe", "config": config},+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_201_CREATED+ entries = [entry for entry in logs if entry["event"] == expected_event]+ assert len(entries) == 1+ assert entries[0]["log_level"] == expected_level+ assert entries[0]["team_id"] == self.team.pk+ assert entries[0]["stripe_user_id"] == "acct_123"+ assert entries[0]["user_id"] == self.user.pk++ after = REGISTRY.get_sample_value("stripe_marketplace_install_total", counter_labels) or 0.0+ assert after - before == 1.0++ @patch("posthog.api.integration.StripeIntegration")+ @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")+ def test_posthog_initiated_install_emits_no_marketplace_log(+ self, mock_oauth_response, MockStripeIntegration, stripe_settings, client: HttpClient+ ):+ mock_oauth_response.return_value = self._create_stripe_integration()+ MockStripeIntegration.return_value = MagicMock()++ client.force_login(self.user)+ with capture_logs() as logs:+ response = client.post(+ f"/api/environments/{self.team.pk}/integrations",+ {+ "kind": "stripe",+ "config": {"state": "next=/foo&token=abc123", "code": "oauth_code_999"},+ },+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_201_CREATED+ assert not [entry for entry in logs if entry["event"].startswith("stripe.marketplace_install")]+# The Stripe Apps OAuth flow (used by stripe_api_access_type: oauth) doesn't sign the# callback redirect — only the install-link OAuth mechanism emits install_signature.# The conflict guard is the defense-in-depth here, not signature verification.@@ -4461,6 +4541,35 @@ class TestStripeIntegrationOAuthTokens:assert secret_payloads["posthog_project_id"] == str(self.team.pk)assert secret_payloads["posthog_oauth_client_id"] == self.oauth_app.client_id+ @patch("stripe.StripeClient")+ @patch("posthog.models.integration.settings")+ def test_write_posthog_secrets_mints_read_only_token(self, mock_settings, MockStripeClient):+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id+ mock_settings.STRIPE_APP_SECRET_KEY = "sk_test"+ MockStripeClient.return_value = MagicMock()++ integration = Integration.objects.create(+ team=self.team,+ kind="stripe",+ config={},+ sensitive_config={},+ integration_id="acct_scope",+ created_by=self.user,+ )+ StripeIntegration(integration).write_posthog_secrets(self.team.pk, self.user)++ token = OAuthAccessToken.objects.filter(application=self.oauth_app).latest("id")++ assert set(token.scope.split()) == {+ "customer_journey:read",+ "experiment:read",+ "feature_flag:read",+ "insight:read",+ "query:read",+ }+ assert not [scope for scope in token.scope.split() if scope.endswith(":write")]+ assert token.scoped_teams == [self.team.pk]+@patch("stripe.StripeClient")@patch("posthog.models.integration.settings")def test_clear_posthog_secrets_uses_account_scope(self, mock_settings, MockStripeClient):diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 14d15ce838a9..cfc182a48a02 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -4952,25 +4952,16 @@ class S3CompatibleIntegration:class StripeIntegration:integration: Integration- # These are the scopes we'll give Stripe when creating a local OAuth App- # and sending them access+ # Every endpoint services/stripe-app/src/posthog/client.ts calls, and nothing else.+ # This token is readable by every member of the customer's Stripe account, so anything+ # granted here is granted to all of them. Read-only by design; do not add a write scope.SCOPES: str = " ".join(["customer_journey:read",- "query:read",- "conversation:read",- "conversation:write","experiment:read","feature_flag:read","insight:read",- "organization:read",- "person:read",- "project:read",- "ticket:read",- "ticket:write",- "user:read",- "hog_flow:read",- "hog_flow:write",+ "query:read",])