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.

refactor(oauth): delete three finished one-off management commands (#108612)

Matt Brooker9965168ad8fc
diff --git a/ee/api/agentic_provisioning/test/test_scope_hydration.py b/ee/api/agentic_provisioning/test/test_scope_hydration.py
index f18af6fb5218..a99ab4f84069 100644
--- a/ee/api/agentic_provisioning/test/test_scope_hydration.py
+++ b/ee/api/agentic_provisioning/test/test_scope_hydration.py
@@ -1,7 +1,3 @@
-from io import StringIO
-
-from django.core.management import call_command
-
from parameterized import parameterized
from posthog.constants import AvailableFeature
@@ -183,64 +179,6 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):
assert refresh_token.revoked is None
assert OAuthAccessToken.objects.filter(token=token).exists()
- def test_backfill_rehydrates_stale_access_and_refresh_scope(self):
- token = self._get_bearer_token()
- access_token = OAuthAccessToken.objects.get(token=token)
- refresh_token = OAuthRefreshToken.objects.get(access_token=access_token)
- assert access_token.scoped_teams == [self.team.id]
-
- newly_provisioned = self._provision_team(self.partner, "Newly provisioned", "proj_new")
-
- call_command("backfill_agentic_provisioning_scope", stdout=StringIO())
-
- access_token.refresh_from_db()
- refresh_token.refresh_from_db()
- assert self.team.id in access_token.scoped_teams
- assert newly_provisioned.id in access_token.scoped_teams
- assert self.team.id in refresh_token.scoped_teams
- assert newly_provisioned.id in refresh_token.scoped_teams
-
- def test_backfill_keeps_consent_team_when_scope_is_stored_in_id_order(self) -> None:
- TeamProvisioningConfig.objects.update_or_create(team=self.team, defaults={"application": self.partner})
- consented = Team.objects.create_with_data(
- initiating_user=self.user, organization=self.organization, name="Consented"
- )
- token = self._request_bearer_token(team_id=consented.id).json()["access_token"]
- access_token = OAuthAccessToken.objects.get(token=token)
- refresh_token = OAuthRefreshToken.objects.get(access_token=access_token)
- for stored in (access_token, refresh_token):
- stored.scoped_teams = [self.team.id, consented.id]
- stored.save(update_fields=["scoped_teams"])
-
- call_command("backfill_agentic_provisioning_scope", stdout=StringIO())
-
- access_token.refresh_from_db()
- refresh_token.refresh_from_db()
- assert access_token.scoped_teams == [consented.id, self.team.id]
- assert refresh_token.scoped_teams == [consented.id, self.team.id]
-
- def test_backfill_leaves_scope_unchanged_when_recomputed_scope_is_empty(self):
- # When the user has lost access, compute_partner_scoped_teams returns [].
- # An empty scoped_teams is unrestricted under the standard permission check, so the
- # backfill must NOT overwrite a restricted token with [] — it leaves the existing
- # restriction intact and reports the token for re-authorization.
- token = self._get_bearer_token()
- access_token = OAuthAccessToken.objects.get(token=token)
- refresh_token = OAuthRefreshToken.objects.get(access_token=access_token)
- assert access_token.scoped_teams == [self.team.id]
-
- self._enable_access_control_as_member()
- self._restrict_team_access(self.team)
-
- out = StringIO()
- call_command("backfill_agentic_provisioning_scope", stdout=out)
-
- access_token.refresh_from_db()
- refresh_token.refresh_from_db()
- assert access_token.scoped_teams == [self.team.id]
- assert refresh_token.scoped_teams == [self.team.id]
- assert "needs re-authorization" in out.getvalue()
-
def test_application_none_yields_empty_scope(self):
# application is never None in practice (oauthrefreshtoken.application_id is
# NOT NULL and issuance always resolves an app), so this pins the helper's
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index f4e78a76ee4b..307e83182867 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -5641,41 +5641,57 @@ class TestStripeIntegrationOAuthTokens:
mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = "orchestrator_client_id"
mock_settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = self.oauth_app.client_id
integration, access_token, refresh_token = self._create_integration_with_tokens()
+ unlinked_refresh_token = OAuthRefreshToken.objects.create(
+ application=self.oauth_app,
+ token="ph_refresh_unlinked",
+ user=self.user,
+ access_token=None,
+ revoked=timezone.now(),
+ scoped_teams=[self.team.pk],
+ )
stripe_int = StripeIntegration(integration)
stripe_int._destroy_posthog_oauth_tokens()
assert not OAuthAccessToken.objects.filter(pk=access_token.pk).exists()
assert not OAuthRefreshToken.objects.filter(pk=refresh_token.pk).exists()
+ assert not OAuthRefreshToken.objects.filter(pk=unlinked_refresh_token.pk).exists()
+ @pytest.mark.parametrize("other_credential", ["other_team_only", "shared_with_this_team"])
@patch("posthog.models.integration.stripe.settings")
- def test_destroy_oauth_tokens_only_affects_same_team(self, mock_settings):
+ def test_destroy_oauth_tokens_only_affects_same_team(self, mock_settings, other_credential):
mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = "orchestrator_client_id"
mock_settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = self.oauth_app.client_id
integration, _, _ = self._create_integration_with_tokens()
other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ other_scoped_teams = {
+ "other_team_only": [other_team.pk],
+ "shared_with_this_team": [self.team.pk, other_team.pk],
+ }[other_credential]
other_access_token = OAuthAccessToken.objects.create(
application=self.oauth_app,
token="ph_access_other",
user=self.user,
expires=timezone.now() + timedelta(days=365),
scope=StripeIntegration.SCOPES,
- scoped_teams=[other_team.pk],
+ scoped_teams=other_scoped_teams,
)
other_refresh_token = OAuthRefreshToken.objects.create(
application=self.oauth_app,
token="ph_refresh_other",
user=self.user,
access_token=other_access_token,
- scoped_teams=[other_team.pk],
+ scoped_teams=other_scoped_teams,
)
stripe_int = StripeIntegration(integration)
stripe_int._destroy_posthog_oauth_tokens()
- assert OAuthAccessToken.objects.filter(pk=other_access_token.pk).exists()
- assert OAuthRefreshToken.objects.filter(pk=other_refresh_token.pk).exists()
+ other_access_token.refresh_from_db()
+ other_refresh_token.refresh_from_db()
+ assert other_access_token.scoped_teams == [other_team.pk]
+ assert other_refresh_token.scoped_teams == [other_team.pk]
@patch("posthog.models.integration.stripe.settings")
def test_destroy_oauth_tokens_noop_when_no_oauth_app(self, mock_settings):
@@ -5732,11 +5748,11 @@ class TestStripeIntegrationOAuthTokens:
assert minted.latest("id").application == self.oauth_app
else:
assert publication.unwritten == STRIPE_POSTHOG_SECRET_NAMES
- assert publication.access_token_id is None
assert not minted.exists()
+ @patch("posthog.models.integration.stripe.lock_oauth_connection")
@patch("posthog.models.integration.stripe.settings")
- def test_destroy_oauth_tokens_spans_the_pre_split_application(self, mock_settings):
+ def test_destroy_oauth_tokens_spans_the_pre_split_application(self, mock_settings, mock_lock):
marketplace_app = OAuthApplication.objects.create(
name="Stripe marketplace",
client_id="marketplace_client_id",
@@ -5750,10 +5766,27 @@ class TestStripeIntegrationOAuthTokens:
integration, legacy_access, legacy_refresh = self._create_integration_with_tokens()
+ def mint_while_waiting(**kwargs):
+ OAuthAccessToken.objects.get_or_create(
+ token="ph_access_minted_at_lock",
+ defaults={
+ "application": self.oauth_app,
+ "user": self.user,
+ "expires": timezone.now() + timedelta(days=1),
+ "scope": StripeIntegration.SCOPES,
+ "scoped_teams": [self.team.pk],
+ },
+ )
+
+ mock_lock.side_effect = mint_while_waiting
+
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()
+ assert not OAuthAccessToken.objects.filter(token="ph_access_minted_at_lock").exists()
+ locked_pairs = {(call.kwargs["user_id"], call.kwargs["application_id"]) for call in mock_lock.call_args_list}
+ assert locked_pairs == {(self.user.pk, marketplace_app.id), (self.user.pk, self.oauth_app.id)}
@patch("stripe.StripeClient")
@patch("posthog.models.integration.oauth.settings")
@@ -5818,6 +5851,7 @@ class TestStripeIntegrationOAuthTokens:
}
assert not [scope for scope in token.scope.split() if scope.endswith(":write")]
assert token.scoped_teams == [self.team.pk]
+ assert OAuthRefreshToken.objects.get(access_token=token).scoped_teams == [self.team.pk]
@patch("stripe.StripeClient")
@patch("posthog.models.integration.oauth.settings")
@@ -5903,15 +5937,53 @@ class TestStripeIntegrationOAuthTokens:
created_by=self.user,
)
stripe_int = StripeIntegration(integration)
- publication = stripe_int.write_posthog_secrets(self.team.pk, self.user)
+ stripe_int.write_posthog_secrets(self.team.pk, self.user)
MockStripeClient.assert_not_called()
mock_capture.assert_called_once()
- assert publication.access_token_id is None
assert not OAuthAccessToken.objects.filter(scoped_teams__contains=[self.team.pk]).exists()
captured_exc = mock_capture.call_args.args[0]
assert isinstance(captured_exc, NotImplementedError)
+ @pytest.mark.parametrize(
+ "failing_secrets,credential_kept",
+ [
+ (STRIPE_POSTHOG_SECRET_NAMES, False),
+ (("posthog_refresh_token",), True),
+ ],
+ ids=["every_write_fails", "refresh_token_write_fails"],
+ )
+ @patch("stripe.StripeClient")
+ @patch("posthog.models.integration.oauth.settings")
+ @patch("posthog.models.integration.stripe.settings")
+ def test_write_posthog_secrets_keeps_the_credential_only_when_a_secret_reaches_stripe(
+ self, mock_settings, mock_oauth_settings, MockStripeClient, failing_secrets, credential_kept
+ ):
+ mock_settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID = "orchestrator_client_id"
+ mock_settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID = self.oauth_app.client_id
+ mock_oauth_settings.STRIPE_APP_CLIENT_ID = "stripe_app_client_id"
+ mock_oauth_settings.STRIPE_APP_SECRET_KEY = "sk_test"
+
+ def create_secret(params, options):
+ if params["name"] in failing_secrets:
+ raise Exception("simulated Stripe API failure")
+
+ MockStripeClient.return_value.apps.secrets.create.side_effect = create_secret
+
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="stripe",
+ config={},
+ sensitive_config={},
+ integration_id="acct_write_failure",
+ created_by=self.user,
+ )
+ publication = StripeIntegration(integration).write_posthog_secrets(self.team.pk, self.user)
+
+ assert publication.unwritten == failing_secrets
+ assert OAuthAccessToken.objects.filter(scoped_teams__contains=[self.team.pk]).exists() is credential_kept
+ assert OAuthRefreshToken.objects.filter(scoped_teams__contains=[self.team.pk]).exists() is credential_kept
+
@patch("posthog.models.integration.stripe.capture_exception")
@patch("stripe.StripeClient")
@patch("posthog.models.integration.oauth.settings")
diff --git a/posthog/management/commands/backfill_agentic_provisioning_scope.py b/posthog/management/commands/backfill_agentic_provisioning_scope.py
deleted file mode 100644
index 7a26804dcfa0..000000000000
--- a/posthog/management/commands/backfill_agentic_provisioning_scope.py
+++ /dev/null
@@ -1,142 +0,0 @@
-import logging
-
-from django.core.management.base import BaseCommand
-from django.db import transaction
-from django.utils import timezone
-
-from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
-
-logger = logging.getLogger(__name__)
-
-
-class Command(BaseCommand):
- help = (
- "Rehydrate scoped_teams on existing agentic provisioning OAuth tokens. "
- "Walks live access + refresh tokens for partner OAuth applications and "
- "recomputes scoped_teams via compute_partner_scoped_teams. Idempotent."
- )
-
- def add_arguments(self, parser):
- parser.add_argument(
- "--application-id",
- type=str,
- help="Limit to a single OAuthApplication id. Defaults to every provisioning partner.",
- )
- parser.add_argument(
- "--dry-run",
- action="store_true",
- help="Compute new scope without writing.",
- )
-
- def handle(self, *args, **options):
- # Local import so the import graph stays small for the management command
- # registry; the provisioning package pulls in a much larger dependency
- # surface than the rest of the command suite.
- from ee.api.agentic_provisioning.tokens import (
- base_team_id_from_scope,
- compute_partner_scoped_teams, # noqa: PLC0415 — keeps the heavy dep off the import path
- )
-
- application_id = options.get("application_id")
- dry_run: bool = options["dry_run"]
-
- application_qs = OAuthApplication.objects.filter(is_provisioning_partner=True)
- if application_id:
- application_qs = application_qs.filter(id=application_id)
-
- applications = list(application_qs)
- if not applications:
- self.stdout.write("No matching provisioning partner applications found.")
- return
-
- total_access = 0
- total_refresh = 0
- changed_access = 0
- changed_refresh = 0
- skipped_empty = 0
-
- for application in applications:
- self.stdout.write(f"Application {application.id} ({application.name}):")
-
- # OAuthAccessToken has no `revoked` column (only refresh tokens do); a revoked
- # access token is hard-deleted, so live tokens are the unexpired ones.
- access_tokens = OAuthAccessToken.objects.filter(application=application)
- for access_token in access_tokens.iterator(chunk_size=200):
- total_access += 1
- if access_token.expires and access_token.expires < timezone.now():
- continue
- user = access_token.user
- if user is None:
- continue
- old_scope = list(access_token.scoped_teams or [])
- base_team_id = base_team_id_from_scope(application, old_scope)
- new_scope = compute_partner_scoped_teams(application, user, base_team_id)
- # compute_partner_scoped_teams returns [] when the base team is gone or the
- # user lost access. An empty scoped_teams is treated as unrestricted by the
- # OAuth permission check (permissions.py), so writing [] here would strip the
- # project restriction from a live token. Leave the existing scope intact and
- # report it for re-authorization, matching the fail-closed issuance/refresh paths.
- if not new_scope:
- skipped_empty += 1
- self.stdout.write(
- f" access_token={access_token.pk} user={user.id} old={sorted(old_scope)} "
- f"new=[] (empty scope; left unchanged, needs re-authorization)"
- )
- continue
- if new_scope == old_scope:
- continue
- changed_access += 1
- self.stdout.write(f" access_token={access_token.pk} user={user.id} old={old_scope} new={new_scope}")
- if not dry_run:
- try:
- with transaction.atomic():
- locked = OAuthAccessToken.objects.select_for_update().get(pk=access_token.pk)
- locked.scoped_teams = new_scope
- locked.save(update_fields=["scoped_teams"])
- except OAuthAccessToken.DoesNotExist:
- # A concurrent refresh deleted this row between read and lock; skip
- # it rather than aborting the whole backfill.
- self.stdout.write(f" access_token={access_token.pk} gone before lock; skipping")
-
- refresh_tokens = OAuthRefreshToken.objects.filter(
- application=application,
- revoked__isnull=True,
- )
- for refresh_token in refresh_tokens.iterator(chunk_size=200):
- total_refresh += 1
- user = refresh_token.user
- if user is None:
- continue
- old_scope = list(refresh_token.scoped_teams or [])
- base_team_id = base_team_id_from_scope(application, old_scope)
- new_scope = compute_partner_scoped_teams(application, user, base_team_id)
- # Same fail-closed rule as access tokens: never overwrite a restricted scope
- # with an empty (unrestricted) one. Leave it for re-authorization.
- if not new_scope:
- skipped_empty += 1
- self.stdout.write(
- f" refresh_token={refresh_token.pk} user={user.id} old={sorted(old_scope)} "
- f"new=[] (empty scope; left unchanged, needs re-authorization)"
- )
- continue
- if new_scope == old_scope:
- continue
- changed_refresh += 1
- self.stdout.write(f" refresh_token={refresh_token.pk} user={user.id} old={old_scope} new={new_scope}")
- if not dry_run:
- try:
- with transaction.atomic():
- locked = OAuthRefreshToken.objects.select_for_update().get(pk=refresh_token.pk)
- locked.scoped_teams = new_scope
- locked.save(update_fields=["scoped_teams"])
- except OAuthRefreshToken.DoesNotExist:
- # A concurrent refresh removed this row between read and lock; skip
- # it rather than aborting the whole backfill.
- self.stdout.write(f" refresh_token={refresh_token.pk} gone before lock; skipping")
-
- verb = "Would update" if dry_run else "Updated"
- self.stdout.write(
- f"{verb} {changed_access}/{total_access} access tokens and "
- f"{changed_refresh}/{total_refresh} refresh tokens. "
- f"{skipped_empty} tokens left unchanged with empty recomputed scope (need re-authorization)."
- )
diff --git a/posthog/management/commands/create_stripe_marketplace_oauth_app.py b/posthog/management/commands/create_stripe_marketplace_oauth_app.py
deleted file mode 100644
index b9ebe896b6c6..000000000000
--- a/posthog/management/commands/create_stripe_marketplace_oauth_app.py
+++ /dev/null
@@ -1,94 +0,0 @@
-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."
- )
-
- configured = settings.STRIPE_MARKETPLACE_OAUTH_CLIENT_ID
- if configured and client_id != configured:
- raise CommandError(
- f"This region runs on STRIPE_MARKETPLACE_OAUTH_CLIENT_ID={configured}. Reconciling "
- f"{client_id} would report success while leaving the application in use untouched."
- )
-
- 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})")
- if existing:
- self.stdout.write(
- f" ceiling_scopes: {' '.join(existing.ceiling_scopes)} -> {StripeIntegration.SCOPES}"
- )
- else:
- 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()
- # ceiling_scopes is scopes + optional_scopes, so leaving optional_scopes alone would keep
- # anything a drifted row carries grantable outside the list this command sets.
- app.optional_scopes = []
- # 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.py
deleted file mode 100644
index 50265f340b00..000000000000
--- a/posthog/management/commands/rotate_stripe_marketplace_tokens.py
+++ /dev/null
@@ -1,126 +0,0 @@
-from argparse import ArgumentParser
-from typing import Any
-
-from django.conf import settings
-from django.core.management.base import BaseCommand, CommandError
-
-from posthog.exceptions_capture import capture_exception
-from posthog.models.integration import STRIPE_POSTHOG_SECRET_NAMES, Integration, StripeIntegration
-from posthog.models.integration.stripe import revoke_team_oauth_tokens
-from posthog.models.oauth import OAuthApplication
-
-
-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 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)
-
- # Mint before revoking. Revoking first strands the customer whenever the Stripe
- # write fails, because their app keeps reading a token that no longer exists.
- publication = stripe_integration.write_posthog_secrets(integration.team_id, created_by)
- if publication.unwritten and len(publication.unwritten) < len(STRIPE_POSTHOG_SECRET_NAMES):
- raise PartialStripeWrite(
- f"Stripe secret store partially updated, unwritten: {', '.join(publication.unwritten)}. "
- "Old and new tokens both left in place; this integration needs manual repair."
- )
- if publication.unwritten:
- raise RuntimeError(f"Stripe secret store not updated: {', '.join(publication.unwritten)}")
-
- revoke_team_oauth_tokens(
- StripeIntegration._posthog_oauth_apps_for_revocation(),
- integration.team_id,
- keep_access_token_ids=[publication.access_token_id] if publication.access_token_id else [],
- )
- except Exception as e:
- # write_posthog_secrets already drops a credential that never reached Stripe, and a
- # partial write must keep both, so there is nothing to unwind here.
- 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.py
deleted file mode 100644
index a61f3dceefb1..000000000000
--- a/posthog/management/commands/test/test_create_stripe_marketplace_oauth_app.py
+++ /dev/null
@@ -1,80 +0,0 @@
-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,
- scopes=["insight:read"],
- optional_scopes=["person:read"],
- )
- 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()
- assert app.optional_scopes == []
- assert set(app.ceiling_scopes) == set(StripeIntegration.SCOPES.split())
-
- def test_refuses_a_client_id_this_region_does_not_run_on(self):
- with self.settings(STRIPE_MARKETPLACE_OAUTH_CLIENT_ID="a_different_client_id"):
- with pytest.raises(CommandError):
- call_command("create_stripe_marketplace_oauth_app", client_id=MARKETPLACE_CLIENT_ID, stdout=StringIO())
-
- assert not OAuthApplication.objects.filter(client_id=MARKETPLACE_CLIENT_ID).exists()
-
- 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.py
deleted file mode 100644
index 04829303b0bc..000000000000
--- a/posthog/management/commands/test/test_rotate_stripe_marketplace_tokens.py
+++ /dev/null
@@ -1,460 +0,0 @@
-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.models.integration.stripe.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)
-
- @patch("stripe.StripeClient")
- def test_sweeps_a_refresh_token_no_access_token_points_at(self, MockStripeClient) -> None:
- mock_client = MagicMock()
- MockStripeClient.return_value = mock_client
-
- integration, stale_access, _ = self._create_integration_with_token(
- self.team, "acct_unlinked", self.old_app, created_by=self.user
- )
- # What the Stripe provisioning refresh leaves behind: the superseded row keeps no link to
- # any access token, so a link-based sweep cannot see it.
- unlinked = OAuthRefreshToken.objects.create(
- application=self.old_app,
- token="ph_refresh_unlinked",
- user=self.user,
- access_token=None,
- scoped_teams=[self.team.pk],
- )
-
- 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=StringIO())
-
- assert not OAuthRefreshToken.objects.filter(pk=unlinked.pk).exists()
- assert not OAuthAccessToken.objects.filter(pk=stale_access.pk).exists()
- assert OAuthAccessToken.objects.filter(application=self.new_app, scoped_teams__contains=[self.team.pk]).exists()
-
- @patch("stripe.StripeClient")
- def test_a_write_that_never_reaches_stripe_leaves_no_credential(self, MockStripeClient) -> None:
- mock_client = MagicMock()
- mock_client.apps.secrets.create.side_effect = Exception("simulated Stripe API failure")
- MockStripeClient.return_value = mock_client
-
- integration, stale_access, stale_refresh = self._create_integration_with_token(
- self.team, "acct_total_failure", 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)
-
- assert "Failed: 1" in out.getvalue()
- # The customer keeps what Stripe is still serving, and the unusable mint is gone.
- assert OAuthAccessToken.objects.filter(pk=stale_access.pk).exists()
- assert OAuthRefreshToken.objects.filter(pk=stale_refresh.pk).exists()
- assert not OAuthAccessToken.objects.filter(
- application=self.new_app, scoped_teams__contains=[self.team.pk]
- ).exists()
-
- @patch("stripe.StripeClient")
- def test_leaves_a_credential_shared_with_another_team(self, MockStripeClient) -> None:
- mock_client = MagicMock()
- MockStripeClient.return_value = mock_client
-
- other_team = Team.objects.create(organization=self.organization, name="Sibling team")
- integration, stale_access, _ = self._create_integration_with_token(
- self.team, "acct_shared", self.old_app, created_by=self.user
- )
- # A provisioning credential can cover several teams at once. Rotating one of them must
- # not take the others down with it.
- shared = OAuthAccessToken.objects.create(
- application=self.old_app,
- token="ph_access_shared",
- user=self.user,
- expires=timezone.now() + timedelta(days=14),
- scope="query:read",
- scoped_teams=[self.team.pk, other_team.pk],
- )
-
- 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=StringIO())
-
- # The sibling keeps working, and this team can no longer reach anything through it.
- shared.refresh_from_db()
- assert shared.scoped_teams == [other_team.pk]
- assert not OAuthAccessToken.objects.filter(pk=stale_access.pk).exists()
-
- @patch("stripe.StripeClient")
- def test_a_multi_team_legacy_credential_cannot_keep_reaching_this_team(self, MockStripeClient) -> None:
- mock_client = MagicMock()
- MockStripeClient.return_value = mock_client
-
- other_team = Team.objects.create(organization=self.organization, name="Second team")
- integration, _, _ = self._create_integration_with_token(
- self.team, "acct_multi", self.old_app, created_by=self.user
- )
- # What a leaked legacy credential looks like after the provisioning refresh recomputes
- # its scope: still on the orchestrator application, now covering more than one team.
- widened = OAuthAccessToken.objects.create(
- application=self.old_app,
- token="ph_access_widened",
- user=self.user,
- expires=timezone.now() + timedelta(days=14),
- scope="query:read",
- scoped_teams=[self.team.pk, other_team.pk],
- )
- widened_refresh = OAuthRefreshToken.objects.create(
- application=self.old_app,
- token="ph_refresh_widened",
- user=self.user,
- access_token=widened,
- scoped_teams=[self.team.pk, other_team.pk],
- )
-
- 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=StringIO())
-
- widened.refresh_from_db()
- widened_refresh.refresh_from_db()
- assert self.team.pk not in widened.scoped_teams
- assert self.team.pk not in widened_refresh.scoped_teams
- assert widened.scoped_teams == [other_team.pk]
-
- @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/stripe.py b/posthog/models/integration/stripe.py
index f817565576d5..ae5894bbed44 100644
--- a/posthog/models/integration/stripe.py
+++ b/posthog/models/integration/stripe.py
@@ -1,6 +1,5 @@
"""Stripe App integration: writing PostHog OAuth secrets into Stripe's Secret Store."""
-from collections.abc import Collection
from datetime import timedelta
from typing import TYPE_CHECKING
@@ -38,22 +37,12 @@ STRIPE_POSTHOG_SECRET_NAMES = (
@frozen
class StripeSecretPublication:
- """What one attempt to publish PostHog's credentials into Stripe's Secret Store produced.
+ """What one attempt to publish PostHog's credentials into Stripe's Secret Store produced."""
- `access_token_id` is None when nothing reached Stripe, because the credential minted for
- that attempt is then unreachable by anyone and is dropped rather than left to expire.
- """
-
- access_token_id: int | None
unwritten: tuple[str, ...]
-def revoke_team_oauth_tokens(
- applications: list[OAuthApplication],
- team_id: int,
- *,
- keep_access_token_ids: Collection[int] = (),
-) -> None:
+def revoke_team_oauth_tokens(applications: list[OAuthApplication], team_id: int) -> None:
"""Remove one team's access to the OAuth credentials these applications hold.
Match refresh tokens by application and team. Do not match them through their access token.
@@ -94,19 +83,15 @@ def revoke_team_oauth_tokens(
OAuthApplication.objects.select_for_update().filter(pk=application_id).first()
shared = [
- *covered_refresh.exclude(scoped_teams=[team_id]).exclude(access_token_id__in=keep_access_token_ids),
- *covered_access.exclude(scoped_teams=[team_id]).exclude(id__in=keep_access_token_ids),
+ *covered_refresh.exclude(scoped_teams=[team_id]),
+ *covered_access.exclude(scoped_teams=[team_id]),
]
for token in shared:
token.scoped_teams = [scoped for scoped in token.scoped_teams if scoped != team_id]
token.save(update_fields=["scoped_teams"])
- OAuthRefreshToken.objects.filter(application__in=applications, scoped_teams=[team_id]).exclude(
- access_token_id__in=keep_access_token_ids
- ).delete()
- OAuthAccessToken.objects.filter(application__in=applications, scoped_teams=[team_id]).exclude(
- id__in=keep_access_token_ids
- ).delete()
+ OAuthRefreshToken.objects.filter(application__in=applications, scoped_teams=[team_id]).delete()
+ OAuthAccessToken.objects.filter(application__in=applications, scoped_teams=[team_id]).delete()
class StripeIntegration:
@@ -148,12 +133,7 @@ class StripeIntegration:
return StripeClient(oauth_config.client_secret)
def write_posthog_secrets(self, team_id: int, created_by: "User") -> StripeSecretPublication:
- """Write PostHog OAuth tokens to Stripe's Secret Store so the Stripe App can call PostHog APIs.
-
- Reports the secrets it could not write. A caller that revokes the previous credential must
- treat a non-empty `unwritten` as failure: Stripe would still be holding the old token, so
- revoking it leaves the customer with nothing that works.
- """
+ """Write PostHog OAuth tokens to Stripe's Secret Store so the Stripe App can call PostHog APIs."""
oauth_app = self._get_posthog_oauth_app()
if not oauth_app:
@@ -161,7 +141,7 @@ class StripeIntegration:
Exception("Stripe marketplace OAuth application not found, cannot write secrets to Stripe"),
{"integration_id": self.integration.id, "team_id": self.integration.team_id},
)
- return StripeSecretPublication(access_token_id=None, unwritten=STRIPE_POSTHOG_SECRET_NAMES)
+ return StripeSecretPublication(unwritten=STRIPE_POSTHOG_SECRET_NAMES)
access_token_value = generate_random_oauth_access_token(None)
access_token = OAuthAccessToken.objects.create(
@@ -224,14 +204,14 @@ class StripeIntegration:
if len(failed) == len(secrets):
return self._discard_unpublished(access_token, tuple(failed))
- return StripeSecretPublication(access_token_id=access_token.pk, unwritten=tuple(failed))
+ return StripeSecretPublication(unwritten=tuple(failed))
@staticmethod
def _discard_unpublished(access_token: OAuthAccessToken, unwritten: tuple[str, ...]) -> StripeSecretPublication:
"""Drop a credential that never reached Stripe, so a retry cannot accumulate live tokens."""
OAuthRefreshToken.objects.filter(access_token=access_token).delete()
access_token.delete()
- return StripeSecretPublication(access_token_id=None, unwritten=unwritten)
+ return StripeSecretPublication(unwritten=unwritten)
def clear_posthog_secrets(self) -> None:
"""Best-effort clear of PostHog secrets from Stripe and revoke local OAuth tokens."""
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index efda2dcf6ac5..b318607d4087 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -159,8 +159,7 @@ ATLASSIAN_APP_CLIENT_SECRET = get_from_env("ATLASSIAN_APP_CLIENT_SECRET", "")
# 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.
+# identity alone. Left unset, a new install gets no PostHog credential.
# - STRIPE_SIGNING_SECRET: Used to verify the authenticity of incoming webhook/agentic provisioning requests from Stripe
STRIPE_APP_CLIENT_ID = get_from_env("STRIPE_APP_CLIENT_ID", "")
STRIPE_APP_OVERRIDE_AUTHORIZE_URL = get_from_env("STRIPE_APP_OVERRIDE_AUTHORIZE_URL", "")