Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(integrations): harden stripe marketplace token rotation and setup (#87261)

Matt Brookera4e8cb8a6e5f
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 3b27a752c888..8c6cf954a33b 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -914,10 +914,10 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial
if validated_data["kind"] == "stripe":
try:
stripe_integration = StripeIntegration(instance)
- unwritten = stripe_integration.write_posthog_secrets(team_id, request.user)
- if unwritten:
+ publication = stripe_integration.write_posthog_secrets(team_id, request.user)
+ if publication.unwritten:
capture_exception(
- Exception(f"Stripe secret store not fully written: {', '.join(unwritten)}"),
+ Exception(f"Stripe secret store not fully written: {', '.join(publication.unwritten)}"),
{"team_id": team_id, "integration_id": instance.id},
)
except Exception as e:
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 2350461ceb86..6acff66470e6 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -4617,16 +4617,17 @@ class TestStripeIntegrationOAuthTokens:
integration_id="acct_split",
created_by=self.user,
)
- unwritten = StripeIntegration(integration).write_posthog_secrets(self.team.pk, self.user)
+ publication = 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 publication.unwritten == ()
assert minted.latest("id").application == self.oauth_app
else:
- assert unwritten == list(STRIPE_POSTHOG_SECRET_NAMES)
+ assert publication.unwritten == STRIPE_POSTHOG_SECRET_NAMES
+ assert publication.access_token_id is None
assert not minted.exists()
@patch("posthog.models.integration.stripe.settings")
@@ -4797,10 +4798,12 @@ class TestStripeIntegrationOAuthTokens:
created_by=self.user,
)
stripe_int = StripeIntegration(integration)
- stripe_int.write_posthog_secrets(self.team.pk, self.user)
+ publication = 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)
diff --git a/posthog/management/commands/create_stripe_marketplace_oauth_app.py b/posthog/management/commands/create_stripe_marketplace_oauth_app.py
index ea2529e67ac5..b9ebe896b6c6 100644
--- a/posthog/management/commands/create_stripe_marketplace_oauth_app.py
+++ b/posthog/management/commands/create_stripe_marketplace_oauth_app.py
@@ -41,6 +41,13 @@ class Command(BaseCommand):
"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
@@ -58,7 +65,12 @@ class Command(BaseCommand):
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}")
+ 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
@@ -66,6 +78,9 @@ class Command(BaseCommand):
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()
diff --git a/posthog/management/commands/rotate_stripe_marketplace_tokens.py b/posthog/management/commands/rotate_stripe_marketplace_tokens.py
index 2efdf2bbd5d6..50265f340b00 100644
--- a/posthog/management/commands/rotate_stripe_marketplace_tokens.py
+++ b/posthog/management/commands/rotate_stripe_marketplace_tokens.py
@@ -3,12 +3,11 @@ 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
+from posthog.models.integration.stripe import revoke_team_oauth_tokens
+from posthog.models.oauth import OAuthApplication
class PartialStripeWrite(Exception):
@@ -36,75 +35,6 @@ class Command(BaseCommand):
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")
@@ -157,38 +87,26 @@ class Command(BaseCommand):
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):
+ 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(unwritten)}. "
+ f"Stripe secret store partially updated, unwritten: {', '.join(publication.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)}")
+ if publication.unwritten:
+ raise RuntimeError(f"Stripe secret store not updated: {', '.join(publication.unwritten)}")
- self._sweep_superseded_tokens(integration.team_id, created_by.id, stale_token_ids)
+ 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:
- # 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()
-
+ # 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}")
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
index 8417d2a664f4..a61f3dceefb1 100644
--- a/posthog/management/commands/test/test_create_stripe_marketplace_oauth_app.py
+++ b/posthog/management/commands/test/test_create_stripe_marketplace_oauth_app.py
@@ -40,6 +40,8 @@ class TestCreateStripeMarketplaceOauthApp(BaseTest):
redirect_uris="https://localhost",
algorithm="RS256",
is_provisioning_partner=True,
+ scopes=["insight:read"],
+ optional_scopes=["person:read"],
)
drifted.update_provisioning(
active=True,
@@ -57,6 +59,15 @@ class TestCreateStripeMarketplaceOauthApp(BaseTest):
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(
diff --git a/posthog/management/commands/test/test_rotate_stripe_marketplace_tokens.py b/posthog/management/commands/test/test_rotate_stripe_marketplace_tokens.py
index ecd1e5a89783..04829303b0bc 100644
--- a/posthog/management/commands/test/test_rotate_stripe_marketplace_tokens.py
+++ b/posthog/management/commands/test/test_rotate_stripe_marketplace_tokens.py
@@ -284,7 +284,7 @@ class TestRotateStripeMarketplaceTokens(BaseTest):
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")
+ @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
@@ -317,6 +317,137 @@ class TestRotateStripeMarketplaceTokens(BaseTest):
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", ""),
diff --git a/posthog/models/integration/stripe.py b/posthog/models/integration/stripe.py
index 1736c1db4ca5..f817565576d5 100644
--- a/posthog/models/integration/stripe.py
+++ b/posthog/models/integration/stripe.py
@@ -1,5 +1,6 @@
"""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
@@ -7,12 +8,14 @@ if TYPE_CHECKING:
from stripe import StripeClient
from django.conf import settings
+from django.db import transaction
from django.utils import timezone
import structlog
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
-from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken, lock_oauth_connection
from posthog.models.user import User
from posthog.models.utils import generate_random_oauth_access_token, generate_random_oauth_refresh_token
from posthog.utils import get_instance_region
@@ -33,6 +36,79 @@ STRIPE_POSTHOG_SECRET_NAMES = (
)
+@frozen
+class StripeSecretPublication:
+ """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:
+ """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.
+ A refresh sets the access token of its predecessor to NULL. The Stripe provisioning refresh
+ sets no source_refresh_token. A match through the link therefore misses rows. Those rows
+ stay usable for REFRESH_TOKEN_GRACE_PERIOD_SECONDS.
+
+ Delete a credential that covers only this team. Narrow a credential that covers other teams:
+ remove this team and keep the rest. The Stripe provisioning refresh can widen a credential to
+ several teams. A skip then leaves this team reachable. A delete then removes teams that this
+ call must not touch.
+
+ Never leave scoped_teams empty. An empty list means unrestricted.
+
+ Take two locks. lock_oauth_connection covers the refresh in django-oauth-toolkit. The
+ application row lock covers the Stripe provisioning refresh. One lock is not enough. A row
+ lock alone lets a token minted during the sweep stay outside the snapshot of the delete.
+ """
+ if not applications:
+ return
+
+ with transaction.atomic():
+ covered_access = OAuthAccessToken.objects.filter(application__in=applications, scoped_teams__contains=[team_id])
+ covered_refresh = OAuthRefreshToken.objects.filter(
+ application__in=applications, scoped_teams__contains=[team_id]
+ )
+
+ user_ids = set(covered_access.values_list("user_id", flat=True)) | set(
+ covered_refresh.values_list("user_id", flat=True)
+ )
+ # Advisory lock before any row lock, and both in a fixed order, so this cannot deadlock
+ # against a mint taking the same locks.
+ for user_id, application_id in sorted(
+ (user_id, application.id) for user_id in user_ids if user_id is not None for application in applications
+ ):
+ lock_oauth_connection(user_id=user_id, application_id=application_id)
+ for application_id in sorted(application.id for application in applications):
+ 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),
+ ]
+ 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()
+
+
class StripeIntegration:
integration: model.Integration
@@ -71,12 +147,12 @@ class StripeIntegration:
return None
return StripeClient(oauth_config.client_secret)
- def write_posthog_secrets(self, team_id: int, created_by: "User") -> list[str]:
+ 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.
- 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.
+ 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.
"""
oauth_app = self._get_posthog_oauth_app()
@@ -85,7 +161,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 list(STRIPE_POSTHOG_SECRET_NAMES)
+ return StripeSecretPublication(access_token_id=None, unwritten=STRIPE_POSTHOG_SECRET_NAMES)
access_token_value = generate_random_oauth_access_token(None)
access_token = OAuthAccessToken.objects.create(
@@ -122,7 +198,7 @@ class StripeIntegration:
client = self._stripe_client()
if client is None:
- return list(secrets)
+ return self._discard_unpublished(access_token, tuple(secrets))
failed: list[str] = []
for name, payload in secrets.items():
@@ -145,7 +221,17 @@ class StripeIntegration:
},
)
- return failed
+ if len(failed) == len(secrets):
+ return self._discard_unpublished(access_token, tuple(failed))
+
+ return StripeSecretPublication(access_token_id=access_token.pk, 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)
def clear_posthog_secrets(self) -> None:
"""Best-effort clear of PostHog secrets from Stripe and revoke local OAuth tokens."""
@@ -180,18 +266,7 @@ class StripeIntegration:
def _destroy_posthog_oauth_tokens(self) -> None:
"""Delete the local OAuth access and refresh tokens created for this Stripe integration."""
- oauth_apps = self._posthog_oauth_apps_for_revocation()
- if not oauth_apps:
- return
-
- team_id = self.integration.team_id
- access_tokens = OAuthAccessToken.objects.filter(
- application__in=oauth_apps,
- scoped_teams__contains=[team_id],
- )
- # Delete refresh tokens first since their FK to access_token is SET_NULL
- OAuthRefreshToken.objects.filter(access_token__in=access_tokens).delete()
- access_tokens.delete()
+ revoke_team_oauth_tokens(self._posthog_oauth_apps_for_revocation(), self.integration.team_id)
def _get_posthog_oauth_app(self):
"""The application new marketplace tokens are minted on.