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(provisioning): resolve stripe oauth app by id, seed scopes (#61224)

Matt Brookerf9e69dbeff29
diff --git a/ee/api/agentic_provisioning/test/test_authorize.py b/ee/api/agentic_provisioning/test/test_authorize.py
index 7ba744c8727c..e6186eb3c9f6 100644
--- a/ee/api/agentic_provisioning/test/test_authorize.py
+++ b/ee/api/agentic_provisioning/test/test_authorize.py
@@ -6,6 +6,7 @@ import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from django.conf import settings
from django.core.cache import cache
from django.test import override_settings
@@ -15,7 +16,7 @@ from posthog.models.user import User
from ee.api.agentic_provisioning import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIX
from ee.api.agentic_provisioning.signature import compute_signature
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET
+from ee.api.agentic_provisioning.test.base import _RSA_KEY, HMAC_SECRET, TEST_STRIPE_OAUTH_CLIENT_ID
DUMMY_CALLBACK = "https://marketplace.stripe.com/oauth/callback"
@@ -83,8 +84,26 @@ class TestAgenticAuthorize(APIBaseTest):
assert code_data["scopes"] == ["query:read", "project:read"]
@pytest.mark.requires_secrets
- @override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET, STRIPE_ORCHESTRATOR_CALLBACK_URL=DUMMY_CALLBACK)
+ @override_settings(
+ STRIPE_SIGNING_SECRET=HMAC_SECRET,
+ STRIPE_ORCHESTRATOR_CALLBACK_URL=DUMMY_CALLBACK,
+ STRIPE_POSTHOG_OAUTH_CLIENT_ID=TEST_STRIPE_OAUTH_CLIENT_ID,
+ OIDC_RSA_PRIVATE_KEY=_RSA_KEY,
+ OAUTH2_PROVIDER={**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": _RSA_KEY},
+ )
def test_full_a1_flow_with_token_exchange(self):
+ # The token exchange resolves the legacy Stripe OAuth app by client_id and now
+ # hard-fails if it's missing, so the e2e flow needs the app row to exist. The
+ # model enforces RS256, which requires OIDC_RSA_PRIVATE_KEY to be set.
+ OAuthApplication.objects.create(
+ name="PostHog Stripe App",
+ client_id=TEST_STRIPE_OAUTH_CLIENT_ID,
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://localhost",
+ algorithm="RS256",
+ )
self._set_pending_auth("state_e2e", self.user.email)
res = self.client.get("/api/agentic/authorize?state=state_e2e")
diff --git a/ee/api/agentic_provisioning/test/test_oauth_token.py b/ee/api/agentic_provisioning/test/test_oauth_token.py
index 7dd2b959de99..083115cc0ef7 100644
--- a/ee/api/agentic_provisioning/test/test_oauth_token.py
+++ b/ee/api/agentic_provisioning/test/test_oauth_token.py
@@ -4,11 +4,18 @@ from urllib.parse import urlencode
from django.core.cache import cache
from django.test import override_settings
+from parameterized import parameterized
+
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from ee.api.agentic_provisioning import AUTH_CODE_CACHE_PREFIX
from ee.api.agentic_provisioning.signature import compute_signature
from ee.api.agentic_provisioning.test.base import HMAC_SECRET, TEST_STRIPE_OAUTH_CLIENT_ID, ProvisioningTestBase
+from ee.api.agentic_provisioning.views import (
+ STRIPE_CONTRACTED_SCOPES,
+ LegacyStripeOAuthAppMissingError,
+ _get_legacy_stripe_oauth_app,
+)
@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
@@ -132,6 +139,29 @@ class TestOAuthTokenExchange(ProvisioningTestBase):
)
assert res.status_code == 401
+ def test_token_exchange_seeds_stripe_app_scopes(self):
+ app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)
+ app.scopes = []
+ app.save(update_fields=["scopes"])
+
+ self._store_auth_code("seed_code")
+ res = self._post_token(self._token_request_body(code="seed_code"))
+
+ assert res.status_code == 200
+ app.refresh_from_db()
+ assert app.scopes == STRIPE_CONTRACTED_SCOPES
+
+ def test_token_exchange_missing_stripe_app_hard_fails(self):
+ OAuthApplication.objects.filter(client_id=TEST_STRIPE_OAUTH_CLIENT_ID).delete()
+
+ self._store_auth_code("orphan_code")
+ res = self._post_token(self._token_request_body(code="orphan_code"))
+
+ assert res.status_code == 500
+ assert res.json()["error"] == "server_error"
+ # No app may be fabricated to paper over the missing configuration.
+ assert not OAuthApplication.objects.filter(client_id=TEST_STRIPE_OAUTH_CLIENT_ID).exists()
+
def test_direct_mint_within_ceiling_grants_requested_scopes(self):
self._set_app_ceiling(["query:read", "project:read"])
self._store_auth_code("ceiling_ok", scopes=["query:read"])
@@ -148,6 +178,7 @@ class TestOAuthTokenExchange(ProvisioningTestBase):
assert res.json()["error"] == "invalid_scope"
def test_refresh_narrows_to_tightened_ceiling(self):
+ self._set_app_ceiling(["query:read", "insight:write"])
self._store_auth_code("refresh_narrow", scopes=["query:read", "insight:write"])
first = self._post_token(self._token_request_body(code="refresh_narrow"))
refresh_token = first.json()["refresh_token"]
@@ -160,6 +191,7 @@ class TestOAuthTokenExchange(ProvisioningTestBase):
assert token.scope == "query:read"
def test_refresh_rejected_when_scopes_outside_ceiling(self):
+ self._set_app_ceiling(["insight:write"])
self._store_auth_code("refresh_reject", scopes=["insight:write"])
first = self._post_token(self._token_request_body(code="refresh_reject"))
refresh_token = first.json()["refresh_token"]
@@ -169,3 +201,44 @@ class TestOAuthTokenExchange(ProvisioningTestBase):
res = self._post_token(refresh_body)
assert res.status_code == 400
assert res.json()["error"] == "invalid_grant"
+
+
+class TestLegacyStripeOAuthApp(ProvisioningTestBase):
+ def _stripe_app(self) -> OAuthApplication:
+ return OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)
+
+ @parameterized.expand([("US",), ("EU",)])
+ def test_resolves_and_seeds_scopes_regardless_of_region(self, region: str):
+ app = self._stripe_app()
+ app.scopes = []
+ app.save(update_fields=["scopes"])
+
+ with override_settings(CLOUD_DEPLOYMENT=region):
+ resolved = _get_legacy_stripe_oauth_app()
+
+ assert resolved.id == app.id
+ resolved.refresh_from_db()
+ assert resolved.scopes == STRIPE_CONTRACTED_SCOPES
+
+ def test_does_not_overwrite_existing_scopes(self):
+ app = self._stripe_app()
+ app.scopes = ["query:read"]
+ app.save(update_fields=["scopes"])
+
+ resolved = _get_legacy_stripe_oauth_app()
+
+ resolved.refresh_from_db()
+ assert resolved.scopes == ["query:read"]
+
+ def test_missing_app_hard_fails_without_fabrication(self):
+ OAuthApplication.objects.filter(client_id=TEST_STRIPE_OAUTH_CLIENT_ID).delete()
+
+ with self.assertRaises(LegacyStripeOAuthAppMissingError):
+ _get_legacy_stripe_oauth_app()
+
+ assert not OAuthApplication.objects.filter(client_id=TEST_STRIPE_OAUTH_CLIENT_ID).exists()
+
+ def test_unconfigured_client_id_hard_fails(self):
+ with override_settings(STRIPE_POSTHOG_OAUTH_CLIENT_ID=""):
+ with self.assertRaises(LegacyStripeOAuthAppMissingError):
+ _get_legacy_stripe_oauth_app()
diff --git a/ee/api/agentic_provisioning/views.py b/ee/api/agentic_provisioning/views.py
index 3e4c7d191528..651aae074954 100644
--- a/ee/api/agentic_provisioning/views.py
+++ b/ee/api/agentic_provisioning/views.py
@@ -91,7 +91,10 @@ PARTNER_RATE_LIMIT_EVENT_NAMES: dict[str, str] = {
_SAFE_STATE_RE = re.compile(r"^[A-Za-z0-9_\-]{1,256}$")
-LEGACY_STRIPE_APP_NAME = "PostHog Stripe App"
+# Stripe's contracted scope ceiling, seeded onto the legacy Stripe Projects OAuth
+# app. Mirrors the de-facto set tokens already carry (`StripeIntegration.SCOPES`,
+# the default in `_exchange_authorization_code` when no per-code scopes are given).
+STRIPE_CONTRACTED_SCOPES: list[str] = StripeIntegration.SCOPES.split()
# Mirrors PersonalAPIKey.label's CharField(max_length=40) - keep in sync if that ever changes.
PROVISIONED_PAT_LABEL_MAX_LENGTH = 40
# Cap partner-supplied prefix below the full label length so " - {team_name}" still
@@ -1060,7 +1063,13 @@ def _exchange_authorization_code(request: Request) -> Response:
return Response({"error": "invalid_grant", "error_description": "User not found"}, status=400)
# Use partner's OAuth app if available, fall back to Stripe
- oauth_app = _get_oauth_app_for_code(code_data)
+ try:
+ oauth_app = _get_oauth_app_for_code(code_data)
+ except LegacyStripeOAuthAppMissingError:
+ _capture_provisioning_event("token_exchange", "oauth_app_missing", grant_type="authorization_code")
+ return Response(
+ {"error": "server_error", "error_description": "OAuth application is not configured"}, status=500
+ )
# Direct-mint bypasses /authorize's OAuthValidator, so the per-app scope
# ceiling has to be enforced here before the token is created by hand.
@@ -2269,28 +2278,48 @@ def _authenticate_bearer(request: Request) -> tuple[Response | None, Any, Any]:
return (_error_response("unauthorized", "Authentication failed", status=401), None, None)
-def _get_legacy_stripe_oauth_app():
- if settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID:
- try:
- return OAuthApplication.objects.get(client_id=settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID)
- except OAuthApplication.DoesNotExist:
- logger.warning(
- "provisioning.oauth_app.client_id_not_found",
- client_id=settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID,
- )
+class LegacyStripeOAuthAppMissingError(Exception):
+ """The configured Stripe Projects OAuth app could not be resolved.
- from oauthlib.common import generate_token
-
- return OAuthApplication.objects.create(
- name=LEGACY_STRIPE_APP_NAME,
- client_id=settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID or generate_token(),
- client_secret="",
- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="https://localhost",
- algorithm="RS256",
- provisioning_can_issue_deep_links=True,
- )
+ Raised instead of fabricating an app on demand: a missing app is an
+ operational misconfiguration, not something to paper over with a freshly
+ created application that carries no scope ceiling.
+ """
+
+
+def _seed_stripe_app_scopes(app: OAuthApplication) -> None:
+ """Seed the Stripe Projects app's scope ceiling when it is unset.
+
+ Region-agnostic by design: US and EU each hold their own OAuthApplication
+ row, so this runs independently the first time the app is resolved in each
+ region. Pre-seeding via the ops step in the slice notes avoids the on-request
+ write, but this keeps the ceiling correct even if that step is missed.
+ """
+ if app.scopes:
+ return
+ app.scopes = list(STRIPE_CONTRACTED_SCOPES)
+ app.save(update_fields=["scopes"])
+
+
+def _get_legacy_stripe_oauth_app() -> OAuthApplication:
+ client_id = settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID
+ if not client_id:
+ error = LegacyStripeOAuthAppMissingError("STRIPE_POSTHOG_OAUTH_CLIENT_ID is not configured")
+ capture_exception(error)
+ raise error
+
+ try:
+ app = OAuthApplication.objects.get(client_id=client_id)
+ except OAuthApplication.DoesNotExist as exc:
+ error = LegacyStripeOAuthAppMissingError("Stripe Projects OAuth app not found for configured client_id")
+ # Chain the DoesNotExist so the captured event keeps its traceback; the new
+ # error was never raised, so it carries no traceback of its own.
+ error.__cause__ = exc
+ capture_exception(error, additional_properties={"client_id": client_id})
+ raise error from None
+
+ _seed_stripe_app_scopes(app)
+ return app
def _get_available_teams_for_user(user: User) -> list[dict[str, Any]]:
@@ -2322,11 +2351,13 @@ def _get_callback_url(partner_id: str) -> str:
return settings.STRIPE_ORCHESTRATOR_CALLBACK_URL
-def _get_oauth_app_for_code(code_data: dict):
+def _get_oauth_app_for_code(code_data: dict) -> OAuthApplication:
"""Resolve the OAuthApplication for a token exchange.
If the auth code was created by a provisioning partner, use that app.
- Otherwise fall back to the legacy Stripe Projects app lookup.
+ Otherwise fall back to the legacy Stripe Projects app lookup, which
+ hard-fails (raising ``LegacyStripeOAuthAppMissingError``) if the configured
+ app is missing rather than fabricating one.
"""
partner_id = code_data.get("partner_id", "")
if partner_id:
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index d4cb501eb51c..ae5fbc39612a 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -3291,7 +3291,7 @@ class StripeIntegration:
# These are the scopes we'll give Stripe when creating a local OAuth App
# and sending them access
- SCOPES = " ".join(
+ SCOPES: str = " ".join(
[
"customer_journey:read",
"query:read",