: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): split the stripe marketplace oauth app from the orchestrator (#84698)
Matt Brookerad13637739a8
diff --git a/ee/partners/stripe/api/provisioning/authentication.py b/ee/partners/stripe/api/provisioning/authentication.pyindex 2cc840b55dfd..137ca43cc7f7 100644--- a/ee/partners/stripe/api/provisioning/authentication.py+++ b/ee/partners/stripe/api/provisioning/authentication.py@@ -3,10 +3,11 @@The only accepted identity is the Stripe orchestrator: tokens issued to theStripe Projects OAuth app (resolved by``settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID``). Tokens bound to any other-application are rejected outright. Identity is the whole check - this namespace-is deliberately isolated from the provisioning-partner config model, so no-``provisioning_*`` capability flags on the app are consulted; the Stripe app is-trusted with full access.+application are rejected outright.++Identity is most of the check, not all of it: ``DeepLinksView`` additionally+requires ``can_issue_deep_links`` on the application, because a deep link mints+a full web session. Other capability flags are not consulted here."""from __future__ import annotationsdiff --git a/ee/partners/stripe/api/provisioning/test/base.py b/ee/partners/stripe/api/provisioning/test/base.pyindex fc11c0bbde0d..ae7a462d6ae1 100644--- a/ee/partners/stripe/api/provisioning/test/base.py+++ b/ee/partners/stripe/api/provisioning/test/base.py@@ -31,8 +31,6 @@ class StripeProvisioningTestBase(APIBaseTest):self._ensure_stripe_oauth_app()def _ensure_stripe_oauth_app(self):- # No provisioning_* flags: this namespace authorizes by identity- # (client_id) alone and does not read the app's provisioning config.self.stripe_app, _ = OAuthApplication.objects.get_or_create(client_id=TEST_STRIPE_OAUTH_CLIENT_ID,defaults={@@ -44,6 +42,7 @@ class StripeProvisioningTestBase(APIBaseTest):"algorithm": "RS256",},)+ self.stripe_app.update_provisioning(can_issue_deep_links=True)def _create_other_partner_app(self, **overrides):defaults = {diff --git a/ee/partners/stripe/api/provisioning/test/test_deep_links.py b/ee/partners/stripe/api/provisioning/test/test_deep_links.pyindex 0fa9e3383004..4bd631cacb19 100644--- a/ee/partners/stripe/api/provisioning/test/test_deep_links.py+++ b/ee/partners/stripe/api/provisioning/test/test_deep_links.py@@ -33,6 +33,15 @@ class TestDeepLinks(StripeProvisioningTestBase):assert me.status_code == 200assert me.json()["email"] == self.user.email+ def test_deep_link_refused_when_the_application_cannot_issue_them(self):+ self.stripe_app.update_provisioning(can_issue_deep_links=False)+ token = self._get_bearer_token()++ res = self._post_signed_with_bearer(DEEP_LINKS_URL, data={"purpose": "dashboard"}, token=token)++ assert res.status_code == 403+ assert res.json()["error"]["code"] == "deep_links_not_enabled"+@parameterized.expand([("absolute_url", "https://evil.example.com/phish"),diff --git a/ee/partners/stripe/api/provisioning/views.py b/ee/partners/stripe/api/provisioning/views.pyindex 39d4961622e7..313d3bd463da 100644--- a/ee/partners/stripe/api/provisioning/views.py+++ b/ee/partners/stripe/api/provisioning/views.py@@ -900,6 +900,15 @@ class DeepLinksView(StripeResourceAPIView):def post(self, request: Request) -> Response:access_token = cast(OAuthAccessToken, request.auth)+ # A deep link logs its user straight in, so reaching this namespace is not enough.+ if not access_token.application.provisioning.can_issue_deep_links:+ capture_provisioning_event("deep_link_created", "not_enabled", partner=access_token.application)+ raise SpecError(+ "deep_links_not_enabled",+ "Deep links are not enabled for this partner",+ status=403,+ )+serializer = DeepLinkSerializer(data=request.data)if not serializer.is_valid():raise SpecError("invalid_request", first_error_message(serializer.errors))diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex 3203e653c6c8..3b27a752c888 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -914,7 +914,12 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerialif validated_data["kind"] == "stripe":try:stripe_integration = StripeIntegration(instance)- stripe_integration.write_posthog_secrets(team_id, request.user)+ unwritten = stripe_integration.write_posthog_secrets(team_id, request.user)+ if unwritten:+ capture_exception(+ Exception(f"Stripe secret store not fully written: {', '.join(unwritten)}"),+ {"team_id": team_id, "integration_id": instance.id},+ )except Exception as e:capture_exception(e)diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex a5d55926abcb..2350461ceb86 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -40,6 +40,7 @@ from posthog.models.integration import (GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS,PRIVATE_CHANNEL_WITHOUT_ACCESS,SLACK_INTEGRATION_KINDS,+ STRIPE_POSTHOG_SECRET_NAMES,EmailIntegration,GitHubInstallationAccess,GitHubIntegration,@@ -4532,7 +4533,8 @@ class TestStripeIntegrationOAuthTokens:@patch("posthog.models.integration.stripe.settings")def test_destroy_oauth_tokens_deletes_tokens(self, mock_settings):- mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = "orchestrator_client_id"+ mock_settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = self.oauth_app.client_idintegration, access_token, refresh_token = self._create_integration_with_tokens()stripe_int = StripeIntegration(integration)@@ -4543,7 +4545,8 @@ class TestStripeIntegrationOAuthTokens:@patch("posthog.models.integration.stripe.settings")def test_destroy_oauth_tokens_only_affects_same_team(self, mock_settings):- mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = "orchestrator_client_id"+ mock_settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = self.oauth_app.client_idintegration, _, _ = self._create_integration_with_tokens()other_team = Team.objects.create(organization=self.organization, name="Other Team")@@ -4572,6 +4575,7 @@ class TestStripeIntegrationOAuthTokens:@patch("posthog.models.integration.stripe.settings")def test_destroy_oauth_tokens_noop_when_no_oauth_app(self, mock_settings):mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = None+ mock_settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = Noneintegration, access_token, refresh_token = self._create_integration_with_tokens()stripe_int = StripeIntegration(integration)@@ -4580,11 +4584,77 @@ class TestStripeIntegrationOAuthTokens:assert OAuthAccessToken.objects.filter(pk=access_token.pk).exists()assert OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists()+ @pytest.mark.parametrize("marketplace_setting", ["configured", "unset", "equal_to_orchestrator"])@patch("stripe.StripeClient")@patch("posthog.models.integration.oauth.settings")@patch("posthog.models.integration.stripe.settings")- def test_write_posthog_secrets_uses_account_scope(self, mock_settings, mock_oauth_settings, MockStripeClient):+ def test_marketplace_token_never_mints_on_the_orchestrator_application(+ self, mock_settings, mock_oauth_settings, MockStripeClient, marketplace_setting+ ):+ orchestrator_app = OAuthApplication.objects.create(+ name="Stripe orchestrator",+ client_id="orchestrator_client_id",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ algorithm="RS256",+ )+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = orchestrator_app.client_id+ mock_settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = {+ "configured": self.oauth_app.client_id,+ "unset": "",+ "equal_to_orchestrator": orchestrator_app.client_id,+ }[marketplace_setting]+ mock_oauth_settings.STRIPE_APP_CLIENT_ID = "stripe_app_client_id"+ mock_oauth_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_split",+ created_by=self.user,+ )+ unwritten = StripeIntegration(integration).write_posthog_secrets(self.team.pk, self.user)++ minted = OAuthAccessToken.objects.filter(scoped_teams__contains=[self.team.pk])+ assert not minted.filter(application=orchestrator_app).exists()++ if marketplace_setting == "configured":+ assert unwritten == []+ assert minted.latest("id").application == self.oauth_app+ else:+ assert unwritten == list(STRIPE_POSTHOG_SECRET_NAMES)+ assert not minted.exists()++ @patch("posthog.models.integration.stripe.settings")+ def test_destroy_oauth_tokens_spans_the_pre_split_application(self, mock_settings):+ marketplace_app = OAuthApplication.objects.create(+ name="Stripe marketplace",+ client_id="marketplace_client_id",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ algorithm="RS256",+ )mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id+ mock_settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = marketplace_app.client_id++ integration, legacy_access, legacy_refresh = self._create_integration_with_tokens()++ StripeIntegration(integration)._destroy_posthog_oauth_tokens()++ assert not OAuthAccessToken.objects.filter(pk=legacy_access.pk).exists()+ assert not OAuthRefreshToken.objects.filter(pk=legacy_refresh.pk).exists()++ @patch("stripe.StripeClient")+ @patch("posthog.models.integration.oauth.settings")+ @patch("posthog.models.integration.stripe.settings")+ def test_write_posthog_secrets_uses_account_scope(self, mock_settings, mock_oauth_settings, MockStripeClient):+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = "orchestrator_client_id"+ mock_settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = self.oauth_app.client_idmock_oauth_settings.STRIPE_APP_CLIENT_ID = "stripe_app_client_id"mock_oauth_settings.STRIPE_APP_SECRET_KEY = "sk_test"mock_client = MagicMock()@@ -4615,7 +4685,8 @@ class TestStripeIntegrationOAuthTokens:@patch("posthog.models.integration.oauth.settings")@patch("posthog.models.integration.stripe.settings")def test_write_posthog_secrets_mints_read_only_token(self, mock_settings, mock_oauth_settings, MockStripeClient):- mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = "orchestrator_client_id"+ mock_settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = self.oauth_app.client_idmock_oauth_settings.STRIPE_APP_CLIENT_ID = "stripe_app_client_id"mock_oauth_settings.STRIPE_APP_SECRET_KEY = "sk_test"MockStripeClient.return_value = MagicMock()@@ -4649,6 +4720,7 @@ class TestStripeIntegrationOAuthTokens:mock_oauth_settings.STRIPE_APP_CLIENT_ID = "stripe_app_client_id"mock_oauth_settings.STRIPE_APP_SECRET_KEY = "sk_test"mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = None+ mock_settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = Nonemock_client = MagicMock()MockStripeClient.return_value = mock_client@@ -4681,7 +4753,8 @@ class TestStripeIntegrationOAuthTokens:def test_stripe_client_uses_live_secret(self, _name, method_name, mock_settings, mock_oauth_settings, MockStripeClient):- mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = "orchestrator_client_id"+ mock_settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = self.oauth_app.client_idmock_oauth_settings.STRIPE_APP_CLIENT_ID = "stripe_app_client_id"mock_oauth_settings.STRIPE_APP_SECRET_KEY = "sk_live"MockStripeClient.return_value = MagicMock()@@ -4709,7 +4782,8 @@ class TestStripeIntegrationOAuthTokens:def test_write_posthog_secrets_skips_when_keys_missing(self, mock_settings, mock_oauth_settings, MockStripeClient, mock_capture):- mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = "orchestrator_client_id"+ mock_settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = self.oauth_app.client_idmock_oauth_settings.STRIPE_APP_CLIENT_ID = Nonemock_oauth_settings.STRIPE_APP_SECRET_KEY = NoneMockStripeClient.return_value = MagicMock()@@ -4737,7 +4811,8 @@ class TestStripeIntegrationOAuthTokens:def test_clear_posthog_secrets_skips_and_revokes_tokens_when_keys_missing(self, mock_settings, mock_oauth_settings, MockStripeClient, mock_capture):- mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = self.oauth_app.client_id+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = "orchestrator_client_id"+ mock_settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = self.oauth_app.client_idmock_oauth_settings.STRIPE_APP_CLIENT_ID = Nonemock_oauth_settings.STRIPE_APP_SECRET_KEY = NoneMockStripeClient.return_value = MagicMock()diff --git a/posthog/management/commands/create_stripe_marketplace_oauth_app.py b/posthog/management/commands/create_stripe_marketplace_oauth_app.pynew file mode 100644index 000000000000..ea2529e67ac5--- /dev/null+++ b/posthog/management/commands/create_stripe_marketplace_oauth_app.py@@ -0,0 +1,79 @@+from argparse import ArgumentParser+from typing import Any++from django.conf import settings+from django.core.management.base import BaseCommand, CommandError++from posthog.models.integration import StripeIntegration+from posthog.models.oauth import OAuthApplication+from posthog.models.oauth_provisioning import ProvisioningConfig++APP_NAME = "PostHog Stripe marketplace app"+++class Command(BaseCommand):+ help = (+ "Create or reconcile the OAuth application the Stripe marketplace app's token is minted on. "+ "Kept separate from the provisioning orchestrator's application because the marketplace token "+ "is readable by every member of the customer's Stripe account, and capabilities are granted "+ "per application."+ )++ def add_arguments(self, parser: ArgumentParser) -> None:+ parser.add_argument(+ "--client-id",+ required=True,+ help="Client id for the marketplace application; must match STRIPE_MARKETPLACE_OAUTH_CLIENT_ID",+ )+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="Report what would be created or changed without writing",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ client_id: str = options["client_id"]+ dry_run: bool = options["dry_run"]++ if client_id == settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID:+ raise CommandError(+ "That is the provisioning orchestrator's client id. Sharing one application is the "+ "problem this command exists to fix."+ )++ existing = OAuthApplication.objects.filter(client_id=client_id).first()++ # Mirrors the orchestrator's row so refresh behaves identically; the Stripe app sends no+ # client secret, so a confidential type would reject it.+ desired = {+ "name": APP_NAME,+ "client_secret": "",+ "client_type": OAuthApplication.CLIENT_PUBLIC,+ "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,+ "redirect_uris": "https://localhost",+ "algorithm": "RS256",+ "is_provisioning_partner": False,+ }++ if dry_run:+ verb = "would reconcile" if existing else "would create"+ self.stdout.write(f"{verb} {APP_NAME} (client_id={client_id})")+ self.stdout.write(f" ceiling_scopes: {StripeIntegration.SCOPES}")+ self.stdout.write(" can_issue_deep_links: False")+ return++ app = existing or OAuthApplication(client_id=client_id)+ for field, value in desired.items():+ setattr(app, field, value)+ app.scopes = StripeIntegration.SCOPES.split()+ # Assigning a fresh config rather than update_provisioning, which merges: on a drifted row+ # that would leave every capability it does not name switched on.+ app.provisioning = ProvisioningConfig()+ app.save()++ self.stdout.write(self.style.SUCCESS(f"{'Reconciled' if existing else 'Created'} {APP_NAME}"))+ self.stdout.write(f" client_id: {client_id}")+ self.stdout.write(f" ceiling_scopes: {' '.join(app.ceiling_scopes)}")+ self.stdout.write(" can_issue_deep_links: False")+ self.stdout.write("")+ self.stdout.write(f"Set STRIPE_MARKETPLACE_OAUTH_CLIENT_ID={client_id} in this region, then deploy.")diff --git a/posthog/management/commands/rotate_stripe_marketplace_tokens.py b/posthog/management/commands/rotate_stripe_marketplace_tokens.pynew file mode 100644index 000000000000..2efdf2bbd5d6--- /dev/null+++ b/posthog/management/commands/rotate_stripe_marketplace_tokens.py@@ -0,0 +1,208 @@+from argparse import ArgumentParser+from typing import Any++from django.conf import settings+from django.core.management.base import BaseCommand, CommandError+from django.db import transaction+from django.db.models import Q++from posthog.exceptions_capture import capture_exception+from posthog.models.integration import STRIPE_POSTHOG_SECRET_NAMES, Integration, StripeIntegration+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken, lock_oauth_connection+++class PartialStripeWrite(Exception):+ """Some secrets reached Stripe and some did not, so neither credential is safe to delete."""+++class Command(BaseCommand):+ help = (+ "Rotate PostHog OAuth tokens for every Stripe marketplace integration onto the "+ "post-split OAuth application, and rewrite the corresponding Stripe Secret Store entries. "+ "Needed because tokens minted before the application split stay valid on the old, "+ "shared application until explicitly revoked."+ )++ def add_arguments(self, parser: ArgumentParser) -> None:+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="Report what would be rotated without revoking tokens, minting replacements, or calling Stripe",+ )+ parser.add_argument(+ "--team-id",+ type=int,+ default=None,+ help="Rotate a single team's Stripe integration only, for testing before a full run",+ )++ def _sweep_superseded_tokens(self, team_id: int, created_by_id: int, stale_token_ids: list[int]) -> None:+ """Remove every credential for this team except the replacement just minted.++ Queried inside the lock rather than deleted by the ids snapshotted before minting: a+ holder of the legacy refresh token can exchange it while Stripe is being written, and+ that mints a pair the snapshot never saw.++ `lock_oauth_connection` is what serializes this against the minting side. Row locks alone+ are not enough, for the reason its docstring gives: a blocked sweep re-checks the locked+ row without widening its snapshot, so a token inserted meanwhile survives.+ """+ apps = StripeIntegration._posthog_oauth_apps_for_revocation()++ with transaction.atomic():+ user_ids = (+ set(+ OAuthAccessToken.objects.filter(application__in=apps, scoped_teams__contains=[team_id]).values_list(+ "user_id", flat=True+ )+ )+ | set(+ OAuthRefreshToken.objects.filter(+ application__in=apps, scoped_teams__contains=[team_id]+ ).values_list("user_id", flat=True)+ )+ | {created_by_id}+ )+ # Before any row lock and in a fixed order, matching the minting side, so the two+ # cannot deadlock against each other.+ for user_id, application_id in sorted(+ (user_id, app.id) for user_id in user_ids if user_id is not None for app in apps+ ):+ lock_oauth_connection(user_id=user_id, application_id=application_id)++ superseded_ids = list(+ OAuthAccessToken.objects.filter(application__in=apps, scoped_teams__contains=[team_id])+ .exclude(id__in=self._replacement_token_ids(team_id, stale_token_ids))+ .values_list("id", flat=True)+ )++ # Neither direction of the access/refresh link is reliably populated, so match both.+ source_refresh_ids = [+ refresh_id+ for refresh_id in OAuthAccessToken.objects.filter(id__in=superseded_ids).values_list(+ "source_refresh_token_id", flat=True+ )+ if refresh_id is not None+ ]+ OAuthRefreshToken.objects.filter(+ Q(access_token_id__in=superseded_ids) | Q(id__in=source_refresh_ids)+ ).delete()+ OAuthAccessToken.objects.filter(id__in=superseded_ids).delete()++ @staticmethod+ def _replacement_token_ids(team_id: int, stale_token_ids: list[int]) -> list[int]:+ """The tokens minted by this run: on the marketplace application and not in the snapshot.++ A refresh of a leaked legacy credential mints onto the orchestrator's application, so it+ cannot be mistaken for the replacement.+ """+ return list(+ OAuthAccessToken.objects.filter(+ application__client_id=settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID,+ scoped_teams__contains=[team_id],+ )+ .exclude(id__in=stale_token_ids)+ .values_list("id", flat=True)+ )++ def handle(self, *args: Any, **options: Any) -> None:+ dry_run: bool = options["dry_run"]+ team_id: int | None = options.get("team_id")++ if not settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID:+ raise CommandError(+ "STRIPE_MARKETPLACE_OAUTH_CLIENT_ID is not set. Rotating now would re-mint tokens onto "+ "the same application these tokens already live on and accomplish nothing."+ )++ if settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID == settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID:+ raise CommandError(+ "STRIPE_MARKETPLACE_OAUTH_CLIENT_ID equals STRIPE_POSTHOG_OAUTH_CLIENT_ID. Rotating now "+ "would re-mint onto the orchestrator's application, which can issue deep links."+ )++ # The application row has to exist before revoking, or rotation strips access with nothing+ # to mint replacements onto.+ if not OAuthApplication.objects.filter(client_id=settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID).exists():+ raise CommandError(+ f"No OAuthApplication exists for client_id={settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID}. "+ "Revoking tokens now would strip access with nothing to mint replacements onto."+ )++ if dry_run:+ self.stdout.write(self.style.WARNING("Running in DRY RUN mode — no tokens or secrets will change"))++ integrations = Integration.objects.filter(kind="stripe").order_by("id")+ if team_id is not None:+ integrations = integrations.filter(team_id=team_id)++ rotated = 0+ skipped: list[str] = []+ failed: list[str] = []++ for integration in integrations.iterator():+ label = f"integration={integration.id} team={integration.team_id}"+ created_by = integration.created_by++ if created_by is None:+ reason = "no created_by user"+ self.stdout.write(self.style.WARNING(f" {label}: skipped ({reason})"))+ skipped.append(f"{label}: {reason}")+ continue++ if dry_run:+ self.stdout.write(f" {label}: would rotate (user={created_by.id})")+ rotated += 1+ continue++ try:+ stripe_integration = StripeIntegration(integration)+ stale_token_ids = list(+ OAuthAccessToken.objects.filter(+ application__in=StripeIntegration._posthog_oauth_apps_for_revocation(),+ scoped_teams__contains=[integration.team_id],+ ).values_list("id", flat=True)+ )++ # Mint before revoking. Revoking first strands the customer whenever the Stripe+ # write fails, because their app keeps reading a token that no longer exists.+ unwritten = stripe_integration.write_posthog_secrets(integration.team_id, created_by)+ if unwritten and len(unwritten) < len(STRIPE_POSTHOG_SECRET_NAMES):+ raise PartialStripeWrite(+ f"Stripe secret store partially updated, unwritten: {', '.join(unwritten)}. "+ "Old and new tokens both left in place; this integration needs manual repair."+ )+ if unwritten:+ raise RuntimeError(f"Stripe secret store not updated: {', '.join(unwritten)}")++ self._sweep_superseded_tokens(integration.team_id, created_by.id, stale_token_ids)+ except Exception as e:+ # A mint that never reached Stripe leaves a credential nobody holds; drop it so+ # retrying does not accumulate one per attempt. A partial write is the opposite:+ # Stripe is already serving the new token for some keys, so deleting it here is+ # what would break the customer.+ if not isinstance(e, PartialStripeWrite):+ orphaned = OAuthAccessToken.objects.filter(+ application__in=StripeIntegration._posthog_oauth_apps_for_revocation(),+ scoped_teams__contains=[integration.team_id],+ ).exclude(id__in=stale_token_ids)+ OAuthRefreshToken.objects.filter(access_token__in=orphaned).delete()+ orphaned.delete()++ capture_exception(e, {"integration_id": integration.id, "team_id": integration.team_id})+ self.stdout.write(self.style.ERROR(f" {label}: failed ({e})"))+ failed.append(f"{label}: {e}")+ continue++ self.stdout.write(self.style.SUCCESS(f" {label}: rotated"))+ rotated += 1++ verb = "Would rotate" if dry_run else "Rotated"+ self.stdout.write("")+ self.stdout.write(self.style.SUCCESS(f"{verb}: {rotated}"))+ self.stdout.write(f"Skipped: {len(skipped)}")+ for line in skipped:+ self.stdout.write(f" - {line}")+ self.stdout.write(f"Failed: {len(failed)}")+ for line in failed:+ self.stdout.write(f" - {line}")diff --git a/posthog/management/commands/test/test_create_stripe_marketplace_oauth_app.py b/posthog/management/commands/test/test_create_stripe_marketplace_oauth_app.pynew file mode 100644index 000000000000..8417d2a664f4--- /dev/null+++ b/posthog/management/commands/test/test_create_stripe_marketplace_oauth_app.py@@ -0,0 +1,69 @@+from io import StringIO++import pytest+from posthog.test.base import BaseTest++from django.core.management import call_command+from django.core.management.base import CommandError++from posthog.models.integration import StripeIntegration+from posthog.models.oauth import OAuthApplication+from posthog.models.oauth_provisioning import ProvisioningConfig++MARKETPLACE_CLIENT_ID = "marketplace_client_id"+ORCHESTRATOR_CLIENT_ID = "orchestrator_client_id"+++class TestCreateStripeMarketplaceOauthApp(BaseTest):+ def test_creates_the_application_locked_down(self):+ call_command("create_stripe_marketplace_oauth_app", client_id=MARKETPLACE_CLIENT_ID, stdout=StringIO())++ app = OAuthApplication.objects.get(client_id=MARKETPLACE_CLIENT_ID)+ assert app.client_type == OAuthApplication.CLIENT_PUBLIC+ assert app.provisioning.can_issue_deep_links is False+ assert set(app.ceiling_scopes) == set(StripeIntegration.SCOPES.split())++ def test_refuses_the_orchestrator_client_id(self):+ with self.settings(STRIPE_POSTHOG_OAUTH_CLIENT_ID=ORCHESTRATOR_CLIENT_ID):+ with pytest.raises(CommandError):+ call_command("create_stripe_marketplace_oauth_app", client_id=ORCHESTRATOR_CLIENT_ID, stdout=StringIO())++ assert not OAuthApplication.objects.filter(client_id=ORCHESTRATOR_CLIENT_ID).exists()++ def test_reconciles_an_application_that_drifted(self):+ drifted = OAuthApplication.objects.create(+ client_id=MARKETPLACE_CLIENT_ID,+ name="wrong name",+ client_secret="",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://localhost",+ algorithm="RS256",+ is_provisioning_partner=True,+ )+ drifted.update_provisioning(+ active=True,+ can_issue_deep_links=True,+ can_provision_resources=True,+ can_create_accounts=True,+ can_use_github_grants=True,+ can_start_wizard_runs=True,+ skip_existing_user_consent=True,+ )++ call_command("create_stripe_marketplace_oauth_app", client_id=MARKETPLACE_CLIENT_ID, stdout=StringIO())++ app = OAuthApplication.objects.get(client_id=MARKETPLACE_CLIENT_ID)+ assert app.client_type == OAuthApplication.CLIENT_PUBLIC+ assert app.is_provisioning_partner is False+ assert app.provisioning == ProvisioningConfig()++ def test_dry_run_writes_nothing(self):+ call_command(+ "create_stripe_marketplace_oauth_app",+ client_id=MARKETPLACE_CLIENT_ID,+ dry_run=True,+ stdout=StringIO(),+ )++ assert not OAuthApplication.objects.filter(client_id=MARKETPLACE_CLIENT_ID).exists()diff --git a/posthog/management/commands/test/test_rotate_stripe_marketplace_tokens.py b/posthog/management/commands/test/test_rotate_stripe_marketplace_tokens.pynew file mode 100644index 000000000000..ecd1e5a89783--- /dev/null+++ b/posthog/management/commands/test/test_rotate_stripe_marketplace_tokens.py@@ -0,0 +1,329 @@+from datetime import timedelta+from io import StringIO++from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.core.management import call_command+from django.core.management.base import CommandError+from django.utils import timezone++from parameterized import parameterized++from posthog.models import Team+from posthog.models.integration import Integration, StripeIntegration+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken+++def _oauth_app(client_id: str) -> OAuthApplication:+ return OAuthApplication.objects.create(+ name=f"App {client_id}",+ client_id=client_id,+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ algorithm="RS256",+ )+++class TestRotateStripeMarketplaceTokens(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.new_app = _oauth_app("marketplace_client_id")+ self.old_app = _oauth_app("legacy_client_id")++ def _create_integration_with_token(+ self, team: Team, integration_id: str, application: OAuthApplication, created_by=None+ ) -> tuple[Integration, OAuthAccessToken, OAuthRefreshToken]:+ integration = Integration.objects.create(+ team=team,+ kind="stripe",+ integration_id=integration_id,+ config={},+ sensitive_config={},+ created_by=created_by,+ )+ access_token = OAuthAccessToken.objects.create(+ application=application,+ token=f"access_{integration_id}",+ user=created_by,+ expires=timezone.now() + timedelta(days=14),+ scope=StripeIntegration.SCOPES,+ scoped_teams=[team.pk],+ )+ refresh_token = OAuthRefreshToken.objects.create(+ application=application,+ token=f"refresh_{integration_id}",+ user=created_by,+ access_token=access_token,+ scoped_teams=[team.pk],+ )+ return integration, access_token, refresh_token++ @patch("stripe.StripeClient")+ def test_dry_run_makes_no_changes(self, MockStripeClient) -> None:+ integration, access_token, refresh_token = self._create_integration_with_token(+ self.team, "acct_dry_run", self.old_app, created_by=self.user+ )++ with self.settings(+ STRIPE_MARKETPLACE_OAUTH_CLIENT_ID=self.new_app.client_id,+ STRIPE_POSTHOG_OAUTH_CLIENT_ID=self.old_app.client_id,+ ):+ call_command("rotate_stripe_marketplace_tokens", "--dry-run")++ assert OAuthAccessToken.objects.filter(pk=access_token.pk).exists()+ assert OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists()+ assert OAuthAccessToken.objects.count() == 1+ MockStripeClient.assert_not_called()++ @patch("stripe.StripeClient")+ def test_real_run_revokes_old_tokens_and_mints_on_marketplace_app(self, MockStripeClient) -> None:+ mock_client = MagicMock()+ MockStripeClient.return_value = mock_client++ integration, old_access, old_refresh = self._create_integration_with_token(+ self.team, "acct_rotate", self.old_app, created_by=self.user+ )++ with self.settings(+ STRIPE_MARKETPLACE_OAUTH_CLIENT_ID=self.new_app.client_id,+ STRIPE_POSTHOG_OAUTH_CLIENT_ID=self.old_app.client_id,+ STRIPE_APP_CLIENT_ID="stripe_app_client_id",+ STRIPE_APP_SECRET_KEY="sk_test",+ ):+ call_command("rotate_stripe_marketplace_tokens")++ assert not OAuthAccessToken.objects.filter(pk=old_access.pk).exists()+ assert not OAuthRefreshToken.objects.filter(pk=old_refresh.pk).exists()++ new_access = OAuthAccessToken.objects.get(application=self.new_app, scoped_teams__contains=[self.team.pk])+ assert new_access.user_id == self.user.id+ assert OAuthRefreshToken.objects.filter(access_token=new_access).exists()++ secret_calls = mock_client.apps.secrets.create.call_args_list+ assert len(secret_calls) == 5+ for call in secret_calls:+ assert call.kwargs["options"] == {"stripe_account": "acct_rotate"}++ def test_skips_integration_with_no_created_by(self) -> None:+ integration = Integration.objects.create(+ team=self.team,+ kind="stripe",+ integration_id="acct_no_owner",+ config={},+ sensitive_config={},+ created_by=None,+ )++ out = StringIO()+ with self.settings(+ STRIPE_MARKETPLACE_OAUTH_CLIENT_ID=self.new_app.client_id,+ STRIPE_POSTHOG_OAUTH_CLIENT_ID=self.old_app.client_id,+ ):+ call_command("rotate_stripe_marketplace_tokens", stdout=out)++ assert integration.created_by is None+ assert OAuthAccessToken.objects.count() == 0+ assert "no created_by user" in out.getvalue()+ assert "Skipped: 1" in out.getvalue()+ assert "Rotated: 0" in out.getvalue()++ @patch("stripe.StripeClient")+ @patch("posthog.management.commands.rotate_stripe_marketplace_tokens.capture_exception")+ def test_one_failure_does_not_block_other_integrations(self, mock_capture, MockStripeClient) -> None:+ mock_client = MagicMock()+ MockStripeClient.return_value = mock_client++ other_team = Team.objects.create(organization=self.organization, name="Other team")+ failing_integration, failing_access, failing_refresh = self._create_integration_with_token(+ self.team, "acct_fails", self.old_app, created_by=self.user+ )+ ok_integration, ok_access, ok_refresh = self._create_integration_with_token(+ other_team, "acct_ok", self.old_app, created_by=self.user+ )++ original_write_secrets = StripeIntegration.write_posthog_secrets++ def flaky_write_posthog_secrets(self, team_id, created_by):+ if self.integration.pk == failing_integration.pk:+ raise Exception("simulated Stripe API failure")+ return original_write_secrets(self, team_id, created_by)++ out = StringIO()+ with (+ self.settings(+ STRIPE_MARKETPLACE_OAUTH_CLIENT_ID=self.new_app.client_id,+ STRIPE_POSTHOG_OAUTH_CLIENT_ID=self.old_app.client_id,+ STRIPE_APP_CLIENT_ID="stripe_app_client_id",+ STRIPE_APP_SECRET_KEY="sk_test",+ ),+ patch.object(StripeIntegration, "write_posthog_secrets", flaky_write_posthog_secrets),+ ):+ call_command("rotate_stripe_marketplace_tokens", stdout=out)++ mock_capture.assert_called_once()++ output = out.getvalue()+ assert "Rotated: 1" in output+ assert "Failed: 1" in output+ assert "simulated Stripe API failure" in output++ # The failing integration keeps a working credential: revocation only happens once the+ # replacement is confirmed live in Stripe. Nothing orphaned is left behind either.+ assert OAuthAccessToken.objects.filter(pk=failing_access.pk).exists()+ assert not OAuthAccessToken.objects.filter(+ application=self.new_app, scoped_teams__contains=[self.team.pk]+ ).exists()++ assert not OAuthAccessToken.objects.filter(pk=ok_access.pk).exists()+ assert OAuthAccessToken.objects.filter(+ application=self.new_app, scoped_teams__contains=[other_team.pk]+ ).exists()++ @patch("stripe.StripeClient")+ @patch("posthog.management.commands.rotate_stripe_marketplace_tokens.capture_exception")+ def test_partial_stripe_write_leaves_both_credentials_in_place(self, mock_capture, MockStripeClient) -> None:+ mock_client = MagicMock()+ MockStripeClient.return_value = mock_client++ def fail_on_refresh_token(params, options):+ if params["name"] == "posthog_refresh_token":+ raise Exception("simulated Stripe API failure")+ return MagicMock()++ mock_client.apps.secrets.create.side_effect = fail_on_refresh_token++ integration, stale_access, stale_refresh = self._create_integration_with_token(+ self.team, "acct_partial", self.old_app, created_by=self.user+ )++ out = StringIO()+ with self.settings(+ STRIPE_MARKETPLACE_OAUTH_CLIENT_ID=self.new_app.client_id,+ STRIPE_POSTHOG_OAUTH_CLIENT_ID=self.old_app.client_id,+ STRIPE_APP_CLIENT_ID="stripe_app_client_id",+ STRIPE_APP_SECRET_KEY="sk_test",+ ):+ call_command("rotate_stripe_marketplace_tokens", stdout=out)++ output = out.getvalue()+ assert "Rotated: 0" in output+ assert "Failed: 1" in output+ assert "needs manual repair" in output++ # Stripe already serves the new token for posthog_access_token, so deleting it would break+ # the customer. The stale token stays too, since it was never confirmed replaced.+ assert OAuthAccessToken.objects.filter(pk=stale_access.pk).exists()+ assert OAuthRefreshToken.objects.filter(pk=stale_refresh.pk).exists()+ assert OAuthAccessToken.objects.filter(application=self.new_app, scoped_teams__contains=[self.team.pk]).exists()++ mock_capture.assert_called_once()++ def test_refuses_when_the_marketplace_id_is_the_orchestrator(self) -> None:+ with self.settings(+ STRIPE_MARKETPLACE_OAUTH_CLIENT_ID=self.old_app.client_id,+ STRIPE_POSTHOG_OAUTH_CLIENT_ID=self.old_app.client_id,+ ):+ with self.assertRaises(CommandError):+ call_command("rotate_stripe_marketplace_tokens")++ @patch("stripe.StripeClient")+ def test_sweeps_a_credential_minted_by_a_refresh_mid_rotation(self, MockStripeClient) -> None:+ mock_client = MagicMock()+ MockStripeClient.return_value = mock_client++ integration, stale_access, stale_refresh = self._create_integration_with_token(+ self.team, "acct_refresh_race", self.old_app, created_by=self.user+ )++ original_write_secrets = StripeIntegration.write_posthog_secrets+ refreshed: dict[str, OAuthAccessToken] = {}++ def refresh_during_write(self, team_id, created_by):+ result = original_write_secrets(self, team_id, created_by)+ # What DOT's refresh path does with the leaked legacy refresh token: a fresh pair on+ # the orchestrator application, created after the rotation snapshotted token ids.+ refreshed["access"] = OAuthAccessToken.objects.create(+ application=stale_access.application,+ token="ph_access_refreshed",+ user=created_by,+ expires=timezone.now() + timedelta(days=14),+ scope="query:read",+ scoped_teams=[team_id],+ )+ OAuthRefreshToken.objects.create(+ application=stale_access.application,+ token="ph_refresh_refreshed",+ user=created_by,+ access_token=refreshed["access"],+ scoped_teams=[team_id],+ )+ return result++ out = StringIO()+ with (+ self.settings(+ STRIPE_MARKETPLACE_OAUTH_CLIENT_ID=self.new_app.client_id,+ STRIPE_POSTHOG_OAUTH_CLIENT_ID=self.old_app.client_id,+ STRIPE_APP_CLIENT_ID="stripe_app_client_id",+ STRIPE_APP_SECRET_KEY="sk_test",+ ),+ patch.object(StripeIntegration, "write_posthog_secrets", refresh_during_write),+ ):+ call_command("rotate_stripe_marketplace_tokens", stdout=out)++ assert "Rotated: 1" in out.getvalue()+ assert not OAuthAccessToken.objects.filter(pk=stale_access.pk).exists()+ assert not OAuthRefreshToken.objects.filter(pk=stale_refresh.pk).exists()+ # The whole point: a snapshot-based delete would have missed this one.+ assert not OAuthAccessToken.objects.filter(pk=refreshed["access"].pk).exists()+ assert not OAuthAccessToken.objects.filter(+ application=self.old_app, scoped_teams__contains=[self.team.pk]+ ).exists()+ assert OAuthAccessToken.objects.filter(application=self.new_app, scoped_teams__contains=[self.team.pk]).exists()++ @patch("stripe.StripeClient")+ @patch("posthog.management.commands.rotate_stripe_marketplace_tokens.lock_oauth_connection")+ def test_takes_the_connection_lock_before_deleting(self, mock_lock, MockStripeClient) -> None:+ mock_client = MagicMock()+ MockStripeClient.return_value = mock_client++ integration, stale_access, _ = self._create_integration_with_token(+ self.team, "acct_lock", self.old_app, created_by=self.user+ )++ deleted_while_unlocked: list[bool] = []+ original_delete = OAuthAccessToken.delete++ def recording_delete(instance, *args, **kwargs):+ deleted_while_unlocked.append(not mock_lock.called)+ return original_delete(instance, *args, **kwargs)++ with (+ self.settings(+ STRIPE_MARKETPLACE_OAUTH_CLIENT_ID=self.new_app.client_id,+ STRIPE_POSTHOG_OAUTH_CLIENT_ID=self.old_app.client_id,+ STRIPE_APP_CLIENT_ID="stripe_app_client_id",+ STRIPE_APP_SECRET_KEY="sk_test",+ ),+ patch.object(OAuthAccessToken, "delete", recording_delete),+ ):+ call_command("rotate_stripe_marketplace_tokens", stdout=StringIO())++ # Row locks alone let a mid-sweep refresh survive, so the advisory lock has to come first.+ locked_pairs = {(call.kwargs["user_id"], call.kwargs["application_id"]) for call in mock_lock.call_args_list}+ assert (self.user.pk, self.old_app.id) in locked_pairs+ assert (self.user.pk, self.new_app.id) in locked_pairs+ assert not any(deleted_while_unlocked)++ @parameterized.expand(+ [+ ("client_id_unset", ""),+ ("client_id_set_but_no_matching_app", "not_yet_created_client_id"),+ ]+ )+ def test_refuses_to_run_when_not_configured(self, _name, client_id) -> None:+ with self.settings(STRIPE_MARKETPLACE_OAUTH_CLIENT_ID=client_id):+ with self.assertRaises(CommandError):+ call_command("rotate_stripe_marketplace_tokens")diff --git a/posthog/models/integration/__init__.py b/posthog/models/integration/__init__.pyindex 567c3dcf2654..f061c2fc9007 100644--- a/posthog/models/integration/__init__.py+++ b/posthog/models/integration/__init__.py@@ -127,7 +127,7 @@ from .slack import (validate_slack_request,)from .snowflake import SnowflakeIntegration, SnowflakeIntegrationError-from .stripe import StripeIntegration+from .stripe import STRIPE_POSTHOG_SECRET_NAMES, StripeIntegrationfrom .twilio import TwilioIntegration__all__ = [@@ -235,6 +235,7 @@ __all__ = ["AWSS3Integration","AWSRedshiftIntegration","S3CompatibleIntegration",+ "STRIPE_POSTHOG_SECRET_NAMES","StripeIntegration","Credentials","Authority",diff --git a/posthog/models/integration/stripe.py b/posthog/models/integration/stripe.pyindex de5de5195b1f..1736c1db4ca5 100644--- a/posthog/models/integration/stripe.py+++ b/posthog/models/integration/stripe.py@@ -22,6 +22,17 @@ from . import model, oauthlogger = structlog.get_logger(__name__)+# Keep in sync with SECRET_NAMES in services/stripe-app/src/posthog/auth.ts; the app reads+# these by name and a mismatch reads as "not connected" rather than as an error.+STRIPE_POSTHOG_SECRET_NAMES = (+ "posthog_region",+ "posthog_access_token",+ "posthog_refresh_token",+ "posthog_project_id",+ "posthog_oauth_client_id",+)++class StripeIntegration:integration: model.Integration@@ -60,13 +71,21 @@ class StripeIntegration:return Nonereturn 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."""+ def write_posthog_secrets(self, team_id: int, created_by: "User") -> list[str]:+ """Write PostHog OAuth tokens to Stripe's Secret Store so the Stripe App can call PostHog APIs.++ Returns the names of any secrets that could not be written. Callers that revoke the+ previous credential must treat a non-empty result as failure: Stripe would still be+ holding the old token, so revoking it leaves the customer with nothing that works.+ """oauth_app = self._get_posthog_oauth_app()if not oauth_app:- logger.warning("PostHog OAuth app not found, cannot write secrets to Stripe")- return+ capture_exception(+ Exception("Stripe marketplace OAuth application not found, cannot write secrets to Stripe"),+ {"integration_id": self.integration.id, "team_id": self.integration.team_id},+ )+ return list(STRIPE_POSTHOG_SECRET_NAMES)access_token_value = generate_random_oauth_access_token(None)access_token = OAuthAccessToken.objects.create(@@ -103,8 +122,9 @@ class StripeIntegration:client = self._stripe_client()if client is None:- return+ return list(secrets)+ failed: list[str] = []for name, payload in secrets.items():try:client.apps.secrets.create(@@ -116,6 +136,7 @@ class StripeIntegration:options={"stripe_account": stripe_user_id},)except Exception as e:+ failed.append(name)capture_exception(e,{@@ -124,6 +145,8 @@ class StripeIntegration:},)+ return failed+def clear_posthog_secrets(self) -> None:"""Best-effort clear of PostHog secrets from Stripe and revoke local OAuth tokens."""stripe_user_id = self.integration.integration_id@@ -135,13 +158,7 @@ class StripeIntegration:self._destroy_posthog_oauth_tokens()return- for name in (- "posthog_region",- "posthog_access_token",- "posthog_refresh_token",- "posthog_project_id",- "posthog_oauth_client_id",- ):+ for name in STRIPE_POSTHOG_SECRET_NAMES:try:client.apps.secrets.delete_where(params={@@ -163,13 +180,13 @@ class StripeIntegration:def _destroy_posthog_oauth_tokens(self) -> None:"""Delete the local OAuth access and refresh tokens created for this Stripe integration."""- oauth_app = self._get_posthog_oauth_app()- if not oauth_app:+ oauth_apps = self._posthog_oauth_apps_for_revocation()+ if not oauth_apps:returnteam_id = self.integration.team_idaccess_tokens = OAuthAccessToken.objects.filter(- application=oauth_app,+ application__in=oauth_apps,scoped_teams__contains=[team_id],)# Delete refresh tokens first since their FK to access_token is SET_NULL@@ -177,7 +194,41 @@ class StripeIntegration:access_tokens.delete()def _get_posthog_oauth_app(self):- if settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID:- return OAuthApplication.objects.filter(client_id=settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID).first()+ """The application new marketplace tokens are minted on.++ Deliberately not the orchestrator's application. This token lands in the customer's+ Stripe Secret Store at account scope, readable by every member of their Stripe account,+ while ee/partners/stripe/api/provisioning/authentication.py authorizes purely on+ application identity. Sharing one application therefore lets any of those people mint a+ deep-link login session as the admin who installed the app.++ Returns None when the setting is unset or names the orchestrator, rather than minting there.+ """+ client_id = settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID+ if not client_id or client_id == settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID:+ # Minting on the orchestrator's application is the vulnerability, whether the setting+ # is unset or mapped to the orchestrator's own id, so both fail closed: a new install+ # gets no credential rather than a privileged one.+ capture_exception(+ Exception(+ "STRIPE_MARKETPLACE_OAUTH_CLIENT_ID is unset or equal to the orchestrator's, "+ "refusing to mint a Stripe marketplace token"+ ),+ {"integration_id": self.integration.id, "team_id": self.integration.team_id},+ )+ return None++ return OAuthApplication.objects.filter(client_id=client_id).first()- return None+ @staticmethod+ def _posthog_oauth_apps_for_revocation() -> list["OAuthApplication"]:+ """Every application a marketplace token may have been minted on, current and legacy.++ Revocation has to span both or tokens issued before the application split survive it.+ """+ client_ids = [+ cid for cid in (settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID, settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID) if cid+ ]+ if not client_ids:+ return []+ return list(OAuthApplication.objects.filter(client_id__in=client_ids))diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.pyindex 70e0d16c3283..b9dbe9aafdbc 100644--- a/posthog/settings/integrations.py+++ b/posthog/settings/integrations.py@@ -124,12 +124,20 @@ ATLASSIAN_APP_CLIENT_SECRET = get_from_env("ATLASSIAN_APP_CLIENT_SECRET", "")# - STRIPE_APP_CLIENT_ID: The app's public client ID, used in the OAuth authorize redirect URL# - STRIPE_APP_OVERRIDE_AUTHORIZE_URL: Optional override for testing (e.g., with a channel link URL)# - STRIPE_APP_SECRET_KEY: API secret key used for HTTP Basic auth during live token exchange/refresh-# - STRIPE_POSTHOG_OAUTH_CLIENT_ID: Client ID of the PostHog OAuthApplication for Stripe to authenticate with PostHog APIs+# - STRIPE_POSTHOG_OAUTH_CLIENT_ID: Client ID of the PostHog OAuthApplication the provisioning+# orchestrator authenticates as. Tokens on this application may mint deep-link login sessions.+# - STRIPE_MARKETPLACE_OAUTH_CLIENT_ID: Client ID of a separate PostHog OAuthApplication for the+# marketplace app's own token. That token is written into the customer's Stripe Secret Store at+# account scope, so every member of their Stripe account can read it. It must not share an+# application with the orchestrator, because the provisioning namespace authorizes on application+# identity alone. Until this is set the two share one application and marketplace tokens can reach+# the provisioning endpoints.# - STRIPE_SIGNING_SECRET: Used to verify the authenticity of incoming webhook/agentic provisioning requests from StripeSTRIPE_APP_CLIENT_ID = get_from_env("STRIPE_APP_CLIENT_ID", "")STRIPE_APP_OVERRIDE_AUTHORIZE_URL = get_from_env("STRIPE_APP_OVERRIDE_AUTHORIZE_URL", "")STRIPE_APP_SECRET_KEY = get_from_env("STRIPE_APP_SECRET_KEY", "")STRIPE_POSTHOG_OAUTH_CLIENT_ID = get_from_env("STRIPE_POSTHOG_OAUTH_CLIENT_ID", "")+STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = get_from_env("STRIPE_MARKETPLACE_OAUTH_CLIENT_ID", "")STRIPE_SIGNING_SECRET = get_from_env("STRIPE_SIGNING_SECRET", "")# WorkOS Radar (bot/fraud detection for auth flows)