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: Move Stripe Projects provisioning to separate folder (#72799)

Rafael Audibert3bf9839c082c
diff --git a/ee/api/agentic_provisioning/signature.py b/ee/api/agentic_provisioning/signature.py
index 42dca455391e..dba3abaccb34 100644
--- a/ee/api/agentic_provisioning/signature.py
+++ b/ee/api/agentic_provisioning/signature.py
@@ -1,3 +1,8 @@
+# TODO(migration): the global-secret verification here (verify_provisioning_signature,
+# STRIPE_SIGNING_SECRET) is Stripe-only — removable once Stripe traffic has fully
+# moved to /api/partners/stripe/. _compute_hmac/_get_raw_body/_parse_signature_header
+# must survive: authentication.py uses them for per-partner HMAC.
+
import re
import hmac
import uuid
diff --git a/ee/api/agentic_provisioning/test/test_health.py b/ee/api/agentic_provisioning/test/test_health.py
index 5f94de6d2020..d463d68b2bd8 100644
--- a/ee/api/agentic_provisioning/test/test_health.py
+++ b/ee/api/agentic_provisioning/test/test_health.py
@@ -1,3 +1,4 @@
+# TODO(migration): Stripe-only coverage - remove once Stripe traffic has fully moved to /api/partners/stripe/ (equivalent tests live in ee/partners/stripe/api/provisioning/test/).
import time
from unittest.mock import patch
diff --git a/ee/api/agentic_provisioning/test/test_services.py b/ee/api/agentic_provisioning/test/test_services.py
index 6dfe6f5c07b8..f6c0298b6e88 100644
--- a/ee/api/agentic_provisioning/test/test_services.py
+++ b/ee/api/agentic_provisioning/test/test_services.py
@@ -1,3 +1,4 @@
+# TODO(migration): Stripe-only coverage - remove once Stripe traffic has fully moved to /api/partners/stripe/ (equivalent tests live in ee/partners/stripe/api/provisioning/test/).
import time
from unittest.mock import MagicMock, patch
diff --git a/ee/api/agentic_provisioning/test/test_signature.py b/ee/api/agentic_provisioning/test/test_signature.py
index 1a283e59ca31..e037baf6613c 100644
--- a/ee/api/agentic_provisioning/test/test_signature.py
+++ b/ee/api/agentic_provisioning/test/test_signature.py
@@ -1,3 +1,4 @@
+# TODO(migration): Stripe-only coverage - remove once Stripe traffic has fully moved to /api/partners/stripe/ (equivalent tests live in ee/partners/stripe/api/provisioning/test/).
import io
import time
from typing import cast
diff --git a/ee/api/agentic_provisioning/test/test_spt.py b/ee/api/agentic_provisioning/test/test_spt.py
index 4835bd357401..f90458622fa4 100644
--- a/ee/api/agentic_provisioning/test/test_spt.py
+++ b/ee/api/agentic_provisioning/test/test_spt.py
@@ -1,3 +1,4 @@
+# TODO(migration): Stripe-only coverage - remove once Stripe traffic has fully moved to /api/partners/stripe/ (equivalent tests live in ee/partners/stripe/api/provisioning/test/).
from unittest.mock import MagicMock, patch
from django.core.cache import cache
diff --git a/ee/api/agentic_provisioning/test/test_update_service.py b/ee/api/agentic_provisioning/test/test_update_service.py
index 3e5fc4a29fae..e4aad78be669 100644
--- a/ee/api/agentic_provisioning/test/test_update_service.py
+++ b/ee/api/agentic_provisioning/test/test_update_service.py
@@ -1,3 +1,4 @@
+# TODO(migration): Stripe-only coverage - remove once Stripe traffic has fully moved to /api/partners/stripe/ (equivalent tests live in ee/partners/stripe/api/provisioning/test/).
from unittest.mock import MagicMock, patch
from django.test import override_settings
diff --git a/ee/api/agentic_provisioning/views.py b/ee/api/agentic_provisioning/views.py
index 3ae7cd73cc86..27209886b358 100644
--- a/ee/api/agentic_provisioning/views.py
+++ b/ee/api/agentic_provisioning/views.py
@@ -123,6 +123,8 @@ GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS = 3600
_SAFE_STATE_RE = re.compile(r"^[A-Za-z0-9_\-]{1,256}$")
+# TODO(migration): Stripe-only - remove once Stripe traffic has fully moved to
+# /api/partners/stripe/ (watch path_namespace on agentic_provisioning events).
# 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).
@@ -144,6 +146,10 @@ PARTNER_TOKEN_EXPIRY_SECONDS = 3600
# 2. pay_as_you_go (plan) — usage-based pricing, no minimum commitment
# 3. analytics (deployable) — provisions a PostHog project, pricing varies
# by parent plan via component pricing
+# TODO(migration): only the Stripe orchestrator consumes this catalog today -
+# removable (along with provisioning_health/provisioning_services) once Stripe
+# traffic has fully moved to /api/partners/stripe/, unless another partner
+# starts using /provisioning/services.
# ---------------------------------------------------------------------------
ANALYTICS_SERVICE_ID = "analytics"
@@ -372,6 +378,9 @@ def account_requests(request: Request) -> Response:
else:
partner_account_id = orchestrator.get("account", "")
+ # TODO(migration): the partner-less fallback below (global Stripe HMAC +
+ # orchestrator.stripe.account) is Stripe-only — remove once Stripe traffic
+ # has fully moved to /api/partners/stripe/.
# If no partner identified, require Stripe Projects HMAC auth
if not partner and not request.headers.get("stripe-signature"):
return typed_error_response("unauthorized", "Authentication required", status=401)
@@ -1236,6 +1245,8 @@ def _exchange_authorization_code(request: Request) -> Response:
# Auth check: PKCE codes require code_verifier, non-PKCE codes require HMAC.
# All verification happens BEFORE cache.delete so a failed attempt doesn't consume the code.
+ # TODO(migration): the HMAC arm is Stripe-only - remove once Stripe traffic
+ # has fully moved to /api/partners/stripe/ (PKCE remains for other partners).
stored_challenge = code_data.get("code_challenge", "")
has_hmac = bool(request.headers.get("stripe-signature"))
if stored_challenge:
@@ -1542,6 +1553,8 @@ def _exchange_refresh_token(request: Request) -> Response:
)
+# TODO(migration): the SPT billing helpers below are Stripe-only - remove once
+# Stripe traffic has fully moved to /api/partners/stripe/.
def _build_billing_token(team: Team, user: User) -> str | None:
from posthog.cloud_utils import get_cached_instance_license
@@ -2497,6 +2510,8 @@ def provisioning_wizard_runs(request: Request, resource_id: str) -> Response:
# ---------------------------------------------------------------------------
# POST /provisioning/resources/:id/update_service
+# TODO(migration): Stripe-only (hard global-HMAC requirement, SPT billing) -
+# remove once Stripe traffic has fully moved to /api/partners/stripe/.
# ---------------------------------------------------------------------------
@@ -2811,6 +2826,8 @@ def deep_links(request: Request) -> Response:
# HMAC partners must include a valid signature on this endpoint - bearer alone
# is not sufficient to mint a full web session via the deep-link primitive.
+ # TODO(migration): HMAC support is Stripe-only - remove this branch once
+ # Stripe traffic has fully moved to /api/partners/stripe/.
if access_token.application.provisioning_auth_method == "hmac":
if not request.META.get("HTTP_STRIPE_SIGNATURE"):
return error_response(
@@ -2892,6 +2909,8 @@ def deep_links(request: Request) -> Response:
def _partner_label(partner: OAuthApplication | None) -> str:
+ # TODO(migration): the "Stripe" fallbacks are for the partner-less legacy
+ # identity - remove once Stripe traffic has fully moved to /api/partners/stripe/.
if not partner:
return "Stripe"
if partner.provisioning_partner_type:
@@ -3000,6 +3019,8 @@ def _enforce_cimd_domain_rate_limit(client_id: str) -> Response | None:
def _verify_hmac_if_present(request: Request) -> Response | None:
+ # TODO(migration): Stripe-only - remove once Stripe traffic has fully moved
+ # to /api/partners/stripe/.
"""Verify HMAC signature only if the Stripe-Signature header is present.
For HMAC partners (Stripe), both HMAC + Bearer are required on resource endpoints.
@@ -3046,12 +3067,16 @@ def _authenticate_bearer(request: Request) -> tuple[Response | None, Any, Any]:
return None, access_token.user, access_token
# Legacy fallback: accept tokens from the Stripe Projects app by client_id
+ # TODO(migration): Stripe-only - remove once Stripe traffic has fully moved
+ # to /api/partners/stripe/.
if app and app.client_id == settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID:
return None, access_token.user, access_token
return (error_response("unauthorized", "Authentication failed", status=401), None, None)
+# TODO(migration): the legacy Stripe app resolution below is Stripe-only -
+# remove once Stripe traffic has fully moved to /api/partners/stripe/.
class LegacyStripeOAuthAppMissingError(Exception):
"""The configured Stripe Projects OAuth app could not be resolved.
@@ -3122,6 +3147,8 @@ def _get_callback_url(partner_id: str) -> str:
except OAuthApplication.DoesNotExist:
pass
+ # TODO(migration): Stripe-only fallback - remove once Stripe traffic has
+ # fully moved to /api/partners/stripe/.
return settings.STRIPE_ORCHESTRATOR_CALLBACK_URL
diff --git a/ee/partners/__init__.py b/ee/partners/__init__.py
new file mode 100644
index 000000000000..64122556e6c8
--- /dev/null
+++ b/ee/partners/__init__.py
@@ -0,0 +1 @@
+"""Partner-specific namespaces: used to manage integrations between PostHog and third-party platform partners."""
diff --git a/ee/partners/stripe/__init__.py b/ee/partners/stripe/__init__.py
new file mode 100644
index 000000000000..a2d292a04113
--- /dev/null
+++ b/ee/partners/stripe/__init__.py
@@ -0,0 +1 @@
+"""Stripe partner surface (Stripe Projects / agentic checkout)."""
diff --git a/ee/partners/stripe/api/__init__.py b/ee/partners/stripe/api/__init__.py
new file mode 100644
index 000000000000..3783d905af86
--- /dev/null
+++ b/ee/partners/stripe/api/__init__.py
@@ -0,0 +1 @@
+"""Stripe partner API surface (Stripe Projects / agentic checkout)."""
diff --git a/ee/partners/stripe/api/provisioning/__init__.py b/ee/partners/stripe/api/provisioning/__init__.py
new file mode 100644
index 000000000000..c32bef4af3e8
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/__init__.py
@@ -0,0 +1,17 @@
+"""Stripe Projects provisioning API - Agentic Provisioning Protocol (APP) 0.1d.
+
+Provider endpoints for the Stripe orchestrator, mounted under
+``/api/partners/stripe/``: account requests, token exchange, resource
+provisioning, service updates, credential rotation, and deep links.
+
+Spec: https://github.com/agentic-provisioning/posthog-spec/blob/master/docs/spec.md
+
+Both cache keys are Stripe-specific and deliberately NOT interoperable with the
+other provisioning surfaces: auth codes are minted and redeemed within this
+namespace, and deep links are minted by ``DeepLinksView`` and consumed by this
+namespace's own login route (``login.py``), not the legacy ``/agentic/login``.
+"""
+
+AUTH_CODE_CACHE_PREFIX = "stripe_provisioning_auth_code:"
+
+DEEP_LINK_CACHE_PREFIX = "stripe_provisioning_deep_link:"
diff --git a/ee/partners/stripe/api/provisioning/analytics.py b/ee/partners/stripe/api/provisioning/analytics.py
new file mode 100644
index 000000000000..c2fb11ae5c1d
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/analytics.py
@@ -0,0 +1,64 @@
+"""Product analytics for the Stripe provisioning namespace.
+
+Provisioning events share one vocabulary across all provisioning API surfaces;
+``path_namespace`` identifies which surface served the request, so per-surface
+traffic is directly observable.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+import posthoganalytics
+
+from posthog.models.oauth import OAuthApplication
+
+PATH_NAMESPACE = "partners_stripe"
+
+
+def capture_provisioning_event(
+ event_type: str,
+ outcome: str,
+ *,
+ partner: OAuthApplication | None = None,
+ **extra: object,
+) -> None:
+ team_id = extra.get("team_id")
+ distinct_id = f"agentic_provisioning_team_{team_id}" if team_id else f"agentic_provisioning_{uuid.uuid4().hex[:16]}"
+ properties: dict[str, object] = {
+ "outcome": outcome,
+ "path_namespace": PATH_NAMESPACE,
+ # Single-caller namespace; tag the type without reading app config.
+ "partner_type": "stripe",
+ **extra,
+ }
+ if partner is not None:
+ properties.setdefault("partner_id", str(partner.id))
+ properties.setdefault("client_name", partner.name)
+ posthoganalytics.capture(
+ f"agentic_provisioning {event_type}",
+ distinct_id=distinct_id,
+ properties=properties,
+ )
+
+
+def capture_signature_event(outcome: str, status_code: int, endpoint: str, **extra: object) -> None:
+ posthoganalytics.capture(
+ "agentic_provisioning signature verification",
+ distinct_id=f"agentic_provisioning_{uuid.uuid4().hex[:16]}",
+ properties={
+ "outcome": outcome,
+ "status_code": status_code,
+ "endpoint": endpoint,
+ "path_namespace": PATH_NAMESPACE,
+ **extra,
+ },
+ )
+
+
+def capture_region_proxy_event(outcome: str, **props: object) -> None:
+ posthoganalytics.capture(
+ "agentic_provisioning region_proxy",
+ distinct_id=f"agentic_provisioning_{uuid.uuid4().hex[:16]}",
+ properties={"outcome": outcome, "path_namespace": PATH_NAMESPACE, **props},
+ )
diff --git a/ee/partners/stripe/api/provisioning/authentication.py b/ee/partners/stripe/api/provisioning/authentication.py
new file mode 100644
index 000000000000..2cc840b55dfd
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/authentication.py
@@ -0,0 +1,60 @@
+"""Bearer authentication for the Stripe provisioning resource endpoints.
+
+The only accepted identity is the Stripe orchestrator: tokens issued to the
+Stripe Projects OAuth app (resolved by
+``settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID``). Tokens bound to any other
+application are rejected outright. Identity is the whole check - this namespace
+is deliberately isolated from the provisioning-partner config model, so no
+``provisioning_*`` capability flags on the app are consulted; the Stripe app is
+trusted with full access.
+"""
+
+from __future__ import annotations
+
+from django.utils import timezone
+
+from rest_framework.authentication import BaseAuthentication
+from rest_framework.request import Request
+
+from posthog.models.oauth import OAuthAccessToken, find_oauth_access_token
+from posthog.models.user import User
+
+from ee.partners.stripe.api.provisioning.core import is_stripe_oauth_app
+from ee.partners.stripe.api.provisioning.exceptions import SpecError
+
+
+class StripeBearerAuthentication(BaseAuthentication):
+ """Authenticate the Stripe orchestrator via an OAuth bearer token.
+
+ Returns ``(user, access_token)`` so views read the token off ``request.auth``.
+ Raises :class:`SpecError` (rendered in the view's envelope) on failure.
+ """
+
+ def authenticate(self, request: Request) -> tuple[User | None, OAuthAccessToken]:
+ auth_header = request.headers.get("authorization", "")
+ if not auth_header.startswith("Bearer "):
+ raise SpecError("unauthorized", "Missing bearer token", status=401)
+
+ token_value = auth_header[len("Bearer ") :].strip()
+ if not token_value:
+ raise SpecError("unauthorized", "Missing bearer token", status=401)
+
+ access_token = find_oauth_access_token(token_value)
+ if access_token is None:
+ raise SpecError("unauthorized", "Invalid access token", status=401)
+
+ if access_token.expires and access_token.expires < timezone.now():
+ raise SpecError("unauthorized", "Access token expired", status=401)
+
+ # This namespace serves exactly one caller. A token minted for any other
+ # application - including other provisioning partners - must fail here;
+ # partner-generic traffic belongs to the legacy provisioning surface.
+ # Being the Stripe app is the entire authorization check.
+ app = access_token.application
+ if app is None or not is_stripe_oauth_app(app):
+ raise SpecError("unauthorized", "Authentication failed", status=401)
+
+ return access_token.user, access_token
+
+ def authenticate_header(self, request: Request) -> str:
+ return "Bearer"
diff --git a/ee/partners/stripe/api/provisioning/billing.py b/ee/partners/stripe/api/provisioning/billing.py
new file mode 100644
index 000000000000..3004eaf1a83b
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/billing.py
@@ -0,0 +1,106 @@
+"""Billing activation via Stripe Shared Payment Tokens (SPT).
+
+Stripe hands the provider a shared payment token in ``payment_credentials``;
+activating it against the billing service starts a paid subscription for the
+provisioned organization.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import requests
+import structlog
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from ee.settings import BILLING_SERVICE_URL
+
+logger = structlog.get_logger(__name__)
+
+
+def _build_billing_token(team: Team, user: User) -> str | None:
+ from posthog.cloud_utils import get_cached_instance_license
+
+ from ee.billing.billing_manager import build_billing_token
+
+ license = get_cached_instance_license()
+ if not license:
+ return None
+ return build_billing_token(license, team.organization, user)
+
+
+def _team_has_active_billing(team: Team, user: User) -> bool:
+ """Check if the team's organization already has an active billing subscription."""
+ try:
+ billing_token = _build_billing_token(team, user)
+ if not billing_token:
+ return False
+
+ res = requests.get(
+ f"{BILLING_SERVICE_URL}/api/billing",
+ headers={"Authorization": f"Bearer {billing_token}"},
+ timeout=30,
+ )
+
+ if res.status_code != 200:
+ return False
+
+ customer = res.json().get("customer", {})
+ return bool(customer.get("has_active_subscription"))
+ except Exception:
+ capture_exception(additional_properties={"team_id": team.id, "org_id": str(team.organization_id)})
+ return False
+
+
+def _activate_billing_with_spt(team: Team, user: User, spt_token: str) -> bool:
+ """Call the billing service to activate a subscription with a Stripe Shared Payment Token.
+
+ Returns True if activation succeeded, False otherwise.
+ """
+ try:
+ billing_token = _build_billing_token(team, user)
+ if not billing_token:
+ capture_exception(Exception("No license found for SPT billing activation"))
+ return False
+
+ res = requests.post(
+ f"{BILLING_SERVICE_URL}/api/activate/authorize",
+ headers={"Authorization": f"Bearer {billing_token}"},
+ json={"shared_payment_token": spt_token},
+ timeout=30,
+ )
+
+ if res.status_code not in (200, 201):
+ capture_exception(
+ Exception(f"Billing SPT activation failed: {res.status_code}"),
+ {"team_id": team.id, "org_id": str(team.organization_id), "status": res.status_code},
+ )
+ return False
+
+ logger.info("stripe_provisioning.spt_billing_activated", team_id=team.id, org_id=str(team.organization_id))
+ return True
+ except Exception:
+ capture_exception(additional_properties={"team_id": team.id, "org_id": str(team.organization_id)})
+ return False
+
+
+def extract_spt(payment_credentials: Any) -> str | None:
+ if isinstance(payment_credentials, dict) and payment_credentials.get("type") == "stripe_payment_token":
+ return payment_credentials.get("stripe_payment_token") or None
+ return None
+
+
+def try_activate_billing_with_spt(payment_credentials: Any, team: Team, user: User) -> bool | None:
+ """Activate billing if an SPT is present, skipping if billing is already active.
+
+ Returns True if succeeded or already active, False if failed, None if no SPT was present.
+ """
+ spt_token = extract_spt(payment_credentials)
+ if not spt_token:
+ return None
+ if _team_has_active_billing(team, user):
+ return True
+ return _activate_billing_with_spt(team, user, spt_token)
diff --git a/ee/partners/stripe/api/provisioning/constants.py b/ee/partners/stripe/api/provisioning/constants.py
new file mode 100644
index 000000000000..78731b51933e
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/constants.py
@@ -0,0 +1,71 @@
+"""Constants for the Stripe Projects provisioning namespace."""
+
+from __future__ import annotations
+
+import re
+
+from posthog.models.integration import StripeIntegration
+
+SUPPORTED_VERSIONS = ["0.1d"]
+MAX_TIMESTAMP_DRIFT_SECONDS = 300
+
+AUTH_CODE_TTL_SECONDS = 300
+DEEP_LINK_TTL_SECONDS = 600
+DEEP_LINK_MAX_PATH_LENGTH = 2000
+
+# Control chars, whitespace, and backslashes never appear in a legitimate in-app path; they are the
+# building blocks of header-injection and backslash-host open-redirect tricks, so reject them outright.
+DEEP_LINK_DISALLOWED_PATH_CHARS = re.compile(r"[\x00-\x20\x7f-\x9f\\]")
+
+ACCESS_TOKEN_EXPIRY_SECONDS = 365 * 24 * 3600
+
+# Default scopes for a Stripe-issued token when the auth code requested none.
+# This namespace enforces no scope ceiling; a code that names scopes gets those.
+STRIPE_CONTRACTED_SCOPES: list[str] = StripeIntegration.SCOPES.split()
+
+# 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
+# survives the truncation. A 37-char prefix would otherwise consume the whole label
+# and the team name would disappear from the truncated result.
+PROVISIONED_PAT_LABEL_PREFIX_MAX_LENGTH = 25
+
+# ---------------------------------------------------------------------------
+# Service catalog vocabulary (spec-visible service ids)
+# ---------------------------------------------------------------------------
+
+ANALYTICS_SERVICE_ID = "analytics"
+FREE_PLAN_SERVICE_ID = "free"
+PAY_AS_YOU_GO_SERVICE_ID = "pay_as_you_go"
+VALID_SERVICE_IDS: set[str] = {FREE_PLAN_SERVICE_ID, PAY_AS_YOU_GO_SERVICE_ID, ANALYTICS_SERVICE_ID}
+
+ALL_CATEGORIES: list[str] = ["analytics", "feature_flags", "ai", "observability"]
+
+# The built catalog is cached instance-wide under Stripe-specific keys, so
+# billing is hit at most once per TTL and this namespace does not share catalog
+# entries with the other provisioning surfaces.
+SERVICES_CACHE_KEY = "stripe_provisioning:services"
+SERVICES_CACHE_TTL = 3600
+SERVICES_CACHE_RETRY_TTL = 300
+SERVICES_CACHE_EXPIRES_KEY = "stripe_provisioning:services:expires_at"
+SERVICES_CACHE_STORE_TTL = 86400
+
+# ---------------------------------------------------------------------------
+# Rate limiting - fixed-window counters keyed within this namespace on a fixed
+# Stripe identity. Limits come from RATE_LIMIT_DEFAULTS; a value <= 0 disables
+# the limit for that endpoint.
+# ---------------------------------------------------------------------------
+
+RATE_LIMIT_CACHE_PREFIX = "stripe_provisioning_rate:"
+RATE_LIMIT_WINDOW_SECONDS = 3600
+RATE_LIMIT_DEFAULTS: dict[str, int] = {
+ "account_requests": 10,
+ "token_exchanges": 20,
+ "resource_creates": 20,
+}
+RATE_LIMIT_EVENT_NAMES: dict[str, str] = {
+ "account_requests": "account_request",
+ "token_exchanges": "token_exchange",
+ "resource_creates": "resource_created",
+}
diff --git a/ee/partners/stripe/api/provisioning/core.py b/ee/partners/stripe/api/provisioning/core.py
new file mode 100644
index 000000000000..d6bc7b5e63b6
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/core.py
@@ -0,0 +1,704 @@
+"""Domain logic for the Stripe provisioning namespace.
+
+The Stripe orchestrator is a fixed, partner-less identity: auth codes are
+minted with an empty ``partner_id`` and token exchange binds to the Stripe
+Projects OAuth app resolved from ``settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID``.
+"""
+
+from __future__ import annotations
+
+import secrets
+import unicodedata
+from typing import Any
+
+from django.conf import settings
+from django.core.cache import cache
+from django.db import IntegrityError, transaction
+from django.utils import timezone
+from django.utils.http import url_has_allowed_host_and_scheme
+
+import structlog
+
+from posthog.api.authentication import password_reset_token_generator
+from posthog.event_usage import report_user_signed_up
+from posthog.exceptions_capture import capture_exception
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
+from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
+from posthog.models.team.team import Team
+from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+from posthog.models.user import User
+from posthog.models.utils import generate_random_token_personal, mask_key_value
+from posthog.rbac.user_access_control import UserAccessControl
+from posthog.tasks.email import send_provisioning_welcome
+
+from ee.partners.stripe.api.provisioning import AUTH_CODE_CACHE_PREFIX
+from ee.partners.stripe.api.provisioning.analytics import capture_provisioning_event
+from ee.partners.stripe.api.provisioning.constants import (
+ ANALYTICS_SERVICE_ID,
+ AUTH_CODE_TTL_SECONDS,
+ DEEP_LINK_DISALLOWED_PATH_CHARS,
+ DEEP_LINK_MAX_PATH_LENGTH,
+ PROVISIONED_PAT_LABEL_MAX_LENGTH,
+ PROVISIONED_PAT_LABEL_PREFIX_MAX_LENGTH,
+ STRIPE_CONTRACTED_SCOPES,
+)
+from ee.partners.stripe.api.provisioning.exceptions import SpecError
+
+logger = structlog.get_logger(__name__)
+
+# Label used in the welcome email and default organization name.
+PARTNER_LABEL = "Stripe"
+
+
+# ---------------------------------------------------------------------------
+# Stripe Projects OAuth app
+# ---------------------------------------------------------------------------
+
+
+class StripeOAuthAppMissingError(Exception):
+ """The configured Stripe Projects OAuth app could not be resolved.
+
+ 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.
+ """
+
+
+def get_stripe_oauth_app() -> OAuthApplication:
+ client_id = settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID
+ if not client_id:
+ error = StripeOAuthAppMissingError("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 = StripeOAuthAppMissingError("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
+
+ return app
+
+
+def is_stripe_oauth_app(app: OAuthApplication) -> bool:
+ """True when ``app`` is the configured Stripe Projects OAuth app.
+
+ Fails closed when ``STRIPE_POSTHOG_OAUTH_CLIENT_ID`` is unset: with no
+ configured Stripe identity, no caller can be the Stripe orchestrator.
+ """
+ client_id = settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID
+ return bool(client_id) and app.client_id == client_id
+
+
+def get_oauth_app_for_code(code_data: dict) -> OAuthApplication:
+ """Resolve the OAuthApplication for a token exchange.
+
+ Codes minted in this namespace always carry an empty ``partner_id`` and
+ resolve to the Stripe Projects app; codes minted by the interactive consent
+ flow may carry a partner id and keep their original app binding. The token
+ view rejects any resolved app that is not the Stripe Projects app - this
+ namespace serves no other partner.
+ """
+ partner_id = code_data.get("partner_id", "")
+ if partner_id:
+ try:
+ return OAuthApplication.objects.get(id=partner_id)
+ except OAuthApplication.DoesNotExist:
+ pass
+
+ return get_stripe_oauth_app()
+
+
+def lock_application(application_id: Any) -> OAuthApplication | None:
+ """Row-lock the OAuthApplication so direct-mint serializes with revoke_application_sessions.
+
+ The revoke updates this row first and holds the lock for its whole transaction before
+ sweeping tokens, so a mint that takes the same lock is forced into one of two safe orders:
+ it holds the lock and its new tokens land before the revoke's sweep (which then catches
+ them), or the revoke committed first and the caller reads the now-visible
+ `sessions_revoked_at` and rejects. Must be called inside `transaction.atomic()`.
+ """
+ return OAuthApplication.objects.select_for_update().filter(pk=application_id).first()
+
+
+# ---------------------------------------------------------------------------
+# Account requests
+# ---------------------------------------------------------------------------
+
+
+def mint_auth_code(
+ *,
+ user_id: int,
+ org_id: str,
+ team_id: int,
+ partner_account_id: str,
+ scopes: list[str],
+ region: str,
+ code_challenge: str,
+ code_challenge_method: str,
+) -> str:
+ """Mint a single-use auth code in the shared cache.
+
+ The value shape is a cross-surface contract: any provisioning token
+ endpoint must be able to redeem it. ``partner_id`` is always empty -
+ Stripe is a fixed, partner-less identity.
+ """
+ code = secrets.token_urlsafe(32)
+ cache.set(
+ f"{AUTH_CODE_CACHE_PREFIX}{code}",
+ {
+ "issued_at": timezone.now().isoformat(),
+ "user_id": user_id,
+ "org_id": org_id,
+ "team_id": team_id,
+ "stripe_account_id": partner_account_id,
+ "partner_id": "",
+ "scopes": scopes,
+ "region": region,
+ "code_challenge": code_challenge,
+ "code_challenge_method": code_challenge_method,
+ },
+ timeout=AUTH_CODE_TTL_SECONDS,
+ )
+ return code
+
+
+def resolve_team_for_existing_user(user: User, requested_team_id: int | None = None) -> Team | None:
+ """Pick a team for an existing user during email-based account linking.
+
+ If requested_team_id is provided and the user has access, use it.
+ Otherwise auto-select: single non-demo team → use it, only demo teams →
+ create a new project, multiple teams → create a new project in the first org.
+ """
+ memberships = list(user.organization_memberships.select_related("organization").all())
+ if not memberships:
+ return None
+
+ org_ids = [m.organization_id for m in memberships]
+
+ if requested_team_id is not None:
+ try:
+ team = Team.objects.get(id=requested_team_id, is_demo=False)
+ except Team.DoesNotExist:
+ return None
+ if team.organization_id not in org_ids:
+ return None
+ return team
+
+ non_demo_teams = list(Team.objects.filter(organization_id__in=org_ids, is_demo=False))
+
+ if len(non_demo_teams) == 1:
+ return non_demo_teams[0]
+
+ # TODO: latent bug - memberships is unordered, so which organization hosts
+ # the new project is arbitrary for multi-org users.
+ organization = memberships[0].organization
+ return Team.objects.create_with_data(initiating_user=user, organization=organization)
+
+
+def handle_existing_user(
+ request_id: str,
+ user: User,
+ scopes: list[str],
+ partner_account_id: str,
+ region: str,
+ requested_team_id: int | None,
+ code_challenge: str,
+ code_challenge_method: str,
+) -> dict[str, Any]:
+ """Silently mint an auth code for an existing account."""
+ team = resolve_team_for_existing_user(user, requested_team_id)
+ if team is None:
+ capture_provisioning_event("account_request", "error", error_code="team_resolution_failed")
+ raise SpecError("team_resolution_failed", "Could not resolve a project for this user", request_id=request_id)
+
+ code = mint_auth_code(
+ user_id=user.id,
+ org_id=str(team.organization_id),
+ team_id=team.id,
+ partner_account_id=partner_account_id,
+ scopes=scopes,
+ region=region,
+ code_challenge=code_challenge,
+ code_challenge_method=code_challenge_method,
+ )
+
+ capture_provisioning_event("account_request", "existing_user", region=region, team_id=team.id)
+
+ return {"id": request_id, "type": "oauth", "oauth": {"code": code}}
+
+
+def handle_new_user(
+ request_id: str,
+ data: dict[str, Any],
+ email: str,
+ scopes: list[str],
+ partner_account_id: str,
+ region: str,
+ code_challenge: str,
+ code_challenge_method: str,
+) -> dict[str, Any]:
+ """Bootstrap a fresh account and mint an auth code."""
+ name = data.get("name", "")
+ first_name = name.split(" ")[0] if name else ""
+
+ configuration = data.get("configuration")
+ if not isinstance(configuration, dict):
+ configuration = {}
+
+ # TODO: latent bug - organization_name is unvalidated; a non-string or
+ # over-long value fails at the DB layer as an uncaught TypeError/DataError
+ # (500) where the spec calls for a 400 invalid_request.
+ org_name = configuration.get("organization_name") or f"{PARTNER_LABEL} ({email})"
+
+ try:
+ organization, team, user = User.objects.bootstrap(
+ organization_name=org_name,
+ email=email,
+ password=None,
+ first_name=first_name,
+ is_email_verified=False,
+ )
+ except IntegrityError:
+ existing = User.objects.filter(email=email).first()
+ if existing:
+ capture_provisioning_event("account_request", "race_condition_existing_user", region=region)
+ return handle_existing_user(
+ request_id,
+ existing,
+ scopes,
+ partner_account_id,
+ region,
+ None,
+ code_challenge,
+ code_challenge_method,
+ )
+ capture_provisioning_event("account_request", "creation_failed", region=region)
+ raise SpecError("account_creation_failed", "Failed to create account", request_id=request_id, status=500)
+
+ capture_provisioning_event("account_request", "new_user", region=region, team_id=team.id)
+
+ # Emit the standard signup event so provisioned accounts flow into the shared
+ # signup / activation / billing analyses, segmentable by client.
+ report_user_signed_up(
+ user,
+ is_instance_first_user=False,
+ is_organization_first_user=True,
+ backend_processor="AgenticProvisioning",
+ social_provider="",
+ user_analytics_metadata=user.get_analytics_metadata(),
+ org_analytics_metadata=organization.get_analytics_metadata(),
+ )
+
+ try:
+ reset_token = password_reset_token_generator.make_token(user)
+ send_provisioning_welcome.delay(user.id, reset_token, PARTNER_LABEL)
+ except Exception:
+ capture_exception(additional_properties={"user_id": user.id, "step": "provisioning_welcome_email"})
+
+ code = mint_auth_code(
+ user_id=user.id,
+ org_id=str(organization.id),
+ team_id=team.id,
+ partner_account_id=partner_account_id,
+ scopes=scopes,
+ region=region,
+ code_challenge=code_challenge,
+ code_challenge_method=code_challenge_method,
+ )
+
+ return {"id": request_id, "type": "oauth", "oauth": {"code": code}}
+
+
+# ---------------------------------------------------------------------------
+# Team scoping
+# ---------------------------------------------------------------------------
+
+
+def user_can_access_team(user: User, team: Team) -> bool:
+ """Verify the user has at least member-level access to the team.
+
+ Org membership alone does not prove access for advanced-permissions
+ orgs that restrict individual teams. Without this check the resolve flow
+ could grant scoped access to a private team as long as the user had any
+ team in the same org.
+ """
+ return UserAccessControl(user=user, team=team).check_access_level_for_object(team, required_level="member")
+
+
+def compute_partner_scoped_teams(
+ application: OAuthApplication | None,
+ user: User,
+ base_team_id: int,
+) -> list[int]:
+ """Compute the durable scope for an OAuth token at issuance/refresh.
+
+ Returns the set of every team where ``TeamProvisioningConfig.application ==
+ application`` (i.e. this app provisioned the team for this user, attributed
+ at create time) AND the team lives in the same organization as ``base_team_id``
+ AND the user still has team-level access. The organization filter pins the
+ token to the authorization context: an app with OAuth grants in multiple orgs
+ for the same user must not be able to reach an org-B team via an org-A token
+ just because the user happens to be a member of both.
+
+ Returns ``[]`` when ``application`` is None (legacy refresh tokens with no
+ app binding). An unattributed token cannot be safely scoped, so it gets no
+ teams and the holder must re-authorize. Falling through would let
+ ``filter(application=None)`` match every TeamProvisioningConfig row with a
+ NULL application across every partner.
+
+ Returns ``[]`` if ``base_team_id`` no longer resolves to a team the user
+ can access; stale scope must not grant ongoing access after ACL revocation
+ or org removal.
+ """
+ if application is None:
+ return []
+
+ try:
+ base_team = Team.objects.select_related("organization").get(id=base_team_id)
+ except Team.DoesNotExist:
+ return []
+ if not user_can_access_team(user, base_team):
+ return []
+
+ candidate_team_ids = set(
+ TeamProvisioningConfig.objects.filter(
+ application=application,
+ team__organization_id=base_team.organization_id,
+ ).values_list("team_id", flat=True)
+ )
+ candidate_team_ids.add(base_team_id)
+
+ granted: set[int] = {base_team_id}
+ other_teams = Team.objects.select_related("organization").filter(
+ id__in=candidate_team_ids - {base_team_id},
+ )
+ for team in other_teams:
+ if user_can_access_team(user, team):
+ granted.add(team.id)
+
+ # sorted() only for deterministic test assertions and log diffs; scope order is not a correctness requirement
+ return sorted(granted)
+
+
+def add_team_to_token_scopes(access_token: OAuthAccessToken, team_id: int) -> None:
+ with transaction.atomic():
+ locked_access_token = OAuthAccessToken.objects.select_for_update().get(pk=access_token.pk)
+ teams = list(locked_access_token.scoped_teams or [])
+ if team_id not in teams:
+ teams.append(team_id)
+ locked_access_token.scoped_teams = teams
+ locked_access_token.save(update_fields=["scoped_teams"])
+ access_token.scoped_teams = teams
+
+ refresh_tokens = OAuthRefreshToken.objects.select_for_update().filter(access_token=locked_access_token)
+ for rt in refresh_tokens:
+ rt_teams = list(rt.scoped_teams or [])
+ if team_id not in rt_teams:
+ rt_teams.append(team_id)
+ rt.scoped_teams = rt_teams
+ rt.save(update_fields=["scoped_teams"])
+
+
+def remove_team_from_token_scopes(access_token: OAuthAccessToken, team_id: int) -> None:
+ """Strip ``team_id`` from every access/refresh token for this app+user combo.
+
+ Removing a resource has to revoke access for any *other* live token the same
+ partner installation might be holding for the same user (e.g. a separate
+ bearer issued via a prior OAuth grant that still has the team in scope).
+ Touching only the calling ``access_token`` would let the partner continue
+ operating on the team via a sibling token after `remove` returned, since
+ operational endpoints accept any team currently in ``scoped_teams``.
+
+ Atomic so a refresh token can never be left with the removed team still in
+ scope while the access token has it stripped - otherwise the orchestrator
+ could refresh and replay the removed team right back into scope.
+ """
+ application = access_token.application
+ user = access_token.user
+ if application is None or user is None:
+ # Defensive: a provisioning bearer token without an app/user shouldn't
+ # exist in practice, but fall back to the single-token strip if it does.
+ application_filter: dict[str, object] = {"pk": access_token.pk}
+ user_filter: dict[str, object] = {}
+ else:
+ application_filter = {"application": application, "user": user}
+ user_filter = {"application": application, "user": user}
+
+ with transaction.atomic():
+ access_tokens = list(
+ OAuthAccessToken.objects.select_for_update()
+ .filter(scoped_teams__contains=[team_id], **application_filter)
+ .order_by("pk")
+ )
+ for at in access_tokens:
+ remaining = [t for t in (at.scoped_teams or []) if t != team_id]
+ refresh_tokens = OAuthRefreshToken.objects.select_for_update().filter(access_token=at)
+ if not remaining:
+ refresh_tokens.update(access_token=None, revoked=timezone.now(), scoped_teams=[])
+ at.delete()
+ continue
+ at.scoped_teams = remaining
+ at.save(update_fields=["scoped_teams"])
+ for rt in refresh_tokens:
+ rt.scoped_teams = [t for t in (rt.scoped_teams or []) if t != team_id]
+ rt.save(update_fields=["scoped_teams"])
+
+ if user_filter:
+ # Orphan refresh tokens (where the access token was already rotated
+ # or deleted) still carry scope. Strip the team from those too.
+ orphan_refresh = OAuthRefreshToken.objects.select_for_update().filter(
+ scoped_teams__contains=[team_id],
+ access_token__isnull=True,
+ revoked__isnull=True,
+ **user_filter,
+ )
+ for rt in orphan_refresh:
+ rt.scoped_teams = [t for t in (rt.scoped_teams or []) if t != team_id]
+ rt.save(update_fields=["scoped_teams"])
+
+
+# ---------------------------------------------------------------------------
+# Resources
+# ---------------------------------------------------------------------------
+
+
+class ProjectIdCollisionError(Exception):
+ """Raised when a project_id is already in use by a team outside the caller's orgs."""
+
+ def __init__(self, project_id: str) -> None:
+ super().__init__(project_id)
+ self.project_id = project_id
+
+
+def _ensure_team_in_token_scopes(
+ access_token: OAuthAccessToken, scoped_teams: list[int], team: Team
+) -> tuple[Team, list[int]]:
+ if team.id in scoped_teams:
+ return team, scoped_teams
+ add_team_to_token_scopes(access_token, team.id)
+ return team, [*scoped_teams, team.id]
+
+
+def resolve_or_create_project_team(
+ project_id: str,
+ scoped_teams: list[int],
+ user: User,
+ configuration: dict,
+ access_token: OAuthAccessToken,
+) -> tuple[Team | None, list[int]]:
+ """Look up or create a team for the given project_id.
+
+ Uses TeamProvisioningConfig (DB-backed with unique constraint) for the
+ project_id → team_id mapping. This ensures idempotency even across cache
+ evictions and handles race conditions via IntegrityError.
+
+ Returns (None, scoped_teams) when an existing team is resolved but the
+ authenticated user lacks team-level access (honors advanced permissions
+ / access controls on top of org membership).
+ """
+ existing = (
+ TeamProvisioningConfig.objects.filter(
+ stripe_project_id=project_id,
+ application=access_token.application,
+ team__organization_id__in=Team.objects.filter(id__in=scoped_teams).values("organization_id"),
+ )
+ .select_related("team")
+ .first()
+ )
+ if existing:
+ if not user_can_access_team(user, existing.team):
+ return None, scoped_teams
+ return _ensure_team_in_token_scopes(access_token, scoped_teams, existing.team)
+
+ base_team = Team.objects.get(id=scoped_teams[0])
+ if not user_can_access_team(user, base_team):
+ return None, scoped_teams
+
+ # TODO: latent bug - project_name is unvalidated; a non-string or over-long
+ # value fails at the DB layer (500) where the spec calls for a 400
+ # invalid_request.
+ project_name = configuration.get("project_name", "Default project")
+ new_team = Team.objects.create_with_data(
+ initiating_user=user,
+ organization=base_team.organization,
+ name=project_name,
+ )
+
+ try:
+ TeamProvisioningConfig.objects.update_or_create(
+ team=new_team,
+ defaults={"stripe_project_id": project_id, "application": access_token.application},
+ )
+ except IntegrityError:
+ new_team.delete()
+ race_winner = (
+ TeamProvisioningConfig.objects.filter(
+ stripe_project_id=project_id,
+ application=access_token.application,
+ team__organization_id__in=Team.objects.filter(id__in=scoped_teams).values("organization_id"),
+ )
+ .select_related("team")
+ .first()
+ )
+ if race_winner:
+ if not user_can_access_team(user, race_winner.team):
+ return None, scoped_teams
+ return _ensure_team_in_token_scopes(access_token, scoped_teams, race_winner.team)
+ raise ProjectIdCollisionError(project_id)
+
+ return _ensure_team_in_token_scopes(access_token, scoped_teams, new_team)
+
+
+def get_provisioning_service_id(team: Team) -> str:
+ try:
+ config = TeamProvisioningConfig.objects.get(team=team)
+ return config.service_id
+ except TeamProvisioningConfig.DoesNotExist:
+ return ANALYTICS_SERVICE_ID
+
+
+def set_provisioning_service_id(team: Team, service_id: str) -> None:
+ TeamProvisioningConfig.objects.update_or_create(
+ team=team,
+ defaults={"service_id": service_id},
+ )
+
+
+# ---------------------------------------------------------------------------
+# Provisioned personal API keys
+# ---------------------------------------------------------------------------
+
+
+def validate_label_prefix(raw: Any) -> str | None:
+ """Validate the optional ``label_prefix`` request field.
+
+ Returns ``None`` when the field is absent or empty (caller creates an
+ unprefixed label). Raises :class:`SpecError` (``invalid_label_prefix``)
+ when the field is present but malformed (wrong type, too long, or contains
+ control or format characters that would render badly in the user's PAT
+ list).
+ """
+ if raw is None:
+ return None
+ if not isinstance(raw, str):
+ raise SpecError("invalid_label_prefix", "label_prefix must be a string")
+
+ stripped = raw.strip()
+ if not stripped:
+ return None
+
+ if len(stripped) > PROVISIONED_PAT_LABEL_PREFIX_MAX_LENGTH:
+ raise SpecError(
+ "invalid_label_prefix",
+ f"label_prefix must be {PROVISIONED_PAT_LABEL_PREFIX_MAX_LENGTH} characters or fewer",
+ )
+
+ # Reject Unicode control (Cc), format (Cf), and line/paragraph separators (Zl/Zp).
+ # Cf is the important one - it includes bidi overrides (U+202A-U+202E) and
+ # isolates (U+2066-U+2069), which a partner could use to re-order surrounding
+ # text in the user's settings page (Trojan Source class). Cc covers C0 + DEL.
+ if any(unicodedata.category(c) in {"Cc", "Cf", "Zl", "Zp"} for c in stripped):
+ raise SpecError("invalid_label_prefix", "label_prefix must not contain control or format characters")
+
+ return stripped
+
+
+def maybe_create_provisioned_pat(
+ user: User, team: Team, granted_scope: str | None, label_prefix: str | None = None
+) -> str | None:
+ """Create a Personal API Key for the provisioned user and return the raw value.
+
+ The key carries the granted OAuth token's scopes (``granted_scope``) as-is;
+ this namespace does not enforce a scope ceiling, so what the token was
+ granted is exactly what the PAT gets. Falls back to the default Stripe scope
+ set when the token carried none.
+
+ scoped_teams is set to [team.id] so the PAT only grants access to the team
+ being provisioned, matching the scoping of the OAuth token issued in the
+ same flow. Without this, a provisioning call from an existing user would
+ return a PAT that reaches across every team the user already belongs to.
+
+ ``label_prefix`` should be pre-validated by ``validate_label_prefix``; pass
+ ``None`` (or any falsy value) to label the key with just the team name.
+ """
+ pat_scopes = [s for s in (granted_scope or "").split() if s] or list(STRIPE_CONTRACTED_SCOPES)
+ # TODO: latent bug - every call mints a new PAT without revoking earlier
+ # ones, so rotate_credentials accumulates live keys instead of rotating
+ # them. A correct fix needs a provenance marker on PersonalAPIKey (or the
+ # provisioned key id recorded on TeamProvisioningConfig) so revocation can
+ # target only provisioned keys - scope alone is ambiguous with keys a user
+ # created via /api/personal_api_keys/ carrying the same team/org scope.
+ try:
+ api_key_value = generate_random_token_personal()
+ label_base = f"{label_prefix} - {team.name}" if label_prefix else team.name
+ # PersonalAPIKey.label is stored as a CharField(max_length=40); cap the
+ # final string to match so we never violate the column constraint.
+ label = label_base[:PROVISIONED_PAT_LABEL_MAX_LENGTH]
+
+ PersonalAPIKey.objects.create(
+ user=user,
+ label=label,
+ secure_value=hash_key_value(api_key_value),
+ mask_value=mask_key_value(api_key_value),
+ scopes=pat_scopes,
+ scoped_teams=[team.id],
+ scoped_organizations=[str(team.organization_id)],
+ )
+
+ return api_key_value
+ except Exception:
+ capture_exception(additional_properties={"user_id": user.id, "team_id": team.id})
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Misc helpers
+# ---------------------------------------------------------------------------
+
+
+def get_available_teams_for_user(user: User) -> list[dict[str, Any]]:
+ """Return the user's non-demo teams for inclusion in the token exchange response.
+
+ Applies the same member-level access check as the scoping paths so names of
+ restricted teams in advanced-permissions orgs are not listed.
+ """
+ org_ids = list(user.organization_memberships.values_list("organization_id", flat=True))
+ teams = Team.objects.filter(organization_id__in=org_ids, is_demo=False).select_related("organization")
+ return [
+ {
+ "id": team.id,
+ "name": team.name,
+ "organization_id": str(team.organization_id),
+ "organization_name": team.organization.name if team.organization else "",
+ }
+ for team in teams
+ if user_can_access_team(user, team)
+ ]
+
+
+def region_to_host(region: str) -> str:
+ region_lower = region.lower()
+ if region_lower == "eu":
+ return "https://eu.posthog.com"
+ elif region_lower in ("us", "dev"):
+ return "https://us.posthog.com"
+ return settings.SITE_URL
+
+
+def is_safe_deep_link_path(path: object) -> bool:
+ """Allow only relative, same-origin in-app paths so a deep link can't become an open redirect."""
+ return (
+ isinstance(path, str)
+ and 0 < len(path) <= DEEP_LINK_MAX_PATH_LENGTH
+ # Reject control chars, whitespace, and backslashes (the `/\` backslash-host form included).
+ and not DEEP_LINK_DISALLOWED_PATH_CHARS.search(path)
+ and path.startswith("/")
+ # Reject protocol-relative (`//`) forms; a single leading `/` keeps it same-origin.
+ and not path.startswith("//")
+ and url_has_allowed_host_and_scheme(path, allowed_hosts=None)
+ )
diff --git a/ee/partners/stripe/api/provisioning/exceptions.py b/ee/partners/stripe/api/provisioning/exceptions.py
new file mode 100644
index 000000000000..53c04b19d1db
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/exceptions.py
@@ -0,0 +1,87 @@
+"""Spec-mandated error envelopes for the Stripe provisioning namespace.
+
+APP 0.1d fixes three error shapes on the wire (plus a flat one used by the
+signature/version checks), so DRF's default error rendering can never leak out
+of these endpoints:
+
+- ``typed``: ``{"type": "error", "error": {...}}`` - account_requests, where
+ ``type`` is the discriminator partners switch on ("oauth" | "error").
+- ``status``: ``{"status": "error", "id": ..., "error": {...}}`` - resource
+ endpoints, whose success envelope carries "status" and "id".
+- ``oauth``: RFC 6749 ``{"error", "error_description"}`` - the token endpoint.
+- ``flat``: ``{"error": {"code", "message"}}`` - signature / API-Version /
+ region-proxy failures, identical on every endpoint.
+
+Views raise :class:`SpecError`; the base view's ``handle_exception`` renders it
+with the view's envelope (or the error's own override - rate-limit errors keep
+the typed shape even on the token endpoint).
+"""
+
+from __future__ import annotations
+
+from typing import Any, Literal
+
+from rest_framework import status as http_status
+from rest_framework.response import Response
+
+Envelope = Literal["typed", "status", "oauth", "flat"]
+
+
+class PreRenderedError(Exception):
+ """Carries an already-rendered error Response through DRF's exception flow.
+
+ The signature/version helpers return flat-envelope Responses; when those
+ checks run in ``initial()`` (outside a handler) the only way to
+ short-circuit is to raise, so this wraps the Response for the base view's
+ ``handle_exception`` to unwrap unchanged.
+ """
+
+ def __init__(self, response: Response) -> None:
+ super().__init__()
+ self.response = response
+
+
+class SpecError(Exception):
+ """An error with a spec-defined code, message, and envelope."""
+
+ def __init__(
+ self,
+ code: str,
+ message: str,
+ *,
+ status: int = http_status.HTTP_400_BAD_REQUEST,
+ request_id: str | None = None,
+ resource_id: str = "",
+ envelope: Envelope | None = None,
+ retry_after: int | None = None,
+ ) -> None:
+ super().__init__(message)
+ self.code = code
+ self.message = message
+ self.status = status
+ self.request_id = request_id
+ self.resource_id = resource_id
+ self.envelope = envelope
+ self.retry_after = retry_after
+
+
+def render_spec_error(error: SpecError, default_envelope: Envelope) -> Response:
+ envelope = error.envelope or default_envelope
+ body: dict[str, Any]
+ if envelope == "typed":
+ body = {"type": "error", "error": {"code": error.code, "message": error.message}}
+ # "id" appears only when a request_id was threaded through; some call
+ # sites carry "" (rendered as "id": "") and others no id at all.
+ if error.request_id is not None:
+ body = {"id": error.request_id, **body}
+ elif envelope == "status":
+ body = {"status": "error", "id": error.resource_id, "error": {"code": error.code, "message": error.message}}
+ elif envelope == "oauth":
+ body = {"error": error.code, "error_description": error.message}
+ else:
+ body = {"error": {"code": error.code, "message": error.message}}
+
+ response = Response(body, status=error.status)
+ if error.retry_after is not None:
+ response["Retry-After"] = str(error.retry_after)
+ return response
diff --git a/ee/partners/stripe/api/provisioning/login.py b/ee/partners/stripe/api/provisioning/login.py
new file mode 100644
index 000000000000..3330bf09770b
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/login.py
@@ -0,0 +1,126 @@
+"""Deep-link login for the Stripe provisioning namespace.
+
+Owns the browser side of the deep-link primitive end to end - the token minted
+by ``DeepLinksView`` is consumed only here, under this namespace's own cache
+key. Kept separate from the legacy ``/agentic/login`` route so Stripe does not
+depend on the provisioning API's login feature.
+
+The token grants a session with no password or SSO challenge, so
+partner-asserted email ownership is the only barrier: an explicitly verified
+email (``is_email_verified is True``) is required before a session is created.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from django.contrib.auth import login as auth_login
+from django.core.cache import cache
+from django.http import HttpResponseBase, HttpResponseRedirect
+
+import structlog
+
+from posthog.api.email_verification import EmailVerifier
+from posthog.exceptions_capture import capture_exception
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from ee.partners.stripe.api.provisioning import DEEP_LINK_CACHE_PREFIX
+from ee.partners.stripe.api.provisioning.analytics import capture_provisioning_event
+from ee.partners.stripe.api.provisioning.core import is_safe_deep_link_path
+
+logger = structlog.get_logger(__name__)
+
+
+def _capture(
+ outcome: str, *, user_id: int | None = None, team_id: int | None = None, purpose: str | None = None
+) -> None:
+ capture_provisioning_event("deep_link_login", outcome, user_id=user_id, team_id=team_id, purpose=purpose)
+
+
+def _redirect_path(team_id: int | None, path: str | None) -> str:
+ if path and is_safe_deep_link_path(path):
+ return path
+ if path:
+ # Unreachable in normal operation (mint-time validation already ran); a hit here
+ # means cache tampering or a mint-side regression.
+ logger.warning("stripe_provisioning.login.unsafe_path_in_cache", path=path)
+ if team_id and Team.objects.filter(id=team_id).exists():
+ return f"/project/{team_id}"
+ return "/"
+
+
+def stripe_provisioning_login(request: Any) -> HttpResponseBase:
+ token = request.GET.get("token", "")
+ if not token:
+ _capture("missing_token")
+ logger.warning("stripe_provisioning.login.missing_token")
+ return HttpResponseRedirect("/?error=missing_token")
+
+ cache_key = f"{DEEP_LINK_CACHE_PREFIX}{token}"
+
+ try:
+ link_data = cache.get(cache_key)
+ except Exception:
+ capture_exception(additional_properties={"cache_key": cache_key})
+ return HttpResponseRedirect("/?error=service_unavailable")
+
+ if link_data is None:
+ _capture("expired_or_invalid_token")
+ logger.warning("stripe_provisioning.login.expired_or_invalid_token")
+ return HttpResponseRedirect("/?error=expired_or_invalid_token")
+
+ # Atomic delete: if another request already consumed this token, reject.
+ if not cache.delete(cache_key):
+ _capture("expired_or_invalid_token")
+ logger.warning("stripe_provisioning.login.token_already_consumed")
+ return HttpResponseRedirect("/?error=expired_or_invalid_token")
+
+ if not isinstance(link_data, dict):
+ _capture("invalid_token_data")
+ logger.warning("stripe_provisioning.login.invalid_token_data")
+ return HttpResponseRedirect("/?error=invalid_token_data")
+
+ user_id = link_data.get("user_id")
+ team_id = link_data.get("team_id")
+ purpose = link_data.get("purpose", "dashboard")
+ path = link_data.get("path")
+
+ if not user_id:
+ _capture("invalid_token_data")
+ logger.warning("stripe_provisioning.login.missing_user_id")
+ return HttpResponseRedirect("/?error=invalid_token_data")
+
+ try:
+ user = User.objects.get(id=user_id)
+ except User.DoesNotExist:
+ _capture("user_not_found", user_id=user_id)
+ capture_exception(Exception("Deep link login user not found"), {"user_id": user_id, "team_id": team_id})
+ return HttpResponseRedirect("/?error=user_not_found")
+
+ if not user.is_active:
+ _capture("user_inactive", user_id=user_id)
+ logger.warning("stripe_provisioning.login.user_inactive", user_id=user_id)
+ return HttpResponseRedirect("/?error=user_inactive")
+
+ # Deep-link login has no password challenge and no SSO step, so partner-asserted
+ # email ownership is the only thing standing between an attacker and a session.
+ # Require explicit is_email_verified=True - don't trust the legacy None passthrough
+ # or the org-level email-verification-disabled flag.
+ if user.is_email_verified is not True:
+ try:
+ EmailVerifier.create_token_and_send_email_verification(user)
+ except Exception:
+ # Intentionally swallowed: the login must stay blocked regardless of email delivery.
+ # EmailVerifier captures the exception internally; the verify_email page has a resend button.
+ logger.warning("stripe_provisioning.login.verification_email_failed", user_id=user.id)
+ _capture("email_unverified", user_id=user_id)
+ logger.warning("stripe_provisioning.login.email_unverified", user_id=user_id)
+ return HttpResponseRedirect(f"/verify_email/{user.uuid}")
+
+ auth_login(request, user, backend="django.contrib.auth.backends.ModelBackend")
+
+ _capture("success", user_id=user_id, team_id=team_id, purpose=purpose)
+ logger.info("stripe_provisioning.login.success", user_id=user_id, team_id=team_id, purpose=purpose)
+
+ return HttpResponseRedirect(_redirect_path(team_id, path))
diff --git a/ee/partners/stripe/api/provisioning/region_proxy.py b/ee/partners/stripe/api/provisioning/region_proxy.py
new file mode 100644
index 000000000000..0091d8991e46
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/region_proxy.py
@@ -0,0 +1,284 @@
+"""US/EU cross-region forwarding for the Stripe provisioning namespace.
+
+Stripe calls a single base URL (us.posthog.com), but the account or token it is
+acting on may live in the EU region. Each view declares a strategy for deciding
+whether the request belongs to the other region:
+
+- ``body_region``: proxy when ``configuration.region`` differs from the
+ current region (account_requests).
+- ``token_lookup``: proxy when the auth code / refresh token isn't found
+ locally (oauth/token).
+- ``bearer_lookup``: proxy when the bearer token isn't found locally (all
+ resource endpoints).
+
+Forwarding preserves the request path, so both regions must expose the same
+routes (they deploy the same code).
+"""
+
+from __future__ import annotations
+
+import json
+import hashlib
+from typing import Any
+from urllib.parse import urlparse, urlunparse
+
+from django.conf import settings
+from django.core.cache import cache
+from django.http import HttpRequest, HttpResponse
+
+import requests
+import structlog
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models.oauth import find_oauth_access_token, find_oauth_refresh_token
+from posthog.utils import get_instance_region
+
+from ee.partners.stripe.api.provisioning import AUTH_CODE_CACHE_PREFIX
+from ee.partners.stripe.api.provisioning.analytics import capture_region_proxy_event
+
+logger = structlog.get_logger(__name__)
+
+PROXY_TIMEOUT = (2, 10)
+DEFAULT_US_DOMAIN = "us.posthog.com"
+DEFAULT_EU_DOMAIN = "eu.posthog.com"
+PROXY_LOOP_HEADER = "X-PostHog-Proxied"
+
+BEARER_PREFIX = "Bearer "
+# "Does this bearer exist locally" cache, keyed within this namespace.
+BEARER_EXISTS_CACHE_PREFIX = "stripe_provisioning_bearer_exists:"
+# Short TTL on "token doesn't exist here" so a newly-minted EU token becomes
+# visible to US (for the short window before EU→US replication catches up) and
+# so a token revoked on the other region starts getting proxied again soon.
+BEARER_EXISTS_POSITIVE_TTL = 300
+BEARER_EXISTS_NEGATIVE_TTL = 30
+
+PROXY_HEADER_ALLOWLIST = frozenset(
+ {
+ "content-type",
+ "accept",
+ "stripe-signature",
+ "api-version",
+ "authorization",
+ "user-agent",
+ }
+)
+
+# Match DRF's compact JSON rendering so proxied bodies read the same as
+# locally rendered ones.
+_JSON_SEPARATORS = (",", ":")
+
+
+def _region_domains() -> tuple[str, str]:
+ """Read at call time, not import time, so @override_settings works in tests."""
+ return (
+ getattr(settings, "REGION_US_DOMAIN", DEFAULT_US_DOMAIN),
+ getattr(settings, "REGION_EU_DOMAIN", DEFAULT_EU_DOMAIN),
+ )
+
+
+def _current_region() -> str | None:
+ region = get_instance_region()
+ if region is None:
+ return None
+ return region.upper()
+
+
+def _other_region_domain(current: str) -> str:
+ us_domain, eu_domain = _region_domains()
+ if current == "US":
+ return eu_domain
+ return us_domain
+
+
+def _request_payload(request: HttpRequest) -> dict[str, Any]:
+ """Parse the request body for the strategy checks without consuming the stream.
+
+ Accessing ``request.body`` caches it, so DRF can still parse it downstream.
+ """
+ try:
+ content_type = request.content_type or ""
+ if "json" in content_type:
+ parsed = json.loads(request.body.decode("utf-8")) if request.body else {}
+ return parsed if isinstance(parsed, dict) else {}
+ return dict(request.POST.items())
+ except Exception:
+ return {}
+
+
+def _proxy_to_region(request: HttpRequest, target_domain: str) -> HttpResponse:
+ parsed_url = urlparse(request.build_absolute_uri())
+ target_url = urlunparse(parsed_url._replace(netloc=target_domain))
+
+ headers = {k: v for k, v in request.headers.items() if k.lower() in PROXY_HEADER_ALLOWLIST}
+ headers["Host"] = target_domain
+ headers[PROXY_LOOP_HEADER] = "1"
+
+ try:
+ response = requests.request(
+ method=request.method or "GET",
+ url=target_url,
+ headers=headers,
+ data=request.body or None,
+ timeout=PROXY_TIMEOUT,
+ )
+
+ logger.info(
+ "stripe_provisioning.proxy.success",
+ target_url=target_url,
+ status_code=response.status_code,
+ )
+
+ if response.status_code == 204:
+ return HttpResponse(status=204)
+
+ try:
+ data = response.json() if response.content else {}
+ except ValueError:
+ data = {"error": "Invalid response from alternate region"}
+
+ return HttpResponse(
+ json.dumps(data, separators=_JSON_SEPARATORS),
+ status=response.status_code,
+ content_type="application/json",
+ )
+
+ except requests.exceptions.RequestException as e:
+ capture_exception(e, {"target_url": target_url, "step": "stripe_provisioning.proxy.failed"})
+ raise
+
+
+def _should_proxy_body_region(request: HttpRequest, current_region: str) -> bool:
+ configuration = _request_payload(request).get("configuration")
+ if not isinstance(configuration, dict):
+ configuration = {}
+ requested_region = (configuration.get("region") or "US").upper()
+ return requested_region != current_region
+
+
+def _should_proxy_token_lookup(request: HttpRequest, current_region: str) -> bool:
+ payload = _request_payload(request)
+ grant_type = payload.get("grant_type", "")
+
+ if grant_type == "authorization_code":
+ code = payload.get("code", "")
+ if not code:
+ return False
+ return cache.get(f"{AUTH_CODE_CACHE_PREFIX}{code}") is None
+
+ if grant_type == "refresh_token":
+ refresh_token_value = payload.get("refresh_token", "")
+ if not refresh_token_value:
+ return False
+ return find_oauth_refresh_token(refresh_token_value) is None
+
+ return False
+
+
+def _bearer_exists_locally(token_value: str) -> bool:
+ # TODO: latent bug - cache backend failures here (and in the token-lookup
+ # check above) propagate as 500s instead of falling back to the local DB
+ # lookup.
+ # SHA-256 the token before using it as a cache key so raw bearer tokens
+ # never appear in Redis keyspace dumps or logs. Tokens are already
+ # high-entropy (256 bits from secrets.token_urlsafe), so an unsalted hash
+ # is sufficient - rainbow tables against 2^256 random inputs are a non-issue.
+ token_hash = hashlib.sha256(token_value.encode("utf-8")).hexdigest()
+ cache_key = f"{BEARER_EXISTS_CACHE_PREFIX}{token_hash}"
+ cached = cache.get(cache_key)
+ if cached is not None:
+ return bool(cached)
+
+ exists = find_oauth_access_token(token_value) is not None
+ ttl = BEARER_EXISTS_POSITIVE_TTL if exists else BEARER_EXISTS_NEGATIVE_TTL
+ cache.set(cache_key, exists, timeout=ttl)
+ return exists
+
+
+def _should_proxy_bearer_lookup(request: HttpRequest, current_region: str) -> bool:
+ auth_header = request.META.get("HTTP_AUTHORIZATION", "")
+ if not auth_header.startswith(BEARER_PREFIX):
+ return False
+
+ token_value = auth_header[len(BEARER_PREFIX) :].strip()
+ if not token_value:
+ return False
+
+ return not _bearer_exists_locally(token_value)
+
+
+_STRATEGY_CHECKS = {
+ "body_region": _should_proxy_body_region,
+ "token_lookup": _should_proxy_token_lookup,
+ "bearer_lookup": _should_proxy_bearer_lookup,
+}
+
+
+class RegionProxyMixin:
+ """Forward the request to the other region when its resources live there.
+
+ Set ``region_proxy_strategy`` on the view. Runs before authentication (a
+ bearer that only exists in the other region must proxy, not 401 locally).
+ On proxy failure, ``body_region`` returns a flat ``proxy_failed`` 502 (the
+ request can't be served locally at all); the lookup strategies fall through
+ to local handling, which produces the appropriate auth error.
+
+ TODO: latent gap - because this runs before authentication and rate
+ limiting, an unauthenticated caller can induce outbound cross-region
+ requests (bounded request amplification).
+ """
+
+ region_proxy_strategy: str | None = None
+
+ def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
+ strategy = self.region_proxy_strategy
+ if strategy is None:
+ return super().dispatch(request, *args, **kwargs) # type: ignore[misc]
+
+ # Cache the raw body before the strategy checks touch it, so DRF's
+ # parsers (and signature verification) can still read it afterwards.
+ _ = request.body
+
+ current = _current_region()
+ # TODO: latent gap - "E2E" instances are not listed here, so they
+ # attempt real cross-region proxying instead of handling locally.
+ if current is None or current in ("DEV", "LOCAL"):
+ return super().dispatch(request, *args, **kwargs) # type: ignore[misc]
+
+ # TODO: latent gap - the loop-prevention header is trusted from raw
+ # client input; a caller can set it to force local handling (and skip
+ # proxying) for a resource that lives in the other region. It can only
+ # suppress proxying, never trigger it.
+ if request.META.get(f"HTTP_{PROXY_LOOP_HEADER.upper().replace('-', '_')}"):
+ return super().dispatch(request, *args, **kwargs) # type: ignore[misc]
+
+ if _STRATEGY_CHECKS[strategy](request, current):
+ target = _other_region_domain(current)
+ logger.info(
+ "stripe_provisioning.proxy.routing",
+ strategy=strategy,
+ current_region=current,
+ target_domain=target,
+ )
+ proxy_props = {
+ "strategy": strategy,
+ "from_region": current,
+ "to_domain": target,
+ "endpoint": request.path,
+ }
+ try:
+ response = _proxy_to_region(request, target)
+ capture_region_proxy_event("proxied", **proxy_props)
+ return response
+ except requests.exceptions.RequestException:
+ capture_region_proxy_event("proxy_failed", **proxy_props)
+ if strategy == "body_region":
+ return HttpResponse(
+ json.dumps(
+ {"error": {"code": "proxy_failed", "message": "Failed to route to correct region"}},
+ separators=_JSON_SEPARATORS,
+ ),
+ status=502,
+ content_type="application/json",
+ )
+
+ return super().dispatch(request, *args, **kwargs) # type: ignore[misc]
diff --git a/ee/partners/stripe/api/provisioning/serializers.py b/ee/partners/stripe/api/provisioning/serializers.py
new file mode 100644
index 000000000000..a5542d2184d0
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/serializers.py
@@ -0,0 +1,267 @@
+"""Request serializers for the Stripe provisioning endpoints.
+
+Error codes, messages, and check order are part of the APP 0.1d wire contract,
+not DRF's default error shape, so validators raise :class:`SpecError`
+(rendered by the view in the spec envelope) instead of DRF ``ValidationError``.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC
+from typing import Any
+
+from django.utils import timezone
+from django.utils.dateparse import parse_datetime
+
+from rest_framework import serializers
+
+from ee.partners.stripe.api.provisioning.analytics import capture_provisioning_event
+from ee.partners.stripe.api.provisioning.constants import VALID_SERVICE_IDS
+from ee.partners.stripe.api.provisioning.core import validate_label_prefix
+from ee.partners.stripe.api.provisioning.exceptions import SpecError
+
+
+def first_error_message(errors: Any) -> str:
+ """Flatten DRF field errors into a single spec-compatible message."""
+ if isinstance(errors, dict):
+ for field, messages in errors.items():
+ nested = first_error_message(messages)
+ return f"{field}: {nested}" if nested else str(field)
+ if isinstance(errors, list) and errors:
+ return first_error_message(errors[0])
+ return str(errors)
+
+
+class AccountRequestSerializer(serializers.Serializer):
+ """POST /provisioning/account_requests body (spec §Account Requests)."""
+
+ # Optional fields carry allow_null=True: per the spec's JSON-compatibility
+ # rule, an explicit null is treated the same as an omitted field (coerced to
+ # the declared default in validate) rather than rejected with a 400.
+ id = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ allow_null=True,
+ default="",
+ help_text="Orchestrator-side account request id, echoed back.",
+ )
+ email = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ allow_null=True,
+ default=None,
+ help_text="Email of the account to create or link. Required.",
+ )
+ name = serializers.CharField(
+ required=False, allow_blank=True, allow_null=True, default="", help_text="Display name of the end user."
+ )
+ scopes = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ allow_null=True,
+ default=list,
+ help_text="OAuth scopes requested for the eventual access token.",
+ )
+ confirmation_secret = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ allow_null=True,
+ default="",
+ help_text="Opaque orchestrator confirmation secret.",
+ )
+ expires_at = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ allow_null=True,
+ default="",
+ help_text="ISO-8601 expiry of the account request; expired requests are rejected.",
+ )
+ configuration = serializers.JSONField(
+ required=False,
+ allow_null=True,
+ default=dict,
+ help_text="Provider-specific configuration: region (US/EU), organization_name, team_id.",
+ )
+ orchestrator = serializers.JSONField(
+ required=False,
+ allow_null=True,
+ default=dict,
+ help_text='Orchestrator identity block; for Stripe: {"type": "stripe", "stripe": {"account": "acct_..."}}.',
+ )
+ code_challenge = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ allow_null=True,
+ default="",
+ help_text="PKCE code challenge (S256, base64url).",
+ )
+ code_challenge_method = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ allow_null=True,
+ default="S256",
+ help_text="PKCE challenge method; only S256 is supported.",
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ # Treat explicit null on optional fields as absent (spec JSON tolerance),
+ # so downstream code sees the declared default rather than None.
+ attrs["id"] = attrs.get("id") or ""
+ attrs["scopes"] = attrs.get("scopes") or []
+ attrs["confirmation_secret"] = attrs.get("confirmation_secret") or ""
+ attrs["code_challenge"] = attrs.get("code_challenge") or ""
+ attrs["code_challenge_method"] = attrs.get("code_challenge_method") or "S256"
+
+ if not attrs.get("email"):
+ capture_provisioning_event("account_request", "error", error_code="missing_email")
+ raise SpecError("invalid_request", "email is required")
+
+ expires_at_str = attrs.get("expires_at") or ""
+ if expires_at_str:
+ # This runs before the signature check, so it must never raise
+ # anything but SpecError: parse_datetime returns None for
+ # non-ISO-8601 input but raises ValueError for well-formed yet
+ # invalid values (e.g. month 13).
+ try:
+ expires_at = parse_datetime(expires_at_str)
+ except ValueError:
+ expires_at = None
+ if expires_at is None:
+ capture_provisioning_event("account_request", "error", error_code="invalid_expires_at")
+ raise SpecError("invalid_request", "expires_at must be a valid ISO 8601 timestamp")
+ if timezone.is_naive(expires_at):
+ # The spec's ISO 8601 permits offset-less values; take them as UTC.
+ expires_at = expires_at.replace(tzinfo=UTC)
+ if expires_at < timezone.now():
+ capture_provisioning_event("account_request", "error", error_code="expired")
+ raise SpecError("expired", "Account request has expired")
+
+ if not isinstance(attrs.get("configuration"), dict):
+ attrs["configuration"] = {}
+ if not isinstance(attrs.get("orchestrator"), dict):
+ attrs["orchestrator"] = {}
+
+ return attrs
+
+
+class ResourceCreateSerializer(serializers.Serializer):
+ """POST /provisioning/resources body (spec §Resources)."""
+
+ service_id = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ allow_null=True,
+ default="",
+ help_text="Requested service: free, pay_as_you_go, or analytics. Defaults to analytics.",
+ )
+ project_id = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ allow_null=True,
+ default="",
+ help_text="Orchestrator-side project id; idempotency key for the provisioned project.",
+ )
+ configuration = serializers.JSONField(
+ required=False, allow_null=True, default=dict, help_text="Provider-specific configuration: project_name."
+ )
+ label_prefix = serializers.JSONField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text="Optional prefix for the label of the provisioned personal API key (max 25 chars).",
+ )
+ payment_credentials = serializers.JSONField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text='Stripe Shared Payment Token block: {"type": "stripe_payment_token", "stripe_payment_token": ...}.',
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ application = self.context.get("application")
+
+ service_id = attrs.get("service_id") or ""
+ if service_id and service_id not in VALID_SERVICE_IDS:
+ capture_provisioning_event("resource_created", "error", partner=application, error_code="unknown_service")
+ raise SpecError("unknown_service", f"Unknown service_id: {service_id}")
+
+ try:
+ attrs["label_prefix"] = validate_label_prefix(attrs.get("label_prefix"))
+ except SpecError:
+ capture_provisioning_event(
+ "resource_created", "error", partner=application, error_code="invalid_label_prefix"
+ )
+ raise
+
+ if not isinstance(attrs.get("configuration"), dict):
+ attrs["configuration"] = {}
+
+ return attrs
+
+
+class UpdateServiceSerializer(serializers.Serializer):
+ """POST /provisioning/resources/:id/update_service body."""
+
+ service_id = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ allow_null=True,
+ default="",
+ help_text="Target service: free, pay_as_you_go, or analytics. Required.",
+ )
+ payment_credentials = serializers.JSONField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text='Stripe Shared Payment Token block: {"type": "stripe_payment_token", "stripe_payment_token": ...}.',
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ resource_id = self.context.get("resource_id", "")
+
+ service_id = attrs.get("service_id") or ""
+ if not service_id:
+ raise SpecError("missing_service_id", "service_id is required", resource_id=resource_id)
+ if service_id not in VALID_SERVICE_IDS:
+ raise SpecError("unknown_service", f"Unknown service_id: {service_id}", resource_id=resource_id)
+
+ return attrs
+
+
+class RotateCredentialsSerializer(serializers.Serializer):
+ """POST /provisioning/resources/:id/rotate_credentials body."""
+
+ label_prefix = serializers.JSONField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text="Optional prefix for the label of the re-issued personal API key (max 25 chars).",
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ try:
+ attrs["label_prefix"] = validate_label_prefix(attrs.get("label_prefix"))
+ except SpecError as exc:
+ capture_provisioning_event("credential_rotation", "error", error_code="invalid_label_prefix")
+ exc.resource_id = self.context.get("resource_id", "")
+ raise
+
+ return attrs
+
+
+class DeepLinkSerializer(serializers.Serializer):
+ """POST /provisioning/deep_links body."""
+
+ purpose = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ allow_null=True,
+ default="dashboard",
+ help_text="Free-form label retained for analytics (e.g. dashboard).",
+ )
+ path = serializers.JSONField(
+ required=False,
+ allow_null=True,
+ default=None,
+ help_text="Relative in-app path the user lands on after login; must start with a single '/'.",
+ )
diff --git a/ee/partners/stripe/api/provisioning/services_catalog.py b/ee/partners/stripe/api/provisioning/services_catalog.py
new file mode 100644
index 000000000000..2b7ebaeaee3d
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/services_catalog.py
@@ -0,0 +1,154 @@
+"""Service catalog for GET /provisioning/services - three services:
+
+1. free (plan) - generous free tier, no credit card required
+2. pay_as_you_go (plan) - usage-based pricing, no minimum commitment
+3. analytics (deployable) - provisions a PostHog project, pricing varies
+ by parent plan via component pricing
+
+The built catalog is cached instance-wide (see constants.py), so billing is
+hit at most once per TTL regardless of which surface serves the request.
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Any
+
+from django.core.cache import cache
+
+import requests
+import structlog
+
+from ee.partners.stripe.api.provisioning.constants import (
+ ALL_CATEGORIES,
+ ANALYTICS_SERVICE_ID,
+ FREE_PLAN_SERVICE_ID,
+ PAY_AS_YOU_GO_SERVICE_ID,
+ SERVICES_CACHE_EXPIRES_KEY,
+ SERVICES_CACHE_KEY,
+ SERVICES_CACHE_RETRY_TTL,
+ SERVICES_CACHE_STORE_TTL,
+ SERVICES_CACHE_TTL,
+)
+from ee.settings import BILLING_SERVICE_URL
+
+logger = structlog.get_logger(__name__)
+
+_EXCLUDED_PRODUCT_TYPES = {"platform_and_support", "integrations"}
+
+# (connect, read) timeout so a hung billing service can't pin a worker while
+# the cached/static fallback is available.
+_BILLING_FETCH_TIMEOUT = (2, 10)
+
+_FALLBACK_DESCRIPTION = "PostHog — AI infrastructure for your product: product & web analytics, session replay, feature flags & experiments, error tracking, AI observability, logs & traces, and more."
+
+
+def _build_free_plan_service() -> dict[str, Any]:
+ return {
+ "id": FREE_PLAN_SERVICE_ID,
+ "description": "Free - generous free tier across all PostHog products, no credit card required.",
+ "categories": ALL_CATEGORIES,
+ "pricing": {"type": "free"},
+ "kind": "plan",
+ "allowed_updates": [PAY_AS_YOU_GO_SERVICE_ID],
+ }
+
+
+def _build_pay_as_you_go_service() -> dict[str, Any]:
+ return {
+ "id": PAY_AS_YOU_GO_SERVICE_ID,
+ "description": "Pay-as-you-go - usage-based pricing across all PostHog products with no minimum commitment.",
+ "categories": ALL_CATEGORIES,
+ "pricing": {
+ "type": "paid",
+ "paid": {
+ "type": "freeform",
+ "freeform": "$0/mo base, usage-based pricing, generous free tier. See https://posthog.com/pricing for rates.",
+ },
+ },
+ "kind": "plan",
+ "allowed_updates": [FREE_PLAN_SERVICE_ID],
+ }
+
+
+def _build_analytics_service(description: str) -> dict[str, Any]:
+ return {
+ "id": ANALYTICS_SERVICE_ID,
+ "description": description,
+ "categories": ALL_CATEGORIES,
+ "pricing": {
+ "type": "component",
+ "component": {
+ "options": [
+ {"parent_service_ids": [FREE_PLAN_SERVICE_ID], "type": "free"},
+ {
+ "parent_service_ids": [PAY_AS_YOU_GO_SERVICE_ID],
+ "type": "paid",
+ "paid": {"type": "freeform", "freeform": "Usage-based pricing, pay only for what you use."},
+ },
+ ]
+ },
+ },
+ "kind": "deployable",
+ # Stripe validates allowed_updates client-side before calling update_service.
+ # Without this, `stripe projects update` rejects plan changes.
+ "allowed_updates": ["service_ref"],
+ }
+
+
+def _fetch_services_from_billing() -> list[dict[str, Any]] | None:
+ """Fetch product catalog from billing and build the service list."""
+ try:
+ res = requests.get(
+ f"{BILLING_SERVICE_URL}/api/products-v2",
+ params={"plan": "standard"},
+ timeout=_BILLING_FETCH_TIMEOUT,
+ )
+ res.raise_for_status()
+ products = res.json().get("products", [])
+ except Exception:
+ logger.exception("stripe_provisioning.services.billing_fetch_failed")
+ return None
+
+ # TODO: latent bug - this transform sits outside the try, so a malformed
+ # product payload (non-dict entries) raises and 500s the endpoint instead
+ # of returning None to trigger the fallback; an empty or fully filtered
+ # product list also produces a description with an empty product listing.
+ product_names = [
+ p.get("name", "")
+ for p in products
+ if p.get("type", "") not in _EXCLUDED_PRODUCT_TYPES and not p.get("inclusion_only")
+ ]
+ description = f"PostHog — {', '.join(n for n in product_names if n).lower()}, and more."
+
+ return [_build_free_plan_service(), _build_pay_as_you_go_service(), _build_analytics_service(description)]
+
+
+def get_services() -> list[dict[str, Any]]:
+ cached = cache.get(SERVICES_CACHE_KEY)
+ expires_at = cache.get(SERVICES_CACHE_EXPIRES_KEY)
+
+ now = time.time()
+ if cached is not None and expires_at is not None and now < expires_at:
+ return cached
+
+ services = _fetch_services_from_billing()
+ if services is not None:
+ cache.set(SERVICES_CACHE_KEY, services, SERVICES_CACHE_STORE_TTL)
+ cache.set(SERVICES_CACHE_EXPIRES_KEY, now + SERVICES_CACHE_TTL, SERVICES_CACHE_STORE_TTL)
+ return services
+
+ if cached is not None:
+ logger.warning("stripe_provisioning.services.serving_stale_cache")
+ cache.set(SERVICES_CACHE_EXPIRES_KEY, now + SERVICES_CACHE_RETRY_TTL, SERVICES_CACHE_STORE_TTL)
+ return cached
+
+ logger.warning("stripe_provisioning.services.no_cache_fallback")
+ fallback = [
+ _build_free_plan_service(),
+ _build_pay_as_you_go_service(),
+ _build_analytics_service(_FALLBACK_DESCRIPTION),
+ ]
+ cache.set(SERVICES_CACHE_KEY, fallback, SERVICES_CACHE_RETRY_TTL)
+ cache.set(SERVICES_CACHE_EXPIRES_KEY, now + SERVICES_CACHE_RETRY_TTL, SERVICES_CACHE_RETRY_TTL)
+ return fallback
diff --git a/ee/partners/stripe/api/provisioning/signature.py b/ee/partners/stripe/api/provisioning/signature.py
new file mode 100644
index 000000000000..eb1ec1e27f65
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/signature.py
@@ -0,0 +1,148 @@
+"""Stripe request-signature and API-Version verification (APP 0.1d).
+
+Implements the spec's legacy signing scheme only: ``Stripe-Signature:
+t=<timestamp>,v1=<hex>`` where the signature is HMAC-SHA256 over
+``"{timestamp}.{body}"``, verified against the global
+``settings.STRIPE_SIGNING_SECRET`` with a 300s drift tolerance.
+
+Future work: the spec also defines a preferred ``Stripe-Signature-V2`` scheme -
+an EdDSA-signed JWT (``alg=EdDSA``, ``typ=JWT``, ``kid``) verified against
+Ed25519 keys fetched from ``GET <orchestrator>/v2/provisioning/public_keys``.
+
+When Stripe moves off legacy HMAC, that verification slots in here, next to
+``verify_stripe_signature``. See the Authentication section of
+https://github.com/agentic-provisioning/posthog-spec/blob/master/docs/spec.md.
+
+The verify helpers return a DRF ``Response`` (flat error envelope) on failure
+and ``None`` on success, so views can keep the spec-mandated check ordering
+explicit with ``if error := verify_...(request): return error``.
+"""
+
+from __future__ import annotations
+
+import hmac
+import hashlib
+
+from django.conf import settings
+from django.http.request import RawPostDataException
+
+import structlog
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.exceptions_capture import capture_exception
+
+from ee.partners.stripe.api.provisioning.analytics import capture_signature_event
+from ee.partners.stripe.api.provisioning.constants import MAX_TIMESTAMP_DRIFT_SECONDS, SUPPORTED_VERSIONS
+
+logger = structlog.get_logger(__name__)
+
+
+def verify_api_version(request: Request) -> Response | None:
+ """Check the API-Version header matches a supported version.
+
+ Returns None if valid, or an error Response if not.
+ """
+ api_version = request.headers.get("api-version", "")
+ if api_version not in SUPPORTED_VERSIONS:
+ _log_and_capture_event("invalid_api_version", 400, request.path, api_version=api_version)
+ return Response(
+ {
+ "error": {
+ "code": "invalid_api_version",
+ "message": f"Supported API-Versions: {', '.join(SUPPORTED_VERSIONS)}",
+ }
+ },
+ status=400,
+ )
+ return None
+
+
+def verify_stripe_signature(request: Request) -> Response | None:
+ """Verify the Stripe-Signature HMAC against the global signing secret.
+
+ Returns None if verification passes, or an error Response if it fails.
+
+ Delegates to the Stripe SDK, which checks the timestamp and every ``v1``
+ signature in the header. During a ``STRIPE_SIGNING_SECRET`` rotation the
+ sender dual-signs each request, so the header carries the old and new
+ signatures at once; matching against any of them keeps verification working
+ across the switch-over instead of breaking the moment the secret changes.
+ """
+ endpoint = request.path
+
+ secret = settings.STRIPE_SIGNING_SECRET
+ if not secret:
+ _log_and_capture_event("server_error", 500, endpoint)
+ return Response({"error": {"code": "server_error", "message": "Signing secret not configured"}}, status=500)
+
+ body = _get_raw_body(request)
+ if body is None:
+ _log_and_capture_event("body_not_readable", 400, endpoint)
+ return Response(
+ {
+ "error": {
+ "code": "body_not_readable",
+ "message": "Unable to read request body for signature verification",
+ }
+ },
+ status=400,
+ )
+
+ try:
+ decoded_body = body.decode("utf-8")
+ except UnicodeDecodeError as e:
+ _log_and_capture_event("body_not_decodable", 400, endpoint, reason=str(e))
+ return Response(
+ {"error": {"code": "body_not_decodable", "message": "Request body must be UTF-8 encoded"}},
+ status=400,
+ )
+
+ # Deferred: the stripe SDK is ~0.45s to import and is only needed on this verify path.
+ import stripe # noqa: PLC0415
+
+ sig_header = request.headers.get("stripe-signature", "")
+ try:
+ stripe.WebhookSignature.verify_header(decoded_body, sig_header, secret, tolerance=MAX_TIMESTAMP_DRIFT_SECONDS)
+ except stripe.SignatureVerificationError as e:
+ _log_and_capture_event("invalid_signature", 401, endpoint, reason=str(e))
+ return Response(
+ {"error": {"code": "invalid_signature", "message": "Signature verification failed"}}, status=401
+ )
+
+ _log_and_capture_event("success", 200, endpoint)
+ return None
+
+
+def compute_signature(secret: str, timestamp: int, body: bytes) -> str:
+ """Compute HMAC-SHA256 signature for a request body. Exposed for testing."""
+ mac = hmac.new(secret.encode(), digestmod=hashlib.sha256)
+ mac.update(f"{timestamp}.".encode())
+ mac.update(body)
+ return mac.digest().hex()
+
+
+def _get_raw_body(request: Request) -> bytes | None:
+ """Get raw request body, returning None if the stream was already consumed."""
+ django_request = getattr(request, "_request", request)
+ if hasattr(django_request, "_body"):
+ return django_request._body
+ try:
+ return django_request.body
+ except RawPostDataException:
+ capture_exception(
+ Exception("Request body stream consumed before signature verification"),
+ {"endpoint": request.path},
+ )
+ logger.exception("signature.stream_consumed", endpoint=request.path)
+ return None
+
+
+def _log_and_capture_event(outcome: str, status_code: int, endpoint: str, **extra: object) -> None:
+ log_kwargs = {"outcome": outcome, "status_code": status_code, "endpoint": endpoint, **extra}
+ if status_code >= 400:
+ logger.warning("signature.verification_failed", **log_kwargs)
+ else:
+ logger.info("signature.verification_ok", **log_kwargs)
+
+ capture_signature_event(outcome, status_code, endpoint, **extra)
diff --git a/ee/partners/stripe/api/provisioning/test/base.py b/ee/partners/stripe/api/provisioning/test/base.py
new file mode 100644
index 000000000000..fc11c0bbde0d
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/test/base.py
@@ -0,0 +1,147 @@
+import json
+import time
+from urllib.parse import urlencode
+
+from posthog.test.base import APIBaseTest
+
+from django.core.cache import cache
+from django.test import override_settings
+
+from rest_framework.test import APIClient
+
+from posthog.models.oauth import OAuthApplication
+
+from ee.partners.stripe.api.provisioning import AUTH_CODE_CACHE_PREFIX
+from ee.partners.stripe.api.provisioning.signature import compute_signature
+
+HMAC_SECRET = "test_hmac_secret"
+TEST_STRIPE_OAUTH_CLIENT_ID = "test_stripe_oauth_client_id"
+
+BASE_PATH = "/api/partners/stripe"
+
+
+@override_settings(
+ STRIPE_SIGNING_SECRET=HMAC_SECRET,
+ STRIPE_POSTHOG_OAUTH_CLIENT_ID=TEST_STRIPE_OAUTH_CLIENT_ID,
+)
+class StripeProvisioningTestBase(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.client = APIClient()
+ self._ensure_stripe_oauth_app()
+
+ def _ensure_stripe_oauth_app(self):
+ # No provisioning_* flags: this namespace authorizes by identity
+ # (client_id) alone and does not read the app's provisioning config.
+ self.stripe_app, _ = OAuthApplication.objects.get_or_create(
+ client_id=TEST_STRIPE_OAUTH_CLIENT_ID,
+ defaults={
+ "name": "PostHog Stripe App",
+ "client_secret": "",
+ "client_type": OAuthApplication.CLIENT_CONFIDENTIAL,
+ "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ "redirect_uris": "https://localhost",
+ "algorithm": "RS256",
+ },
+ )
+
+ def _create_other_partner_app(self, **overrides):
+ defaults = {
+ "client_id": "other-partner",
+ "name": "Other Partner",
+ "client_secret": "",
+ "client_type": OAuthApplication.CLIENT_CONFIDENTIAL,
+ "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ "redirect_uris": "https://localhost",
+ "algorithm": "RS256",
+ }
+ defaults.update(overrides)
+ return OAuthApplication.objects.create(**defaults)
+
+ def _sign_body(self, body: bytes, timestamp: int | None = None) -> str:
+ ts = timestamp if timestamp is not None else int(time.time())
+ sig = compute_signature(HMAC_SECRET, ts, body)
+ return f"t={ts},v1={sig}"
+
+ def _post_signed(
+ self, url: str, data: dict | bytes | None = None, content_type: str = "application/json", **kwargs
+ ):
+ body: bytes
+ if content_type == "application/json":
+ body = json.dumps(data or {}).encode()
+ elif isinstance(data, bytes):
+ body = data
+ elif data is not None:
+ body = urlencode(data).encode()
+ else:
+ body = b""
+ sig = self._sign_body(body)
+ return self.client.post(
+ url,
+ data=body,
+ content_type=content_type,
+ HTTP_STRIPE_SIGNATURE=sig,
+ HTTP_API_VERSION="0.1d",
+ **kwargs,
+ )
+
+ def _get_signed(self, url: str, **kwargs):
+ sig = self._sign_body(b"")
+ return self.client.get(
+ url,
+ HTTP_STRIPE_SIGNATURE=sig,
+ HTTP_API_VERSION="0.1d",
+ **kwargs,
+ )
+
+ def _get_signed_with_bearer(self, url: str, token: str, **kwargs):
+ sig = self._sign_body(b"")
+ return self.client.get(
+ url,
+ HTTP_STRIPE_SIGNATURE=sig,
+ HTTP_API_VERSION="0.1d",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ **kwargs,
+ )
+
+ def _post_signed_with_bearer(self, url: str, data: dict | None = None, token: str = "", **kwargs):
+ body = json.dumps(data or {}).encode()
+ sig = self._sign_body(body)
+ return self.client.post(
+ url,
+ data=body,
+ content_type="application/json",
+ HTTP_STRIPE_SIGNATURE=sig,
+ HTTP_API_VERSION="0.1d",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ **kwargs,
+ )
+
+ def _seed_auth_code(self, code: str, **overrides):
+ value = {
+ "user_id": self.user.id,
+ "org_id": str(self.organization.id),
+ "team_id": self.team.id,
+ "stripe_account_id": "acct_123",
+ "scopes": ["query:read"],
+ "region": "US",
+ **overrides,
+ }
+ cache.set(f"{AUTH_CODE_CACHE_PREFIX}{code}", value, timeout=300)
+ return value
+
+ def _request_bearer_token(self):
+ code = f"test_code_{id(self)}"
+ self._seed_auth_code(code)
+ body = urlencode({"grant_type": "authorization_code", "code": code}).encode()
+ ts = int(time.time())
+ sig = compute_signature(HMAC_SECRET, ts, body)
+ return self.client.post(
+ f"{BASE_PATH}/oauth/token",
+ data=body,
+ content_type="application/x-www-form-urlencoded",
+ headers={"stripe-signature": f"t={ts},v1={sig}", "api-version": "0.1d"},
+ )
+
+ def _get_bearer_token(self) -> str:
+ return self._request_bearer_token().json()["access_token"]
diff --git a/ee/partners/stripe/api/provisioning/test/test_account_requests.py b/ee/partners/stripe/api/provisioning/test/test_account_requests.py
new file mode 100644
index 000000000000..043083a459b0
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/test/test_account_requests.py
@@ -0,0 +1,178 @@
+from datetime import timedelta
+
+from unittest.mock import patch
+
+from django.core.cache import cache
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models.user import User
+
+from ee.partners.stripe.api.provisioning import AUTH_CODE_CACHE_PREFIX
+from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, StripeProvisioningTestBase
+
+URL = f"{BASE_PATH}/provisioning/account_requests"
+
+
+def _account_request(email: str, **overrides) -> dict:
+ body = {
+ "id": "acctreq_test",
+ "email": email,
+ "scopes": ["query:read"],
+ "expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),
+ "orchestrator": {"type": "stripe", "stripe": {"account": "acct_test"}},
+ }
+ body.update(overrides)
+ return body
+
+
+class TestAccountRequests(StripeProvisioningTestBase):
+ def test_new_user_gets_auth_code_and_welcome_email(self):
+ with patch("ee.partners.stripe.api.provisioning.core.send_provisioning_welcome") as welcome:
+ res = self._post_signed(URL, data=_account_request("[email protected]"))
+ assert res.status_code == 200
+ body = res.json()
+ assert body["id"] == "acctreq_test"
+ assert body["type"] == "oauth"
+
+ code_data = cache.get(f"{AUTH_CODE_CACHE_PREFIX}{body['oauth']['code']}")
+ user = User.objects.get(email="[email protected]")
+ assert code_data["user_id"] == user.id
+ assert code_data["partner_id"] == ""
+ assert code_data["stripe_account_id"] == "acct_test"
+ assert code_data["scopes"] == ["query:read"]
+ assert code_data["issued_at"]
+ welcome.delay.assert_called_once()
+ assert welcome.delay.call_args[0][2] == "Stripe"
+
+ def test_existing_user_gets_silent_code_for_requested_team(self):
+ res = self._post_signed(
+ URL, data=_account_request(self.user.email, configuration={"region": "US", "team_id": self.team.id})
+ )
+ assert res.status_code == 200
+ body = res.json()
+ assert body["type"] == "oauth"
+ code_data = cache.get(f"{AUTH_CODE_CACHE_PREFIX}{body['oauth']['code']}")
+ assert code_data["user_id"] == self.user.id
+ assert code_data["team_id"] == self.team.id
+
+ def test_optional_fields_accept_explicit_null(self):
+ # Spec JSON tolerance: an explicit null on an optional field is treated
+ # as absent, not rejected with a 400.
+ res = self._post_signed(
+ URL,
+ data=_account_request(
+ self.user.email,
+ id=None,
+ scopes=None,
+ confirmation_secret=None,
+ expires_at=None,
+ code_challenge=None,
+ code_challenge_method=None,
+ configuration=None,
+ ),
+ )
+ assert res.status_code == 200
+ assert res.json()["type"] == "oauth"
+
+ def test_wizard_configuration_block_is_ignored(self):
+ res = self._post_signed(
+ URL,
+ data=_account_request(
+ configuration={
+ "region": "US",
+ "wizard": {"grant_id": "g", "installation_id": "i", "repository": "o/r"},
+ },
+ ),
+ )
+ assert res.status_code == 200
+ assert "wizard" not in res.json()
+
+ def test_missing_signature_is_unauthorized(self):
+ res = self.client.post(URL, data=_account_request("[email protected]"), format="json", HTTP_API_VERSION="0.1d")
+ assert res.status_code == 401
+ assert res.json() == {"type": "error", "error": {"code": "unauthorized", "message": "Authentication required"}}
+
+ @parameterized.expand(
+ [
+ (
+ "missing_email",
+ _account_request(""),
+ 400,
+ "invalid_request",
+ "email is required",
+ ),
+ (
+ "expired_request",
+ _account_request("[email protected]", expires_at="2020-01-01T00:00:00+00:00"),
+ 400,
+ "expired",
+ "Account request has expired",
+ ),
+ (
+ "expired_request_naive_timestamp",
+ _account_request("[email protected]", expires_at="2020-01-01T00:00:00"),
+ 400,
+ "expired",
+ "Account request has expired",
+ ),
+ (
+ "malformed_expires_at",
+ _account_request("[email protected]", expires_at="not-a-date"),
+ 400,
+ "invalid_request",
+ "expires_at must be a valid ISO 8601 timestamp",
+ ),
+ (
+ "out_of_range_expires_at",
+ _account_request("[email protected]", expires_at="2020-13-01T00:00:00+00:00"),
+ 400,
+ "invalid_request",
+ "expires_at must be a valid ISO 8601 timestamp",
+ ),
+ (
+ "missing_stripe_account",
+ _account_request("[email protected]", orchestrator={"type": "stripe", "stripe": {}}),
+ 400,
+ "invalid_request",
+ "orchestrator.stripe.account is required",
+ ),
+ (
+ "non_integer_team_id",
+ _account_request("[email protected]", configuration={"team_id": "abc"}),
+ 400,
+ "invalid_request",
+ "configuration.team_id must be an integer",
+ ),
+ (
+ "bad_code_challenge_method",
+ _account_request("[email protected]", code_challenge="a" * 43, code_challenge_method="plain"),
+ 400,
+ "invalid_request",
+ "Only S256 code_challenge_method is supported",
+ ),
+ (
+ "short_code_challenge",
+ _account_request("[email protected]", code_challenge="short"),
+ 400,
+ "invalid_request",
+ "code_challenge must be 43-128 characters using base64url charset",
+ ),
+ ]
+ )
+ def test_invalid_requests_are_rejected(self, _name, body, status, code, message):
+ res = self._post_signed(URL, data=body)
+ assert res.status_code == status
+ data = res.json()
+ assert data["type"] == "error"
+ assert data["error"] == {"code": code, "message": message}
+
+ def test_missing_email_takes_priority_over_missing_signature(self):
+ # Body validation runs before the signature requirement, so a request
+ # that is both unsigned and missing the email reports the email error.
+ res = self.client.post(URL, data={"id": "r1"}, format="json", HTTP_API_VERSION="0.1d")
+ assert res.status_code == 400
+ assert res.json()["error"]["code"] == "invalid_request"
+ assert res.json()["error"]["message"] == "email is required"
diff --git a/ee/partners/stripe/api/provisioning/test/test_deep_links.py b/ee/partners/stripe/api/provisioning/test/test_deep_links.py
new file mode 100644
index 000000000000..0fa9e3383004
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/test/test_deep_links.py
@@ -0,0 +1,50 @@
+from urllib.parse import parse_qs, urlparse
+
+from parameterized import parameterized
+
+from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, StripeProvisioningTestBase
+
+DEEP_LINKS_URL = f"{BASE_PATH}/provisioning/deep_links"
+
+
+class TestDeepLinks(StripeProvisioningTestBase):
+ def test_deep_link_logs_the_user_in_via_agentic_login(self):
+ token = self._get_bearer_token()
+ res = self._post_signed_with_bearer(
+ DEEP_LINKS_URL, data={"purpose": "dashboard", "path": f"/project/{self.team.id}/insights"}, token=token
+ )
+ assert res.status_code == 200
+ body = res.json()
+ assert body["purpose"] == "dashboard"
+ assert body["expires_at"]
+ assert f"team_id={self.team.id}" in body["url"]
+ assert "/api/partners/stripe/login?token=" in body["url"]
+
+ self.user.is_email_verified = True
+ self.user.save(update_fields=["is_email_verified"])
+ self.client.logout()
+
+ deep_link_token = parse_qs(urlparse(body["url"]).query)["token"][0]
+ login = self.client.get(f"/api/partners/stripe/login?token={deep_link_token}")
+ assert login.status_code == 302
+ assert login["Location"] == f"/project/{self.team.id}/insights"
+
+ me = self.client.get("/api/users/@me/")
+ assert me.status_code == 200
+ assert me.json()["email"] == self.user.email
+
+ @parameterized.expand(
+ [
+ ("absolute_url", "https://evil.example.com/phish"),
+ ("protocol_relative", "//evil.example.com"),
+ ("backslash_host", "/\\evil.example.com"),
+ ]
+ )
+ def test_unsafe_paths_rejected(self, _name, path):
+ token = self._get_bearer_token()
+ res = self._post_signed_with_bearer(DEEP_LINKS_URL, data={"path": path}, token=token)
+ assert res.status_code == 400
+ assert res.json()["error"] == {
+ "code": "invalid_path",
+ "message": "path must be a relative in-app path beginning with a single '/'",
+ }
diff --git a/ee/partners/stripe/api/provisioning/test/test_e2e_flow.py b/ee/partners/stripe/api/provisioning/test/test_e2e_flow.py
new file mode 100644
index 000000000000..6db9928608c2
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/test/test_e2e_flow.py
@@ -0,0 +1,175 @@
+import time
+from datetime import timedelta
+from urllib.parse import parse_qs, urlencode, urlparse
+
+from django.utils import timezone
+
+from posthog.models.user import User
+
+from ee.partners.stripe.api.provisioning.signature import compute_signature
+from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, HMAC_SECRET, StripeProvisioningTestBase
+
+
+class TestE2EProvisioningFlow(StripeProvisioningTestBase):
+ def _exchange(self, params: dict):
+ body = urlencode(params).encode()
+ ts = int(time.time())
+ sig = compute_signature(HMAC_SECRET, ts, body)
+ return self.client.post(
+ f"{BASE_PATH}/oauth/token",
+ data=body,
+ content_type="application/x-www-form-urlencoded",
+ headers={"stripe-signature": f"t={ts},v1={sig}", "api-version": "0.1d"},
+ )
+
+ def test_full_provisioning_flow(self):
+ # 1. Health check
+ res = self._get_signed(f"{BASE_PATH}/provisioning/health")
+ assert res.status_code == 200
+ assert res.json()["status"] == "ok"
+
+ # 2. List services (billing not available in tests, falls back to the static catalog)
+ res = self._get_signed(f"{BASE_PATH}/provisioning/services")
+ assert res.status_code == 200
+ assert {service["id"] for service in res.json()["data"]} == {"free", "pay_as_you_go", "analytics"}
+
+ # 3. Account request (new user)
+ account_request = {
+ "id": "acctreq_e2e_test",
+ "object": "account_request",
+ "email": "[email protected]",
+ "scopes": ["query:read", "project:read"],
+ "client_capabilities": ["browser"],
+ "confirmation_secret": "cs_e2e_secret",
+ "expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),
+ "orchestrator": {
+ "type": "stripe",
+ "stripe": {
+ "organisation": "org_e2e",
+ "account": "acct_e2e",
+ },
+ },
+ }
+ res = self._post_signed(f"{BASE_PATH}/provisioning/account_requests", data=account_request)
+ assert res.status_code == 200
+ assert res.json()["type"] == "oauth"
+ auth_code = res.json()["oauth"]["code"]
+
+ # 4. Exchange authorization code for tokens
+ res = self._exchange({"grant_type": "authorization_code", "code": auth_code})
+ assert res.status_code == 200
+ token_data = res.json()
+ assert token_data["token_type"] == "bearer"
+ access_token = token_data["access_token"]
+ refresh_token = token_data["refresh_token"]
+ assert access_token.startswith("pha_")
+ assert refresh_token.startswith("phr_")
+ assert token_data["account"]["id"]
+
+ # 5. Provision a resource
+ res = self._post_signed_with_bearer(
+ f"{BASE_PATH}/provisioning/resources",
+ data={"service_id": "analytics"},
+ token=access_token,
+ )
+ assert res.status_code == 200
+ resource_data = res.json()
+ assert resource_data["status"] == "complete"
+ resource_id = resource_data["id"]
+ assert "api_key" in resource_data["complete"]["access_configuration"]
+
+ # 6. Get resource status
+ res = self._get_signed_with_bearer(f"{BASE_PATH}/provisioning/resources/{resource_id}", token=access_token)
+ assert res.status_code == 200
+ assert res.json()["status"] == "complete"
+ assert res.json()["id"] == resource_id
+
+ # 7. Rotate credentials (generates a new api_token)
+ original_api_key = resource_data["complete"]["access_configuration"]["api_key"]
+ res = self._post_signed_with_bearer(
+ f"{BASE_PATH}/provisioning/resources/{resource_id}/rotate_credentials", token=access_token
+ )
+ assert res.status_code == 200
+ assert res.json()["status"] == "complete"
+ rotated_api_key = res.json()["complete"]["access_configuration"]["api_key"]
+ assert rotated_api_key != original_api_key
+
+ # 8. Update the service
+ res = self._post_signed_with_bearer(
+ f"{BASE_PATH}/provisioning/resources/{resource_id}/update_service",
+ data={"service_id": "free"},
+ token=access_token,
+ )
+ assert res.status_code == 200
+ assert res.json()["service_id"] == "free"
+
+ # 9. Deep link - create and use it to login (consumed by /api/partners/stripe/login)
+ res = self._post_signed_with_bearer(
+ f"{BASE_PATH}/provisioning/deep_links", data={"purpose": "dashboard"}, token=access_token
+ )
+ assert res.status_code == 200
+ deep_link_url = res.json()["url"]
+ deep_link_token = parse_qs(urlparse(deep_link_url).query)["token"][0]
+
+ # In prod the user verifies the email via the welcome reset link (which flips
+ # is_email_verified=True) before any deep-link login works. Simulate that here.
+ provisioned_user = User.objects.get(email="[email protected]")
+ provisioned_user.is_email_verified = True
+ provisioned_user.save(update_fields=["is_email_verified"])
+
+ login_res = self.client.get(f"/api/partners/stripe/login?token={deep_link_token}")
+ assert login_res.status_code == 302
+ assert "/project/" in login_res["Location"]
+
+ me_res = self.client.get("/api/users/@me/")
+ assert me_res.status_code == 200
+ assert me_res.json()["email"] == "[email protected]"
+
+ reuse_res = self.client.get(f"/api/partners/stripe/login?token={deep_link_token}")
+ assert reuse_res.status_code == 302
+ assert "expired_or_invalid_token" in reuse_res["Location"]
+
+ # 10. Refresh the token
+ res = self._exchange({"grant_type": "refresh_token", "refresh_token": refresh_token})
+ assert res.status_code == 200
+ new_access_token = res.json()["access_token"]
+ assert new_access_token != access_token
+ assert new_access_token.startswith("pha_")
+
+ # 11. New token works; the rotated-out one no longer does
+ res = self._get_signed_with_bearer(f"{BASE_PATH}/provisioning/resources/{resource_id}", token=new_access_token)
+ assert res.status_code == 200
+ res = self._get_signed_with_bearer(f"{BASE_PATH}/provisioning/resources/{resource_id}", token=access_token)
+ assert res.status_code == 401
+
+ def test_existing_user_provisioning_flow(self):
+ User.objects.create_and_join(
+ organization=self.organization,
+ password="testpass",
+ first_name="Existing",
+ )
+
+ account_request = {
+ "id": "acctreq_existing_e2e",
+ "email": "[email protected]",
+ "scopes": ["query:read", "project:read"],
+ "expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),
+ "orchestrator": {"type": "stripe", "stripe": {"account": "acct_e2e_existing"}},
+ }
+ res = self._post_signed(f"{BASE_PATH}/provisioning/account_requests", data=account_request)
+ assert res.status_code == 200
+ assert res.json()["type"] == "oauth"
+
+ res = self._exchange({"grant_type": "authorization_code", "code": res.json()["oauth"]["code"]})
+ assert res.status_code == 200
+ token_data = res.json()
+ access_token = token_data["access_token"]
+ assert len(token_data["account"]["available_teams"]) >= 1
+
+ res = self._post_signed_with_bearer(
+ f"{BASE_PATH}/provisioning/resources", data={"service_id": "analytics"}, token=access_token
+ )
+ assert res.status_code == 200
+ assert res.json()["status"] == "complete"
+ assert "api_key" in res.json()["complete"]["access_configuration"]
diff --git a/ee/partners/stripe/api/provisioning/test/test_oauth_token.py b/ee/partners/stripe/api/provisioning/test/test_oauth_token.py
new file mode 100644
index 000000000000..35ba9ca390a5
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/test/test_oauth_token.py
@@ -0,0 +1,185 @@
+import time
+import base64
+import hashlib
+import secrets
+from urllib.parse import urlencode
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.models.oauth import OAuthAccessToken, OAuthRefreshToken
+from posthog.models.organization import OrganizationMembership
+from posthog.models.team.team import Team
+from posthog.models.utils import generate_random_oauth_refresh_token
+
+from ee.models.rbac.access_control import AccessControl
+from ee.partners.stripe.api.provisioning.signature import compute_signature
+from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, HMAC_SECRET, StripeProvisioningTestBase
+
+TOKEN_URL = f"{BASE_PATH}/oauth/token"
+
+
+class TestOAuthToken(StripeProvisioningTestBase):
+ def _post_token(self, params: dict, signed: bool = True):
+ body = urlencode(params).encode()
+ headers = {"api-version": "0.1d"}
+ if signed:
+ ts = int(time.time())
+ headers["stripe-signature"] = f"t={ts},v1={compute_signature(HMAC_SECRET, ts, body)}"
+ return self.client.post(TOKEN_URL, data=body, content_type="application/x-www-form-urlencoded", headers=headers)
+
+ def test_authorization_code_exchange(self):
+ self._seed_auth_code("code_happy")
+ res = self._post_token({"grant_type": "authorization_code", "code": "code_happy"})
+ assert res.status_code == 200
+ data = res.json()
+ assert data["token_type"] == "bearer"
+ assert data["access_token"].startswith("pha_")
+ assert data["refresh_token"].startswith("phr_")
+ assert data["expires_in"] == 365 * 24 * 3600
+ assert data["account"]["id"] == str(self.organization.id)
+ assert data["account"]["payment_credentials"] == "orchestrator"
+ assert any(team["id"] == self.team.id for team in data["account"]["available_teams"])
+
+ def test_auth_code_is_single_use(self):
+ self._seed_auth_code("code_once")
+ assert self._post_token({"grant_type": "authorization_code", "code": "code_once"}).status_code == 200
+ res = self._post_token({"grant_type": "authorization_code", "code": "code_once"})
+ assert res.status_code == 400
+ assert res.json()["error"] == "invalid_grant"
+
+ def test_pkce_code_redeemable_with_verifier_and_no_signature(self):
+ verifier = secrets.token_urlsafe(48)
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()).rstrip(b"=").decode()
+ self._seed_auth_code("code_pkce", code_challenge=challenge, code_challenge_method="S256")
+ res = self._post_token(
+ {"grant_type": "authorization_code", "code": "code_pkce", "code_verifier": verifier}, signed=False
+ )
+ assert res.status_code == 200
+ assert res.json()["access_token"].startswith("pha_")
+
+ @parameterized.expand(
+ [
+ ("unsupported_grant", {"grant_type": "password"}, True, 400, "unsupported_grant_type"),
+ ("missing_code", {"grant_type": "authorization_code"}, True, 400, "invalid_request"),
+ ("unknown_code", {"grant_type": "authorization_code", "code": "nope"}, True, 400, "invalid_grant"),
+ ("missing_refresh_token", {"grant_type": "refresh_token"}, True, 400, "invalid_request"),
+ (
+ "unknown_refresh_token",
+ {"grant_type": "refresh_token", "refresh_token": "phr_x"},
+ True,
+ 400,
+ "invalid_grant",
+ ),
+ ]
+ )
+ def test_rejected_grants(self, _name, params, signed, status, error):
+ res = self._post_token(params, signed=signed)
+ assert res.status_code == status
+ assert res.json()["error"] == error
+
+ def test_unsigned_non_pkce_code_requires_authentication(self):
+ self._seed_auth_code("code_unsigned")
+ res = self._post_token({"grant_type": "authorization_code", "code": "code_unsigned"}, signed=False)
+ assert res.status_code == 401
+ assert res.json() == {"error": "invalid_request", "error_description": "Authentication required"}
+
+ def test_pkce_code_requires_verifier(self):
+ self._seed_auth_code("code_pkce_only", code_challenge="a" * 43, code_challenge_method="S256")
+ res = self._post_token({"grant_type": "authorization_code", "code": "code_pkce_only"}, signed=False)
+ assert res.status_code == 401
+ assert res.json()["error_description"] == "code_verifier is required for PKCE"
+
+ def test_requested_scopes_are_granted_without_ceiling(self):
+ # No scope ceiling in this namespace: whatever the code requests is granted.
+ self._seed_auth_code("code_wide", scopes=["query:read", "project:read"])
+ res = self._post_token({"grant_type": "authorization_code", "code": "code_wide"})
+ assert res.status_code == 200
+ token = OAuthAccessToken.objects.get(token=res.json()["access_token"])
+ assert set(token.scope.split()) == {"query:read", "project:read"}
+
+ def test_sessions_revoked_fails_closed_for_codes_without_issued_at(self):
+ self.stripe_app.sessions_revoked_at = timezone.now()
+ self.stripe_app.save(update_fields=["sessions_revoked_at"])
+ self._seed_auth_code("code_revoked")
+ res = self._post_token({"grant_type": "authorization_code", "code": "code_revoked"})
+ assert res.status_code == 400
+ assert res.json() == {
+ "error": "invalid_grant",
+ "error_description": "Application sessions were revoked; re-authorize.",
+ }
+
+ def test_refresh_token_rotation(self):
+ first = self._request_bearer_token().json()
+ res = self._post_token({"grant_type": "refresh_token", "refresh_token": first["refresh_token"]})
+ assert res.status_code == 200
+ rotated = res.json()
+ assert rotated["access_token"] != first["access_token"]
+ assert rotated["refresh_token"] != first["refresh_token"]
+ assert rotated["access_token"].startswith("pha_")
+
+ # The rotated-out refresh token is revoked, and the old access token is gone.
+ replay = self._post_token({"grant_type": "refresh_token", "refresh_token": first["refresh_token"]})
+ assert replay.status_code == 400
+ assert replay.json()["error"] == "invalid_grant"
+ detail = self._get_signed_with_bearer(
+ f"{BASE_PATH}/provisioning/resources/{self.team.id}", token=first["access_token"]
+ )
+ assert detail.status_code == 401
+
+ def test_available_teams_exclude_acl_restricted_teams(self):
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ restricted_team = Team.objects.create_with_data(
+ initiating_user=self.user, organization=self.organization, name="Restricted team"
+ )
+ AccessControl.objects.create(
+ team=restricted_team,
+ access_level="none",
+ resource="project",
+ resource_id=str(restricted_team.id),
+ )
+
+ data = self._request_bearer_token().json()
+ team_ids = [team["id"] for team in data["account"]["available_teams"]]
+ assert self.team.id in team_ids
+ assert restricted_team.id not in team_ids
+
+ def test_code_bound_to_non_stripe_app_not_redeemable(self):
+ other_app = self._create_other_partner_app()
+ self._seed_auth_code("code_other_partner", partner_id=str(other_app.id))
+
+ res = self._post_token({"grant_type": "authorization_code", "code": "code_other_partner"})
+ assert res.status_code == 400
+ assert res.json() == {
+ "error": "invalid_grant",
+ "error_description": "Authorization code was not issued for the Stripe Projects app",
+ }
+
+ def test_refresh_token_from_non_stripe_app_not_rotatable(self):
+ other_app = self._create_other_partner_app()
+ refresh_value = generate_random_oauth_refresh_token(None)
+ OAuthRefreshToken.objects.create(
+ application=other_app, token=refresh_value, user=self.user, scoped_teams=[self.team.id]
+ )
+
+ res = self._post_token({"grant_type": "refresh_token", "refresh_token": refresh_value})
+ assert res.status_code == 400
+ assert res.json() == {
+ "error": "invalid_grant",
+ "error_description": "Refresh token was not issued for the Stripe Projects app",
+ }
+ # Rejected before any mutation: the token survives unrevoked.
+ assert OAuthRefreshToken.objects.get(token=refresh_value).revoked is None
+
+ def test_refresh_is_possession_only(self):
+ first = self._request_bearer_token().json()
+ res = self._post_token({"grant_type": "refresh_token", "refresh_token": first["refresh_token"]}, signed=False)
+ assert res.status_code == 200
diff --git a/ee/partners/stripe/api/provisioning/test/test_region_proxy.py b/ee/partners/stripe/api/provisioning/test/test_region_proxy.py
new file mode 100644
index 000000000000..d3f098273971
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/test/test_region_proxy.py
@@ -0,0 +1,109 @@
+import json
+from datetime import timedelta
+
+from unittest.mock import MagicMock, patch
+
+from django.utils import timezone
+
+from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, StripeProvisioningTestBase
+
+
+def _fake_upstream(payload: dict, status_code: int = 200) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.content = json.dumps(payload).encode()
+ response.json.return_value = payload
+ return response
+
+
+class TestRegionProxy(StripeProvisioningTestBase):
+ def _account_request(self, region: str) -> dict:
+ return {
+ "id": "acctreq_proxy",
+ "email": "[email protected]",
+ "expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),
+ "configuration": {"region": region},
+ "orchestrator": {"type": "stripe", "stripe": {"account": "acct_test"}},
+ }
+
+ def test_mismatched_body_region_is_proxied_with_path_preserved(self):
+ with (
+ patch("ee.partners.stripe.api.provisioning.region_proxy.get_instance_region", return_value="US"),
+ patch(
+ "ee.partners.stripe.api.provisioning.region_proxy.requests.request",
+ return_value=_fake_upstream({"type": "oauth", "oauth": {"code": "eu_code"}}),
+ ) as proxied,
+ ):
+ res = self._post_signed(f"{BASE_PATH}/provisioning/account_requests", data=self._account_request("EU"))
+
+ assert res.status_code == 200
+ assert res.json() == {"type": "oauth", "oauth": {"code": "eu_code"}}
+ target_url = proxied.call_args.kwargs["url"]
+ assert target_url == f"http://eu.posthog.com{BASE_PATH}/provisioning/account_requests"
+ assert proxied.call_args.kwargs["headers"]["X-PostHog-Proxied"] == "1"
+
+ def test_matching_region_is_served_locally(self):
+ with (
+ patch("ee.partners.stripe.api.provisioning.region_proxy.get_instance_region", return_value="US"),
+ patch("ee.partners.stripe.api.provisioning.region_proxy.requests.request") as proxied,
+ ):
+ res = self._post_signed(f"{BASE_PATH}/provisioning/account_requests", data=self._account_request("US"))
+ assert res.status_code == 200
+ proxied.assert_not_called()
+
+ def test_proxy_loop_header_forces_local_handling(self):
+ with (
+ patch("ee.partners.stripe.api.provisioning.region_proxy.get_instance_region", return_value="US"),
+ patch("ee.partners.stripe.api.provisioning.region_proxy.requests.request") as proxied,
+ ):
+ res = self._post_signed(
+ f"{BASE_PATH}/provisioning/account_requests",
+ data=self._account_request("EU"),
+ HTTP_X_POSTHOG_PROXIED="1",
+ )
+ assert res.status_code == 200
+ proxied.assert_not_called()
+
+ def test_unknown_bearer_is_proxied(self):
+ with (
+ patch("ee.partners.stripe.api.provisioning.region_proxy.get_instance_region", return_value="US"),
+ patch(
+ "ee.partners.stripe.api.provisioning.region_proxy.requests.request",
+ return_value=_fake_upstream({"status": "complete", "id": "42"}),
+ ) as proxied,
+ ):
+ res = self._get_signed_with_bearer(f"{BASE_PATH}/provisioning/resources/42", token="pha_only_in_eu")
+ assert res.status_code == 200
+ assert res.json()["status"] == "complete"
+ assert proxied.call_args.kwargs["url"].endswith(f"{BASE_PATH}/provisioning/resources/42")
+
+ def test_unknown_auth_code_is_proxied(self):
+ with (
+ patch("ee.partners.stripe.api.provisioning.region_proxy.get_instance_region", return_value="US"),
+ patch(
+ "ee.partners.stripe.api.provisioning.region_proxy.requests.request",
+ return_value=_fake_upstream({"token_type": "bearer", "access_token": "pha_eu"}),
+ ) as proxied,
+ ):
+ res = self._post_signed(
+ f"{BASE_PATH}/oauth/token",
+ data={"grant_type": "authorization_code", "code": "code_only_in_eu"},
+ content_type="application/x-www-form-urlencoded",
+ )
+ assert res.status_code == 200
+ assert res.json()["access_token"] == "pha_eu"
+ proxied.assert_called_once()
+
+ def test_failed_body_region_proxy_returns_502(self):
+ import requests as requests_lib
+
+ with (
+ patch("ee.partners.stripe.api.provisioning.region_proxy.get_instance_region", return_value="US"),
+ patch(
+ "ee.partners.stripe.api.provisioning.region_proxy.requests.request",
+ side_effect=requests_lib.exceptions.ConnectionError("boom"),
+ ),
+ ):
+ res = self._post_signed(f"{BASE_PATH}/provisioning/account_requests", data=self._account_request("EU"))
+ assert res.status_code == 502
+ assert res.json() == {"error": {"code": "proxy_failed", "message": "Failed to route to correct region"}}
diff --git a/ee/partners/stripe/api/provisioning/test/test_remove_and_rotate.py b/ee/partners/stripe/api/provisioning/test/test_remove_and_rotate.py
new file mode 100644
index 000000000000..173c5d6b29e4
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/test/test_remove_and_rotate.py
@@ -0,0 +1,53 @@
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+
+from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, StripeProvisioningTestBase
+
+RESOURCES_URL = f"{BASE_PATH}/provisioning/resources"
+
+
+class TestRemoveAndRotate(StripeProvisioningTestBase):
+ def test_rotate_credentials_issues_new_api_key_and_pat(self):
+ token = self._get_bearer_token()
+ original_api_key = self.team.api_token
+
+ res = self._post_signed_with_bearer(
+ f"{RESOURCES_URL}/{self.team.id}/rotate_credentials", data={"label_prefix": "Rotated"}, token=token
+ )
+ assert res.status_code == 200
+ body = res.json()
+ assert body["status"] == "complete"
+ rotated_api_key = body["complete"]["access_configuration"]["api_key"]
+ assert rotated_api_key != original_api_key
+ self.team.refresh_from_db()
+ assert self.team.api_token == rotated_api_key
+ assert body["complete"]["access_configuration"]["personal_api_key"].startswith("phx_")
+ assert PersonalAPIKey.objects.filter(user=self.user, label__startswith="Rotated - ").exists()
+
+ def test_rotate_rejects_invalid_label_prefix_with_resource_id(self):
+ token = self._get_bearer_token()
+ res = self._post_signed_with_bearer(
+ f"{RESOURCES_URL}/{self.team.id}/rotate_credentials", data={"label_prefix": "x" * 26}, token=token
+ )
+ assert res.status_code == 400
+ assert res.json() == {
+ "status": "error",
+ "id": str(self.team.id),
+ "error": {"code": "invalid_label_prefix", "message": "label_prefix must be 25 characters or fewer"},
+ }
+
+ def test_remove_detaches_resource_and_strips_token_scope(self):
+ token = self._get_bearer_token()
+ create = self._post_signed_with_bearer(RESOURCES_URL, data={"service_id": "analytics"}, token=token)
+ assert create.status_code == 200
+ assert TeamProvisioningConfig.objects.filter(team=self.team).exists()
+
+ res = self._post_signed_with_bearer(f"{RESOURCES_URL}/{self.team.id}/remove", token=token)
+ assert res.status_code == 200
+ assert res.json() == {"status": "removed", "id": str(self.team.id)}
+ assert not TeamProvisioningConfig.objects.filter(team=self.team).exists()
+
+ # The team left the token's scope; since it was the only scoped team the
+ # token itself is gone, so further calls are unauthorized.
+ detail = self._get_signed_with_bearer(f"{RESOURCES_URL}/{self.team.id}", token=token)
+ assert detail.status_code == 401
diff --git a/ee/partners/stripe/api/provisioning/test/test_resources.py b/ee/partners/stripe/api/provisioning/test/test_resources.py
new file mode 100644
index 000000000000..6b008c730380
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/test/test_resources.py
@@ -0,0 +1,194 @@
+from datetime import timedelta
+
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models.oauth import OAuthAccessToken
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+from posthog.models.utils import generate_random_oauth_access_token
+
+from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, StripeProvisioningTestBase
+
+RESOURCES_URL = f"{BASE_PATH}/provisioning/resources"
+
+
+class TestResources(StripeProvisioningTestBase):
+ def test_create_returns_access_configuration_and_pat(self):
+ token = self._get_bearer_token()
+ res = self._post_signed_with_bearer(
+ RESOURCES_URL, data={"service_id": "analytics", "label_prefix": "Stripe"}, token=token
+ )
+ assert res.status_code == 200
+ body = res.json()
+ assert body["status"] == "complete"
+ assert body["id"] == str(self.team.id)
+ assert body["service_id"] == "analytics"
+ config = body["complete"]["access_configuration"]
+ assert config["api_key"] == self.team.api_token
+ assert config["host"]
+ assert config["personal_api_key"].startswith("phx_")
+
+ pat = PersonalAPIKey.objects.get(user=self.user)
+ assert pat.label == f"Stripe - {self.team.name}"[:40]
+ assert pat.scoped_teams == [self.team.id]
+
+ assert TeamProvisioningConfig.objects.get(team=self.team).service_id == "analytics"
+
+ def test_create_with_project_id_is_idempotent(self):
+ token = self._get_bearer_token()
+ first = self._post_signed_with_bearer(RESOURCES_URL, data={"project_id": "proj_1"}, token=token)
+ assert first.status_code == 200
+ second = self._post_signed_with_bearer(RESOURCES_URL, data={"project_id": "proj_1"}, token=token)
+ assert second.status_code == 200
+ assert first.json()["id"] == second.json()["id"]
+ # A project_id provisions a dedicated team, distinct from the consent team.
+ assert first.json()["id"] != str(self.team.id)
+
+ def test_unknown_service_rejected(self):
+ token = self._get_bearer_token()
+ res = self._post_signed_with_bearer(RESOURCES_URL, data={"service_id": "nonsense"}, token=token)
+ assert res.status_code == 400
+ assert res.json() == {
+ "status": "error",
+ "id": "",
+ "error": {"code": "unknown_service", "message": "Unknown service_id: nonsense"},
+ }
+
+ @parameterized.expand(
+ [
+ ("too_long", "x" * 26, "label_prefix must be 25 characters or fewer"),
+ ("bidi_override", "evil‮prefix", "label_prefix must not contain control or format characters"),
+ ("non_string", 123, "label_prefix must be a string"),
+ ]
+ )
+ def test_invalid_label_prefix_rejected(self, _name, prefix, message):
+ token = self._get_bearer_token()
+ res = self._post_signed_with_bearer(RESOURCES_URL, data={"label_prefix": prefix}, token=token)
+ assert res.status_code == 400
+ assert res.json()["error"] == {"code": "invalid_label_prefix", "message": message}
+
+ def test_pay_as_you_go_requires_payment_credentials(self):
+ token = self._get_bearer_token()
+ res = self._post_signed_with_bearer(RESOURCES_URL, data={"service_id": "pay_as_you_go"}, token=token)
+ assert res.status_code == 400
+ assert res.json()["error"]["code"] == "requires_payment_credentials"
+
+ def test_pay_as_you_go_with_spt_activates_billing(self):
+ token = self._get_bearer_token()
+ with (
+ patch("ee.partners.stripe.api.provisioning.billing._team_has_active_billing", return_value=False),
+ patch(
+ "ee.partners.stripe.api.provisioning.billing._activate_billing_with_spt", return_value=True
+ ) as activate,
+ ):
+ res = self._post_signed_with_bearer(
+ RESOURCES_URL,
+ data={
+ "service_id": "pay_as_you_go",
+ "payment_credentials": {"type": "stripe_payment_token", "stripe_payment_token": "spt_1"},
+ },
+ token=token,
+ )
+ assert res.status_code == 200
+ assert res.json()["service_id"] == "pay_as_you_go"
+ activate.assert_called_once()
+ assert activate.call_args[0][2] == "spt_1"
+
+ def test_failed_spt_activation_is_reported(self):
+ token = self._get_bearer_token()
+ with (
+ patch("ee.partners.stripe.api.provisioning.billing._team_has_active_billing", return_value=False),
+ patch("ee.partners.stripe.api.provisioning.billing._activate_billing_with_spt", return_value=False),
+ ):
+ res = self._post_signed_with_bearer(
+ RESOURCES_URL,
+ data={
+ "service_id": "analytics",
+ "payment_credentials": {"type": "stripe_payment_token", "stripe_payment_token": "spt_1"},
+ },
+ token=token,
+ )
+ assert res.status_code == 400
+ assert res.json() == {
+ "status": "error",
+ "id": str(self.team.id),
+ "error": {"code": "requires_payment_credentials", "message": "Billing activation failed"},
+ }
+
+ def test_detail_returns_resource(self):
+ token = self._get_bearer_token()
+ res = self._get_signed_with_bearer(f"{RESOURCES_URL}/{self.team.id}", token=token)
+ assert res.status_code == 200
+ body = res.json()
+ assert body["status"] == "complete"
+ assert body["id"] == str(self.team.id)
+ assert body["complete"]["access_configuration"]["api_key"] == self.team.api_token
+
+ @parameterized.expand(
+ [
+ ("non_numeric", "abc", 400, "invalid_resource_id"),
+ ("out_of_scope", "999999", 403, "forbidden"),
+ ]
+ )
+ def test_detail_rejects_bad_resource_ids(self, _name, resource_id, status, code):
+ token = self._get_bearer_token()
+ res = self._get_signed_with_bearer(f"{RESOURCES_URL}/{resource_id}", token=token)
+ assert res.status_code == status
+ body = res.json()
+ assert body["status"] == "error"
+ assert body["id"] == resource_id
+ assert body["error"]["code"] == code
+
+ @parameterized.expand(
+ [
+ ("missing", None, "Missing bearer token"),
+ ("unknown", "pha_bogus", "Invalid access token"),
+ ]
+ )
+ def test_bearer_required(self, _name, token, message):
+ if token is None:
+ res = self.client.get(f"{RESOURCES_URL}/{self.team.id}", HTTP_API_VERSION="0.1d")
+ else:
+ res = self._get_signed_with_bearer(f"{RESOURCES_URL}/{self.team.id}", token=token)
+ assert res.status_code == 401
+ assert res.json() == {
+ "status": "error",
+ "id": "",
+ "error": {"code": "unauthorized", "message": message},
+ }
+
+ def test_signature_required_even_with_valid_bearer(self):
+ token = self._get_bearer_token()
+ res = self.client.get(
+ f"{RESOURCES_URL}/{self.team.id}",
+ HTTP_API_VERSION="0.1d",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ assert res.status_code == 401
+ assert res.json() == {"error": {"code": "invalid_signature", "message": "Signature verification failed"}}
+
+ def test_bearer_from_another_app_rejected(self):
+ # Authorization is by identity alone: a token for any app other than the
+ # Stripe Projects app is rejected regardless of its config.
+ other_app = self._create_other_partner_app()
+ token_value = generate_random_oauth_access_token(None)
+ OAuthAccessToken.objects.create(
+ application=other_app,
+ token=token_value,
+ user=self.user,
+ expires=timezone.now() + timedelta(days=1),
+ scope="query:read",
+ scoped_teams=[self.team.id],
+ )
+
+ res = self._get_signed_with_bearer(f"{RESOURCES_URL}/{self.team.id}", token=token_value)
+ assert res.status_code == 401
+ assert res.json() == {
+ "status": "error",
+ "id": "",
+ "error": {"code": "unauthorized", "message": "Authentication failed"},
+ }
diff --git a/ee/partners/stripe/api/provisioning/test/test_services_catalog.py b/ee/partners/stripe/api/provisioning/test/test_services_catalog.py
new file mode 100644
index 000000000000..a9d12e4d8c5f
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/test/test_services_catalog.py
@@ -0,0 +1,65 @@
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import cache
+from django.test import TestCase
+
+from ee.partners.stripe.api.provisioning.constants import (
+ ANALYTICS_SERVICE_ID,
+ FREE_PLAN_SERVICE_ID,
+ PAY_AS_YOU_GO_SERVICE_ID,
+ SERVICES_CACHE_EXPIRES_KEY,
+)
+from ee.partners.stripe.api.provisioning.services_catalog import _FALLBACK_DESCRIPTION, get_services
+
+
+def _billing_response(products: list[dict]) -> MagicMock:
+ res = MagicMock()
+ res.json.return_value = {"products": products}
+ res.raise_for_status.return_value = None
+ return res
+
+
+class TestServicesCatalog(TestCase):
+ def setUp(self):
+ super().setUp()
+ cache.clear()
+
+ def test_catalog_built_from_billing_products_filters_and_lists_names(self):
+ products: list[dict] = [
+ {"name": "Product analytics", "type": "product_analytics"},
+ {"name": "Session replay", "type": "session_replay"},
+ {"name": "Support", "type": "platform_and_support"},
+ {"name": "Data pipelines", "type": "integrations"},
+ {"name": "Add-on", "type": "product_analytics", "inclusion_only": True},
+ ]
+ with patch(
+ "ee.partners.stripe.api.provisioning.services_catalog.requests.get",
+ return_value=_billing_response(products),
+ ):
+ services = get_services()
+
+ by_id = {s["id"]: s for s in services}
+ assert set(by_id) == {FREE_PLAN_SERVICE_ID, PAY_AS_YOU_GO_SERVICE_ID, ANALYTICS_SERVICE_ID}
+ # Excluded types and inclusion_only entries drop out; the rest are lowercased into the blurb.
+ assert by_id[ANALYTICS_SERVICE_ID]["description"] == "PostHog — product analytics, session replay, and more."
+
+ def test_stale_cache_served_when_billing_fetch_fails(self):
+ products = [{"name": "Product analytics", "type": "product_analytics"}]
+ with patch(
+ "ee.partners.stripe.api.provisioning.services_catalog.requests.get",
+ return_value=_billing_response(products),
+ ):
+ fresh = get_services()
+
+ # Expire the cache window, then make billing unavailable: the stale entry is served
+ # rather than falling back to the static description.
+ cache.set(SERVICES_CACHE_EXPIRES_KEY, 0, 60)
+ with patch(
+ "ee.partners.stripe.api.provisioning.services_catalog.requests.get",
+ side_effect=Exception("billing down"),
+ ):
+ stale = get_services()
+
+ assert stale == fresh
+ analytics = next(s for s in stale if s["id"] == ANALYTICS_SERVICE_ID)
+ assert analytics["description"] != _FALLBACK_DESCRIPTION
diff --git a/ee/partners/stripe/api/provisioning/test/test_signature.py b/ee/partners/stripe/api/provisioning/test/test_signature.py
new file mode 100644
index 000000000000..d87db62577b1
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/test/test_signature.py
@@ -0,0 +1,66 @@
+import time
+
+from django.test import override_settings
+
+from parameterized import parameterized
+
+from ee.partners.stripe.api.provisioning.signature import compute_signature
+from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, HMAC_SECRET, StripeProvisioningTestBase
+
+HEALTH_URL = f"{BASE_PATH}/provisioning/health"
+
+
+class TestSignatureVerification(StripeProvisioningTestBase):
+ def test_valid_signature_and_version(self):
+ res = self._get_signed(HEALTH_URL)
+ assert res.status_code == 200
+ assert res.json() == {"supported_versions": ["0.1d"], "status": "ok"}
+
+ def test_wrong_secret_rejected(self):
+ ts = int(time.time())
+ sig = compute_signature("wrong_secret", ts, b"")
+ res = self.client.get(HEALTH_URL, HTTP_STRIPE_SIGNATURE=f"t={ts},v1={sig}", HTTP_API_VERSION="0.1d")
+ assert res.status_code == 401
+ assert res.json() == {"error": {"code": "invalid_signature", "message": "Signature verification failed"}}
+
+ def test_expired_timestamp_rejected(self):
+ stale_ts = int(time.time()) - 600
+ res = self.client.get(
+ HEALTH_URL, HTTP_STRIPE_SIGNATURE=self._sign_body(b"", timestamp=stale_ts), HTTP_API_VERSION="0.1d"
+ )
+ assert res.status_code == 401
+ assert res.json()["error"]["code"] == "invalid_signature"
+
+ def test_missing_signature_header_rejected(self):
+ res = self.client.get(HEALTH_URL, HTTP_API_VERSION="0.1d")
+ assert res.status_code == 401
+ assert res.json()["error"]["code"] == "invalid_signature"
+
+ def test_dual_signed_header_matches_either_secret(self):
+ # During secret rotation the sender includes v1 entries for the old and
+ # new secret; verification must pass if any of them matches.
+ ts = int(time.time())
+ old_sig = compute_signature("retired_secret", ts, b"")
+ current_sig = compute_signature(HMAC_SECRET, ts, b"")
+ res = self.client.get(
+ HEALTH_URL,
+ HTTP_STRIPE_SIGNATURE=f"t={ts},v1={old_sig},v1={current_sig}",
+ HTTP_API_VERSION="0.1d",
+ )
+ assert res.status_code == 200
+
+ @override_settings(STRIPE_SIGNING_SECRET="")
+ def test_missing_secret_is_server_error(self):
+ res = self._get_signed(HEALTH_URL)
+ assert res.status_code == 500
+ assert res.json()["error"]["code"] == "server_error"
+
+ @parameterized.expand([("missing", None), ("unsupported", "9.9z")])
+ def test_bad_api_version_rejected(self, _name, version):
+ sig = self._sign_body(b"")
+ if version is None:
+ res = self.client.get(HEALTH_URL, HTTP_STRIPE_SIGNATURE=sig)
+ else:
+ res = self.client.get(HEALTH_URL, HTTP_STRIPE_SIGNATURE=sig, HTTP_API_VERSION=version)
+ assert res.status_code == 400
+ assert res.json() == {"error": {"code": "invalid_api_version", "message": "Supported API-Versions: 0.1d"}}
diff --git a/ee/partners/stripe/api/provisioning/test/test_throttles.py b/ee/partners/stripe/api/provisioning/test/test_throttles.py
new file mode 100644
index 000000000000..3b3b3c730982
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/test/test_throttles.py
@@ -0,0 +1,64 @@
+from datetime import timedelta
+
+from unittest.mock import patch
+
+from django.core.cache import cache
+from django.utils import timezone
+
+from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, StripeProvisioningTestBase
+
+URL = f"{BASE_PATH}/provisioning/account_requests"
+
+
+class TestRateLimits(StripeProvisioningTestBase):
+ def setUp(self):
+ super().setUp()
+ cache.clear()
+
+ def _account_request(self) -> dict:
+ return {
+ "id": "acctreq_throttle",
+ "email": self.user.email,
+ "expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),
+ "orchestrator": {"type": "stripe", "stripe": {"account": "acct_test"}},
+ }
+
+ def test_account_requests_are_rate_limited(self):
+ with patch.dict("ee.partners.stripe.api.provisioning.throttling.RATE_LIMIT_DEFAULTS", {"account_requests": 1}):
+ assert self._post_signed(URL, data=self._account_request()).status_code == 200
+ res = self._post_signed(URL, data=self._account_request())
+ assert res.status_code == 429
+ assert res.json() == {
+ "type": "error",
+ "error": {
+ "code": "rate_limited",
+ "message": "Rate limit exceeded (account_requests). Try again later.",
+ },
+ }
+ assert int(res["Retry-After"]) > 0
+
+ def test_zero_default_disables_the_limit(self):
+ with patch.dict("ee.partners.stripe.api.provisioning.throttling.RATE_LIMIT_DEFAULTS", {"account_requests": 0}):
+ assert self._post_signed(URL, data=self._account_request()).status_code == 200
+ assert self._post_signed(URL, data=self._account_request()).status_code == 200
+
+ def test_resource_creates_use_status_envelope(self):
+ token = self._get_bearer_token()
+ with patch.dict("ee.partners.stripe.api.provisioning.throttling.RATE_LIMIT_DEFAULTS", {"resource_creates": 1}):
+ first = self._post_signed_with_bearer(
+ f"{BASE_PATH}/provisioning/resources", data={"service_id": "analytics"}, token=token
+ )
+ assert first.status_code == 200
+ res = self._post_signed_with_bearer(
+ f"{BASE_PATH}/provisioning/resources", data={"service_id": "analytics"}, token=token
+ )
+ assert res.status_code == 429
+ assert res.json() == {
+ "status": "error",
+ "id": "",
+ "error": {
+ "code": "rate_limited",
+ "message": "Rate limit exceeded. Try again later.",
+ },
+ }
+ assert int(res["Retry-After"]) > 0
diff --git a/ee/partners/stripe/api/provisioning/test/test_update_service.py b/ee/partners/stripe/api/provisioning/test/test_update_service.py
new file mode 100644
index 000000000000..6f354d76154c
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/test/test_update_service.py
@@ -0,0 +1,72 @@
+import json
+
+from posthog.models.oauth import OAuthApplication
+from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+
+from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, StripeProvisioningTestBase
+
+
+class TestUpdateService(StripeProvisioningTestBase):
+ def _url(self, resource_id) -> str:
+ return f"{BASE_PATH}/provisioning/resources/{resource_id}/update_service"
+
+ def test_update_to_free_succeeds(self):
+ token = self._get_bearer_token()
+ res = self._post_signed_with_bearer(self._url(self.team.id), data={"service_id": "free"}, token=token)
+ assert res.status_code == 200
+ body = res.json()
+ assert body["status"] == "complete"
+ assert body["service_id"] == "free"
+ assert TeamProvisioningConfig.objects.get(team=self.team).service_id == "free"
+
+ def test_bearer_alone_is_not_enough(self):
+ # update_service changes billing, so the orchestrator HMAC is required
+ # on top of the bearer token.
+ token = self._get_bearer_token()
+ res = self.client.post(
+ self._url(self.team.id),
+ data=json.dumps({"service_id": "free"}),
+ content_type="application/json",
+ HTTP_API_VERSION="0.1d",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ assert res.status_code == 401
+ assert res.json() == {"error": {"code": "invalid_signature", "message": "Signature verification failed"}}
+
+ def test_missing_and_unknown_service_ids_rejected(self):
+ token = self._get_bearer_token()
+ res = self._post_signed_with_bearer(self._url(self.team.id), data={}, token=token)
+ assert res.status_code == 400
+ assert res.json() == {
+ "status": "error",
+ "id": str(self.team.id),
+ "error": {"code": "missing_service_id", "message": "service_id is required"},
+ }
+
+ res = self._post_signed_with_bearer(self._url(self.team.id), data={"service_id": "bogus"}, token=token)
+ assert res.status_code == 400
+ assert res.json()["error"]["code"] == "unknown_service"
+
+ def test_resource_owned_by_another_partner_is_forbidden(self):
+ token = self._get_bearer_token()
+ other_app = OAuthApplication.objects.create(
+ client_id="other-partner",
+ name="Other Partner",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://localhost",
+ algorithm="RS256",
+ )
+ TeamProvisioningConfig.objects.update_or_create(team=self.team, defaults={"application": other_app})
+
+ res = self._post_signed_with_bearer(self._url(self.team.id), data={"service_id": "free"}, token=token)
+ assert res.status_code == 403
+ assert res.json()["error"]["code"] == "forbidden"
+ assert res.json()["error"]["message"] == "Resource owned by a different provisioning partner"
+
+ def test_pay_as_you_go_requires_payment_credentials(self):
+ token = self._get_bearer_token()
+ res = self._post_signed_with_bearer(self._url(self.team.id), data={"service_id": "pay_as_you_go"}, token=token)
+ assert res.status_code == 400
+ assert res.json()["error"]["code"] == "requires_payment_credentials"
diff --git a/ee/partners/stripe/api/provisioning/throttling.py b/ee/partners/stripe/api/provisioning/throttling.py
new file mode 100644
index 000000000000..e0b49090e0ea
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/throttling.py
@@ -0,0 +1,113 @@
+"""Rate limiting for the Stripe provisioning namespace.
+
+Fixed-window counters with fixed per-endpoint limits from ``RATE_LIMIT_DEFAULTS``
+- this namespace serves a single caller (Stripe), so the window is keyed on a
+constant identity rather than any OAuthApplication field. A limit <= 0 disables
+it. The caller can burst up to 2x the limit across a window boundary; switch to
+a sliding window if that ever matters.
+"""
+
+from __future__ import annotations
+
+import time
+from typing import ClassVar
+
+from django.core.cache import cache
+
+import structlog
+from rest_framework.request import Request
+from rest_framework.throttling import BaseThrottle
+from rest_framework.views import APIView
+
+from ee.partners.stripe.api.provisioning.analytics import capture_provisioning_event
+from ee.partners.stripe.api.provisioning.constants import (
+ RATE_LIMIT_CACHE_PREFIX,
+ RATE_LIMIT_DEFAULTS,
+ RATE_LIMIT_EVENT_NAMES,
+ RATE_LIMIT_WINDOW_SECONDS,
+)
+from ee.partners.stripe.api.provisioning.exceptions import SpecError
+
+logger = structlog.get_logger(__name__)
+
+# Single-caller namespace: the rate-limit window is keyed on this constant, not
+# on any per-app identity or config.
+_STRIPE_RATE_LIMIT_KEY = "stripe"
+
+
+class StripeFixedWindowThrottle(BaseThrottle):
+ """Fixed-window counter keyed on the endpoint + window-of-epoch."""
+
+ endpoint: ClassVar[str]
+
+ def __init__(self) -> None:
+ self.limit = RATE_LIMIT_DEFAULTS[self.endpoint]
+ self.count = 0
+
+ def allow_request(self, request: Request, view: APIView) -> bool:
+ if self.limit <= 0:
+ return True
+
+ window_index = int(time.time()) // RATE_LIMIT_WINDOW_SECONDS
+ cache_key = f"{RATE_LIMIT_CACHE_PREFIX}{self.endpoint}:{_STRIPE_RATE_LIMIT_KEY}:{window_index}"
+
+ try:
+ cache.add(cache_key, 0, timeout=RATE_LIMIT_WINDOW_SECONDS)
+ self.count = cache.incr(cache_key)
+ except (ValueError, ConnectionError, TimeoutError) as e:
+ logger.warning("stripe_provisioning_rate_limit_cache_error", endpoint=self.endpoint, error=str(e))
+ # cache.add preserves any counter a concurrent request already initialized,
+ # so a transient cache error doesn't reset the window when at the limit.
+ cache.add(cache_key, 1, timeout=RATE_LIMIT_WINDOW_SECONDS)
+ self.count = 1
+
+ return self.count <= self.limit
+
+ def wait(self) -> float:
+ return float(RATE_LIMIT_WINDOW_SECONDS - (int(time.time()) % RATE_LIMIT_WINDOW_SECONDS))
+
+
+class AccountRequestsThrottle(StripeFixedWindowThrottle):
+ endpoint = "account_requests"
+
+
+class TokenExchangesThrottle(StripeFixedWindowThrottle):
+ endpoint = "token_exchanges"
+
+
+class ResourceCreatesThrottle(StripeFixedWindowThrottle):
+ endpoint = "resource_creates"
+
+
+def enforce_stripe_rate_limit(
+ throttle_cls: type[StripeFixedWindowThrottle],
+ request: Request,
+ view: APIView,
+ *,
+ message: str | None = None,
+ envelope: str | None = None,
+) -> None:
+ """Raise a spec ``rate_limited`` error when the caller is over budget.
+
+ ``message``/``envelope`` default to the typed-envelope wording used by
+ account_requests and the token endpoint; the resource endpoints pass their
+ own status-envelope variants.
+ """
+ throttle = throttle_cls()
+ if throttle.allow_request(request, view):
+ return
+
+ endpoint = throttle_cls.endpoint
+ capture_provisioning_event(
+ RATE_LIMIT_EVENT_NAMES[endpoint],
+ "rate_limited",
+ limit=throttle.limit,
+ count=throttle.count,
+ )
+ raise SpecError(
+ "rate_limited",
+ message or f"Rate limit exceeded ({endpoint}). Try again later.",
+ status=429,
+ envelope=envelope or "typed", # type: ignore[arg-type]
+ retry_after=int(throttle.wait()),
+ )
diff --git a/ee/partners/stripe/api/provisioning/urls.py b/ee/partners/stripe/api/provisioning/urls.py
new file mode 100644
index 000000000000..77240ab9bcde
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/urls.py
@@ -0,0 +1,72 @@
+"""Routes for the Stripe Projects provisioning namespace.
+
+Included from ``ee/urls.py`` under ``api/partners/stripe/``. Stripe builds
+provider URLs as ``provisioning.base_url + "provisioning/<name>"`` (the token
+endpoint is configured explicitly in the app manifest), so the concrete paths
+are ``/api/partners/stripe/provisioning/...`` and
+``/api/partners/stripe/oauth/token``.
+"""
+
+from django.urls import path
+from django.views.decorators.csrf import csrf_exempt
+
+from ee.partners.stripe.api.provisioning import views
+from ee.partners.stripe.api.provisioning.login import stripe_provisioning_login
+
+urlpatterns = [
+ path(
+ "login",
+ stripe_provisioning_login,
+ name="stripe_provisioning_login",
+ ),
+ path(
+ "provisioning/health",
+ csrf_exempt(views.HealthView.as_view()),
+ name="stripe_provisioning_health",
+ ),
+ path(
+ "provisioning/services",
+ csrf_exempt(views.ServicesView.as_view()),
+ name="stripe_provisioning_services",
+ ),
+ path(
+ "provisioning/account_requests",
+ csrf_exempt(views.AccountRequestsView.as_view()),
+ name="stripe_provisioning_account_requests",
+ ),
+ path(
+ "oauth/token",
+ csrf_exempt(views.OAuthTokenView.as_view()),
+ name="stripe_provisioning_oauth_token",
+ ),
+ path(
+ "provisioning/resources",
+ csrf_exempt(views.ResourcesCreateView.as_view()),
+ name="stripe_provisioning_resources_create",
+ ),
+ path(
+ "provisioning/resources/<str:resource_id>/rotate_credentials",
+ csrf_exempt(views.RotateCredentialsView.as_view()),
+ name="stripe_provisioning_rotate_credentials",
+ ),
+ path(
+ "provisioning/resources/<str:resource_id>/update_service",
+ csrf_exempt(views.UpdateServiceView.as_view()),
+ name="stripe_provisioning_update_service",
+ ),
+ path(
+ "provisioning/resources/<str:resource_id>/remove",
+ csrf_exempt(views.ResourceRemoveView.as_view()),
+ name="stripe_provisioning_resource_remove",
+ ),
+ path(
+ "provisioning/resources/<str:resource_id>",
+ csrf_exempt(views.ResourceDetailView.as_view()),
+ name="stripe_provisioning_resource_detail",
+ ),
+ path(
+ "provisioning/deep_links",
+ csrf_exempt(views.DeepLinksView.as_view()),
+ name="stripe_provisioning_deep_links",
+ ),
+]
diff --git a/ee/partners/stripe/api/provisioning/views.py b/ee/partners/stripe/api/provisioning/views.py
new file mode 100644
index 000000000000..39d4961622e7
--- /dev/null
+++ b/ee/partners/stripe/api/provisioning/views.py
@@ -0,0 +1,952 @@
+"""Stripe Projects provisioning endpoints (APP 0.1d provider surface).
+
+Mounted under ``/api/partners/stripe/``. Stripe is the only accepted caller:
+every request is authenticated with the global ``Stripe-Signature`` HMAC, and
+resource endpoints additionally require a bearer token issued to the Stripe
+Projects OAuth app (the token endpoint accepts PKCE in place of the HMAC).
+
+Check order is part of the observable wire behavior (which error a request
+with several problems gets). Endpoints whose checks are uniform - signature
+then API-Version before the handler - inherit them from
+:class:`SignatureCheckedMixin` so a new endpoint cannot ship without them.
+``account_requests`` and ``oauth/token`` interleave their checks with body
+parsing (body errors before the signature requirement; PKCE accepted in place
+of the HMAC), so those two run every check explicitly in the handler.
+"""
+
+from __future__ import annotations
+
+import re
+import base64
+import hashlib
+import secrets
+from datetime import datetime, timedelta
+from typing import Any, ClassVar, cast
+
+from django.core.cache import cache
+from django.db import transaction
+from django.utils import timezone
+
+from drf_spectacular.utils import extend_schema
+from rest_framework.authentication import BaseAuthentication
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models.oauth import OAuthAccessToken, OAuthRefreshToken
+from posthog.models.team.team import Team
+from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+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
+
+from ee.partners.stripe.api.provisioning import AUTH_CODE_CACHE_PREFIX, DEEP_LINK_CACHE_PREFIX
+from ee.partners.stripe.api.provisioning.analytics import capture_provisioning_event
+from ee.partners.stripe.api.provisioning.authentication import StripeBearerAuthentication
+from ee.partners.stripe.api.provisioning.billing import try_activate_billing_with_spt
+from ee.partners.stripe.api.provisioning.constants import (
+ ACCESS_TOKEN_EXPIRY_SECONDS,
+ ANALYTICS_SERVICE_ID,
+ DEEP_LINK_TTL_SECONDS,
+ PAY_AS_YOU_GO_SERVICE_ID,
+ STRIPE_CONTRACTED_SCOPES,
+ SUPPORTED_VERSIONS,
+)
+from ee.partners.stripe.api.provisioning.core import (
+ ProjectIdCollisionError,
+ StripeOAuthAppMissingError,
+ compute_partner_scoped_teams,
+ get_available_teams_for_user,
+ get_oauth_app_for_code,
+ get_provisioning_service_id,
+ handle_existing_user,
+ handle_new_user,
+ is_safe_deep_link_path,
+ is_stripe_oauth_app,
+ lock_application,
+ maybe_create_provisioned_pat,
+ region_to_host,
+ remove_team_from_token_scopes,
+ resolve_or_create_project_team,
+ set_provisioning_service_id,
+)
+from ee.partners.stripe.api.provisioning.exceptions import Envelope, PreRenderedError, SpecError, render_spec_error
+from ee.partners.stripe.api.provisioning.region_proxy import RegionProxyMixin
+from ee.partners.stripe.api.provisioning.serializers import (
+ AccountRequestSerializer,
+ DeepLinkSerializer,
+ ResourceCreateSerializer,
+ RotateCredentialsSerializer,
+ UpdateServiceSerializer,
+ first_error_message,
+)
+from ee.partners.stripe.api.provisioning.services_catalog import get_services
+from ee.partners.stripe.api.provisioning.signature import verify_api_version, verify_stripe_signature
+from ee.partners.stripe.api.provisioning.throttling import (
+ AccountRequestsThrottle,
+ ResourceCreatesThrottle,
+ TokenExchangesThrottle,
+ enforce_stripe_rate_limit,
+)
+
+_CODE_CHALLENGE_RE = re.compile(r"[A-Za-z0-9_\-]+")
+
+
+class StripeProvisioningAPIView(RegionProxyMixin, APIView):
+ """Base for every endpoint in this namespace.
+
+ Unauthenticated by default; errors raised as :class:`SpecError` render in
+ the view's spec envelope.
+ """
+
+ authentication_classes: list[type[BaseAuthentication]] = []
+ permission_classes: list = []
+ spec_envelope: ClassVar[Envelope] = "flat"
+
+ def handle_exception(self, exc: Exception) -> Response:
+ if isinstance(exc, PreRenderedError):
+ return exc.response
+ if isinstance(exc, SpecError):
+ return render_spec_error(exc, self.spec_envelope)
+ return super().handle_exception(exc)
+
+
+class SignatureCheckedMixin:
+ """Runs the spec's mandatory Stripe-Signature and API-Version checks as
+ part of the request flow (after authentication, before the handler), so
+ every endpoint built on it is signed-only by construction. A bearer alone
+ is never sufficient: a stolen token without the signing secret cannot mint
+ keys or read credentials."""
+
+ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:
+ super().initial(request, *args, **kwargs) # type: ignore[misc]
+ if error := verify_stripe_signature(request):
+ raise PreRenderedError(error)
+ if error := verify_api_version(request):
+ raise PreRenderedError(error)
+
+
+# ---------------------------------------------------------------------------
+# GET /provisioning/health - liveness probe, returns supported protocol versions
+# ---------------------------------------------------------------------------
+
+
+class HealthView(SignatureCheckedMixin, StripeProvisioningAPIView):
+ @extend_schema(exclude=True)
+ def get(self, request: Request) -> Response:
+ return Response({"supported_versions": SUPPORTED_VERSIONS, "status": "ok"})
+
+
+# ---------------------------------------------------------------------------
+# GET /provisioning/services - returns the catalog of provisionable services
+# ---------------------------------------------------------------------------
+
+
+class ServicesView(SignatureCheckedMixin, StripeProvisioningAPIView):
+ @extend_schema(exclude=True)
+ def get(self, request: Request) -> Response:
+ return Response({"data": get_services()})
+
+
+# ---------------------------------------------------------------------------
+# POST /provisioning/account_requests - onboard a new or existing user and
+# return an auth code
+# ---------------------------------------------------------------------------
+
+
+class AccountRequestsView(StripeProvisioningAPIView):
+ spec_envelope = "typed"
+ region_proxy_strategy = "body_region"
+
+ @extend_schema(exclude=True)
+ def post(self, request: Request) -> Response:
+ if error := verify_api_version(request):
+ return error
+
+ serializer = AccountRequestSerializer(data=request.data)
+ if not serializer.is_valid():
+ raise SpecError("invalid_request", first_error_message(serializer.errors))
+ data = serializer.validated_data
+
+ request_id = data["id"]
+ email = data["email"]
+ scopes = data["scopes"]
+ configuration = data["configuration"]
+ orchestrator = data["orchestrator"]
+
+ # Partner account ID: generic field, with the Stripe-nested form preferred
+ orchestrator_type = orchestrator.get("type", "")
+ if orchestrator_type == "stripe":
+ stripe_info = orchestrator.get("stripe") or {}
+ partner_account_id = stripe_info.get("account", "")
+ else:
+ partner_account_id = orchestrator.get("account", "")
+
+ if not request.headers.get("stripe-signature"):
+ raise SpecError("unauthorized", "Authentication required", status=401)
+ if error := verify_stripe_signature(request):
+ return error
+
+ if not partner_account_id:
+ capture_provisioning_event("account_request", "error", error_code="missing_stripe_account")
+ raise SpecError("invalid_request", "orchestrator.stripe.account is required")
+
+ enforce_stripe_rate_limit(AccountRequestsThrottle, request, self)
+
+ code_challenge = data["code_challenge"]
+ code_challenge_method = data["code_challenge_method"]
+ if code_challenge and code_challenge_method != "S256":
+ raise SpecError("invalid_request", "Only S256 code_challenge_method is supported")
+ if code_challenge and (
+ len(code_challenge) < 43 or len(code_challenge) > 128 or not _CODE_CHALLENGE_RE.fullmatch(code_challenge)
+ ):
+ raise SpecError("invalid_request", "code_challenge must be 43-128 characters using base64url charset")
+
+ region = (configuration.get("region") or "US").upper()
+
+ requested_team_id = configuration.get("team_id")
+ if requested_team_id is not None:
+ try:
+ requested_team_id = int(requested_team_id)
+ except (ValueError, TypeError):
+ raise SpecError("invalid_request", "configuration.team_id must be an integer", request_id=request_id)
+
+ existing_user = User.objects.filter(email=email).first()
+
+ if existing_user:
+ return Response(
+ handle_existing_user(
+ request_id,
+ existing_user,
+ scopes,
+ partner_account_id,
+ region,
+ requested_team_id,
+ code_challenge,
+ code_challenge_method,
+ )
+ )
+
+ return Response(
+ handle_new_user(
+ request_id,
+ data,
+ email,
+ scopes,
+ partner_account_id,
+ region,
+ code_challenge,
+ code_challenge_method,
+ )
+ )
+
+
+# ---------------------------------------------------------------------------
+# POST /oauth/token - exchange auth codes or refresh tokens for access tokens
+# ---------------------------------------------------------------------------
+
+
+class OAuthTokenView(StripeProvisioningAPIView):
+ spec_envelope = "oauth"
+ region_proxy_strategy = "token_lookup"
+
+ @extend_schema(exclude=True)
+ def post(self, request: Request) -> Response:
+ grant_type = request.data.get("grant_type", "")
+
+ if grant_type == "authorization_code":
+ return self._exchange_authorization_code(request)
+ elif grant_type == "refresh_token":
+ return self._exchange_refresh_token(request)
+
+ capture_provisioning_event("token_exchange", "unsupported_grant_type", grant_type=grant_type)
+ raise SpecError("unsupported_grant_type", f"Unsupported grant_type: {grant_type}")
+
+ def _exchange_authorization_code(self, request: Request) -> Response:
+ code = request.data.get("code", "")
+ if not code:
+ capture_provisioning_event("token_exchange", "missing_code", grant_type="authorization_code")
+ raise SpecError("invalid_request", "code is required")
+
+ cache_key = f"{AUTH_CODE_CACHE_PREFIX}{code}"
+ code_data = cache.get(cache_key)
+ if code_data is None:
+ capture_provisioning_event("token_exchange", "invalid_code", grant_type="authorization_code")
+ raise SpecError("invalid_grant", "Invalid or expired authorization code")
+
+ # Auth check: PKCE codes require code_verifier, non-PKCE codes require HMAC.
+ # All verification happens BEFORE cache.delete so a failed attempt doesn't consume the code.
+ stored_challenge = code_data.get("code_challenge", "")
+ has_hmac = bool(request.headers.get("stripe-signature"))
+ if stored_challenge:
+ code_verifier = request.data.get("code_verifier", "")
+ if not code_verifier:
+ capture_provisioning_event("token_exchange", "missing_code_verifier", grant_type="authorization_code")
+ raise SpecError("invalid_request", "code_verifier is required for PKCE", status=401)
+ computed = (
+ base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode("ascii")).digest())
+ .rstrip(b"=")
+ .decode("ascii")
+ )
+ if computed != stored_challenge:
+ capture_provisioning_event("token_exchange", "pkce_mismatch", grant_type="authorization_code")
+ raise SpecError("invalid_grant", "PKCE code_verifier does not match")
+ elif not has_hmac:
+ capture_provisioning_event("token_exchange", "missing_signature", grant_type="authorization_code")
+ raise SpecError("invalid_request", "Authentication required", status=401)
+ else:
+ if error := verify_stripe_signature(request):
+ return error
+
+ # Consume the code before rate limiting so a leaked auth code can't be replayed
+ # to burn the bucket. Auth codes are single-use by spec, so the tradeoff
+ # (rate-limited client loses the code) is acceptable - clients can
+ # re-initiate the OAuth flow if rate-limited.
+ cache.delete(cache_key)
+
+ enforce_stripe_rate_limit(TokenExchangesThrottle, request, self)
+
+ user_id = code_data["user_id"]
+ team_id = code_data["team_id"]
+ scopes = code_data.get("scopes", [])
+
+ try:
+ user = User.objects.get(id=user_id)
+ except User.DoesNotExist:
+ capture_provisioning_event("token_exchange", "user_not_found", grant_type="authorization_code")
+ raise SpecError("invalid_grant", "User not found")
+
+ try:
+ oauth_app = get_oauth_app_for_code(code_data)
+ except StripeOAuthAppMissingError:
+ capture_provisioning_event("token_exchange", "oauth_app_missing", grant_type="authorization_code")
+ raise SpecError("server_error", "OAuth application is not configured", status=500)
+
+ # Stripe-only namespace: a consent-flow code bound to another partner's
+ # app is not redeemable here and must use that partner's own surface.
+ if not is_stripe_oauth_app(oauth_app):
+ capture_provisioning_event("token_exchange", "non_stripe_app", grant_type="authorization_code")
+ raise SpecError("invalid_grant", "Authorization code was not issued for the Stripe Projects app")
+
+ # Lock the app row before reading the revoke stamp and minting, so this serializes
+ # with revoke_application_sessions (see lock_application). Provisioning auth codes
+ # live in the cache, not OAuthGrant, so the revoke's sweep can't reach them - the
+ # `issued_at` carried on the code is what a revoke is checked against. Codes minted
+ # without the field fail closed (they expire in AUTH_CODE_TTL_SECONDS and the
+ # client can re-run the flow).
+ with transaction.atomic():
+ locked_app = lock_application(oauth_app.pk) if oauth_app else None
+ sessions_revoked_at = locked_app.sessions_revoked_at if locked_app else None
+ if sessions_revoked_at is not None:
+ issued_at_raw = code_data.get("issued_at")
+ issued_at = datetime.fromisoformat(issued_at_raw) if issued_at_raw else None
+ if issued_at is None or issued_at < sessions_revoked_at:
+ capture_provisioning_event("token_exchange", "sessions_revoked", grant_type="authorization_code")
+ raise SpecError("invalid_grant", "Application sessions were revoked; re-authorize.")
+
+ # No scope ceiling in this namespace: Stripe is trusted with full
+ # access, so it receives exactly the scopes it requested (falling back
+ # to the default Stripe set when none were requested).
+ requested_scopes = scopes if scopes else list(STRIPE_CONTRACTED_SCOPES)
+ scope_str = " ".join(requested_scopes)
+
+ token_expiry = ACCESS_TOKEN_EXPIRY_SECONDS
+
+ scoped_teams = compute_partner_scoped_teams(oauth_app, user, team_id)
+ # A partner token carries its restriction in scoped_teams alone, and the standard
+ # OAuth permission check treats an empty scoped_teams as unrestricted (permissions.py).
+ # compute_partner_scoped_teams returns [] exactly when the base team is gone or the
+ # user lost access, so minting here would hand out a project-unrestricted bearer.
+ # Fail closed and force re-authorization.
+ if not scoped_teams:
+ capture_provisioning_event("token_exchange", "no_accessible_teams", grant_type="authorization_code")
+ raise SpecError("invalid_grant", "No accessible teams for this authorization; re-authorize.")
+
+ access_token_value = generate_random_oauth_access_token(None)
+ access_token = OAuthAccessToken.objects.create(
+ application=oauth_app,
+ token=access_token_value,
+ user=user,
+ expires=timezone.now() + timedelta(seconds=token_expiry),
+ scope=scope_str,
+ scoped_teams=scoped_teams,
+ )
+
+ refresh_token_value = generate_random_oauth_refresh_token(None)
+ OAuthRefreshToken.objects.create(
+ application=oauth_app,
+ token=refresh_token_value,
+ user=user,
+ access_token=access_token,
+ scoped_teams=scoped_teams,
+ )
+
+ account_id = str(code_data.get("org_id", ""))
+
+ available_teams = get_available_teams_for_user(user)
+
+ capture_provisioning_event(
+ "token_exchange",
+ "success",
+ partner=oauth_app,
+ grant_type="authorization_code",
+ team_id=team_id,
+ user_id=user.id,
+ granted_team_count=len(scoped_teams),
+ )
+
+ return Response(
+ {
+ "token_type": "bearer",
+ "access_token": access_token_value,
+ "refresh_token": refresh_token_value,
+ "expires_in": token_expiry,
+ "account": {
+ "id": account_id,
+ "payment_credentials": "orchestrator",
+ "available_teams": available_teams,
+ },
+ }
+ )
+
+ def _exchange_refresh_token(self, request: Request) -> Response:
+ refresh_token_value = request.data.get("refresh_token", "")
+ if not refresh_token_value:
+ capture_provisioning_event("token_exchange", "missing_refresh_token", grant_type="refresh_token")
+ raise SpecError("invalid_request", "refresh_token is required")
+
+ # Lock the app row first (revoke_application_sessions locks it before sweeping tokens),
+ # then re-read the refresh token under that lock, so the rotate-and-mint serializes with
+ # the revoke: either we hold the lock and our new tokens land before its sweep, or it
+ # committed first and we see the token already revoked (or the stamp) and reject. Looking
+ # the app up by id first (without locking the token row) keeps the lock order app→token,
+ # matching the revoke, so the two can't deadlock.
+ with transaction.atomic():
+ application_id = (
+ OAuthRefreshToken.objects.filter(token=refresh_token_value, revoked__isnull=True)
+ .values_list("application_id", flat=True)
+ .first()
+ )
+ locked_app = lock_application(application_id) if application_id else None
+ old_refresh = (
+ OAuthRefreshToken.objects.select_related("user", "access_token")
+ .filter(token=refresh_token_value, revoked__isnull=True)
+ .first()
+ )
+ if old_refresh is None:
+ capture_provisioning_event("token_exchange", "invalid_refresh_token", grant_type="refresh_token")
+ raise SpecError("invalid_grant", "Invalid or revoked refresh token")
+
+ oauth_app = locked_app
+
+ # Stripe-only namespace: refresh tokens minted for any other
+ # application (or with no application) are not rotatable here.
+ # Checked before any token row is mutated.
+ if oauth_app is None or not is_stripe_oauth_app(oauth_app):
+ capture_provisioning_event("token_exchange", "non_stripe_app", grant_type="refresh_token")
+ raise SpecError("invalid_grant", "Refresh token was not issued for the Stripe Projects app")
+ user = old_refresh.user
+ old_scoped_teams = old_refresh.scoped_teams or []
+ # base_team_id at refresh: the first team in the prior scope. The consent team
+ # (authorized at grant time) has the lowest id and sorts first at issuance;
+ # partner-provisioned teams are always created later, so they take higher ids
+ # and are only ever appended after it. [0] is therefore the consent team. This
+ # ordering is load-bearing: compute_partner_scoped_teams re-adds the consent
+ # team only when it is base_team_id (it has no TeamProvisioningConfig for this
+ # app), so a lower-id provisioned team becoming [0] would silently drop the
+ # consent team from the refreshed scope. If the prior token was somehow empty-
+ # scoped, fall back to zero so the helper short-circuits without claiming a team.
+ base_team_id = old_scoped_teams[0] if old_scoped_teams else 0
+ scoped_teams = compute_partner_scoped_teams(oauth_app, user, base_team_id)
+ # Same fail-closed rule as issuance: an empty scoped_teams is unrestricted under the
+ # standard permission check, so a refresh whose base team vanished or whose access was
+ # revoked must re-authorize rather than rotate into a project-unrestricted token.
+ # Checked before any token row is mutated so a rejected refresh never revokes the
+ # caller's only token.
+ if not scoped_teams:
+ capture_provisioning_event("token_exchange", "no_accessible_teams", grant_type="refresh_token")
+ raise SpecError("invalid_grant", "No accessible teams for this token; re-authorize.")
+ old_scope = (
+ old_refresh.access_token.scope if old_refresh.access_token else " ".join(STRIPE_CONTRACTED_SCOPES)
+ )
+
+ sessions_revoked_at = locked_app.sessions_revoked_at if locked_app else None
+ if sessions_revoked_at is not None and old_refresh.created < sessions_revoked_at:
+ capture_provisioning_event("token_exchange", "sessions_revoked", grant_type="refresh_token")
+ raise SpecError("invalid_grant", "Application sessions were revoked; re-authorize.")
+
+ # No scope ceiling in this namespace: carry the prior token's scopes
+ # forward unchanged.
+ new_scope = old_scope
+
+ enforce_stripe_rate_limit(TokenExchangesThrottle, request, self)
+
+ old_access = old_refresh.access_token
+ old_refresh.access_token = None
+ old_refresh.revoked = timezone.now()
+ old_refresh.save(update_fields=["access_token", "revoked"])
+
+ if old_access:
+ old_access.delete()
+
+ token_expiry = ACCESS_TOKEN_EXPIRY_SECONDS
+
+ new_access_value = generate_random_oauth_access_token(None)
+ new_access = OAuthAccessToken.objects.create(
+ application=oauth_app,
+ token=new_access_value,
+ user=user,
+ expires=timezone.now() + timedelta(seconds=token_expiry),
+ scope=new_scope,
+ scoped_teams=scoped_teams,
+ )
+
+ new_refresh_value = generate_random_oauth_refresh_token(None)
+ OAuthRefreshToken.objects.create(
+ application=oauth_app,
+ token=new_refresh_value,
+ user=user,
+ access_token=new_access,
+ scoped_teams=scoped_teams,
+ )
+
+ capture_provisioning_event(
+ "token_exchange",
+ "success",
+ partner=oauth_app,
+ grant_type="refresh_token",
+ team_id=base_team_id,
+ user_id=user.id if user else None,
+ granted_team_count=len(scoped_teams),
+ )
+
+ return Response(
+ {
+ "token_type": "bearer",
+ "access_token": new_access_value,
+ "refresh_token": new_refresh_value,
+ "expires_in": token_expiry,
+ }
+ )
+
+
+# ---------------------------------------------------------------------------
+# Resource endpoints - bearer-authenticated, status envelope
+# ---------------------------------------------------------------------------
+
+
+class StripeResourceAPIView(SignatureCheckedMixin, StripeProvisioningAPIView):
+ spec_envelope = "status"
+ region_proxy_strategy = "bearer_lookup"
+ authentication_classes = [StripeBearerAuthentication]
+
+ def parse_resource_team_id(self, resource_id: str, access_token: OAuthAccessToken) -> int:
+ try:
+ team_id = int(resource_id)
+ except (ValueError, TypeError):
+ raise SpecError("invalid_resource_id", "Invalid resource ID", resource_id=resource_id)
+
+ # TODO: latent bug - this checks only the token's issuance-time scoped_teams,
+ # not the user's current team-level access. If the user is later removed from
+ # the team/org, the (long-lived) bearer can still read/rotate/update/remove
+ # the resource until it is refreshed (refresh re-derives scope via
+ # compute_partner_scoped_teams). Revalidate live access here to close it.
+ if team_id not in (access_token.scoped_teams or []):
+ raise SpecError("forbidden", "Resource not accessible with this token", resource_id=resource_id, status=403)
+ return team_id
+
+ def get_team(self, team_id: int, resource_id: str) -> Team:
+ try:
+ return Team.objects.get(id=team_id)
+ except Team.DoesNotExist:
+ raise SpecError("not_found", "Resource not found", resource_id=resource_id, status=404)
+
+
+class ResourcesCreateView(StripeResourceAPIView):
+ @extend_schema(exclude=True)
+ def post(self, request: Request) -> Response:
+ user = cast(User, request.user)
+ access_token = cast(OAuthAccessToken, request.auth)
+
+ app = access_token.application
+ enforce_stripe_rate_limit(
+ ResourceCreatesThrottle,
+ request,
+ self,
+ message="Rate limit exceeded. Try again later.",
+ envelope="status",
+ )
+
+ serializer = ResourceCreateSerializer(data=request.data, context={"application": app})
+ if not serializer.is_valid():
+ raise SpecError("invalid_request", first_error_message(serializer.errors))
+ data = serializer.validated_data
+
+ service_id = data["service_id"]
+ label_prefix = data["label_prefix"]
+
+ scoped_teams = access_token.scoped_teams or []
+ if not scoped_teams:
+ capture_provisioning_event("resource_created", "error", partner=app, error_code="no_team")
+ raise SpecError("no_team", "No team associated with this token")
+
+ project_id = data["project_id"]
+ configuration = data["configuration"]
+
+ if project_id:
+ try:
+ team, scoped_teams = resolve_or_create_project_team(
+ project_id, scoped_teams, user, configuration, access_token
+ )
+ except ProjectIdCollisionError:
+ capture_provisioning_event(
+ "resource_created", "error", partner=app, error_code="project_id_conflict", project_id=project_id
+ )
+ raise SpecError("project_id_conflict", "Project ID already linked to another organization", status=409)
+ if team is None:
+ capture_provisioning_event(
+ "resource_created", "error", partner=app, error_code="not_found", project_id=project_id
+ )
+ raise SpecError("not_found", "Resource not found", status=404)
+ else:
+ team_id = scoped_teams[0]
+ try:
+ team = Team.objects.get(id=team_id)
+ except Team.DoesNotExist:
+ capture_provisioning_event(
+ "resource_created", "error", partner=app, error_code="team_not_found", team_id=team_id
+ )
+ raise SpecError("team_not_found", "Team not found", resource_id=str(team_id), status=404)
+
+ # TODO: latent bug - this runs on every call, so a repeated create for
+ # an existing team overwrites its service_id (not idempotent), and the
+ # write lands before the billing checks below.
+ resolved_service_id = service_id or ANALYTICS_SERVICE_ID
+ set_provisioning_service_id(team, resolved_service_id)
+
+ # TODO: latent bug - the team, provisioning config, and token scopes
+ # are already persisted; a billing failure below returns an error to
+ # the orchestrator while leaving a usable, unbilled project behind.
+ billing_result = try_activate_billing_with_spt(data["payment_credentials"], team, user)
+ has_spt = billing_result is not None
+ if billing_result is False:
+ capture_provisioning_event(
+ "resource_created",
+ "error",
+ partner=app,
+ error_code="requires_payment_credentials",
+ service_id=resolved_service_id,
+ team_id=team.id,
+ has_spt=has_spt,
+ )
+ # TODO: update_service reports this same billing failure as
+ # billing_activation_failed; the two codes should converge.
+ raise SpecError("requires_payment_credentials", "Billing activation failed", resource_id=str(team.id))
+
+ if resolved_service_id == PAY_AS_YOU_GO_SERVICE_ID and billing_result is None:
+ capture_provisioning_event(
+ "resource_created",
+ "error",
+ partner=app,
+ error_code="requires_payment_credentials",
+ service_id=resolved_service_id,
+ team_id=team.id,
+ )
+ raise SpecError("requires_payment_credentials", "Payment credentials required for paid plan")
+
+ region = get_instance_region() or "US"
+ host = region_to_host(region)
+
+ capture_provisioning_event(
+ "resource_created",
+ "success",
+ partner=app,
+ service_id=resolved_service_id,
+ team_id=team.id,
+ has_spt=has_spt,
+ billing_result=str(billing_result),
+ )
+
+ access_configuration: dict[str, str] = {
+ "api_key": team.api_token,
+ "host": host,
+ }
+ if personal_api_key := maybe_create_provisioned_pat(user, team, access_token.scope, label_prefix=label_prefix):
+ access_configuration["personal_api_key"] = personal_api_key
+
+ return Response(
+ {
+ "status": "complete",
+ "id": str(team.id),
+ "service_id": resolved_service_id,
+ "complete": {
+ "access_configuration": access_configuration,
+ },
+ }
+ )
+
+
+class ResourceDetailView(StripeResourceAPIView):
+ @extend_schema(exclude=True)
+ def get(self, request: Request, resource_id: str) -> Response:
+ access_token = cast(OAuthAccessToken, request.auth)
+
+ # TODO: latent gap - unlike update_service/remove there is no
+ # cross-application ownership check on TeamProvisioningConfig, so a
+ # token whose scope includes a team provisioned by another application
+ # can still read its credentials.
+ team_id = self.parse_resource_team_id(resource_id, access_token)
+ team = self.get_team(team_id, resource_id)
+
+ service_id = get_provisioning_service_id(team)
+ region = get_instance_region() or "US"
+ host = region_to_host(region)
+
+ return Response(
+ {
+ "status": "complete",
+ "id": resource_id,
+ "service_id": service_id,
+ "complete": {
+ "access_configuration": {
+ "api_key": team.api_token,
+ "host": host,
+ },
+ },
+ }
+ )
+
+
+class RotateCredentialsView(StripeResourceAPIView):
+ @extend_schema(exclude=True)
+ def post(self, request: Request, resource_id: str) -> Response:
+ user = cast(User, request.user)
+ access_token = cast(OAuthAccessToken, request.auth)
+
+ serializer = RotateCredentialsSerializer(data=request.data, context={"resource_id": resource_id})
+ if not serializer.is_valid():
+ raise SpecError("invalid_request", first_error_message(serializer.errors), resource_id=resource_id)
+ label_prefix = serializer.validated_data["label_prefix"]
+
+ # TODO: latent gap - unlike update_service/remove there is no
+ # cross-application ownership check on TeamProvisioningConfig, so a
+ # token whose scope includes a team provisioned by another application
+ # can rotate its credentials.
+ team_id = self.parse_resource_team_id(resource_id, access_token)
+ team = self.get_team(team_id, resource_id)
+
+ try:
+ # The bearer flow resolves the token outside DRF's session machinery,
+ # so read impersonation off the token directly.
+ team.reset_token_and_save(user=user, is_impersonated_session=access_token.impersonated_by_id is not None)
+ except Exception:
+ capture_exception(additional_properties={"team_id": team_id})
+ capture_provisioning_event("credential_rotation", "failed", team_id=team_id)
+ raise SpecError(
+ "credential_rotation_failed", "Failed to rotate credentials", resource_id=resource_id, status=500
+ )
+
+ capture_provisioning_event("credential_rotation", "success", team_id=team_id)
+
+ service_id = get_provisioning_service_id(team)
+ region = get_instance_region() or "US"
+ host = region_to_host(region)
+
+ access_configuration: dict[str, str] = {
+ "api_key": team.api_token,
+ "host": host,
+ }
+ if personal_api_key := maybe_create_provisioned_pat(user, team, access_token.scope, label_prefix=label_prefix):
+ access_configuration["personal_api_key"] = personal_api_key
+
+ return Response(
+ {
+ "status": "complete",
+ "id": resource_id,
+ "service_id": service_id,
+ "complete": {
+ "access_configuration": access_configuration,
+ },
+ }
+ )
+
+
+class UpdateServiceView(StripeResourceAPIView):
+ @extend_schema(exclude=True)
+ def post(self, request: Request, resource_id: str) -> Response:
+ user = cast(User, request.user)
+ access_token = cast(OAuthAccessToken, request.auth)
+
+ team_id = self.parse_resource_team_id(resource_id, access_token)
+ team = self.get_team(team_id, resource_id)
+
+ # A config with a non-null application belongs to the partner that provisioned
+ # it; a null application is unclaimed (every team gets one by default) and is
+ # mutable by any in-scope caller. Reject only a cross-partner mutation.
+ owning_application_id = (
+ TeamProvisioningConfig.objects.filter(team_id=team_id).values_list("application_id", flat=True).first()
+ )
+ if owning_application_id is not None and owning_application_id != access_token.application_id:
+ raise SpecError(
+ "forbidden", "Resource owned by a different provisioning partner", resource_id=resource_id, status=403
+ )
+
+ serializer = UpdateServiceSerializer(data=request.data, context={"resource_id": resource_id})
+ if not serializer.is_valid():
+ raise SpecError("invalid_request", first_error_message(serializer.errors), resource_id=resource_id)
+ data = serializer.validated_data
+ service_id = data["service_id"]
+
+ billing_result = try_activate_billing_with_spt(data["payment_credentials"], team, user)
+ has_spt = billing_result is not None
+ if billing_result is False:
+ capture_provisioning_event(
+ "update_service",
+ "error",
+ error_code="billing_activation_failed",
+ service_id=service_id,
+ team_id=team_id,
+ has_spt=has_spt,
+ )
+ raise SpecError(
+ "billing_activation_failed",
+ "Failed to activate billing with payment credentials",
+ resource_id=resource_id,
+ )
+
+ if service_id == PAY_AS_YOU_GO_SERVICE_ID and billing_result is None:
+ capture_provisioning_event(
+ "update_service",
+ "error",
+ error_code="requires_payment_credentials",
+ service_id=service_id,
+ team_id=team_id,
+ )
+ raise SpecError(
+ "requires_payment_credentials", "Payment credentials required for paid plan", resource_id=resource_id
+ )
+
+ set_provisioning_service_id(team, service_id)
+
+ region = get_instance_region() or "US"
+ host = region_to_host(region)
+
+ capture_provisioning_event(
+ "update_service",
+ "success",
+ service_id=service_id,
+ team_id=team_id,
+ has_spt=has_spt,
+ billing_result=str(billing_result),
+ )
+
+ return Response(
+ {
+ "status": "complete",
+ "id": resource_id,
+ "service_id": service_id,
+ "complete": {
+ "access_configuration": {
+ "api_key": team.api_token,
+ "host": host,
+ },
+ },
+ }
+ )
+
+
+class ResourceRemoveView(StripeResourceAPIView):
+ """Detaches the resource from the orchestrator: removes it from the token's
+ scope and clears provisioning metadata. Preserves the underlying team and
+ user data so the customer can still access PostHog directly."""
+
+ @extend_schema(exclude=True)
+ def post(self, request: Request, resource_id: str) -> Response:
+ access_token = cast(OAuthAccessToken, request.auth)
+
+ team_id = self.parse_resource_team_id(resource_id, access_token)
+
+ try:
+ # Clear the mapping only if it is unclaimed or owned by the caller's
+ # application; an in-scope partner must not delete another partner's
+ # provisioning mapping for the same team.
+ # TODO: latent gap - when the config is owned by another application
+ # the delete is silently skipped, yet the team is still stripped
+ # from token scopes and "removed" is returned, so the mapping
+ # survives with no signal to the caller.
+ config = TeamProvisioningConfig.objects.filter(team_id=team_id).first()
+ if config is not None and config.application_id in (None, access_token.application_id):
+ config.delete()
+ except Exception:
+ capture_exception(additional_properties={"team_id": team_id, "step": "remove_provisioning_config"})
+ capture_provisioning_event("resource_removed", "error", team_id=team_id, error_code="remove_config_failed")
+ raise SpecError("remove_failed", "Failed to remove resource", resource_id=resource_id, status=500)
+
+ remove_team_from_token_scopes(access_token, team_id)
+
+ capture_provisioning_event("resource_removed", "success", team_id=team_id)
+
+ return Response({"status": "removed", "id": resource_id})
+
+
+# ---------------------------------------------------------------------------
+# POST /provisioning/deep_links
+# ---------------------------------------------------------------------------
+
+
+class DeepLinksView(StripeResourceAPIView):
+ @extend_schema(exclude=True)
+ def post(self, request: Request) -> Response:
+ access_token = cast(OAuthAccessToken, request.auth)
+
+ serializer = DeepLinkSerializer(data=request.data)
+ if not serializer.is_valid():
+ raise SpecError("invalid_request", first_error_message(serializer.errors))
+ data = serializer.validated_data
+
+ # `purpose` is a free-form label retained for analytics. `path` is the generic
+ # destination: any in-app path the partner wants the user to land on after login.
+ purpose = data["purpose"]
+ path = data["path"]
+ if path and not is_safe_deep_link_path(path):
+ capture_provisioning_event(
+ "deep_link_created", "invalid_path", partner=access_token.application, purpose=purpose
+ )
+ raise SpecError("invalid_path", "path must be a relative in-app path beginning with a single '/'")
+
+ scoped_teams = access_token.scoped_teams or []
+ team_id = scoped_teams[0] if scoped_teams else None
+
+ region = get_instance_region() or "US"
+ host = region_to_host(region)
+
+ token = secrets.token_urlsafe(32)
+ cache.set(
+ f"{DEEP_LINK_CACHE_PREFIX}{token}",
+ {
+ "user_id": access_token.user_id,
+ "team_id": team_id,
+ "purpose": purpose,
+ "path": path or None,
+ },
+ timeout=DEEP_LINK_TTL_SECONDS,
+ )
+
+ expires_at = timezone.now() + timedelta(seconds=DEEP_LINK_TTL_SECONDS)
+
+ url = f"{host}/api/partners/stripe/login?token={token}"
+ if team_id:
+ url += f"&team_id={team_id}"
+
+ capture_provisioning_event(
+ "deep_link_created", "success", partner=access_token.application, purpose=purpose, team_id=team_id
+ )
+
+ return Response(
+ {
+ "purpose": purpose,
+ "url": url,
+ "expires_at": expires_at.isoformat(),
+ }
+ )
diff --git a/ee/urls.py b/ee/urls.py
index 844f4e2a425f..407103abe538 100644
--- a/ee/urls.py
+++ b/ee/urls.py
@@ -275,7 +275,14 @@ urlpatterns: list[Any] = [
name="scim_resource_types",
),
path("scim/v2/<uuid:domain_id>/Schemas", csrf_exempt(scim_views.SCIMSchemasView.as_view()), name="scim_schemas"),
- # Agentic Provisioning Protocol (APP 0.1d)
+ # Stripe Projects provisioning (APP 0.1d) — the namespace the Stripe app
+ # manifest points at (provisioning.base_url = .../api/partners/stripe/)
+ path("api/partners/stripe/", include("ee.partners.stripe.api.provisioning.urls")),
+ # Account Provisioning
+ # TODO(migration): the Stripe-only routes below (health, services,
+ # update_service) and Stripe's use of the rest are served by
+ # /api/partners/stripe/ - remove the Stripe-only ones once Stripe traffic
+ # has fully moved (watch path_namespace on agentic_provisioning events).
path(
"api/agentic/provisioning/health",
csrf_exempt(agentic_provisioning_views.provisioning_health),
@@ -367,6 +374,9 @@ urlpatterns: list[Any] = [
name="agentic_login",
),
# Generic provisioning URL aliases (keep /api/agentic/... for backward compat)
+ # TODO(migration): health, services, and update_service in this block are
+ # Stripe-only — remove them once Stripe traffic has fully moved to
+ # /api/partners/stripe/, unless another partner adopts them.
path(
"api/provisioning/health",
csrf_exempt(agentic_provisioning_views.provisioning_health),
diff --git a/services/stripe-app/package.json b/services/stripe-app/package.json
index f80b1e90582f..ee93f5f20af5 100644
--- a/services/stripe-app/package.json
+++ b/services/stripe-app/package.json
@@ -1,6 +1,6 @@
{
"name": "@posthog/stripe",
- "version": "1.1.0",
+ "version": "1.3.0",
"description": "PostHog Stripe app",
"license": "MIT",
"scripts": {
diff --git a/services/stripe-app/stripe-app.json b/services/stripe-app/stripe-app.json
index 9e88f38fbea4..54106a49f9f0 100644
--- a/services/stripe-app/stripe-app.json
+++ b/services/stripe-app/stripe-app.json
@@ -2,10 +2,10 @@
"$schema": "https://stripe.com/stripe-app.schema.json",
"id": "com.posthog.stripe",
"name": "PostHog",
- "version": "1.2.11",
+ "version": "1.3.0",
"icon": "./assets/logomark.png",
"provisioning": {
- "base_url": "https://us.posthog.com/api/agentic/",
+ "base_url": "https://us.posthog.com/api/partners/stripe/",
"oauth_scopes": [
"query:read",
"project:read",
@@ -14,7 +14,7 @@
"customer_journey:read",
"insight:read"
],
- "oauth_token_endpoint": "https://us.posthog.com/api/agentic/oauth/token",
+ "oauth_token_endpoint": "https://us.posthog.com/api/partners/stripe/oauth/token",
"oauth_client_id": "3pFZtlNOg7UEBtr8t0rBAEbI8E4GBf1YqIC2L4jJ",
"oauth_client_secret_secret_store_key": "oauth_client_secret",
"account_configuration_schema": "{\"type\":\"object\",\"properties\":{\"region\":{\"type\":\"string\",\"enum\":[\"US\",\"EU\"],\"description\":\"Which PostHog region to connect the Stripe account to\"},\"organization_name\":{\"type\":\"string\",\"description\":\"Name for the PostHog organization\"}},\"required\":[\"region\"],\"additionalProperties\":false}",