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(agentic-provisioning): drop stripe-only surface and hmac auth (#73387)

Rafael Audibertb091a97ab29b
diff --git a/ee/api/agentic_provisioning/authentication.py b/ee/api/agentic_provisioning/authentication.py
index efd5f28f01e8..f730098aedae 100644
--- a/ee/api/agentic_provisioning/authentication.py
+++ b/ee/api/agentic_provisioning/authentication.py
@@ -1,7 +1,5 @@
from __future__ import annotations
-import hmac
-import time
import uuid
import hashlib
@@ -26,13 +24,9 @@ from posthog.api.oauth.cimd import (
from posthog.exceptions_capture import capture_exception
from posthog.models.oauth import OAuthApplication, find_oauth_access_token
-from .signature import _compute_hmac, _get_raw_body, _parse_signature_header
-
logger = structlog.get_logger(__name__)
BEARER_PREFIX = "Bearer "
-STRIPE_SIGNATURE_HEADER = "HTTP_STRIPE_SIGNATURE"
-MAX_TIMESTAMP_DRIFT_SECONDS = 300
class ProvisioningAuthentication(BaseAuthentication):
@@ -40,12 +34,12 @@ class ProvisioningAuthentication(BaseAuthentication):
Partners are OAuthApplications with provisioning fields set (provisioning_auth_method
is non-empty). The OAuthApplication handles standard OAuth (tokens, scopes, consent)
- and also stores provisioning config: auth method, signing secret, feature flags
+ and also stores provisioning config: auth method, feature flags
(provisioning_can_create_accounts, provisioning_can_provision_resources), and rate limits.
- Partners are identified from request signals (HMAC header, Bearer token, or
- client_id param) and dispatched to the matching auth strategy. Returns None
- if no partner is identified, allowing legacy HMAC auth to handle the request.
+ Partners are identified from request signals (Bearer token or client_id param)
+ and dispatched to the matching auth strategy. Returns None if no partner is
+ identified.
"""
cimd_registration_pending: bool = False
@@ -56,11 +50,7 @@ class ProvisioningAuthentication(BaseAuthentication):
return None
try:
- if app.provisioning_auth_method == "hmac":
- user = self._verify_hmac(request, app)
- _capture_auth_event(app, "success", endpoint=request.path)
- return (user, app)
- elif app.provisioning_auth_method == "bearer":
+ if app.provisioning_auth_method == "bearer":
user = self._verify_bearer(request, app)
_capture_auth_event(app, "success", endpoint=request.path)
return (user, app)
@@ -76,17 +66,12 @@ class ProvisioningAuthentication(BaseAuthentication):
def _identify_partner(self, request: Request) -> OAuthApplication | None:
app = None
- # 1. Check for HMAC signature header -> look up by signing secret
- if request.META.get(STRIPE_SIGNATURE_HEADER):
- app = self._identify_hmac_partner(request)
-
- # 2. Check for Bearer token -> look up OAuthApplication
- if app is None:
- auth_header = request.META.get("HTTP_AUTHORIZATION", "")
- if auth_header.startswith(BEARER_PREFIX):
- app = self._identify_bearer_partner(auth_header)
+ # 1. Check for Bearer token -> look up OAuthApplication
+ auth_header = request.META.get("HTTP_AUTHORIZATION", "")
+ if auth_header.startswith(BEARER_PREFIX):
+ app = self._identify_bearer_partner(auth_header)
- # 3. Check for client_id in request body (PKCE public clients)
+ # 2. Check for client_id in request body (PKCE public clients)
if app is None:
client_id = request.data.get("client_id") or request.query_params.get("client_id")
if client_id:
@@ -97,32 +82,6 @@ class ProvisioningAuthentication(BaseAuthentication):
return app
- def _identify_hmac_partner(self, request: Request) -> OAuthApplication | None:
- apps = OAuthApplication.objects.filter(
- provisioning_auth_method="hmac",
- provisioning_signing_secret__isnull=False,
- provisioning_active=True,
- )
-
- sig_header = request.META.get(STRIPE_SIGNATURE_HEADER, "")
- parsed = _parse_signature_header(sig_header)
- if parsed is None:
- return None
-
- timestamp_str, signature_hex = parsed
- body = _get_raw_body(request)
- if body is None:
- return None
-
- for app in apps:
- if not app.provisioning_signing_secret:
- continue
- expected = _compute_hmac(app.provisioning_signing_secret, timestamp_str, body)
- if hmac.compare_digest(expected.lower(), signature_hex.lower()):
- return app
-
- return None
-
def _identify_bearer_partner(self, auth_header: str) -> OAuthApplication | None:
token_value = auth_header[len(BEARER_PREFIX) :].strip()
if not token_value:
@@ -198,27 +157,6 @@ class ProvisioningAuthentication(BaseAuthentication):
except OAuthApplication.DoesNotExist:
return None
- def _verify_hmac(self, request: Request, app: OAuthApplication):
- sig_header = request.META.get(STRIPE_SIGNATURE_HEADER, "")
- parsed = _parse_signature_header(sig_header)
- if parsed is None:
- raise AuthenticationFailed("Missing or malformed signature header")
-
- timestamp_str, signature_hex = parsed
- timestamp = int(timestamp_str)
- if abs(int(time.time()) - timestamp) > MAX_TIMESTAMP_DRIFT_SECONDS:
- raise AuthenticationFailed("Timestamp too old or too far in the future")
-
- body = _get_raw_body(request)
- if body is None:
- raise AuthenticationFailed("Unable to read request body for signature verification")
-
- expected = _compute_hmac(app.provisioning_signing_secret, timestamp_str, body)
- if not hmac.compare_digest(expected.lower(), signature_hex.lower()):
- raise AuthenticationFailed("Signature verification failed")
-
- return None
-
def _verify_bearer(self, request: Request, app: OAuthApplication):
auth_header = request.META.get("HTTP_AUTHORIZATION", "")
if not auth_header.startswith(BEARER_PREFIX):
diff --git a/ee/api/agentic_provisioning/region_proxy.py b/ee/api/agentic_provisioning/region_proxy.py
index 4e16a46ff993..55cdad851b45 100644
--- a/ee/api/agentic_provisioning/region_proxy.py
+++ b/ee/api/agentic_provisioning/region_proxy.py
@@ -48,8 +48,6 @@ PROXY_HEADER_ALLOWLIST = frozenset(
{
"content-type",
"accept",
- "stripe-signature",
- "api-version",
"authorization",
"user-agent",
}
@@ -185,8 +183,7 @@ def region_proxy(strategy: str):
# Cache the raw body before any `request.data` access downstream.
# Without this, DRF parses the stream when a strategy check reads
# request.data, then _proxy_to_region raises RawPostDataException
- # when it tries to forward request.body. Previously this was a
- # side effect of verify_stripe_signature running here.
+ # when it tries to forward request.body.
_ = request.body
current = _current_region()
diff --git a/ee/api/agentic_provisioning/signature.py b/ee/api/agentic_provisioning/signature.py
deleted file mode 100644
index dba3abaccb34..000000000000
--- a/ee/api/agentic_provisioning/signature.py
+++ /dev/null
@@ -1,159 +0,0 @@
-# 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
-import hashlib
-
-from django.conf import settings
-from django.http.request import RawPostDataException
-
-import structlog
-import posthoganalytics
-from rest_framework.request import Request
-from rest_framework.response import Response
-
-from posthog.exceptions_capture import capture_exception
-
-logger = structlog.get_logger(__name__)
-
-SUPPORTED_VERSIONS = ["0.1d"]
-API_VERSION = SUPPORTED_VERSIONS[0]
-SIGNATURE_HEADER = "Stripe-Signature"
-API_VERSION_HEADER = "API-Version"
-MAX_TIMESTAMP_DRIFT_SECONDS = 300
-
-
-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:
- endpoint = request.path
- _log_and_capture_event("invalid_api_version", 400, endpoint, 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_provisioning_signature(request: Request) -> Response | None:
- """Verify the Stripe-Signature HMAC.
-
- Returns None if verification passes, or an error Response if it fails.
- Called at the top of every view (Vercel-style, not middleware).
-
- 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. Keeping it
- # out of module scope keeps it off django.setup() (signature.py is reachable from ready() via billing).
- 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."""
- return _compute_hmac(secret, str(timestamp), body)
-
-
-def _compute_hmac(signing_key: str, timestamp_str: str, body: bytes) -> str:
- mac = hmac.new(signing_key.encode(), digestmod=hashlib.sha256)
- mac.update(f"{timestamp_str}.".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)
-
- posthoganalytics.capture(
- "agentic_provisioning signature verification",
- distinct_id=f"agentic_provisioning_{uuid.uuid4().hex[:16]}",
- properties={"outcome": outcome, "status_code": status_code, "endpoint": endpoint, **extra},
- )
-
-
-_SIG_RE = re.compile(r"t=(\d+),v1=([0-9a-fA-F]{64})")
-
-
-def _parse_signature_header(header: str) -> tuple[str, str] | None:
- """Parse 't=<timestamp>,v1=<hex>' into (timestamp_str, hex). Returns None on failure."""
- m = _SIG_RE.search(header)
- if not m:
- return None
- return m.group(1), m.group(2)
diff --git a/ee/api/agentic_provisioning/test/base.py b/ee/api/agentic_provisioning/test/base.py
index a93195948a38..40a996febe67 100644
--- a/ee/api/agentic_provisioning/test/base.py
+++ b/ee/api/agentic_provisioning/test/base.py
@@ -1,131 +1,118 @@
import json
-import time
-from urllib.parse import urlencode
+import base64
+import hashlib
+import secrets
from posthog.test.base import APIBaseTest
from django.core.cache import cache
-from django.test import override_settings
+from django.utils import timezone
from rest_framework.test import APIClient
-from ee.api.agentic_provisioning.signature import compute_signature
from ee.api.agentic_provisioning.views import AUTH_CODE_CACHE_PREFIX
-HMAC_SECRET = "test_hmac_secret"
-TEST_STRIPE_OAUTH_CLIENT_ID = "test_stripe_oauth_client_id"
+TEST_PARTNER_CLIENT_ID = "test_partner_client_id"
+
+# Broad ceiling so token exchanges in tests aren't rejected by the per-app scope cap.
+TEST_PARTNER_SCOPES = [
+ "query:read",
+ "feature_flag:read",
+ "insight:read",
+ "organization:read",
+ "person:read",
+ "project:read",
+ "user:read",
+]
-@override_settings(
- STRIPE_SIGNING_SECRET=HMAC_SECRET,
- STRIPE_POSTHOG_OAUTH_CLIENT_ID=TEST_STRIPE_OAUTH_CLIENT_ID,
-)
class ProvisioningTestBase(APIBaseTest):
def setUp(self):
super().setUp()
self.client = APIClient()
- self._ensure_stripe_oauth_app()
+ self.partner = self._ensure_partner_app()
- def _ensure_stripe_oauth_app(self):
+ def _ensure_partner_app(self):
from posthog.models.oauth import OAuthApplication
- OAuthApplication.objects.get_or_create(
- client_id=TEST_STRIPE_OAUTH_CLIENT_ID,
+ app, _ = OAuthApplication.objects.get_or_create(
+ client_id=TEST_PARTNER_CLIENT_ID,
defaults={
- "name": "PostHog Stripe App",
+ "name": "Test Provisioning Partner",
"client_secret": "",
"client_type": OAuthApplication.CLIENT_CONFIDENTIAL,
"authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,
- "redirect_uris": "https://localhost",
+ "redirect_uris": "https://partner.example.com/callback",
"algorithm": "RS256",
+ "scopes": TEST_PARTNER_SCOPES,
+ "provisioning_auth_method": "bearer",
+ "provisioning_partner_type": "test_partner",
+ "provisioning_active": True,
+ "provisioning_can_create_accounts": True,
+ "provisioning_can_provision_resources": True,
"provisioning_can_issue_deep_links": True,
- # The test app stands in for the grandfathered legacy Stripe app, which is
- # the one app that still mints a provisioned PAT.
+ # Stands in for the one grandfathered app that still mints a provisioned PAT.
"provisioning_issues_personal_api_key": True,
},
)
+ return app
- 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
- ):
+ def _post_api(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_api(self, url: str, **kwargs):
+ return self.client.get(url, **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 _get_with_bearer(self, url: str, token: str, **kwargs):
+ return self._get_api(url, 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 _post_with_bearer(self, url: str, data: dict | None = None, token: str = "", **kwargs):
+ return self._post_api(url, data, HTTP_AUTHORIZATION=f"Bearer {token}", **kwargs)
+
+ def _pkce_pair(self) -> tuple[str, str]:
+ verifier = secrets.token_urlsafe(48)
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()).rstrip(b"=").decode()
+ return verifier, challenge
- def _request_bearer_token(self):
- code = f"test_code_{id(self)}"
+ def _mint_auth_code(self, scopes: list[str] | None = None, partner=None) -> tuple[str, str]:
+ """Seed an auth code in the cache for the test partner. Returns (code, code_verifier)."""
+ partner = partner or self.partner
+ verifier, challenge = self._pkce_pair()
+ code = secrets.token_urlsafe(16)
cache.set(
f"{AUTH_CODE_CACHE_PREFIX}{code}",
{
+ "issued_at": timezone.now().isoformat(),
"user_id": self.user.id,
"org_id": str(self.organization.id),
"team_id": self.team.id,
- "stripe_account_id": "acct_123",
- "scopes": ["query:read"],
+ "partner_id": str(partner.id),
+ "scopes": scopes if scopes is not None else ["query:read"],
"region": "US",
+ "code_challenge": challenge,
+ "code_challenge_method": "S256",
},
timeout=300,
)
- body = urlencode({"grant_type": "authorization_code", "code": code}).encode()
- ts = int(time.time())
- sig = compute_signature(HMAC_SECRET, ts, body)
+ return code, verifier
+
+ def _request_bearer_token(self, scopes: list[str] | None = None, partner=None):
+ code, verifier = self._mint_auth_code(scopes=scopes, partner=partner)
return self.client.post(
"/api/agentic/oauth/token",
- data=body,
- content_type="application/x-www-form-urlencoded",
- headers={"stripe-signature": f"t={ts},v1={sig}", "api-version": "0.1d"},
+ data={"grant_type": "authorization_code", "code": code, "code_verifier": verifier},
)
def _get_bearer_token(self) -> str:
diff --git a/ee/api/agentic_provisioning/test/test_account_requests.py b/ee/api/agentic_provisioning/test/test_account_requests.py
index 45a4923f510d..086ffd126068 100644
--- a/ee/api/agentic_provisioning/test/test_account_requests.py
+++ b/ee/api/agentic_provisioning/test/test_account_requests.py
@@ -1,5 +1,3 @@
-import json
-import time
from datetime import datetime, timedelta
from urllib.parse import parse_qs, urlparse
@@ -19,38 +17,50 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from ee.api.agentic_provisioning import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIX
-from ee.api.agentic_provisioning.signature import compute_signature
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase
+from ee.api.agentic_provisioning.test.base import ProvisioningTestBase
from ee.api.agentic_provisioning.views import _capture_provisioning_event
-HMAC_PARTNER_SECRET = "test_hmac_partner_secret"
+ACCOUNT_REQUESTS_URL = "/api/agentic/provisioning/account_requests"
+VALID_CODE_CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestAccountRequests(ProvisioningTestBase):
def _account_request_payload(self, **overrides):
payload = {
"id": "acctreq_test123",
- "object": "account_request",
"email": "[email protected]",
"scopes": ["query:read", "project:read"],
- "client_capabilities": ["browser"],
- "confirmation_secret": "cs_test_secret",
"expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),
- "orchestrator": {
- "type": "stripe",
- "stripe": {
- "organisation": "org_stripe_123",
- "account": "acct_stripe_456",
- },
- },
}
payload.update(overrides)
return payload
+ def _post_account_request(self, payload, token: str | None = None):
+ return self._post_with_bearer(ACCOUNT_REQUESTS_URL, payload, token=token or self._get_bearer_token())
+
+ def _silent_partner_token_for(self, user: User) -> str:
+ # A skip-consent partner may only mint silently for an existing user when the
+ # bearer token belongs to that same user (see _caller_proved_existing_trust).
+ self.partner.provisioning_skip_existing_user_consent = True
+ self.partner.save(update_fields=["provisioning_skip_existing_user_consent"])
+ token = OAuthAccessToken.objects.create(
+ user=user,
+ application=self.partner,
+ token=f"tok_{user.id}",
+ expires=timezone.now() + timedelta(hours=1),
+ scope="query:read",
+ )
+ return token.token
+
+ def test_no_identified_partner_returns_401(self):
+ res = self._post_api(ACCOUNT_REQUESTS_URL, self._account_request_payload())
+ assert res.status_code == 401
+ data = res.json()
+ assert data["type"] == "error"
+ assert data["error"]["code"] == "unauthorized"
+
def test_new_user_returns_oauth_type_with_code(self):
- payload = self._account_request_payload()
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ res = self._post_account_request(self._account_request_payload())
assert res.status_code == 200
data = res.json()
assert data["id"] == "acctreq_test123"
@@ -60,8 +70,7 @@ class TestAccountRequests(ProvisioningTestBase):
assert User.objects.filter(email="[email protected]").exists()
def test_new_user_creates_org_and_team(self):
- payload = self._account_request_payload()
- self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ self._post_account_request(self._account_request_payload())
user = User.objects.get(email="[email protected]")
assert user.organization is not None
assert user.team is not None
@@ -69,14 +78,12 @@ class TestAccountRequests(ProvisioningTestBase):
def test_new_user_starts_unverified(self):
# Partner-asserted email ownership is not trusted: the user must prove they own
# the inbox before any session is issued (see agentic_login).
- payload = self._account_request_payload()
- self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ self._post_account_request(self._account_request_payload())
user = User.objects.get(email="[email protected]")
assert user.is_email_verified is False
def test_new_user_auth_code_cached_with_issued_at(self):
- payload = self._account_request_payload()
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ res = self._post_account_request(self._account_request_payload())
code = res.json()["oauth"]["code"]
code_data = cache.get(f"{AUTH_CODE_CACHE_PREFIX}{code}")
assert code_data is not None
@@ -85,92 +92,55 @@ class TestAccountRequests(ProvisioningTestBase):
assert "issued_at" in code_data
datetime.fromisoformat(code_data["issued_at"])
- def test_existing_user_returns_oauth_type_with_code(self):
- User.objects.create_and_join(
- organization=self.organization, email="[email protected]", password="testpass", first_name="Existing"
- )
- payload = self._account_request_payload(email="[email protected]")
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
- assert res.status_code == 200
- data = res.json()
- assert data["id"] == "acctreq_test123"
- assert data["type"] == "oauth"
- assert "code" in data["oauth"]
-
def test_existing_user_auth_code_cached_with_team(self):
- User.objects.create_and_join(
- organization=self.organization, email="[email protected]", password="testpass", first_name="Existing"
- )
- payload = self._account_request_payload(email="[email protected]")
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ token = self._silent_partner_token_for(self.user)
+ res = self._post_account_request(self._account_request_payload(email=self.user.email), token=token)
+ assert res.status_code == 200
+ assert res.json()["type"] == "oauth"
code = res.json()["oauth"]["code"]
code_data = cache.get(f"{AUTH_CODE_CACHE_PREFIX}{code}")
assert code_data is not None
- assert code_data["stripe_account_id"] == "acct_stripe_456"
assert code_data["team_id"] == self.team.id
assert code_data["region"] == "US"
+ assert code_data["partner_id"] == str(self.partner.id)
def test_existing_user_with_requested_team_id(self):
- user = User.objects.create_and_join(
- organization=self.organization, email="[email protected]", password="testpass", first_name="Existing"
- )
- second_team = Team.objects.create_with_data(initiating_user=user, organization=self.organization)
- payload = self._account_request_payload(
- configuration={"team_id": second_team.id},
- )
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ token = self._silent_partner_token_for(self.user)
+ second_team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)
+ payload = self._account_request_payload(email=self.user.email, configuration={"team_id": second_team.id})
+ res = self._post_account_request(payload, token=token)
assert res.status_code == 200
code = res.json()["oauth"]["code"]
code_data = cache.get(f"{AUTH_CODE_CACHE_PREFIX}{code}")
assert code_data["team_id"] == second_team.id
- def test_existing_user_with_invalid_team_id_returns_400(self):
- User.objects.create_and_join(
- organization=self.organization, email="[email protected]", password="testpass", first_name="Existing"
- )
- payload = self._account_request_payload(
- configuration={"team_id": 999999},
- )
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
- assert res.status_code == 400
- assert res.json()["error"]["code"] == "team_resolution_failed"
-
- def test_existing_user_with_non_numeric_team_id_returns_400(self):
- User.objects.create_and_join(
- organization=self.organization, email="[email protected]", password="testpass", first_name="Existing"
- )
- payload = self._account_request_payload(
- configuration={"team_id": "abc"},
- )
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ @parameterized.expand(
+ [
+ ("nonexistent", 999999, "team_resolution_failed"),
+ ("non_numeric", "abc", "invalid_request"),
+ ]
+ )
+ def test_existing_user_with_bad_team_id_returns_400(self, _name, team_id, expected_code):
+ token = self._silent_partner_token_for(self.user)
+ payload = self._account_request_payload(email=self.user.email, configuration={"team_id": team_id})
+ res = self._post_account_request(payload, token=token)
assert res.status_code == 400
- assert res.json()["error"]["code"] == "invalid_request"
+ assert res.json()["error"]["code"] == expected_code
def test_existing_user_with_inaccessible_team_id_returns_400(self):
- User.objects.create_and_join(
- organization=self.organization, email="[email protected]", password="testpass", first_name="Existing"
- )
+ token = self._silent_partner_token_for(self.user)
other_org = Organization.objects.create(name="Other Org")
other_team = Team.objects.create(organization=other_org, name="Other Team")
- payload = self._account_request_payload(
- configuration={"team_id": other_team.id},
- )
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ payload = self._account_request_payload(email=self.user.email, configuration={"team_id": other_team.id})
+ res = self._post_account_request(payload, token=token)
assert res.status_code == 400
assert res.json()["error"]["code"] == "team_resolution_failed"
def test_existing_user_multi_team_creates_new_project(self):
- user = User.objects.create_and_join(
- organization=self.organization, email="[email protected]", password="testpass", first_name="Existing"
- )
- Team.objects.create_with_data(initiating_user=user, organization=self.organization)
+ token = self._silent_partner_token_for(self.user)
+ Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)
team_count_before = Team.objects.filter(organization=self.organization, is_demo=False).count()
- payload = self._account_request_payload(email="[email protected]")
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ res = self._post_account_request(self._account_request_payload(email=self.user.email), token=token)
assert res.status_code == 200
assert res.json()["type"] == "oauth"
team_count_after = Team.objects.filter(organization=self.organization, is_demo=False).count()
@@ -178,118 +148,79 @@ class TestAccountRequests(ProvisioningTestBase):
def test_expired_request_returns_400(self):
payload = self._account_request_payload(expires_at=(timezone.now() - timedelta(minutes=1)).isoformat())
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ res = self._post_account_request(payload)
assert res.status_code == 400
assert res.json()["type"] == "error"
def test_missing_email_returns_400(self):
payload = self._account_request_payload()
del payload["email"]
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
- assert res.status_code == 400
-
- def test_missing_stripe_account_returns_400(self):
- payload = self._account_request_payload()
- del payload["orchestrator"]
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ res = self._post_account_request(payload)
assert res.status_code == 400
- assert res.json()["error"]["code"] == "invalid_request"
-
- def test_invalid_signature_returns_401(self):
- payload = self._account_request_payload()
- res = self.client.post(
- "/api/agentic/provisioning/account_requests",
- data=payload,
- content_type="application/json",
- headers={"api-version": "0.1d"},
- )
- assert res.status_code == 401
def test_new_user_with_name(self):
- payload = self._account_request_payload(name="Jane Doe", email="[email protected]")
- self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ self._post_account_request(self._account_request_payload(name="Jane Doe", email="[email protected]"))
user = User.objects.get(email="[email protected]")
assert user.first_name == "Jane"
@parameterized.expand(
[
("with_name", {"region": "US", "organization_name": "Acme Corp"}, "Acme Corp"),
- ("without_name", {"region": "US"}, "Stripe ([email protected])"),
+ ("without_name", {"region": "US"}, "Test_partner ([email protected])"),
]
)
def test_new_user_organization_name(self, _name, config, expected_org_name):
- payload = self._account_request_payload(email="[email protected]", configuration=config)
- self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ self._post_account_request(self._account_request_payload(email="[email protected]", configuration=config))
user = User.objects.get(email="[email protected]")
org = user.organization
assert org is not None
assert org.name == expected_org_name
- @override_settings(CLOUD_DEPLOYMENT="US")
+ @parameterized.expand(
+ [
+ ("us_instance_eu_region", "US", "EU", "eu.posthog.com"),
+ ("eu_instance_us_region", "EU", "US", "us.posthog.com"),
+ ]
+ )
@patch("ee.api.agentic_provisioning.region_proxy._proxy_to_region")
- def test_region_mismatch_proxies_to_other_region(self, mock_proxy):
+ def test_region_mismatch_proxies_to_other_region(self, _name, deployment, region, expected_host, mock_proxy):
mock_proxy.return_value = Response({"type": "oauth", "oauth": {"code": "proxied"}})
- payload = self._account_request_payload(configuration={"region": "EU"})
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ payload = self._account_request_payload(configuration={"region": region})
+ with override_settings(CLOUD_DEPLOYMENT=deployment):
+ res = self._post_account_request(payload)
assert res.status_code == 200
mock_proxy.assert_called_once()
- args = mock_proxy.call_args
- assert args[0][1] == "eu.posthog.com"
+ assert mock_proxy.call_args[0][1] == expected_host
@override_settings(CLOUD_DEPLOYMENT="US")
def test_matching_region_succeeds(self):
payload = self._account_request_payload(configuration={"region": "US"})
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ res = self._post_account_request(payload)
assert res.status_code == 200
assert res.json()["type"] == "oauth"
- @override_settings(CLOUD_DEPLOYMENT="EU")
- @patch("ee.api.agentic_provisioning.region_proxy._proxy_to_region")
- def test_eu_instance_proxies_us_region(self, mock_proxy):
- mock_proxy.return_value = Response({"type": "oauth", "oauth": {"code": "proxied"}})
- payload = self._account_request_payload(configuration={"region": "US"})
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
- assert res.status_code == 200
- mock_proxy.assert_called_once()
- args = mock_proxy.call_args
- assert args[0][1] == "us.posthog.com"
-
- def test_no_region_defaults_to_us_and_succeeds(self):
- payload = self._account_request_payload()
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
- assert res.status_code == 200
-
@patch("ee.api.agentic_provisioning.views.User.objects.bootstrap", side_effect=IntegrityError)
def test_integrity_error_with_existing_user_falls_back(self, _mock_bootstrap):
User.objects.create_and_join(
organization=self.organization, email="[email protected]", password="testpass", first_name="Race"
)
- payload = self._account_request_payload(email="[email protected]")
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ payload = self._account_request_payload(email="[email protected]", code_challenge=VALID_CODE_CHALLENGE)
+ res = self._post_account_request(payload)
assert res.status_code == 200
- assert res.json()["type"] == "oauth"
+ # The race fell back to the existing-user path; without trust proof for that user
+ # the partner is sent through consent rather than getting a silent code.
+ assert res.json()["type"] == "requires_auth"
@patch("ee.api.agentic_provisioning.views.User.objects.bootstrap", side_effect=IntegrityError)
def test_integrity_error_without_existing_user_returns_500(self, _mock_bootstrap):
payload = self._account_request_payload(email="[email protected]")
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ res = self._post_account_request(payload)
assert res.status_code == 500
assert res.json()["error"]["code"] == "account_creation_failed"
- def test_hmac_partner_existing_user_still_gets_direct_code(self):
- User.objects.create_and_join(
- organization=self.organization, email="[email protected]", password="testpass", first_name="Existing"
- )
- payload = self._account_request_payload(email="[email protected]")
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
- assert res.status_code == 200
- assert res.json()["type"] == "oauth"
- assert "code" in res.json()["oauth"]
-
@patch("ee.api.agentic_provisioning.views._capture_provisioning_event")
def test_new_user_capture_includes_team_id(self, mock_capture_event):
- payload = self._account_request_payload(email="[email protected]")
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ res = self._post_account_request(self._account_request_payload(email="[email protected]"))
assert res.status_code == 200
user = User.objects.get(email="[email protected]")
@@ -302,24 +233,9 @@ class TestAccountRequests(ProvisioningTestBase):
assert len(new_user_calls) == 1
kwargs = new_user_calls[0].kwargs
assert kwargs["team_id"] == team.id
- # Stripe HMAC path has no OAuthApplication partner, so there's no client to attribute.
- assert kwargs["partner"] is None
+ assert kwargs["partner"] == self.partner
- @patch("ee.api.agentic_provisioning.views.report_user_signed_up")
- def test_new_user_emits_signup_event(self, mock_signup):
- payload = self._account_request_payload(email="[email protected]")
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
- assert res.status_code == 200
- assert mock_signup.call_count == 1
- kwargs = mock_signup.call_args.kwargs
- assert kwargs["backend_processor"] == "AgenticProvisioning"
- assert kwargs["is_organization_first_user"] is True
- # Stripe HMAC path has no OAuthApplication, so no client name.
- assert kwargs["social_provider"] == ""
-
-
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestPKCEPartnerExistingUserConsent(ProvisioningTestBase):
def setUp(self):
super().setUp()
@@ -340,13 +256,7 @@ class TestPKCEPartnerExistingUserConsent(ProvisioningTestBase):
)
def _post_as_pkce_partner(self, data: dict):
- body = json.dumps(data).encode()
- return self.client.post(
- "/api/agentic/provisioning/account_requests",
- data=body,
- content_type="application/json",
- HTTP_API_VERSION="0.1d",
- )
+ return self._post_api(ACCOUNT_REQUESTS_URL, data)
def _account_request_payload(self, **overrides):
payload = {
@@ -354,11 +264,9 @@ class TestPKCEPartnerExistingUserConsent(ProvisioningTestBase):
"email": "[email protected]",
"scopes": ["query:read"],
"client_id": "pkce-test-partner",
- "confirmation_secret": "cs_test",
- "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
+ "code_challenge": VALID_CODE_CHALLENGE,
"code_challenge_method": "S256",
"expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),
- "orchestrator": {"type": "test", "account": "acct_123"},
}
payload.update(overrides)
return payload
@@ -488,14 +396,13 @@ class TestPKCEPartnerExistingUserConsent(ProvisioningTestBase):
assert "code_challenge" in res.json()["error"]["message"]
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestSilentRemintRequiresTrustProof(ProvisioningTestBase):
"""A partner with skip_existing_user_consent=True can only mint silently for an
existing user when the caller proved a prior trust relationship with that user
- (live partner credential for HMAC, the user's own token for bearer). Otherwise
- the consent screen is required. This holds whether or not the user has reviewed
- their credentials: an unreviewed account is still a pre-existing account that a
- caller must not be able to silently link."""
+ (a bearer token belonging to that user). Otherwise the consent screen is
+ required. This holds whether or not the user has reviewed their credentials:
+ an unreviewed account is still a pre-existing account that a caller must not
+ be able to silently link."""
def setUp(self):
super().setUp()
@@ -531,23 +438,6 @@ class TestSilentRemintRequiresTrustProof(ProvisioningTestBase):
provisioning_can_provision_resources=True,
provisioning_skip_existing_user_consent=True,
)
- self.hmac_partner = OAuthApplication.objects.create(
- client_id="hmac-partner",
- name="HMAC Partner",
- client_secret="",
- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="https://hmac.example.com/callback",
- algorithm="RS256",
- is_first_party=True,
- provisioning_auth_method="hmac",
- provisioning_signing_secret=HMAC_PARTNER_SECRET,
- provisioning_partner_type="test_partner",
- provisioning_active=True,
- provisioning_can_create_accounts=True,
- provisioning_can_provision_resources=True,
- provisioning_skip_existing_user_consent=True,
- )
self.bearer_partner = OAuthApplication.objects.create(
client_id="bearer-partner",
name="Bearer Partner",
@@ -566,47 +456,19 @@ class TestSilentRemintRequiresTrustProof(ProvisioningTestBase):
)
def _post_as_partner(self, data: dict, client_id: str = "silent-partner"):
- payload = {**data, "client_id": client_id}
- body = json.dumps(payload).encode()
- return self.client.post(
- "/api/agentic/provisioning/account_requests",
- data=body,
- content_type="application/json",
- HTTP_API_VERSION="0.1d",
- )
-
- def _post_as_hmac_partner(self, data: dict):
- body = json.dumps(data).encode()
- ts = int(time.time())
- sig = compute_signature(HMAC_PARTNER_SECRET, ts, body)
- return self.client.post(
- "/api/agentic/provisioning/account_requests",
- data=body,
- content_type="application/json",
- HTTP_STRIPE_SIGNATURE=f"t={ts},v1={sig}",
- HTTP_API_VERSION="0.1d",
- )
+ return self._post_api(ACCOUNT_REQUESTS_URL, {**data, "client_id": client_id})
def _post_as_bearer_partner(self, data: dict, token: str):
- body = json.dumps(data).encode()
- return self.client.post(
- "/api/agentic/provisioning/account_requests",
- data=body,
- content_type="application/json",
- HTTP_AUTHORIZATION=f"Bearer {token}",
- HTTP_API_VERSION="0.1d",
- )
+ return self._post_with_bearer(ACCOUNT_REQUESTS_URL, data, token=token)
def _account_request_payload(self, **overrides):
payload = {
"id": "acctreq_silent_test",
"email": "[email protected]",
"scopes": ["query:read"],
- "confirmation_secret": "cs_test",
- "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
+ "code_challenge": VALID_CODE_CHALLENGE,
"code_challenge_method": "S256",
"expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),
- "orchestrator": {"type": "test", "account": "acct_123"},
}
payload.update(overrides)
return payload
@@ -631,14 +493,6 @@ class TestSilentRemintRequiresTrustProof(ProvisioningTestBase):
scope="query:read",
)
- def _make_live_refresh_token(self, user: User, partner: OAuthApplication) -> OAuthRefreshToken:
- return OAuthRefreshToken.objects.create(
- user=user,
- application=partner,
- token=f"rtok_{user.id}_{partner.id}",
- revoked=None,
- )
-
def _make_revoked_refresh_token(self, user: User, partner: OAuthApplication) -> OAuthRefreshToken:
return OAuthRefreshToken.objects.create(
user=user,
@@ -658,23 +512,6 @@ class TestSilentRemintRequiresTrustProof(ProvisioningTestBase):
assert data["type"] == "requires_auth"
assert "oauth" not in data
- @parameterized.expand(
- [
- ("live_access_token", lambda self, user: self._make_live_access_token(user, self.hmac_partner)),
- ("live_refresh_token", lambda self, user: self._make_live_refresh_token(user, self.hmac_partner)),
- ]
- )
- def test_reviewed_user_with_live_credential_from_authenticated_caller_silent_still_works(
- self, _name, setup_credential
- ):
- user = self._make_user(credentials_reviewed=True)
- setup_credential(self, user)
- res = self._post_as_hmac_partner(self._account_request_payload())
- assert res.status_code == 200
- data = res.json()
- assert data["type"] == "oauth"
- assert "code" in data["oauth"]
-
@parameterized.expand([("reviewed", True), ("unreviewed", False)])
def test_pkce_caller_with_live_credential_requires_consent(self, _name, reviewed):
# A public PKCE caller is unauthenticated, so an existing live credential for the
@@ -715,15 +552,6 @@ class TestSilentRemintRequiresTrustProof(ProvisioningTestBase):
assert pending is not None
assert pending["partner_id"] == str(self.partner.id)
- def _mint_bearer_token(self, user: User, partner: OAuthApplication, raw_token: str) -> None:
- OAuthAccessToken.objects.create(
- user=user,
- application=partner,
- token=raw_token,
- expires=timezone.now() + timedelta(hours=1),
- scope="query:read",
- )
-
@parameterized.expand([("reviewed", True), ("unreviewed", False)])
def test_bearer_caller_cannot_remint_for_other_user(self, _name, reviewed):
# A bearer token only proves the caller holds *some* user's token under the partner's
@@ -739,9 +567,9 @@ class TestSilentRemintRequiresTrustProof(ProvisioningTestBase):
password="testpass",
first_name="Attacker",
)
- self._mint_bearer_token(attacker, self.bearer_partner, "attacker_bearer_token")
+ attacker_token = self._make_live_access_token(attacker, self.bearer_partner).token
- res = self._post_as_bearer_partner(self._account_request_payload(), token="attacker_bearer_token")
+ res = self._post_as_bearer_partner(self._account_request_payload(), token=attacker_token)
assert res.status_code == 200
data = res.json()
assert data["type"] == "requires_auth"
@@ -752,40 +580,15 @@ class TestSilentRemintRequiresTrustProof(ProvisioningTestBase):
# The legitimate bearer re-link path: the caller presents the user's own token, which
# is genuine proof of an existing trust relationship, so it stays silent in either state.
user = self._make_user(credentials_reviewed=reviewed)
- self._mint_bearer_token(user, self.bearer_partner, "owner_bearer_token")
-
- res = self._post_as_bearer_partner(self._account_request_payload(), token="owner_bearer_token")
- assert res.status_code == 200
- data = res.json()
- assert data["type"] == "oauth"
- assert "code" in data["oauth"]
+ token = self._make_live_access_token(user, self.bearer_partner).token
- @parameterized.expand([("reviewed", True), ("unreviewed", False)])
- def test_hmac_first_link_existing_user_requires_consent(self, _name, reviewed):
- # HMAC proof is "the partner already holds a live credential for this user". On a first
- # link there is none, so even a trusted HMAC partner must get consent before linking a
- # pre-existing account, regardless of review state.
- self._make_user(credentials_reviewed=reviewed)
- res = self._post_as_hmac_partner(self._account_request_payload())
- assert res.status_code == 200
- data = res.json()
- assert data["type"] == "requires_auth"
- assert "oauth" not in data
-
- @parameterized.expand([("reviewed", True), ("unreviewed", False)])
- def test_hmac_relink_existing_user_with_live_credential_silent(self, _name, reviewed):
- # Genuine HMAC re-link: the partner holds a live credential for the user, so it may
- # mint silently whether or not the user has reviewed credentials.
- user = self._make_user(credentials_reviewed=reviewed)
- self._make_live_access_token(user, self.hmac_partner)
- res = self._post_as_hmac_partner(self._account_request_payload())
+ res = self._post_as_bearer_partner(self._account_request_payload(), token=token)
assert res.status_code == 200
data = res.json()
assert data["type"] == "oauth"
assert "code" in data["oauth"]
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestCaptureProvisioningEvent(ProvisioningTestBase):
def _make_partner(self, partner_type: str = "test_partner") -> OAuthApplication:
return OAuthApplication.objects.create(
diff --git a/ee/api/agentic_provisioning/test/test_account_requests_wizard.py b/ee/api/agentic_provisioning/test/test_account_requests_wizard.py
index e208561c627c..626a91d155f2 100644
--- a/ee/api/agentic_provisioning/test/test_account_requests_wizard.py
+++ b/ee/api/agentic_provisioning/test/test_account_requests_wizard.py
@@ -7,12 +7,12 @@ from django.test import override_settings
from django.utils import timezone
from posthog.models.integration import GitHubInstallationAccess, GitHubIntegration, GitHubUserAuthorization
-from posthog.models.oauth import OAuthApplication
from posthog.models.user import OnboardingSkippedReason, User
from ee.api.agentic_provisioning import GITHUB_GRANT_CACHE_PREFIX, github_grants
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase
+from ee.api.agentic_provisioning.test.base import ProvisioningTestBase
+ACCOUNT_REQUESTS_URL = "/api/agentic/provisioning/account_requests"
INSTALLATION_ID = "777"
CODE_CHALLENGE = "a" * 43
@@ -38,23 +38,6 @@ def _installation_access() -> GitHubInstallationAccess:
@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")
class TestAccountRequestsWizardBlock(ProvisioningTestBase):
- def setUp(self):
- super().setUp()
- self.partner = OAuthApplication.objects.create(
- name="Drop Partner",
- client_id="drop_partner_client_id",
- client_secret="",
- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="https://posthog.com/api/wizard/oauth-callback",
- algorithm="RS256",
- provisioning_auth_method="hmac",
- provisioning_signing_secret=HMAC_SECRET,
- provisioning_partner_type="posthog_website",
- provisioning_active=True,
- provisioning_can_create_accounts=True,
- )
-
def _payload(self, email: str, wizard: dict | None = None) -> dict:
configuration: dict = {"region": "US"}
if wizard is not None:
@@ -70,7 +53,7 @@ class TestAccountRequestsWizardBlock(ProvisioningTestBase):
return github_grants.create_grant(self.partner, AUTHORIZATION, email)
def _post(self, payload: dict):
- return self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ return self._post_with_bearer(ACCOUNT_REQUESTS_URL, payload, token=self._get_bearer_token())
def test_without_wizard_block_response_and_email_unchanged(self):
with patch("ee.api.agentic_provisioning.views.send_provisioning_welcome") as mock_email:
diff --git a/ee/api/agentic_provisioning/test/test_authorize.py b/ee/api/agentic_provisioning/test/test_authorize.py
index 83a5fc7c241b..7946c94d423e 100644
--- a/ee/api/agentic_provisioning/test/test_authorize.py
+++ b/ee/api/agentic_provisioning/test/test_authorize.py
@@ -1,12 +1,8 @@
-import json
-import time
from urllib.parse import quote
-from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.core.cache import cache
-from django.test import override_settings
from parameterized import parameterized
@@ -15,24 +11,47 @@ from posthog.models.oauth import OAuthApplication
from posthog.models.user import User
from ee.api.agentic_provisioning import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIX
-from ee.api.agentic_provisioning.signature import compute_signature
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, TEST_STRIPE_OAUTH_CLIENT_ID
+from ee.api.agentic_provisioning.test.base import TEST_PARTNER_SCOPES, ProvisioningTestBase
-DUMMY_CALLBACK = "https://marketplace.stripe.com/oauth/callback"
+PARTNER_CALLBACK = "https://partner.example.com/callback"
-@override_settings(STRIPE_ORCHESTRATOR_CALLBACK_URL=DUMMY_CALLBACK)
-class TestAgenticAuthorize(APIBaseTest):
- def _set_pending_auth(self, state: str, email: str, **extra):
+class AuthorizeTestBase(ProvisioningTestBase):
+ def setUp(self):
+ super().setUp()
+ self.client.force_login(self.user)
+
+ def _set_pending_auth(self, state: str, email: str, partner: OAuthApplication | None = None, **extra):
+ partner = partner or self.partner
data = {
"email": email,
"scopes": ["query:read", "project:read"],
- "stripe_account_id": "acct_123",
+ "partner_id": str(partner.id),
+ "partner_name": partner.name,
"region": "US",
**extra,
}
cache.set(f"{PENDING_AUTH_CACHE_PREFIX}{state}", data, timeout=600)
+ def _make_skip_consent_partner(self) -> OAuthApplication:
+ return OAuthApplication.objects.create(
+ client_id="authorize-skip-consent-partner",
+ name="Skip Consent Partner",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris=PARTNER_CALLBACK,
+ algorithm="RS256",
+ is_first_party=True,
+ scopes=TEST_PARTNER_SCOPES,
+ provisioning_auth_method="bearer",
+ provisioning_partner_type="test_partner",
+ provisioning_active=True,
+ provisioning_skip_existing_user_consent=True,
+ )
+
+
+class TestAgenticAuthorize(AuthorizeTestBase):
def test_requires_login(self):
self.client.logout()
res = self.client.get("/api/agentic/authorize?state=test_state")
@@ -59,22 +78,15 @@ class TestAgenticAuthorize(APIBaseTest):
assert "partner_name=Test+Partner" in res["Location"]
assert "state=state_mismatch" in res["Location"]
- def test_redirects_to_callback_with_code(self):
- self._set_pending_auth("state_ok", self.user.email)
+ def test_trusted_partner_auto_redirects_with_code(self):
+ partner = self._make_skip_consent_partner()
+ self._set_pending_auth("state_ok", self.user.email, partner=partner, consent_required=False)
res = self.client.get("/api/agentic/authorize?state=state_ok")
assert res.status_code == 302
- assert res["Location"].startswith(DUMMY_CALLBACK)
+ assert res["Location"].startswith(PARTNER_CALLBACK)
assert "code=" in res["Location"]
assert "state=state_ok" in res["Location"]
- def test_pending_auth_deleted_after_use(self):
- self._set_pending_auth("state_once", self.user.email)
- self.client.get("/api/agentic/authorize?state=state_once")
- assert cache.get(f"{PENDING_AUTH_CACHE_PREFIX}state_once") is None
-
- def test_auth_code_created_in_cache(self):
- self._set_pending_auth("state_code", self.user.email)
- res = self.client.get("/api/agentic/authorize?state=state_code")
code = res["Location"].split("code=")[1].split("&")[0]
code_data = cache.get(f"{AUTH_CODE_CACHE_PREFIX}{code}")
assert code_data is not None
@@ -82,22 +94,8 @@ class TestAgenticAuthorize(APIBaseTest):
assert code_data["org_id"] == str(self.team.organization.id)
assert code_data["team_id"] == self.team.id
assert code_data["scopes"] == ["query:read", "project:read"]
-
- def _make_skip_consent_partner(self) -> OAuthApplication:
- return OAuthApplication.objects.create(
- client_id="authorize-skip-consent-partner",
- name="Skip Consent Partner",
- client_secret="",
- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="https://partner.example.com/callback",
- algorithm="RS256",
- is_first_party=True,
- provisioning_auth_method="hmac",
- provisioning_partner_type="test_partner",
- provisioning_active=True,
- provisioning_skip_existing_user_consent=True,
- )
+ assert code_data["partner_id"] == str(partner.id)
+ assert cache.get(f"{PENDING_AUTH_CACHE_PREFIX}state_ok") is None
@parameterized.expand(
[
@@ -112,50 +110,49 @@ class TestAgenticAuthorize(APIBaseTest):
def test_skip_consent_partner_not_auto_approved(self, name, extra):
partner = self._make_skip_consent_partner()
state = f"state_{name}"
- self._set_pending_auth(
- state,
- self.user.email,
- partner_id=str(partner.id),
- partner_name=partner.name,
- **extra,
- )
+ self._set_pending_auth(state, self.user.email, partner=partner, **extra)
res = self.client.get(f"/api/agentic/authorize?state={state}")
assert res.status_code == 302
assert "/agentic/authorize?" in res["Location"]
- assert not res["Location"].startswith("https://partner.example.com/callback")
+ assert not res["Location"].startswith(PARTNER_CALLBACK)
assert "code=" not in res["Location"]
assert cache.get(f"{PENDING_AUTH_CACHE_PREFIX}{state}") is not None
- @override_settings(
- STRIPE_SIGNING_SECRET=HMAC_SECRET,
- STRIPE_POSTHOG_OAUTH_CLIENT_ID=TEST_STRIPE_OAUTH_CLIENT_ID,
- )
- def test_full_a1_flow_with_token_exchange(self):
- # The token exchange resolves the legacy Stripe OAuth app by client_id and now
- # hard-fails if it's missing, so the e2e flow needs the app row to exist.
- OAuthApplication.objects.create(
- name="PostHog Stripe App",
- client_id=TEST_STRIPE_OAUTH_CLIENT_ID,
- client_secret="",
- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="https://localhost",
- algorithm="RS256",
+ def test_pending_state_without_partner_not_auto_trusted(self):
+ self._set_pending_auth("state_no_partner", self.user.email, partner_id="", partner_name="")
+ res = self.client.get("/api/agentic/authorize?state=state_no_partner")
+ assert res.status_code == 302
+ assert "/agentic/authorize?" in res["Location"]
+ assert "code=" not in res["Location"]
+ assert cache.get(f"{PENDING_AUTH_CACHE_PREFIX}state_no_partner") is not None
+
+ def test_user_without_org_redirects_with_error(self):
+ orphan = User.objects.create(email="[email protected]", first_name="Orphan")
+ self.client.force_login(orphan)
+ self._set_pending_auth("state_no_org", "[email protected]", scopes=[])
+ res = self.client.get("/api/agentic/authorize?state=state_no_org")
+ assert res.status_code == 302
+ assert "error=no_organization" in res["Location"]
+
+ def test_full_authorize_flow_with_token_exchange(self):
+ partner = self._make_skip_consent_partner()
+ verifier, challenge = self._pkce_pair()
+ self._set_pending_auth(
+ "state_e2e",
+ self.user.email,
+ partner=partner,
+ consent_required=False,
+ code_challenge=challenge,
+ code_challenge_method="S256",
)
- self._set_pending_auth("state_e2e", self.user.email)
res = self.client.get("/api/agentic/authorize?state=state_e2e")
assert res.status_code == 302
code = res["Location"].split("code=")[1].split("&")[0]
- body = json.dumps({"grant_type": "authorization_code", "code": code}).encode()
- ts = int(time.time())
- sig = compute_signature(HMAC_SECRET, ts, body)
- token_res = self.client.post(
+ token_res = self._post_api(
"/api/agentic/oauth/token",
- data=body,
- content_type="application/json",
- headers={"stripe-signature": f"t={ts},v1={sig}", "api-version": "0.1d"},
+ {"grant_type": "authorization_code", "code": code, "code_verifier": verifier},
)
assert token_res.status_code == 200
data = token_res.json()
@@ -164,25 +161,14 @@ class TestAgenticAuthorize(APIBaseTest):
assert data["token_type"] == "bearer"
-class AgenticAuthorizeMultiOrgBase(APIBaseTest):
+class AgenticAuthorizeMultiOrgBase(AuthorizeTestBase):
def setUp(self):
super().setUp()
self.org2 = Organization.objects.create(name="Second Org")
OrganizationMembership.objects.create(user=self.user, organization=self.org2, level=15)
self.team2 = Team.objects.create(organization=self.org2, name="Second Project", api_token="token_2")
- def _set_pending_auth(self, state: str, email: str, **extra):
- data = {
- "email": email,
- "scopes": ["query:read", "project:read"],
- "stripe_account_id": "acct_123",
- "region": "US",
- **extra,
- }
- cache.set(f"{PENDING_AUTH_CACHE_PREFIX}{state}", data, timeout=600)
-
-@override_settings(STRIPE_ORCHESTRATOR_CALLBACK_URL=DUMMY_CALLBACK)
class TestAgenticAuthorizeMultiOrg(AgenticAuthorizeMultiOrgBase):
def test_multi_org_redirects_to_spa(self):
self._set_pending_auth("state_multi", self.user.email)
@@ -197,18 +183,16 @@ class TestAgenticAuthorizeMultiOrg(AgenticAuthorizeMultiOrgBase):
assert cache.get(f"{PENDING_AUTH_CACHE_PREFIX}state_preserve") is not None
-@override_settings(STRIPE_ORCHESTRATOR_CALLBACK_URL=DUMMY_CALLBACK)
class TestAgenticAuthorizeConfirm(AgenticAuthorizeMultiOrgBase):
+ def _confirm(self, state: str, team_id):
+ return self._post_api("/api/agentic/authorize/confirm/", {"state": state, "team_id": team_id})
+
def test_confirm_creates_auth_code_for_selected_team(self):
self._set_pending_auth("state_confirm", self.user.email)
- res = self.client.post(
- "/api/agentic/authorize/confirm/",
- {"state": "state_confirm", "team_id": self.team2.id},
- content_type="application/json",
- )
+ res = self._confirm("state_confirm", self.team2.id)
assert res.status_code == 200
data = res.json()
- assert data["redirect_url"].startswith(DUMMY_CALLBACK)
+ assert data["redirect_url"].startswith(PARTNER_CALLBACK)
assert "code=" in data["redirect_url"]
assert "state=state_confirm" in data["redirect_url"]
@@ -219,11 +203,7 @@ class TestAgenticAuthorizeConfirm(AgenticAuthorizeMultiOrgBase):
def test_confirm_consumes_pending_state(self):
self._set_pending_auth("state_consume", self.user.email)
- self.client.post(
- "/api/agentic/authorize/confirm/",
- {"state": "state_consume", "team_id": self.team.id},
- content_type="application/json",
- )
+ self._confirm("state_consume", self.team.id)
assert cache.get(f"{PENDING_AUTH_CACHE_PREFIX}state_consume") is None
@patch("ee.api.agentic_provisioning.views._capture_provisioning_event")
@@ -234,18 +214,14 @@ class TestAgenticAuthorizeConfirm(AgenticAuthorizeMultiOrgBase):
client_secret="",
client_type=OAuthApplication.CLIENT_PUBLIC,
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris=DUMMY_CALLBACK,
+ redirect_uris=PARTNER_CALLBACK,
algorithm="RS256",
provisioning_auth_method="pkce",
provisioning_partner_type="test_partner",
provisioning_active=True,
)
- self._set_pending_auth("state_attr", self.user.email, partner_id=str(partner.id), partner_name=partner.name)
- res = self.client.post(
- "/api/agentic/authorize/confirm/",
- {"state": "state_attr", "team_id": self.team.id},
- content_type="application/json",
- )
+ self._set_pending_auth("state_attr", self.user.email, partner=partner)
+ res = self._confirm("state_attr", self.team.id)
assert res.status_code == 200
success_calls = [
@@ -254,22 +230,20 @@ class TestAgenticAuthorizeConfirm(AgenticAuthorizeMultiOrgBase):
assert len(success_calls) == 1
assert success_calls[0].kwargs["partner"] == partner
+ def test_confirm_without_partner_returns_missing_callback(self):
+ self._set_pending_auth("state_no_partner", self.user.email, partner_id="")
+ res = self._confirm("state_no_partner", self.team.id)
+ assert res.status_code == 400
+ assert res.json()["error"] == "missing_callback"
+
def test_confirm_rejects_expired_state(self):
- res = self.client.post(
- "/api/agentic/authorize/confirm/",
- {"state": "nonexistent", "team_id": self.team.id},
- content_type="application/json",
- )
+ res = self._confirm("nonexistent", self.team.id)
assert res.status_code == 400
assert res.json()["error"] == "expired_or_invalid_state"
def test_confirm_rejects_email_mismatch(self):
self._set_pending_auth("state_wrong_email", "[email protected]")
- res = self.client.post(
- "/api/agentic/authorize/confirm/",
- {"state": "state_wrong_email", "team_id": self.team.id},
- content_type="application/json",
- )
+ res = self._confirm("state_wrong_email", self.team.id)
assert res.status_code == 403
assert res.json()["error"] == "email_mismatch"
@@ -278,43 +252,16 @@ class TestAgenticAuthorizeConfirm(AgenticAuthorizeMultiOrgBase):
other_org = Organization.objects.create(name="Other Org")
other_team = Team.objects.create(organization=other_org, name="Other Project", api_token="token_other")
- res = self.client.post(
- "/api/agentic/authorize/confirm/",
- {"state": "state_no_access", "team_id": other_team.id},
- content_type="application/json",
- )
+ res = self._confirm("state_no_access", other_team.id)
assert res.status_code == 403
assert res.json()["error"] == "team_not_accessible"
def test_confirm_rejects_nonexistent_team(self):
self._set_pending_auth("state_bad_team", self.user.email)
- res = self.client.post(
- "/api/agentic/authorize/confirm/",
- {"state": "state_bad_team", "team_id": 999999},
- content_type="application/json",
- )
+ res = self._confirm("state_bad_team", 999999)
assert res.status_code == 404
assert res.json()["error"] == "team_not_found"
def test_confirm_rejects_missing_params(self):
- res = self.client.post(
- "/api/agentic/authorize/confirm/",
- {"state": "something"},
- content_type="application/json",
- )
+ res = self._post_api("/api/agentic/authorize/confirm/", {"state": "something"})
assert res.status_code == 400
-
-
-@override_settings(STRIPE_ORCHESTRATOR_CALLBACK_URL=DUMMY_CALLBACK)
-class TestAgenticAuthorizeNoOrg(APIBaseTest):
- def test_user_without_org_redirects_with_error(self):
- orphan = User.objects.create(email="[email protected]", first_name="Orphan")
- self.client.force_login(orphan)
- cache.set(
- f"{PENDING_AUTH_CACHE_PREFIX}state_no_org",
- {"email": "[email protected]", "scopes": [], "stripe_account_id": "", "region": "US"},
- timeout=600,
- )
- res = self.client.get("/api/agentic/authorize?state=state_no_org")
- assert res.status_code == 302
- assert "error=no_organization" in res["Location"]
diff --git a/ee/api/agentic_provisioning/test/test_deep_links.py b/ee/api/agentic_provisioning/test/test_deep_links.py
index c01295e8e4c9..7b4f4ae5326d 100644
--- a/ee/api/agentic_provisioning/test/test_deep_links.py
+++ b/ee/api/agentic_provisioning/test/test_deep_links.py
@@ -1,19 +1,17 @@
from unittest.mock import patch
from django.core.cache import cache
-from django.test import override_settings
from parameterized import parameterized
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase
+from ee.api.agentic_provisioning.test.base import ProvisioningTestBase
from ee.api.agentic_provisioning.views import DEEP_LINK_CACHE_PREFIX
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestDeepLinks(ProvisioningTestBase):
def test_deep_link_returns_url(self):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/deep_links",
data={"purpose": "dashboard"},
token=token,
@@ -27,7 +25,7 @@ class TestDeepLinks(ProvisioningTestBase):
def test_deep_link_url_contains_team_id(self):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/deep_links",
data={"purpose": "dashboard"},
token=token,
@@ -38,7 +36,7 @@ class TestDeepLinks(ProvisioningTestBase):
@patch("ee.api.agentic_provisioning.views._capture_provisioning_event")
def test_deep_link_capture_attributes_client(self, mock_capture_event):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/deep_links",
data={"purpose": "dashboard"},
token=token,
@@ -51,22 +49,17 @@ class TestDeepLinks(ProvisioningTestBase):
assert len(success_calls) == 1
partner = success_calls[0].kwargs["partner"]
assert partner is not None
- assert partner.name == "PostHog Stripe App"
+ assert partner.name == "Test Provisioning Partner"
def test_deep_link_missing_bearer_returns_401(self):
- res = self._post_signed("/api/agentic/provisioning/deep_links", data={"purpose": "dashboard"})
+ res = self._post_api("/api/agentic/provisioning/deep_links", data={"purpose": "dashboard"})
assert res.status_code == 401
def test_deep_link_denied_when_partner_not_allowed(self):
- from posthog.models.oauth import OAuthApplication
-
- from ee.api.agentic_provisioning.test.base import TEST_STRIPE_OAUTH_CLIENT_ID
-
token = self._get_bearer_token()
- OAuthApplication.objects.filter(client_id=TEST_STRIPE_OAUTH_CLIENT_ID).update(
- provisioning_can_issue_deep_links=False
- )
- res = self._post_signed_with_bearer(
+ self.partner.provisioning_can_issue_deep_links = False
+ self.partner.save(update_fields=["provisioning_can_issue_deep_links"])
+ res = self._post_with_bearer(
"/api/agentic/provisioning/deep_links",
data={"purpose": "dashboard"},
token=token,
@@ -74,10 +67,21 @@ class TestDeepLinks(ProvisioningTestBase):
assert res.status_code == 403
assert res.json()["error"]["code"] == "deep_links_not_enabled"
+ def test_outstanding_token_of_hmac_configured_partner_rejected(self):
+ token = self._get_bearer_token()
+ self.partner.provisioning_auth_method = "hmac"
+ self.partner.save(update_fields=["provisioning_auth_method"])
+ res = self._post_with_bearer(
+ "/api/agentic/provisioning/deep_links",
+ data={"purpose": "dashboard"},
+ token=token,
+ )
+ assert res.status_code == 401
+
def test_deep_link_with_path_redirects_there(self):
token = self._get_bearer_token()
target = f"/project/{self.team.id}/replay/019e6d10-c3b0-7000-8000-000000000000"
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/deep_links",
data={"path": target},
token=token,
@@ -108,7 +112,7 @@ class TestDeepLinks(ProvisioningTestBase):
)
def test_deep_link_rejects_unsafe_path(self, _name: str, path: str):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/deep_links",
data={"path": path},
token=token,
@@ -116,29 +120,7 @@ class TestDeepLinks(ProvisioningTestBase):
assert res.status_code == 400
assert res.json()["error"]["code"] == "invalid_path"
- def test_deep_link_requires_hmac_signature_for_hmac_partner(self):
- from posthog.models.oauth import OAuthApplication
-
- from ee.api.agentic_provisioning.test.base import TEST_STRIPE_OAUTH_CLIENT_ID
-
- token = self._get_bearer_token()
- OAuthApplication.objects.filter(client_id=TEST_STRIPE_OAUTH_CLIENT_ID).update(
- provisioning_auth_method="hmac",
- provisioning_active=True,
- provisioning_can_provision_resources=True,
- )
- res = self.client.post(
- "/api/agentic/provisioning/deep_links",
- data={"purpose": "dashboard"},
- content_type="application/json",
- HTTP_API_VERSION="0.1d",
- HTTP_AUTHORIZATION=f"Bearer {token}",
- )
- assert res.status_code == 401
- assert res.json()["error"]["code"] == "hmac_signature_required"
-
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestAgenticLogin(ProvisioningTestBase):
def setUp(self):
super().setUp()
diff --git a/ee/api/agentic_provisioning/test/test_e2e_flow.py b/ee/api/agentic_provisioning/test/test_e2e_flow.py
index a9508c850e3b..ec6c6f4cd01d 100644
--- a/ee/api/agentic_provisioning/test/test_e2e_flow.py
+++ b/ee/api/agentic_provisioning/test/test_e2e_flow.py
@@ -1,66 +1,42 @@
-import json
-import time
-import base64
-import hashlib
-import secrets
from datetime import timedelta
-from urllib.parse import parse_qs, urlencode, urlparse
+from urllib.parse import parse_qs, urlparse
-from django.test import override_settings
from django.utils import timezone
from posthog.models.oauth import OAuthApplication
from posthog.models.user import User
-from ee.api.agentic_provisioning.signature import compute_signature
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase
+from ee.api.agentic_provisioning.test.base import ProvisioningTestBase
+
+TOKEN_URL = "/api/agentic/oauth/token"
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestE2EProvisioningFlow(ProvisioningTestBase):
- """Walk through the full APP 0.1d provisioning flow end-to-end."""
+ """Walk through the full partner provisioning flow end-to-end."""
def test_full_provisioning_flow(self):
- # 1. Health check
- res = self._get_signed("/api/agentic/provisioning/health")
- assert res.status_code == 200
- assert res.json()["status"] == "ok"
-
- # 2. List services (billing not available in tests, returns empty)
- res = self._get_signed("/api/agentic/provisioning/services")
- assert res.status_code == 200
+ partner_token = self._get_bearer_token()
- # 3. Account request (new user)
+ # 1. Account request (new user) from the bearer-authenticated partner
+ verifier, challenge = self._pkce_pair()
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",
+ "code_challenge": challenge,
+ "code_challenge_method": "S256",
"expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),
- "orchestrator": {
- "type": "stripe",
- "stripe": {
- "organisation": "org_e2e",
- "account": "acct_e2e",
- },
- },
}
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=account_request)
+ res = self._post_with_bearer(
+ "/api/agentic/provisioning/account_requests", data=account_request, token=partner_token
+ )
assert res.status_code == 200
assert res.json()["type"] == "oauth"
auth_code = res.json()["oauth"]["code"]
- # 4. Exchange authorization code for tokens
- token_body = urlencode({"grant_type": "authorization_code", "code": auth_code}).encode()
- ts = int(time.time())
- sig = compute_signature(HMAC_SECRET, ts, token_body)
- res = self.client.post(
- "/api/agentic/oauth/token",
- data=token_body,
- content_type="application/x-www-form-urlencoded",
- headers={"stripe-signature": f"t={ts},v1={sig}", "api-version": "0.1d"},
+ # 2. Exchange authorization code for tokens (PKCE)
+ res = self._post_api(
+ TOKEN_URL, {"grant_type": "authorization_code", "code": auth_code, "code_verifier": verifier}
)
assert res.status_code == 200
token_data = res.json()
@@ -71,32 +47,24 @@ class TestE2EProvisioningFlow(ProvisioningTestBase):
assert refresh_token.startswith("phr_")
assert token_data["account"]["id"]
- # 5. Provision a resource
- res = self._post_signed_with_bearer(
- "/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
- token=access_token,
- )
+ # 3. Provision a resource
+ res = self._post_with_bearer("/api/agentic/provisioning/resources", data={}, 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"/api/agentic/provisioning/resources/{resource_id}",
- token=access_token,
- )
+ # 4. Get resource status
+ res = self._get_with_bearer(f"/api/agentic/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)
+ # 5. Rotate credentials (generates a new api_token)
original_api_key = resource_data["complete"]["access_configuration"]["api_key"]
- res = self._post_signed_with_bearer(
- f"/api/agentic/provisioning/resources/{resource_id}/rotate_credentials",
- token=access_token,
+ res = self._post_with_bearer(
+ f"/api/agentic/provisioning/resources/{resource_id}/rotate_credentials", token=access_token
)
assert res.status_code == 200
assert res.json()["status"] == "complete"
@@ -104,18 +72,14 @@ class TestE2EProvisioningFlow(ProvisioningTestBase):
rotated_api_key = res.json()["complete"]["access_configuration"]["api_key"]
assert rotated_api_key != original_api_key
- # 8. Deep link — create and use it to login
- res = self._post_signed_with_bearer(
- "/api/agentic/provisioning/deep_links",
- data={"purpose": "dashboard"},
- token=access_token,
+ # 6. Deep link — create and use it to login
+ res = self._post_with_bearer(
+ "/api/agentic/provisioning/deep_links", data={"purpose": "dashboard"}, token=access_token
)
assert res.status_code == 200
deep_link_url = res.json()["url"]
assert "expires_at" in res.json()
-
- parsed = urlparse(deep_link_url)
- deep_link_token = parse_qs(parsed.query)["token"][0]
+ 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.
@@ -135,94 +99,21 @@ class TestE2EProvisioningFlow(ProvisioningTestBase):
assert reuse_res.status_code == 302
assert "expired_or_invalid_token" in reuse_res["Location"]
- # 9. Refresh the token
- refresh_body = urlencode({"grant_type": "refresh_token", "refresh_token": refresh_token}).encode()
- ts = int(time.time())
- sig = compute_signature(HMAC_SECRET, ts, refresh_body)
- res = self.client.post(
- "/api/agentic/oauth/token",
- data=refresh_body,
- content_type="application/x-www-form-urlencoded",
- headers={"stripe-signature": f"t={ts},v1={sig}", "api-version": "0.1d"},
- )
+ # 7. Refresh the token
+ res = self._post_api(TOKEN_URL, {"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_")
- # 10. Verify new token works on resource endpoint
- res = self._get_signed_with_bearer(
- f"/api/agentic/provisioning/resources/{resource_id}",
- token=new_access_token,
- )
+ # 8. New token works; the rotated-out one no longer does
+ res = self._get_with_bearer(f"/api/agentic/provisioning/resources/{resource_id}", token=new_access_token)
assert res.status_code == 200
assert res.json()["status"] == "complete"
- # 11. Old token should no longer work (it was deleted during refresh)
- res = self._get_signed_with_bearer(
- f"/api/agentic/provisioning/resources/{resource_id}",
- token=access_token,
- )
+ res = self._get_with_bearer(f"/api/agentic/provisioning/resources/{resource_id}", token=access_token)
assert res.status_code == 401
- def test_existing_user_provisioning_flow(self):
- """E2E: existing user gets linked via email without browser redirect."""
- User.objects.create_and_join(
- organization=self.organization,
- password="testpass",
- first_name="Existing",
- )
-
- # 1. Account request for existing user — should return oauth directly
- account_request = {
- "id": "acctreq_existing_e2e",
- "object": "account_request",
- "email": "[email protected]",
- "scopes": ["query:read", "project:read"],
- "client_capabilities": ["browser"],
- "confirmation_secret": "cs_existing_secret",
- "expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),
- "orchestrator": {
- "type": "stripe",
- "stripe": {
- "organisation": "org_e2e",
- "account": "acct_e2e_existing",
- },
- },
- }
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=account_request)
- assert res.status_code == 200
- assert res.json()["type"] == "oauth"
- auth_code = res.json()["oauth"]["code"]
-
- # 2. Exchange authorization code for tokens
- token_body = urlencode({"grant_type": "authorization_code", "code": auth_code}).encode()
- ts = int(time.time())
- sig = compute_signature(HMAC_SECRET, ts, token_body)
- res = self.client.post(
- "/api/agentic/oauth/token",
- data=token_body,
- content_type="application/x-www-form-urlencoded",
- headers={"stripe-signature": f"t={ts},v1={sig}", "api-version": "0.1d"},
- )
- assert res.status_code == 200
- token_data = res.json()
- access_token = token_data["access_token"]
- assert access_token.startswith("pha_")
- assert "available_teams" in token_data["account"]
- assert len(token_data["account"]["available_teams"]) >= 1
-
- # 3. Provision a resource
- res = self._post_signed_with_bearer(
- "/api/agentic/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"]
-
def test_pkce_existing_user_consent_e2e(self):
"""E2E: PKCE partner with existing user goes through browser consent flow."""
OAuthApplication.objects.create(
@@ -234,6 +125,7 @@ class TestE2EProvisioningFlow(ProvisioningTestBase):
redirect_uris="https://partner.example.com/callback",
algorithm="RS256",
is_first_party=True,
+ scopes=["query:read"],
provisioning_auth_method="pkce",
provisioning_partner_type="test_partner",
provisioning_active=True,
@@ -249,28 +141,17 @@ class TestE2EProvisioningFlow(ProvisioningTestBase):
)
# 1. Partner calls account_requests - gets requires_auth (not a direct code)
- code_verifier = secrets.token_urlsafe(32)
- code_challenge = (
- base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode("ascii")).digest())
- .rstrip(b"=")
- .decode("ascii")
- )
+ verifier, challenge = self._pkce_pair()
account_request = {
"id": "acctreq_consent_e2e",
"email": "[email protected]",
"scopes": ["query:read"],
"client_id": "pkce-e2e-partner",
- "code_challenge": code_challenge,
+ "code_challenge": challenge,
"code_challenge_method": "S256",
"expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),
- "orchestrator": {"type": "test", "account": "acct_e2e"},
}
- res = self.client.post(
- "/api/agentic/provisioning/account_requests",
- data=json.dumps(account_request).encode(),
- content_type="application/json",
- HTTP_API_VERSION="0.1d",
- )
+ res = self._post_api("/api/agentic/provisioning/account_requests", account_request)
assert res.status_code == 200
data = res.json()
assert data["type"] == "requires_auth"
@@ -285,15 +166,10 @@ class TestE2EProvisioningFlow(ProvisioningTestBase):
assert res.status_code == 302
redirect_url = res["Location"]
assert "/agentic/authorize?" in redirect_url
- parsed_redirect = urlparse(redirect_url)
- consent_state = parse_qs(parsed_redirect.query)["state"][0]
+ consent_state = parse_qs(urlparse(redirect_url).query)["state"][0]
# 3. User approves on the consent page (simulated via agentic_authorize_confirm)
- res = self.client.post(
- "/api/agentic/authorize/confirm/",
- data=json.dumps({"state": consent_state, "team_id": self.team.id}),
- content_type="application/json",
- )
+ res = self._post_api("/api/agentic/authorize/confirm/", {"state": consent_state, "team_id": self.team.id})
assert res.status_code == 200
callback_redirect = res.json()["redirect_url"]
parsed_callback = urlparse(callback_redirect)
@@ -301,18 +177,8 @@ class TestE2EProvisioningFlow(ProvisioningTestBase):
auth_code = parse_qs(parsed_callback.query)["code"][0]
# 4. Partner exchanges auth code for tokens using PKCE
- token_body = urlencode(
- {
- "grant_type": "authorization_code",
- "code": auth_code,
- "code_verifier": code_verifier,
- }
- ).encode()
- res = self.client.post(
- "/api/agentic/oauth/token",
- data=token_body,
- content_type="application/x-www-form-urlencoded",
- HTTP_API_VERSION="0.1d",
+ res = self._post_api(
+ TOKEN_URL, {"grant_type": "authorization_code", "code": auth_code, "code_verifier": verifier}
)
assert res.status_code == 200
token_data = res.json()
@@ -321,13 +187,7 @@ class TestE2EProvisioningFlow(ProvisioningTestBase):
assert access_token.startswith("pha_")
# 5. Partner provisions a resource with the token
- res = self.client.post(
- "/api/agentic/provisioning/resources",
- data=json.dumps({"service_id": "analytics"}).encode(),
- content_type="application/json",
- HTTP_API_VERSION="0.1d",
- HTTP_AUTHORIZATION=f"Bearer {access_token}",
- )
+ res = self._post_with_bearer("/api/agentic/provisioning/resources", data={}, 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/api/agentic_provisioning/test/test_github_grants.py b/ee/api/agentic_provisioning/test/test_github_grants.py
index 434bb1360bce..bccc586811ba 100644
--- a/ee/api/agentic_provisioning/test/test_github_grants.py
+++ b/ee/api/agentic_provisioning/test/test_github_grants.py
@@ -9,7 +9,7 @@ from posthog.models.integration import GitHubUserAuthorization
from posthog.models.oauth import OAuthApplication
from ee.api.agentic_provisioning import GITHUB_GRANT_CACHE_PREFIX, github_grants
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase
+from ee.api.agentic_provisioning.test.base import ProvisioningTestBase
ACCESS_TOKEN = "gho_secret_user_token"
@@ -61,20 +61,13 @@ REPOSITORIES_RESPONSE = _github_response(
class TestGitHubGrants(ProvisioningTestBase):
def setUp(self):
super().setUp()
- self.partner = OAuthApplication.objects.create(
- name="Drop Partner",
- client_id="drop_partner_client_id",
- client_secret="",
- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="https://posthog.com/api/wizard/oauth-callback",
- algorithm="RS256",
- provisioning_auth_method="hmac",
- provisioning_signing_secret=HMAC_SECRET,
- provisioning_partner_type="posthog_website",
- provisioning_active=True,
- provisioning_can_create_accounts=True,
- )
+ self.bearer = self._get_bearer_token()
+
+ def _post_grants(self, body: dict):
+ return self._post_with_bearer("/api/agentic/provisioning/github/grants", body, token=self.bearer)
+
+ def _get_grants(self, url: str):
+ return self._get_with_bearer(url, self.bearer)
def _create_grant_via_api(self):
with (
@@ -84,8 +77,7 @@ class TestGitHubGrants(ProvisioningTestBase):
),
patch("ee.api.agentic_provisioning.github_grants.github_request", return_value=EMAILS_RESPONSE),
):
- return self._post_signed(
- "/api/agentic/provisioning/github/grants",
+ return self._post_grants(
{"code": "gh_code", "redirect_uri": "https://posthog.com/api/wizard/github/callback"},
)
@@ -97,8 +89,7 @@ class TestGitHubGrants(ProvisioningTestBase):
) as mock_exchange,
patch("ee.api.agentic_provisioning.github_grants.github_request", return_value=EMAILS_RESPONSE),
):
- response = self._post_signed(
- "/api/agentic/provisioning/github/grants",
+ response = self._post_grants(
{"code": "gh_code", "redirect_uri": "https://posthog.com/api/wizard/github/callback"},
)
@@ -126,7 +117,7 @@ class TestGitHubGrants(ProvisioningTestBase):
]
)
def test_create_grant_requires_code(self, _name, body, expected_status, expected_code):
- response = self._post_signed("/api/agentic/provisioning/github/grants", body)
+ response = self._post_grants(body)
assert response.status_code == expected_status
assert response.json()["error"]["code"] == expected_code
@@ -135,7 +126,7 @@ class TestGitHubGrants(ProvisioningTestBase):
"ee.api.agentic_provisioning.views.GitHubIntegration.github_user_from_code",
return_value=None,
):
- response = self._post_signed("/api/agentic/provisioning/github/grants", {"code": "bad_code"})
+ response = self._post_grants({"code": "bad_code"})
assert response.status_code == 502
assert response.json()["error"]["code"] == "github_exchange_failed"
@@ -144,7 +135,7 @@ class TestGitHubGrants(ProvisioningTestBase):
"ee.api.agentic_provisioning.views.GitHubIntegration.github_user_from_code",
side_effect=requests.RequestException("boom"),
):
- response = self._post_signed("/api/agentic/provisioning/github/grants", {"code": "gh_code"})
+ response = self._post_grants({"code": "gh_code"})
assert response.status_code == 502
assert response.json()["error"]["code"] == "github_unavailable"
@@ -167,7 +158,6 @@ class TestGitHubGrants(ProvisioningTestBase):
"/api/agentic/provisioning/github/grants",
data={"client_id": pkce_partner.client_id, "code": "gh_code"},
format="json",
- HTTP_API_VERSION="0.1d",
)
assert response.status_code == 403
assert response.json()["error"]["code"] == "forbidden"
@@ -181,7 +171,7 @@ class TestGitHubGrants(ProvisioningTestBase):
),
patch("ee.api.agentic_provisioning.github_grants.github_request", return_value=no_verified),
):
- response = self._post_signed("/api/agentic/provisioning/github/grants", {"code": "gh_code"})
+ response = self._post_grants({"code": "gh_code"})
assert response.status_code == 200, response.json()
body = response.json()
assert body["email"] is None
@@ -198,7 +188,7 @@ class TestGitHubGrants(ProvisioningTestBase):
),
patch("ee.api.agentic_provisioning.github_grants.github_request", return_value=denied),
):
- response = self._post_signed("/api/agentic/provisioning/github/grants", {"code": "gh_code"})
+ response = self._post_grants({"code": "gh_code"})
assert response.status_code == 502
assert response.json()["error"]["code"] == "email_unavailable"
@@ -207,14 +197,13 @@ class TestGitHubGrants(ProvisioningTestBase):
"/api/agentic/provisioning/github/grants",
data={"code": "gh_code"},
format="json",
- HTTP_API_VERSION="0.1d",
)
assert response.status_code == 401
def test_create_grant_requires_account_creation_permission(self):
self.partner.provisioning_can_create_accounts = False
self.partner.save()
- response = self._post_signed("/api/agentic/provisioning/github/grants", {"code": "gh_code"})
+ response = self._post_grants({"code": "gh_code"})
assert response.status_code == 403
assert response.json()["error"]["code"] == "forbidden"
@@ -242,7 +231,7 @@ class TestGitHubGrants(ProvisioningTestBase):
return REPOSITORIES_RESPONSE
with patch("ee.api.agentic_provisioning.github_grants.github_request", side_effect=fake_github_request):
- response = self._get_signed(f"{base_url}/{grant.grant_id}/repositories")
+ response = self._get_grants(f"{base_url}/{grant.grant_id}/repositories")
assert response.status_code == 200, response.json()
body = response.json()
@@ -258,7 +247,7 @@ class TestGitHubGrants(ProvisioningTestBase):
]
def test_repositories_unknown_grant_returns_404(self):
- response = self._get_signed("/api/agentic/provisioning/github/grants/nonexistent/repositories")
+ response = self._get_grants("/api/agentic/provisioning/github/grants/nonexistent/repositories")
assert response.status_code == 404
assert response.json()["error"]["code"] == "grant_not_found"
@@ -276,7 +265,7 @@ class TestGitHubGrants(ProvisioningTestBase):
provisioning_can_create_accounts=True,
)
grant = github_grants.create_grant(other_partner, AUTHORIZATION, "[email protected]")
- response = self._get_signed(f"/api/agentic/provisioning/github/grants/{grant.grant_id}/repositories")
+ response = self._get_grants(f"/api/agentic/provisioning/github/grants/{grant.grant_id}/repositories")
assert response.status_code == 404
assert response.json()["error"]["code"] == "grant_not_found"
@@ -293,8 +282,8 @@ class TestGitHubGrants(ProvisioningTestBase):
patch("ee.api.agentic_provisioning.views.GITHUB_GRANT_POLL_RATE_LIMIT_MAX", 1),
patch("ee.api.agentic_provisioning.github_grants.github_request", side_effect=fake_github_request),
):
- first = self._get_signed(url)
- second = self._get_signed(url)
+ first = self._get_grants(url)
+ second = self._get_grants(url)
assert first.status_code == 200
assert second.status_code == 429
assert second["Retry-After"]
@@ -305,6 +294,6 @@ class TestGitHubGrants(ProvisioningTestBase):
"ee.api.agentic_provisioning.github_grants.github_request",
return_value=_github_response(500, {}),
):
- response = self._get_signed(f"/api/agentic/provisioning/github/grants/{grant.grant_id}/repositories")
+ response = self._get_grants(f"/api/agentic/provisioning/github/grants/{grant.grant_id}/repositories")
assert response.status_code == 502
assert response.json()["error"]["code"] == "github_unavailable"
diff --git a/ee/api/agentic_provisioning/test/test_health.py b/ee/api/agentic_provisioning/test/test_health.py
deleted file mode 100644
index d463d68b2bd8..000000000000
--- a/ee/api/agentic_provisioning/test/test_health.py
+++ /dev/null
@@ -1,64 +0,0 @@
-# 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
-
-from django.test import override_settings
-
-from ee.api.agentic_provisioning.signature import compute_signature
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase
-
-
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
-class TestProvisioningHealth(ProvisioningTestBase):
- def test_valid_request(self):
- res = self._get_signed("/api/agentic/provisioning/health")
- assert res.status_code == 200
- data = res.json()
- assert data["supported_versions"] == ["0.1d"]
- assert data["status"] == "ok"
-
- def test_missing_signature_returns_401(self):
- res = self.client.get("/api/agentic/provisioning/health", headers={"api-version": "0.1d"})
- assert res.status_code == 401
-
- def test_invalid_signature_returns_401(self):
- res = self.client.get(
- "/api/agentic/provisioning/health",
- headers={"stripe-signature": f"t={int(time.time())},v1={'00' * 32}", "api-version": "0.1d"},
- )
- assert res.status_code == 401
-
- def test_missing_api_version_returns_400(self):
- sig = self._sign_body(b"")
- res = self.client.get("/api/agentic/provisioning/health", headers={"stripe-signature": sig})
- assert res.status_code == 400
-
- def test_wrong_api_version_returns_400(self):
- sig = self._sign_body(b"")
- res = self.client.get(
- "/api/agentic/provisioning/health", headers={"stripe-signature": sig, "api-version": "1.0"}
- )
- assert res.status_code == 400
-
- def test_expired_timestamp_returns_401(self):
- old_ts = int(time.time()) - 600
- sig = compute_signature(HMAC_SECRET, old_ts, b"")
- res = self.client.get(
- "/api/agentic/provisioning/health",
- headers={"stripe-signature": f"t={old_ts},v1={sig}", "api-version": "0.1d"},
- )
- assert res.status_code == 401
-
- @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
- def test_signature_succeeds_with_rate_limiting_enabled(self, _mock):
- res = self._get_signed("/api/agentic/provisioning/health")
- assert res.status_code == 200
-
- @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
- def test_post_signature_succeeds_with_rate_limiting_enabled(self, _mock):
- res = self._post_signed(
- "/api/agentic/provisioning/account-requests",
- data={"email": "[email protected]", "account_name": "Test"},
- )
- assert res.status_code not in (400, 500), f"Unexpected error: {res.json()}"
diff --git a/ee/api/agentic_provisioning/test/test_oauth_token.py b/ee/api/agentic_provisioning/test/test_oauth_token.py
index 75e62c9dec76..9ee5513eea5f 100644
--- a/ee/api/agentic_provisioning/test/test_oauth_token.py
+++ b/ee/api/agentic_provisioning/test/test_oauth_token.py
@@ -1,9 +1,7 @@
-import time
+import uuid
from datetime import timedelta
-from urllib.parse import urlencode
from django.core.cache import cache
-from django.test import override_settings
from django.utils import timezone
from parameterized import parameterized
@@ -11,52 +9,38 @@ from parameterized import parameterized
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from ee.api.agentic_provisioning import AUTH_CODE_CACHE_PREFIX
-from ee.api.agentic_provisioning.signature import compute_signature
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, TEST_STRIPE_OAUTH_CLIENT_ID, ProvisioningTestBase
-from ee.api.agentic_provisioning.views import (
- STRIPE_CONTRACTED_SCOPES,
- LegacyStripeOAuthAppMissingError,
- _get_legacy_stripe_oauth_app,
-)
+from ee.api.agentic_provisioning.test.base import TEST_PARTNER_SCOPES, ProvisioningTestBase
+
+TOKEN_URL = "/api/agentic/oauth/token"
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestOAuthTokenExchange(ProvisioningTestBase):
def _set_app_ceiling(self, scopes: list[str]) -> None:
- OAuthApplication.objects.filter(client_id=TEST_STRIPE_OAUTH_CLIENT_ID).update(scopes=scopes)
-
- def _store_auth_code(self, code: str = "test_code", **overrides):
- data = {
- "user_id": self.user.id,
- "org_id": str(self.organization.id),
- "team_id": self.team.id,
- "stripe_account_id": "acct_123",
- "scopes": ["query:read", "project:read"],
- "region": "US",
- }
- data.update(overrides)
- cache.set(f"{AUTH_CODE_CACHE_PREFIX}{code}", data, timeout=300)
- return code
-
- def _token_request_body(self, **overrides):
- params = {"grant_type": "authorization_code", "code": "test_code"}
- params.update(overrides)
- return urlencode(params).encode()
-
- def _post_token(self, body: bytes):
- ts = int(time.time())
- sig = compute_signature(HMAC_SECRET, ts, body)
- return self.client.post(
- "/api/agentic/oauth/token",
- data=body,
- content_type="application/x-www-form-urlencoded",
- headers={"stripe-signature": f"t={ts},v1={sig}", "api-version": "0.1d"},
- )
+ OAuthApplication.objects.filter(id=self.partner.id).update(scopes=scopes)
+
+ def _mint_code_with_overrides(self, scopes: list[str] | None = None, **overrides) -> tuple[str, str]:
+ code, verifier = self._mint_auth_code(scopes=scopes)
+ key = f"{AUTH_CODE_CACHE_PREFIX}{code}"
+ data = cache.get(key)
+ for field, value in overrides.items():
+ if value is None:
+ data.pop(field, None)
+ else:
+ data[field] = value
+ cache.set(key, data, timeout=300)
+ return code, verifier
+
+ def _exchange_code(self, code: str, verifier: str):
+ return self._post_api(TOKEN_URL, {"grant_type": "authorization_code", "code": code, "code_verifier": verifier})
+
+ def _refresh(self, refresh_token: str):
+ return self._post_api(TOKEN_URL, {"grant_type": "refresh_token", "refresh_token": refresh_token})
+
+ def _stamp_session_revoke(self, when=None) -> None:
+ OAuthApplication.objects.filter(id=self.partner.id).update(sessions_revoked_at=when or timezone.now())
def test_valid_code_exchange_returns_tokens(self):
- self._store_auth_code("test_code")
- body = self._token_request_body()
- res = self._post_token(body)
+ res = self._request_bearer_token()
assert res.status_code == 200
data = res.json()
assert data["token_type"] == "bearer"
@@ -64,162 +48,149 @@ class TestOAuthTokenExchange(ProvisioningTestBase):
assert data["refresh_token"].startswith("phr_")
assert data["expires_in"] > 0
assert "scope" not in data
- assert "account" in data
assert data["account"]["id"] == str(self.organization.id)
- assert "available_teams" in data["account"]
assert len(data["account"]["available_teams"]) >= 1
team_entry = data["account"]["available_teams"][0]
assert "id" in team_entry
assert "name" in team_entry
assert "organization_id" in team_entry
- def test_invalid_code_returns_400(self):
- body = self._token_request_body(code="nonexistent")
- res = self._post_token(body)
+ def test_code_is_single_use(self):
+ code, verifier = self._mint_auth_code()
+ assert self._exchange_code(code, verifier).status_code == 200
+ res = self._exchange_code(code, verifier)
assert res.status_code == 400
assert res.json()["error"] == "invalid_grant"
- def test_code_is_single_use(self):
- self._store_auth_code("single_use_code")
- body = self._token_request_body(code="single_use_code")
- res1 = self._post_token(body)
- assert res1.status_code == 200
- res2 = self._post_token(body)
- assert res2.status_code == 400
-
- def test_refresh_token_exchange(self):
- self._store_auth_code("code_for_refresh")
- body = self._token_request_body(code="code_for_refresh")
- first_res = self._post_token(body)
- refresh_token = first_res.json()["refresh_token"]
-
- refresh_body = urlencode({"grant_type": "refresh_token", "refresh_token": refresh_token}).encode()
- res = self._post_token(refresh_body)
- assert res.status_code == 200
- data = res.json()
- assert data["access_token"].startswith("pha_")
- assert data["refresh_token"].startswith("phr_")
- assert data["access_token"] != first_res.json()["access_token"]
+ @parameterized.expand(
+ [
+ (
+ "invalid_code",
+ {"grant_type": "authorization_code", "code": "nonexistent", "code_verifier": "x"},
+ "invalid_grant",
+ ),
+ ("missing_code", {"grant_type": "authorization_code"}, "invalid_request"),
+ ("unsupported_grant_type", {"grant_type": "client_credentials"}, "unsupported_grant_type"),
+ ("invalid_refresh_token", {"grant_type": "refresh_token", "refresh_token": "phr_invalid"}, "invalid_grant"),
+ ]
+ )
+ def test_rejected_grants(self, _name, params, error):
+ res = self._post_api(TOKEN_URL, params)
+ assert res.status_code == 400
+ assert res.json()["error"] == error
+
+ def test_code_without_challenge_requires_authentication(self):
+ code, verifier = self._mint_code_with_overrides(code_challenge=None, code_challenge_method=None)
+ res = self._exchange_code(code, verifier)
+ assert res.status_code == 401
+ assert res.json() == {"error": "invalid_request", "error_description": "Authentication required"}
- def test_invalid_refresh_token_returns_400(self):
- body = urlencode({"grant_type": "refresh_token", "refresh_token": "phr_invalid"}).encode()
- res = self._post_token(body)
+ def test_missing_code_verifier_returns_401(self):
+ code, _verifier = self._mint_auth_code()
+ res = self._post_api(TOKEN_URL, {"grant_type": "authorization_code", "code": code})
+ assert res.status_code == 401
+ assert res.json()["error_description"] == "code_verifier is required for PKCE"
+
+ def test_pkce_mismatch_returns_400_without_consuming_code(self):
+ code, verifier = self._mint_auth_code()
+ res = self._exchange_code(code, "wrong_verifier_" + "a" * 32)
assert res.status_code == 400
+ assert res.json()["error"] == "invalid_grant"
+ # Verification runs before the code is consumed, so a failed attempt must not burn it.
+ assert self._exchange_code(code, verifier).status_code == 200
- def test_unsupported_grant_type_returns_400(self):
- body = urlencode({"grant_type": "client_credentials"}).encode()
- res = self._post_token(body)
+ @parameterized.expand([("unknown_partner", str(uuid.uuid4())), ("missing_partner", "")])
+ def test_code_without_resolvable_partner_returns_invalid_grant(self, _name, partner_id):
+ code, verifier = self._mint_code_with_overrides(partner_id=partner_id)
+ res = self._exchange_code(code, verifier)
assert res.status_code == 400
+ assert res.json() == {
+ "error": "invalid_grant",
+ "error_description": "Unknown application for this authorization code",
+ }
- def test_missing_code_returns_400(self):
- body = urlencode({"grant_type": "authorization_code"}).encode()
- res = self._post_token(body)
+ def test_code_with_empty_scopes_rejected(self):
+ code, verifier = self._mint_auth_code(scopes=[])
+ res = self._exchange_code(code, verifier)
assert res.status_code == 400
+ assert res.json()["error"] == "invalid_scope"
- def test_refresh_token_is_single_use(self):
- self._store_auth_code("code_for_replay")
- body = self._token_request_body(code="code_for_replay")
- first_res = self._post_token(body)
- refresh_token = first_res.json()["refresh_token"]
-
- refresh_body = urlencode({"grant_type": "refresh_token", "refresh_token": refresh_token}).encode()
- res1 = self._post_token(refresh_body)
- assert res1.status_code == 200
-
- res2 = self._post_token(refresh_body)
- assert res2.status_code == 400
- assert res2.json()["error"] == "invalid_grant"
-
- def test_missing_signature_returns_401(self):
- self._store_auth_code("test_code")
- body = self._token_request_body()
- res = self.client.post(
- "/api/agentic/oauth/token",
- data=body,
- content_type="application/x-www-form-urlencoded",
- headers={"api-version": "0.1d"},
+ def test_omitted_request_scopes_resolve_to_app_ceiling(self):
+ partner_token = self._get_bearer_token()
+ verifier, challenge = self._pkce_pair()
+ res = self._post_with_bearer(
+ "/api/agentic/provisioning/account_requests",
+ data={
+ "id": "req_scopeless",
+ "email": "[email protected]",
+ "code_challenge": challenge,
+ "code_challenge_method": "S256",
+ },
+ token=partner_token,
)
- assert res.status_code == 401
-
- def test_token_exchange_seeds_stripe_app_scopes(self):
- app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)
- app.scopes = []
- app.save(update_fields=["scopes"])
-
- self._store_auth_code("seed_code")
- res = self._post_token(self._token_request_body(code="seed_code"))
-
assert res.status_code == 200
- app.refresh_from_db()
- assert app.scopes == STRIPE_CONTRACTED_SCOPES
+ code = res.json()["oauth"]["code"]
- def test_token_exchange_missing_stripe_app_hard_fails(self):
- OAuthApplication.objects.filter(client_id=TEST_STRIPE_OAUTH_CLIENT_ID).delete()
+ exchange = self._exchange_code(code, verifier)
+ assert exchange.status_code == 200
+ token = OAuthAccessToken.objects.get(token=exchange.json()["access_token"])
+ assert set(token.scope.split()) == set(TEST_PARTNER_SCOPES)
- self._store_auth_code("orphan_code")
- res = self._post_token(self._token_request_body(code="orphan_code"))
+ def test_refresh_token_rotation_is_single_use(self):
+ first = self._request_bearer_token().json()
+ res = self._refresh(first["refresh_token"])
+ assert res.status_code == 200
+ rotated = res.json()
+ assert rotated["access_token"].startswith("pha_")
+ assert rotated["refresh_token"].startswith("phr_")
+ assert rotated["access_token"] != first["access_token"]
+ assert rotated["refresh_token"] != first["refresh_token"]
- assert res.status_code == 500
- assert res.json()["error"] == "server_error"
- # No app may be fabricated to paper over the missing configuration.
- assert not OAuthApplication.objects.filter(client_id=TEST_STRIPE_OAUTH_CLIENT_ID).exists()
+ replay = self._refresh(first["refresh_token"])
+ assert replay.status_code == 400
+ assert replay.json()["error"] == "invalid_grant"
def test_direct_mint_within_ceiling_grants_requested_scopes(self):
self._set_app_ceiling(["query:read", "project:read"])
- self._store_auth_code("ceiling_ok", scopes=["query:read"])
- res = self._post_token(self._token_request_body(code="ceiling_ok"))
+ code, verifier = self._mint_auth_code(scopes=["query:read"])
+ res = self._exchange_code(code, verifier)
assert res.status_code == 200
token = OAuthAccessToken.objects.get(token=res.json()["access_token"])
assert token.scope == "query:read"
def test_direct_mint_outside_ceiling_returns_invalid_scope(self):
self._set_app_ceiling(["query:read"])
- self._store_auth_code("ceiling_bad", scopes=["query:read", "insight:write"])
- res = self._post_token(self._token_request_body(code="ceiling_bad"))
+ code, verifier = self._mint_auth_code(scopes=["query:read", "insight:write"])
+ res = self._exchange_code(code, verifier)
assert res.status_code == 400
assert res.json()["error"] == "invalid_scope"
def test_refresh_narrows_to_tightened_ceiling(self):
self._set_app_ceiling(["query:read", "insight:write"])
- self._store_auth_code("refresh_narrow", scopes=["query:read", "insight:write"])
- first = self._post_token(self._token_request_body(code="refresh_narrow"))
- refresh_token = first.json()["refresh_token"]
+ first = self._request_bearer_token(scopes=["query:read", "insight:write"]).json()
self._set_app_ceiling(["query:read"])
- refresh_body = urlencode({"grant_type": "refresh_token", "refresh_token": refresh_token}).encode()
- res = self._post_token(refresh_body)
+ res = self._refresh(first["refresh_token"])
assert res.status_code == 200
token = OAuthAccessToken.objects.get(token=res.json()["access_token"])
assert token.scope == "query:read"
def test_refresh_rejected_when_scopes_outside_ceiling(self):
self._set_app_ceiling(["insight:write"])
- self._store_auth_code("refresh_reject", scopes=["insight:write"])
- first = self._post_token(self._token_request_body(code="refresh_reject"))
- refresh_token = first.json()["refresh_token"]
+ first = self._request_bearer_token(scopes=["insight:write"]).json()
self._set_app_ceiling(["query:read"])
- refresh_body = urlencode({"grant_type": "refresh_token", "refresh_token": refresh_token}).encode()
- res = self._post_token(refresh_body)
+ res = self._refresh(first["refresh_token"])
assert res.status_code == 400
assert res.json()["error"] == "invalid_grant"
- def _stamp_session_revoke(self, when=None) -> None:
- OAuthApplication.objects.filter(client_id=TEST_STRIPE_OAUTH_CLIENT_ID).update(
- sessions_revoked_at=when or timezone.now()
- )
-
def test_refresh_rejected_when_token_predates_session_revoke(self):
# Stamp without sweeping, simulating a refresh token the bulk revoke missed.
- self._store_auth_code("revoke_refresh", issued_at=timezone.now().isoformat())
- first = self._post_token(self._token_request_body(code="revoke_refresh"))
- refresh_token = first.json()["refresh_token"]
-
+ first = self._request_bearer_token().json()
self._stamp_session_revoke()
tokens_before = OAuthAccessToken.objects.count()
- refresh_body = urlencode({"grant_type": "refresh_token", "refresh_token": refresh_token}).encode()
- res = self._post_token(refresh_body)
+ res = self._refresh(first["refresh_token"])
assert res.status_code == 400
body = res.json()
assert body["error"] == "invalid_grant"
@@ -228,14 +199,10 @@ class TestOAuthTokenExchange(ProvisioningTestBase):
def test_refresh_allowed_when_token_postdates_session_revoke(self):
self._stamp_session_revoke(timezone.now() - timedelta(hours=1))
- self._store_auth_code("post_revoke", issued_at=timezone.now().isoformat())
- first = self._post_token(self._token_request_body(code="post_revoke"))
+ first = self._request_bearer_token()
assert first.status_code == 200
- refresh_body = urlencode(
- {"grant_type": "refresh_token", "refresh_token": first.json()["refresh_token"]}
- ).encode()
- res = self._post_token(refresh_body)
+ res = self._refresh(first.json()["refresh_token"])
assert res.status_code == 200
@parameterized.expand(
@@ -246,54 +213,15 @@ class TestOAuthTokenExchange(ProvisioningTestBase):
]
)
def test_code_exchange_against_session_revoke_stamp(self, _name, issued_offset_seconds, expected_status):
- overrides = {}
- if issued_offset_seconds is not None:
- overrides["issued_at"] = (timezone.now() + timedelta(seconds=issued_offset_seconds)).isoformat()
- self._store_auth_code("revoke_code", **overrides)
+ issued_at = (
+ (timezone.now() + timedelta(seconds=issued_offset_seconds)).isoformat()
+ if issued_offset_seconds is not None
+ else None
+ )
+ code, verifier = self._mint_code_with_overrides(issued_at=issued_at)
self._stamp_session_revoke()
- res = self._post_token(self._token_request_body(code="revoke_code"))
+ res = self._exchange_code(code, verifier)
assert res.status_code == expected_status
if expected_status == 400:
assert res.json()["error"] == "invalid_grant"
-
-
-class TestLegacyStripeOAuthApp(ProvisioningTestBase):
- def _stripe_app(self) -> OAuthApplication:
- return OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)
-
- @parameterized.expand([("US",), ("EU",)])
- def test_resolves_and_seeds_scopes_regardless_of_region(self, region: str):
- app = self._stripe_app()
- app.scopes = []
- app.save(update_fields=["scopes"])
-
- with override_settings(CLOUD_DEPLOYMENT=region):
- resolved = _get_legacy_stripe_oauth_app()
-
- assert resolved.id == app.id
- resolved.refresh_from_db()
- assert resolved.scopes == STRIPE_CONTRACTED_SCOPES
-
- def test_does_not_overwrite_existing_scopes(self):
- app = self._stripe_app()
- app.scopes = ["query:read"]
- app.save(update_fields=["scopes"])
-
- resolved = _get_legacy_stripe_oauth_app()
-
- resolved.refresh_from_db()
- assert resolved.scopes == ["query:read"]
-
- def test_missing_app_hard_fails_without_fabrication(self):
- OAuthApplication.objects.filter(client_id=TEST_STRIPE_OAUTH_CLIENT_ID).delete()
-
- with self.assertRaises(LegacyStripeOAuthAppMissingError):
- _get_legacy_stripe_oauth_app()
-
- assert not OAuthApplication.objects.filter(client_id=TEST_STRIPE_OAUTH_CLIENT_ID).exists()
-
- def test_unconfigured_client_id_hard_fails(self):
- with override_settings(STRIPE_POSTHOG_OAUTH_CLIENT_ID=""):
- with self.assertRaises(LegacyStripeOAuthAppMissingError):
- _get_legacy_stripe_oauth_app()
diff --git a/ee/api/agentic_provisioning/test/test_partner_rate_limits.py b/ee/api/agentic_provisioning/test/test_partner_rate_limits.py
index e8cb63e8bbb3..507fc8f979e4 100644
--- a/ee/api/agentic_provisioning/test/test_partner_rate_limits.py
+++ b/ee/api/agentic_provisioning/test/test_partner_rate_limits.py
@@ -1,12 +1,7 @@
-import json
-import base64
-import hashlib
-import secrets
from datetime import timedelta
from urllib.parse import urlencode
from django.core.cache import cache
-from django.test import override_settings
from django.utils import timezone
from parameterized import parameterized
@@ -15,13 +10,12 @@ from rest_framework.test import APIClient
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
from ee.api.agentic_provisioning import AUTH_CODE_CACHE_PREFIX
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase
+from ee.api.agentic_provisioning.test.base import ProvisioningTestBase
from ee.api.agentic_provisioning.views import PARTNER_RATE_LIMIT_DEFAULTS
PARTNER_CLIENT_ID = "partner_rate_limit_test"
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestPartnerRateLimits(ProvisioningTestBase):
def setUp(self):
super().setUp()
@@ -50,41 +44,7 @@ class TestPartnerRateLimits(ProvisioningTestBase):
super().tearDown()
def _get_partner_bearer_token(self) -> str:
- code_verifier = secrets.token_urlsafe(32)
- code_challenge = (
- base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode("ascii")).digest())
- .rstrip(b"=")
- .decode("ascii")
- )
- code = secrets.token_urlsafe(32)
- cache.set(
- f"{AUTH_CODE_CACHE_PREFIX}{code}",
- {
- "user_id": self.user.id,
- "org_id": str(self.organization.id),
- "team_id": self.team.id,
- "partner_id": str(self.partner_app.id),
- "scopes": ["query:read"],
- "region": "US",
- "code_challenge": code_challenge,
- "code_challenge_method": "S256",
- },
- timeout=300,
- )
- body = urlencode(
- {
- "grant_type": "authorization_code",
- "code": code,
- "code_verifier": code_verifier,
- }
- ).encode()
- res = self.client.post(
- "/api/agentic/oauth/token",
- data=body,
- content_type="application/x-www-form-urlencoded",
- HTTP_API_VERSION="0.1d",
- )
- return res.json()["access_token"]
+ return self._request_bearer_token(partner=self.partner_app).json()["access_token"]
# --- Unit tests for the rate limit helper ---
@@ -185,27 +145,7 @@ class TestPartnerRateLimits(ProvisioningTestBase):
self._get_partner_bearer_token()
# Second exchange should be rate limited
- code_verifier = secrets.token_urlsafe(32)
- code_challenge = (
- base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode("ascii")).digest())
- .rstrip(b"=")
- .decode("ascii")
- )
- code = secrets.token_urlsafe(32)
- cache.set(
- f"{AUTH_CODE_CACHE_PREFIX}{code}",
- {
- "user_id": self.user.id,
- "org_id": str(self.organization.id),
- "team_id": self.team.id,
- "partner_id": str(self.partner_app.id),
- "scopes": ["query:read"],
- "region": "US",
- "code_challenge": code_challenge,
- "code_challenge_method": "S256",
- },
- timeout=300,
- )
+ code, code_verifier = self._mint_auth_code(partner=self.partner_app)
body = urlencode(
{
"grant_type": "authorization_code",
@@ -217,7 +157,6 @@ class TestPartnerRateLimits(ProvisioningTestBase):
"/api/agentic/oauth/token",
data=body,
content_type="application/x-www-form-urlencoded",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 429
@@ -257,7 +196,6 @@ class TestPartnerRateLimits(ProvisioningTestBase):
"/api/agentic/oauth/token",
data=body,
content_type="application/x-www-form-urlencoded",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 200
@@ -288,7 +226,6 @@ class TestPartnerRateLimits(ProvisioningTestBase):
"/api/agentic/oauth/token",
data=body,
content_type="application/x-www-form-urlencoded",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 429
@@ -305,37 +242,10 @@ class TestPartnerRateLimits(ProvisioningTestBase):
# Re-set the resource_creates limit counter fresh
# (cache.clear wiped it, but we need 1 request to fill it)
- res = self.client.post(
- "/api/agentic/provisioning/resources",
- data=json.dumps({"service_id": "analytics"}).encode(),
- content_type="application/json",
- HTTP_API_VERSION="0.1d",
- HTTP_AUTHORIZATION=f"Bearer {token}",
- )
+ res = self._post_with_bearer("/api/agentic/provisioning/resources", {}, token=token)
assert res.status_code == 200
- res = self.client.post(
- "/api/agentic/provisioning/resources",
- data=json.dumps({"service_id": "analytics"}).encode(),
- content_type="application/json",
- HTTP_API_VERSION="0.1d",
- HTTP_AUTHORIZATION=f"Bearer {token}",
- )
+ res = self._post_with_bearer("/api/agentic/provisioning/resources", {}, token=token)
assert res.status_code == 429
assert res.json()["status"] == "error"
assert res.json()["error"]["code"] == "rate_limited"
-
- # --- Stripe Projects (legacy HMAC) is not rate limited ---
-
- def test_stripe_projects_not_rate_limited(self):
- for _ in range(15):
- payload = {
- "id": f"acctreq_{secrets.token_hex(8)}",
- "email": f"user_{secrets.token_hex(4)}@example.com",
- "scopes": ["query:read"],
- "confirmation_secret": "cs_test",
- "expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),
- "orchestrator": {"type": "stripe", "stripe": {"account": "acct_123"}},
- }
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
- assert res.status_code in (200, 201), f"Expected success, got {res.status_code}: {res.json()}"
diff --git a/ee/api/agentic_provisioning/test/test_provisioning_auth.py b/ee/api/agentic_provisioning/test/test_provisioning_auth.py
index 1d2179f96f58..a842e208e9f5 100644
--- a/ee/api/agentic_provisioning/test/test_provisioning_auth.py
+++ b/ee/api/agentic_provisioning/test/test_provisioning_auth.py
@@ -1,66 +1,27 @@
import json
-import time
-import base64
-import hashlib
-import secrets
-from urllib.parse import urlencode
-from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from django.core.cache import cache as real_cache
-from django.test import override_settings
from parameterized import parameterized
-from rest_framework.test import APIClient
from posthog.api.oauth.cimd import _blocked_key, _cache_key
from posthog.models.oauth import OAuthApplication
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.user import User
from ee.api.agentic_provisioning.authentication import ProvisioningAuthentication
-from ee.api.agentic_provisioning.signature import compute_signature
+from ee.api.agentic_provisioning.test.base import ProvisioningTestBase
-HMAC_SECRET = "test_hmac_secret"
WIZARD_CLIENT_ID = "test-wizard-client"
-TEST_STRIPE_OAUTH_CLIENT_ID = "test_stripe_oauth_client_id"
-def _pkce_pair():
- """Generate a PKCE code_verifier and code_challenge pair."""
- verifier = secrets.token_urlsafe(32)
- challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()).rstrip(b"=").decode("ascii")
- return verifier, challenge
-
-
-@override_settings(
- STRIPE_SIGNING_SECRET=HMAC_SECRET,
- STRIPE_POSTHOG_OAUTH_CLIENT_ID=TEST_STRIPE_OAUTH_CLIENT_ID,
- STRIPE_ORCHESTRATOR_CALLBACK_URL="https://stripe.com/callback",
-)
-class TestProvisioningAuthentication(APIBaseTest):
+class TestProvisioningAuthentication(ProvisioningTestBase):
def setUp(self):
super().setUp()
- self.client = APIClient()
-
- # Delete and recreate to ensure clean state with all provisioning fields
- OAuthApplication.objects.filter(client_id__in=[TEST_STRIPE_OAUTH_CLIENT_ID, WIZARD_CLIENT_ID]).delete()
-
- self.stripe_app = OAuthApplication.objects.create(
- client_id=TEST_STRIPE_OAUTH_CLIENT_ID,
- name="PostHog Stripe App",
- client_secret="",
- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="https://stripe.com/callback",
- algorithm="RS256",
- provisioning_auth_method="hmac",
- provisioning_signing_secret=HMAC_SECRET,
- provisioning_partner_type="stripe",
- provisioning_active=True,
- provisioning_can_create_accounts=True,
- provisioning_can_provision_resources=True,
- )
+ OAuthApplication.objects.filter(client_id=WIZARD_CLIENT_ID).delete()
self.wizard_app = OAuthApplication.objects.create(
client_id=WIZARD_CLIENT_ID,
name="PostHog Wizard",
@@ -76,148 +37,115 @@ class TestProvisioningAuthentication(APIBaseTest):
provisioning_can_create_accounts=True,
provisioning_can_provision_resources=True,
)
- self.wizard_app.refresh_from_db()
- def _sign_body(self, body: bytes) -> str:
- ts = int(time.time())
- sig = compute_signature(HMAC_SECRET, ts, body)
- return f"t={ts},v1={sig}"
+ def _wizard_account_request(self, request_id: str, email: str, challenge: str):
+ return self._post_api(
+ "/api/agentic/provisioning/account_requests",
+ {
+ "id": request_id,
+ "email": email,
+ "client_id": WIZARD_CLIENT_ID,
+ "code_challenge": challenge,
+ "code_challenge_method": "S256",
+ },
+ )
- # --- HMAC identification ---
+ def _exchange_code(self, code: str, verifier: str):
+ return self.client.post(
+ "/api/agentic/oauth/token",
+ data={"grant_type": "authorization_code", "code": code, "code_verifier": verifier},
+ )
- def test_hmac_partner_identified_by_signature(self):
- body = json.dumps(
- {
- "id": "req_1",
- "email": "[email protected]",
- "orchestrator": {"type": "stripe", "stripe": {"account": "acct_123"}},
- }
- ).encode()
- sig = self._sign_body(body)
- res = self.client.post(
+ # --- Bearer identification ---
+
+ def test_bearer_partner_identified_by_token(self):
+ token = self._get_bearer_token()
+ res = self._post_with_bearer(
"/api/agentic/provisioning/account_requests",
- data=body,
- content_type="application/json",
- headers={"stripe-signature": sig, "api-version": "0.1d"},
+ {"id": "req_bearer", "email": "[email protected]"},
+ token=token,
)
assert res.status_code == 200
assert res.json()["type"] == "oauth"
- # --- PKCE flow ---
+ def test_inactive_bearer_partner_rejected(self):
+ token = self._get_bearer_token()
+ self.partner.provisioning_active = False
+ self.partner.save(update_fields=["provisioning_active"])
- def test_pkce_wizard_new_user_full_flow(self):
- verifier, challenge = _pkce_pair()
+ res = self._post_with_bearer(
+ "/api/agentic/provisioning/account_requests",
+ {"id": "req_inactive_bearer", "email": "[email protected]"},
+ token=token,
+ )
+ assert res.status_code == 401
+ assert res.json()["error"]["code"] == "unauthorized"
- # Step 1: account_requests with PKCE
- res = self.client.post(
+ # --- HMAC partners are fail-closed ---
+
+ def test_hmac_partner_can_no_longer_authenticate(self):
+ OAuthApplication.objects.create(
+ client_id="legacy-hmac-partner",
+ name="Legacy HMAC Partner",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://legacy.example.com/callback",
+ algorithm="RS256",
+ provisioning_auth_method="hmac",
+ provisioning_partner_type="stripe",
+ provisioning_active=True,
+ provisioning_can_create_accounts=True,
+ provisioning_can_provision_resources=True,
+ )
+
+ res = self._post_api(
"/api/agentic/provisioning/account_requests",
- data={
- "id": "req_wizard_1",
- "email": "[email protected]",
- "client_id": WIZARD_CLIENT_ID,
- "code_challenge": challenge,
- "code_challenge_method": "S256",
- },
- content_type="application/json",
- headers={"api-version": "0.1d"},
+ {"id": "req_hmac", "email": "[email protected]", "client_id": "legacy-hmac-partner"},
+ HTTP_STRIPE_SIGNATURE="t=1234567890,v1=deadbeef",
)
+ assert res.status_code == 401
+ assert res.json()["error"]["code"] == "unauthorized"
+
+ # --- PKCE flow ---
+
+ def test_pkce_wizard_new_user_full_flow(self):
+ verifier, challenge = self._pkce_pair()
+
+ res = self._wizard_account_request("req_wizard_1", "[email protected]", challenge)
assert res.status_code == 200
data = res.json()
assert data["type"] == "oauth"
code = data["oauth"]["code"]
- # Step 2: exchange code with code_verifier
- res = self.client.post(
- "/api/agentic/oauth/token",
- data=urlencode(
- {
- "grant_type": "authorization_code",
- "code": code,
- "code_verifier": verifier,
- }
- ),
- content_type="application/x-www-form-urlencoded",
- headers={"api-version": "0.1d"},
- )
+ res = self._exchange_code(code, verifier)
assert res.status_code == 200
tokens = res.json()
assert "access_token" in tokens
assert "refresh_token" in tokens
assert tokens["expires_in"] == 3600
- # Step 3: use bearer token for resources
- res = self.client.post(
- "/api/agentic/provisioning/resources",
- data=json.dumps({"service_id": "analytics"}),
- content_type="application/json",
- headers={"authorization": f"Bearer {tokens['access_token']}", "api-version": "0.1d"},
- )
+ res = self._post_with_bearer("/api/agentic/provisioning/resources", {}, token=tokens["access_token"])
assert res.status_code == 200
assert res.json()["status"] == "complete"
assert "api_key" in res.json()["complete"]["access_configuration"]
- def test_pkce_wrong_verifier_rejected(self):
- _, challenge = _pkce_pair()
+ @parameterized.expand(
+ [
+ ("wrong_verifier", "wrong_verifier_value", 400),
+ ("missing_verifier", "", 401),
+ ]
+ )
+ def test_pkce_code_exchange_requires_matching_verifier(self, _name, verifier, expected_status):
+ _, challenge = self._pkce_pair()
- res = self.client.post(
- "/api/agentic/provisioning/account_requests",
- data={
- "id": "req_bad_pkce",
- "email": "[email protected]",
- "client_id": WIZARD_CLIENT_ID,
- "code_challenge": challenge,
- "code_challenge_method": "S256",
- },
- content_type="application/json",
- headers={"api-version": "0.1d"},
- )
+ res = self._wizard_account_request("req_bad_pkce", "[email protected]", challenge)
code = res.json()["oauth"]["code"]
- res = self.client.post(
- "/api/agentic/oauth/token",
- data=urlencode(
- {
- "grant_type": "authorization_code",
- "code": code,
- "code_verifier": "wrong_verifier_value",
- }
- ),
- content_type="application/x-www-form-urlencoded",
- headers={"api-version": "0.1d"},
- )
- assert res.status_code == 400
- assert res.json()["error"] == "invalid_grant"
-
- def test_pkce_missing_verifier_rejected(self):
- _, challenge = _pkce_pair()
-
- res = self.client.post(
- "/api/agentic/provisioning/account_requests",
- data={
- "id": "req_no_verifier",
- "email": "[email protected]",
- "client_id": WIZARD_CLIENT_ID,
- "code_challenge": challenge,
- "code_challenge_method": "S256",
- },
- content_type="application/json",
- headers={"api-version": "0.1d"},
- )
- code = res.json()["oauth"]["code"]
-
- # Without code_verifier or HMAC, the request is unauthenticated
- res = self.client.post(
- "/api/agentic/oauth/token",
- data=urlencode(
- {
- "grant_type": "authorization_code",
- "code": code,
- }
- ),
- content_type="application/x-www-form-urlencoded",
- headers={"api-version": "0.1d"},
- )
- assert res.status_code == 401
+ res = self._exchange_code(code, verifier)
+ assert res.status_code == expected_status
+ if expected_status == 400:
+ assert res.json()["error"] == "invalid_grant"
# --- can_create_accounts enforcement ---
@@ -236,15 +164,9 @@ class TestProvisioningAuthentication(APIBaseTest):
provisioning_can_create_accounts=False,
)
- res = self.client.post(
+ res = self._post_api(
"/api/agentic/provisioning/account_requests",
- data={
- "id": "req_disabled",
- "email": "[email protected]",
- "client_id": "disabled-partner",
- },
- content_type="application/json",
- headers={"api-version": "0.1d"},
+ {"id": "req_disabled", "email": "[email protected]", "client_id": "disabled-partner"},
)
assert res.status_code == 403
assert res.json()["error"]["code"] == "forbidden"
@@ -252,23 +174,10 @@ class TestProvisioningAuthentication(APIBaseTest):
# --- Org naming ---
def test_wizard_org_named_with_partner_type(self):
- from posthog.models.user import User
-
- verifier, challenge = _pkce_pair()
+ _, challenge = self._pkce_pair()
- self.client.post(
- "/api/agentic/provisioning/account_requests",
- data={
- "id": "req_org_name",
- "email": email,
- "client_id": WIZARD_CLIENT_ID,
- "code_challenge": challenge,
- "code_challenge_method": "S256",
- },
- content_type="application/json",
- headers={"api-version": "0.1d"},
- )
+ self._wizard_account_request("req_org_name", email, challenge)
user = User.objects.get(email=email)
membership = user.organization_memberships.first()
@@ -276,125 +185,17 @@ class TestProvisioningAuthentication(APIBaseTest):
org = membership.organization
assert org.name == f"Wizard ({email})"
- # --- Token expiry ---
-
- def test_new_tokens_expire_in_one_hour(self):
- verifier, challenge = _pkce_pair()
-
- res = self.client.post(
- "/api/agentic/provisioning/account_requests",
- data={
- "id": "req_expiry",
- "email": "[email protected]",
- "client_id": WIZARD_CLIENT_ID,
- "code_challenge": challenge,
- "code_challenge_method": "S256",
- },
- content_type="application/json",
- headers={"api-version": "0.1d"},
- )
- code = res.json()["oauth"]["code"]
-
- res = self.client.post(
- "/api/agentic/oauth/token",
- data=urlencode(
- {
- "grant_type": "authorization_code",
- "code": code,
- "code_verifier": verifier,
- }
- ),
- content_type="application/x-www-form-urlencoded",
- headers={"api-version": "0.1d"},
- )
- assert res.json()["expires_in"] == 3600
-
- # --- Stripe regression ---
-
- def test_stripe_hmac_flow_still_works(self):
- body = json.dumps(
- {
- "id": "req_stripe",
- "email": "[email protected]",
- "orchestrator": {"type": "stripe", "stripe": {"account": "acct_456"}},
- }
- ).encode()
- sig = self._sign_body(body)
- res = self.client.post(
- "/api/agentic/provisioning/account_requests",
- data=body,
- content_type="application/json",
- headers={"stripe-signature": sig, "api-version": "0.1d"},
- )
- assert res.status_code == 200
- assert res.json()["type"] == "oauth"
-
- def test_legacy_stripe_without_partner_still_works(self):
- """Stripe flow should work even if provisioning fields are not set (falls through to legacy)."""
- self.stripe_app.provisioning_auth_method = ""
- self.stripe_app.save(update_fields=["provisioning_auth_method"])
-
- body = json.dumps(
- {
- "id": "req_legacy",
- "email": "[email protected]",
- "orchestrator": {"type": "stripe", "stripe": {"account": "acct_789"}},
- }
- ).encode()
- sig = self._sign_body(body)
- res = self.client.post(
- "/api/agentic/provisioning/account_requests",
- data=body,
- content_type="application/json",
- headers={"stripe-signature": sig, "api-version": "0.1d"},
- )
- assert res.status_code == 200
- assert res.json()["type"] == "oauth"
-
# --- PAT scopes ---
def test_default_off_app_mints_no_provisioned_pat(self):
- from posthog.models.personal_api_key import PersonalAPIKey
-
- verifier, challenge = _pkce_pair()
+ verifier, challenge = self._pkce_pair()
- res = self.client.post(
- "/api/agentic/provisioning/account_requests",
- data={
- "id": "req_pat",
- "email": email,
- "client_id": WIZARD_CLIENT_ID,
- "code_challenge": challenge,
- "code_challenge_method": "S256",
- },
- content_type="application/json",
- headers={"api-version": "0.1d"},
- )
+ res = self._wizard_account_request("req_pat", email, challenge)
code = res.json()["oauth"]["code"]
+ token = self._exchange_code(code, verifier).json()["access_token"]
- res = self.client.post(
- "/api/agentic/oauth/token",
- data=urlencode(
- {
- "grant_type": "authorization_code",
- "code": code,
- "code_verifier": verifier,
- }
- ),
- content_type="application/x-www-form-urlencoded",
- headers={"api-version": "0.1d"},
- )
- token = res.json()["access_token"]
-
- self.client.post(
- "/api/agentic/provisioning/resources",
- data=json.dumps({"service_id": "analytics"}),
- content_type="application/json",
- headers={"authorization": f"Bearer {token}", "api-version": "0.1d"},
- )
-
- from posthog.models.user import User
+ self._post_with_bearer("/api/agentic/provisioning/resources", {}, token=token)
user = User.objects.get(email=email)
# The wizard app does not set provisioning_issues_personal_api_key, so no PAT is minted.
@@ -403,115 +204,31 @@ class TestProvisioningAuthentication(APIBaseTest):
# --- is_active kill switch ---
- def test_inactive_hmac_partner_rejected(self):
- self.stripe_app.provisioning_active = False
- self.stripe_app.save(update_fields=["provisioning_active"])
-
- body = json.dumps(
- {
- "id": "req_inactive",
- "email": "[email protected]",
- "orchestrator": {"type": "stripe", "stripe": {"account": "acct_inactive"}},
- }
- ).encode()
- sig = self._sign_body(body)
- res = self.client.post(
- "/api/agentic/provisioning/account_requests",
- data=body,
- content_type="application/json",
- headers={"stripe-signature": sig, "api-version": "0.1d"},
- )
- # Inactive HMAC partner is filtered out of identification, falls through to legacy
- # which still works via verify_provisioning_signature (same secret in settings)
- # But the ProvisioningAuthentication won't return it
- assert res.status_code == 200
-
- self.stripe_app.provisioning_active = True
- self.stripe_app.save(update_fields=["provisioning_active"])
-
def test_inactive_pkce_partner_rejected(self):
self.wizard_app.provisioning_active = False
self.wizard_app.save(update_fields=["provisioning_active"])
- _, challenge = _pkce_pair()
- res = self.client.post(
- "/api/agentic/provisioning/account_requests",
- data={
- "id": "req_inactive_pkce",
- "email": "[email protected]",
- "client_id": WIZARD_CLIENT_ID,
- "code_challenge": challenge,
- "code_challenge_method": "S256",
- },
- content_type="application/json",
- headers={"api-version": "0.1d"},
- )
- # Inactive partner not identified -> no partner + no HMAC -> 401
+ _, challenge = self._pkce_pair()
+ res = self._wizard_account_request("req_inactive_pkce", "[email protected]", challenge)
assert res.status_code == 401
- self.wizard_app.provisioning_active = True
- self.wizard_app.save(update_fields=["provisioning_active"])
-
- # --- Encrypted signing_secret round-trip ---
-
- def test_signing_secret_encrypts_and_decrypts_for_hmac(self):
- app = OAuthApplication.objects.get(id=self.stripe_app.id)
- assert app.provisioning_signing_secret == HMAC_SECRET
-
- from ee.api.agentic_provisioning.signature import _compute_hmac
-
- body = b'{"test": "data"}'
- expected = _compute_hmac(app.provisioning_signing_secret, "12345", body)
- computed = _compute_hmac(HMAC_SECRET, "12345", body)
- assert expected == computed
-
# --- can_provision_resources enforcement ---
def test_partner_without_can_provision_resources_rejected(self):
- verifier, challenge = _pkce_pair()
+ token = self._get_bearer_token()
- res = self.client.post(
- "/api/agentic/provisioning/account_requests",
- data={
- "id": "req_no_prov",
- "email": "[email protected]",
- "client_id": WIZARD_CLIENT_ID,
- "code_challenge": challenge,
- "code_challenge_method": "S256",
- },
- content_type="application/json",
- headers={"api-version": "0.1d"},
- )
- code = res.json()["oauth"]["code"]
+ self.partner.provisioning_can_provision_resources = False
+ self.partner.save(update_fields=["provisioning_can_provision_resources"])
- res = self.client.post(
- "/api/agentic/oauth/token",
- data=urlencode({"grant_type": "authorization_code", "code": code, "code_verifier": verifier}),
- content_type="application/x-www-form-urlencoded",
- headers={"api-version": "0.1d"},
- )
- token = res.json()["access_token"]
-
- self.wizard_app.provisioning_can_provision_resources = False
- self.wizard_app.save(update_fields=["provisioning_can_provision_resources"])
-
- res = self.client.post(
- "/api/agentic/provisioning/resources",
- data=json.dumps({"service_id": "analytics"}),
- content_type="application/json",
- headers={"authorization": f"Bearer {token}", "api-version": "0.1d"},
- )
+ res = self._post_with_bearer("/api/agentic/provisioning/resources", {}, token=token)
assert res.status_code == 403
- self.wizard_app.provisioning_can_provision_resources = True
- self.wizard_app.save(update_fields=["provisioning_can_provision_resources"])
-
# --- CIMD URL-based PKCE identification ---
@patch("posthog.api.oauth.cimd.refresh_cimd_metadata_task")
def test_pkce_partner_identified_by_cimd_url(self, mock_refresh):
cimd_url = "https://example.com/api/oauth/wizard/client-metadata"
- cimd_app = OAuthApplication.objects.create(
+ OAuthApplication.objects.create(
name="CIMD Wizard",
client_secret="",
client_type=OAuthApplication.CLIENT_PUBLIC,
@@ -527,28 +244,24 @@ class TestProvisioningAuthentication(APIBaseTest):
provisioning_can_provision_resources=True,
)
- verifier, challenge = _pkce_pair()
- res = self.client.post(
+ _, challenge = self._pkce_pair()
+ res = self._post_api(
"/api/agentic/provisioning/account_requests",
- data={
+ {
"id": "req_cimd_pkce",
"email": "[email protected]",
"client_id": cimd_url,
"code_challenge": challenge,
"code_challenge_method": "S256",
},
- content_type="application/json",
- headers={"api-version": "0.1d"},
)
assert res.status_code == 200
assert res.json()["type"] == "oauth"
- cimd_app.delete()
-
@patch("posthog.api.oauth.cimd.refresh_cimd_metadata_task")
def test_cimd_url_inactive_partner_rejected(self, mock_refresh):
cimd_url = "https://example.com/api/oauth/wizard/client-metadata-inactive"
- cimd_app = OAuthApplication.objects.create(
+ OAuthApplication.objects.create(
name="Inactive CIMD Wizard",
client_secret="",
client_type=OAuthApplication.CLIENT_PUBLIC,
@@ -563,23 +276,19 @@ class TestProvisioningAuthentication(APIBaseTest):
provisioning_can_create_accounts=True,
)
- _, challenge = _pkce_pair()
- res = self.client.post(
+ _, challenge = self._pkce_pair()
+ res = self._post_api(
"/api/agentic/provisioning/account_requests",
- data={
+ {
"id": "req_cimd_inactive",
"email": "[email protected]",
"client_id": cimd_url,
"code_challenge": challenge,
"code_challenge_method": "S256",
},
- content_type="application/json",
- headers={"api-version": "0.1d"},
)
assert res.status_code == 401
- cimd_app.delete()
-
@parameterized.expand(
[
("stale_cache_fires_refresh", False, 1),
@@ -606,7 +315,6 @@ class TestProvisioningAuthentication(APIBaseTest):
provisioning_can_create_accounts=True,
provisioning_can_provision_resources=True,
)
- self.addCleanup(cimd_app.delete)
self.addCleanup(real_cache.delete, _cache_key(cimd_url))
# _identify_pkce_partner warms the blocklist cache with a 1-year TTL; clear it too.
self.addCleanup(real_cache.delete, _blocked_key(cimd_url))
@@ -626,17 +334,15 @@ class TestProvisioningAuthentication(APIBaseTest):
# --- PKCE code_challenge_method validation ---
def test_plain_code_challenge_method_rejected(self):
- res = self.client.post(
+ res = self._post_api(
"/api/agentic/provisioning/account_requests",
- data={
+ {
"id": "req_plain",
"email": "[email protected]",
"client_id": WIZARD_CLIENT_ID,
"code_challenge": "some_challenge",
"code_challenge_method": "plain",
},
- content_type="application/json",
- headers={"api-version": "0.1d"},
)
assert res.status_code == 400
assert "S256" in res.json()["error"]["message"]
@@ -671,21 +377,15 @@ def _cimd_mock_response(metadata: dict | None, status_code: int = 200):
@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))
-@override_settings(
- STRIPE_APP_SECRET_KEY=HMAC_SECRET,
- STRIPE_POSTHOG_OAUTH_CLIENT_ID=TEST_STRIPE_OAUTH_CLIENT_ID,
- STRIPE_ORCHESTRATOR_CALLBACK_URL="https://stripe.com/callback",
-)
-class TestCimdProvisioningAutoRegistration(APIBaseTest):
+class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):
def setUp(self):
super().setUp()
- self.client = APIClient()
OAuthApplication.objects.filter(cimd_metadata_url=CIMD_PROV_URL).delete()
real_cache.clear()
@patch("ee.api.agentic_provisioning.authentication.register_cimd_provisioning_application_task")
def test_new_cimd_partner_returns_202_and_kicks_off_registration(self, mock_task, _url_mock):
- _, challenge = _pkce_pair()
+ _, challenge = self._pkce_pair()
res = self.client.post(
"/api/agentic/provisioning/account_requests",
data={
@@ -696,7 +396,6 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"code_challenge_method": "S256",
},
content_type="application/json",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 202
@@ -719,7 +418,7 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
assert app.provisioning_can_create_accounts
assert app.provisioning_can_provision_resources
- _, challenge = _pkce_pair()
+ _, challenge = self._pkce_pair()
res = self.client.post(
"/api/agentic/provisioning/account_requests",
data={
@@ -730,7 +429,6 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"code_challenge_method": "S256",
},
content_type="application/json",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 200
assert res.json()["type"] == "oauth"
@@ -755,7 +453,7 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
# A later agentic provisioning auth request must propagate the edit — the bug was that
# this raw-lookup path never refreshed, so the ceiling stayed frozen at registration.
- _, challenge = _pkce_pair()
+ _, challenge = self._pkce_pair()
res = self.client.post(
"/api/agentic/provisioning/account_requests",
data={
@@ -766,7 +464,6 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"code_challenge_method": "S256",
},
content_type="application/json",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 200
@@ -786,7 +483,7 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
cimd_metadata_url=CIMD_PROV_URL,
)
- _, challenge = _pkce_pair()
+ _, challenge = self._pkce_pair()
res = self.client.post(
"/api/agentic/provisioning/account_requests",
data={
@@ -797,7 +494,6 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"code_challenge_method": "S256",
},
content_type="application/json",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 200
@@ -820,7 +516,7 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"ee.api.agentic_provisioning.authentication.apply_provisioning_defaults",
side_effect=RuntimeError("simulated DB error"),
):
- _, challenge = _pkce_pair()
+ _, challenge = self._pkce_pair()
res = self.client.post(
"/api/agentic/provisioning/account_requests",
data={
@@ -831,13 +527,12 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"code_challenge_method": "S256",
},
content_type="application/json",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 401
@patch("ee.api.agentic_provisioning.authentication.register_cimd_provisioning_application_task")
def test_new_cimd_url_returns_202_not_401(self, mock_task, _url_mock):
- _, challenge = _pkce_pair()
+ _, challenge = self._pkce_pair()
res = self.client.post(
"/api/agentic/provisioning/account_requests",
data={
@@ -848,7 +543,6 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"code_challenge_method": "S256",
},
content_type="application/json",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 202
assert res.json()["type"] == "registering"
@@ -872,7 +566,7 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
provisioning_rate_limit_account_requests=10,
)
- _, challenge = _pkce_pair()
+ _, challenge = self._pkce_pair()
def post_account_request(email: str):
return self.client.post(
@@ -885,7 +579,6 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"code_challenge_method": "S256",
},
content_type="application/json",
- HTTP_API_VERSION="0.1d",
)
assert post_account_request("[email protected]").status_code == 200
@@ -905,7 +598,7 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
from ee.api.agentic_provisioning.views import CIMD_DOMAIN_RATE_LIMIT_MAX
base_domain = "evil.example.com"
- _, challenge = _pkce_pair()
+ _, challenge = self._pkce_pair()
for i in range(CIMD_DOMAIN_RATE_LIMIT_MAX):
url = f"https://{base_domain}/path-{i}/metadata.json"
@@ -919,7 +612,6 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"code_challenge_method": "S256",
},
content_type="application/json",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 202, f"Request {i} failed: {res.json()}"
@@ -934,7 +626,6 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"code_challenge_method": "S256",
},
content_type="application/json",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 429
assert res.json()["error"]["code"] == "rate_limited"
@@ -944,7 +635,7 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
def test_cimd_domain_rate_limit_does_not_block_different_domains(self, mock_task, _url_mock):
from ee.api.agentic_provisioning.views import CIMD_DOMAIN_RATE_LIMIT_MAX
- _, challenge = _pkce_pair()
+ _, challenge = self._pkce_pair()
for i in range(CIMD_DOMAIN_RATE_LIMIT_MAX + 2):
url = f"https://domain-{i}.example.com/.well-known/metadata.json"
@@ -958,7 +649,6 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"code_challenge_method": "S256",
},
content_type="application/json",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 202, f"Request {i} for domain-{i} failed: {res.json()}"
@@ -968,7 +658,7 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
from ee.api.agentic_provisioning.views import CIMD_DOMAIN_RATE_LIMIT_MAX
base_domain = "existing.example.com"
- _, challenge = _pkce_pair()
+ _, challenge = self._pkce_pair()
for i in range(CIMD_DOMAIN_RATE_LIMIT_MAX + 1):
url = f"https://{base_domain}/path-{i}/metadata.json"
@@ -998,14 +688,11 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"code_challenge_method": "S256",
},
content_type="application/json",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 200
@patch("posthog.api.oauth.cimd.refresh_cimd_metadata_task")
def test_self_serve_org_named_after_client_name(self, mock_refresh, _url_mock):
- from posthog.models.user import User
-
OAuthApplication.objects.create(
name="Partner App",
client_secret="",
@@ -1022,7 +709,7 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
)
- _, challenge = _pkce_pair()
+ _, challenge = self._pkce_pair()
self.client.post(
"/api/agentic/provisioning/account_requests",
data={
@@ -1033,7 +720,6 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"code_challenge_method": "S256",
},
content_type="application/json",
- HTTP_API_VERSION="0.1d",
)
user = User.objects.get(email=email)
@@ -1045,7 +731,7 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
block_cimd_url(CIMD_PROV_URL)
- _, challenge = _pkce_pair()
+ _, challenge = self._pkce_pair()
res = self.client.post(
"/api/agentic/provisioning/account_requests",
data={
@@ -1056,7 +742,6 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"code_challenge_method": "S256",
},
content_type="application/json",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 401
@@ -1080,7 +765,7 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
)
block_cimd_url(CIMD_PROV_URL)
- _, challenge = _pkce_pair()
+ _, challenge = self._pkce_pair()
res = self.client.post(
"/api/agentic/provisioning/account_requests",
data={
@@ -1091,6 +776,5 @@ class TestCimdProvisioningAutoRegistration(APIBaseTest):
"code_challenge_method": "S256",
},
content_type="application/json",
- HTTP_API_VERSION="0.1d",
)
assert res.status_code == 401
diff --git a/ee/api/agentic_provisioning/test/test_region_proxy.py b/ee/api/agentic_provisioning/test/test_region_proxy.py
index b0e11b8f6927..c6c082c3e4b1 100644
--- a/ee/api/agentic_provisioning/test/test_region_proxy.py
+++ b/ee/api/agentic_provisioning/test/test_region_proxy.py
@@ -163,7 +163,7 @@ class TestProxyHeaderAllowlist(BaseTest):
mock_requests.request.return_value = mock_response
raw = factory.post(
- "/api/agentic/provisioning/health",
+ "/api/agentic/provisioning/account_requests",
data={},
format="json",
HTTP_COOKIE="sessionid=secret123",
@@ -181,19 +181,16 @@ class TestProxyHeaderAllowlist(BaseTest):
assert "cookie" not in header_keys_lower
assert "x-forwarded-for" not in header_keys_lower
+ assert "stripe-signature" not in header_keys_lower
+ assert "authorization" in header_keys_lower
assert "host" in header_keys_lower
assert forwarded_headers["Host"] == "eu.posthog.com"
class TestDecoratorIntegration(ProvisioningTestBase):
@override_settings(CLOUD_DEPLOYMENT="US")
- def test_hmac_failure_returns_401_without_proxying(self):
- res = self.client.post(
- "/api/agentic/provisioning/account_requests",
- data={"email": "[email protected]"},
- content_type="application/json",
- headers={"api-version": "0.1d"},
- )
+ def test_unauthenticated_request_returns_401_without_proxying(self):
+ res = self._post_api("/api/agentic/provisioning/account_requests", data={"email": "[email protected]"})
assert res.status_code == 401
@override_settings(CLOUD_DEPLOYMENT="US")
@@ -201,7 +198,7 @@ class TestDecoratorIntegration(ProvisioningTestBase):
def test_proxy_success_returns_proxied_response(self, mock_proxy):
mock_proxy.return_value = Response({"type": "oauth", "oauth": {"code": "abc"}})
payload = {"email": "[email protected]", "configuration": {"region": "EU"}}
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ res = self._post_api("/api/agentic/provisioning/account_requests", data=payload)
assert mock_proxy.called
assert res.status_code == 200
@@ -212,7 +209,7 @@ class TestDecoratorIntegration(ProvisioningTestBase):
mock_proxy.side_effect = requests.exceptions.ConnectionError("connection refused")
payload = {"email": "[email protected]", "configuration": {"region": "EU"}}
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ res = self._post_api("/api/agentic/provisioning/account_requests", data=payload)
assert res.status_code == 502
assert res.json()["error"]["code"] == "proxy_failed"
@@ -222,9 +219,10 @@ class TestDecoratorIntegration(ProvisioningTestBase):
"email": "[email protected]",
"configuration": {"region": "EU"},
"scopes": ["query:read"],
- "orchestrator": {"type": "stripe", "stripe": {"account": "acct_dev"}},
}
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ res = self._post_with_bearer(
+ "/api/agentic/provisioning/account_requests", data=payload, token=self._get_bearer_token()
+ )
assert res.status_code == 200
assert res.json()["type"] == "oauth"
@@ -234,9 +232,10 @@ class TestDecoratorIntegration(ProvisioningTestBase):
"email": "[email protected]",
"configuration": {"region": "US"},
"scopes": ["query:read"],
- "orchestrator": {"type": "stripe", "stripe": {"account": "acct_us"}},
}
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ res = self._post_with_bearer(
+ "/api/agentic/provisioning/account_requests", data=payload, token=self._get_bearer_token()
+ )
assert res.status_code == 200
assert res.json()["type"] == "oauth"
@@ -250,48 +249,45 @@ class TestBearerLookupDecoratorCoverage(ProvisioningTestBase):
cache.clear()
self._local_token = self._get_bearer_token()
- def _resource_endpoints(self) -> list[tuple[str, str, str]]:
+ def _resource_endpoints(self) -> list[tuple[str, str]]:
return [
- ("POST", f"/api/agentic/provisioning/resources", ""),
- ("GET", f"/api/agentic/provisioning/resources/{self.team.id}", ""),
- ("POST", f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials", ""),
- ("POST", f"/api/agentic/provisioning/resources/{self.team.id}/update_service", "free"),
- ("POST", f"/api/agentic/provisioning/resources/{self.team.id}/remove", ""),
- ("POST", f"/api/agentic/provisioning/deep_links", ""),
+ ("POST", "/api/agentic/provisioning/resources"),
+ ("GET", f"/api/agentic/provisioning/resources/{self.team.id}"),
+ ("POST", f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials"),
+ ("POST", f"/api/agentic/provisioning/resources/{self.team.id}/remove"),
+ ("POST", "/api/agentic/provisioning/deep_links"),
]
- def _call(self, method: str, url: str, token: str, extra: str):
+ def _call(self, method: str, url: str, token: str):
data = {}
- if "update_service" in url:
- data = {"service_id": extra}
if "deep_links" in url:
data = {"purpose": "dashboard"}
if method == "GET":
- return self._get_signed_with_bearer(url, token=token)
- return self._post_signed_with_bearer(url, data=data, token=token)
+ return self._get_with_bearer(url, token=token)
+ return self._post_with_bearer(url, data=data, token=token)
@override_settings(CLOUD_DEPLOYMENT="US")
@patch("ee.api.agentic_provisioning.region_proxy._proxy_to_region")
def test_unknown_bearer_token_is_proxied_on_every_endpoint(self, mock_proxy):
mock_proxy.return_value = Response({"status": "ok"}, status=200)
- for method, url, extra in self._resource_endpoints():
+ for method, url in self._resource_endpoints():
mock_proxy.reset_mock()
cache.clear()
- self._call(method, url, "totally_unknown_token", extra)
+ self._call(method, url, "totally_unknown_token")
assert mock_proxy.called, f"{method} {url} should have proxied unknown bearer to other region"
@override_settings(CLOUD_DEPLOYMENT="US")
@patch("ee.api.agentic_provisioning.region_proxy._proxy_to_region")
def test_known_bearer_token_is_not_proxied(self, mock_proxy):
- for method, url, extra in self._resource_endpoints():
+ for method, url in self._resource_endpoints():
mock_proxy.reset_mock()
cache.clear()
# A fresh token per iteration — the /remove handler revokes the token
# when scope becomes empty, so one call can invalidate the next.
token = self._get_bearer_token()
- self._call(method, url, token, extra)
+ self._call(method, url, token)
assert not mock_proxy.called, f"{method} {url} should not proxy for a locally valid bearer token"
@@ -306,7 +302,6 @@ class TestDecoratorCoverageContract(BaseTest):
"provisioning_resources_create": "bearer_lookup",
"provisioning_resource_detail": "bearer_lookup",
"provisioning_rotate_credentials": "bearer_lookup",
- "provisioning_update_service": "bearer_lookup",
"provisioning_resource_remove": "bearer_lookup",
"deep_links": "bearer_lookup",
"account_requests": "body_region",
@@ -396,10 +391,11 @@ class TestCrossRegionLoopback(ProvisioningTestBase):
"email": "[email protected]",
"configuration": {"region": "EU"},
"scopes": ["query:read"],
- "orchestrator": {"type": "stripe", "stripe": {"account": "acct_eu_loop"}},
}
- res = self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ res = self._post_with_bearer(
+ "/api/agentic/provisioning/account_requests", data=payload, token=self._get_bearer_token()
+ )
assert mock_request.called, "US instance should have proxied to EU"
assert captured["host"] == "eu.posthog.com"
@@ -424,7 +420,7 @@ class TestCrossRegionLoopback(ProvisioningTestBase):
mock_request.side_effect = side_effect
unknown_token = "pha_totally_bogus_token_not_in_db"
- res = self._get_signed_with_bearer(
+ res = self._get_with_bearer(
f"/api/agentic/provisioning/resources/{self.team.id}",
token=unknown_token,
)
@@ -480,9 +476,10 @@ class TestCrossRegionLoopback(ProvisioningTestBase):
"email": "[email protected]",
"configuration": {"region": "EU"},
"scopes": ["query:read"],
- "orchestrator": {"type": "stripe", "stripe": {"account": "acct_loop_guard"}},
}
- self._post_signed("/api/agentic/provisioning/account_requests", data=payload)
+ self._post_with_bearer(
+ "/api/agentic/provisioning/account_requests", data=payload, token=self._get_bearer_token()
+ )
assert call_count["n"] == 1, (
f"proxy should fire exactly once (US→EU); got {call_count['n']} — loop header not respected"
diff --git a/ee/api/agentic_provisioning/test/test_resources.py b/ee/api/agentic_provisioning/test/test_resources.py
index 2b230a7325f4..26e3afdf7a3b 100644
--- a/ee/api/agentic_provisioning/test/test_resources.py
+++ b/ee/api/agentic_provisioning/test/test_resources.py
@@ -1,24 +1,20 @@
from unittest.mock import patch
-from django.test import override_settings
-
from parameterized import parameterized
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team.team import Team
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, TEST_STRIPE_OAUTH_CLIENT_ID, ProvisioningTestBase
+from ee.api.agentic_provisioning.test.base import ProvisioningTestBase
from ee.api.agentic_provisioning.views import _maybe_create_provisioned_pat
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestProvisioningResources(ProvisioningTestBase):
def test_create_resource_returns_complete(self):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
token=token,
)
assert res.status_code == 200
@@ -31,9 +27,8 @@ class TestProvisioningResources(ProvisioningTestBase):
@patch("ee.api.agentic_provisioning.views._capture_provisioning_event")
def test_create_resource_capture_attributes_client(self, mock_capture_event):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
token=token,
)
assert res.status_code == 200
@@ -44,11 +39,11 @@ class TestProvisioningResources(ProvisioningTestBase):
assert len(success_calls) == 1
partner = success_calls[0].kwargs["partner"]
assert partner is not None
- assert partner.name == "PostHog Stripe App"
+ assert partner.name == "Test Provisioning Partner"
def test_get_resource_returns_complete(self):
token = self._get_bearer_token()
- res = self._get_signed_with_bearer(
+ res = self._get_with_bearer(
f"/api/agentic/provisioning/resources/{self.team.id}",
token=token,
)
@@ -59,7 +54,7 @@ class TestProvisioningResources(ProvisioningTestBase):
def test_get_resource_wrong_team_returns_403(self):
token = self._get_bearer_token()
- res = self._get_signed_with_bearer(
+ res = self._get_with_bearer(
"/api/agentic/provisioning/resources/99999",
token=token,
)
@@ -67,64 +62,31 @@ class TestProvisioningResources(ProvisioningTestBase):
def test_get_resource_invalid_id_returns_400(self):
token = self._get_bearer_token()
- res = self._get_signed_with_bearer(
+ res = self._get_with_bearer(
"/api/agentic/provisioning/resources/not-a-number",
token=token,
)
assert res.status_code == 400
def test_create_resource_missing_bearer_returns_401(self):
- res = self._post_signed("/api/agentic/provisioning/resources", data={"service_id": "analytics"})
+ res = self._post_api("/api/agentic/provisioning/resources")
assert res.status_code == 401
def test_create_resource_invalid_bearer_returns_401(self):
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
token="pha_invalid_token",
)
assert res.status_code == 401
def test_get_resource_missing_bearer_returns_401(self):
- res = self._get_signed(f"/api/agentic/provisioning/resources/{self.team.id}")
+ res = self._get_api(f"/api/agentic/provisioning/resources/{self.team.id}")
assert res.status_code == 401
- def test_get_resource_returns_service_id_from_create(self):
- token = self._get_bearer_token()
- self._post_signed_with_bearer(
- "/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
- token=token,
- )
- res = self._get_signed_with_bearer(
- f"/api/agentic/provisioning/resources/{self.team.id}",
- token=token,
- )
- assert res.json()["service_id"] == "analytics"
-
- def test_get_resource_defaults_service_id_without_create(self):
- token = self._get_bearer_token()
- res = self._get_signed_with_bearer(
- f"/api/agentic/provisioning/resources/{self.team.id}",
- token=token,
- )
- assert res.json()["service_id"] == "analytics"
-
- def test_create_resource_defaults_service_id_to_analytics(self):
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- "/api/agentic/provisioning/resources",
- data={},
- token=token,
- )
- assert res.status_code == 200
- assert res.json()["service_id"] == "analytics"
-
def test_create_resource_includes_personal_api_key(self):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
token=token,
)
assert res.status_code == 200
@@ -134,18 +96,16 @@ class TestProvisioningResources(ProvisioningTestBase):
def test_create_resource_creates_pat_for_user(self):
initial_count = PersonalAPIKey.objects.filter(user=self.user).count()
token = self._get_bearer_token()
- self._post_signed_with_bearer(
+ self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
token=token,
)
assert PersonalAPIKey.objects.filter(user=self.user).count() == initial_count + 1
def test_create_resource_pat_label_defaults_to_team_name(self):
token = self._get_bearer_token()
- self._post_signed_with_bearer(
+ self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
token=token,
)
pat = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()
@@ -156,12 +116,11 @@ class TestProvisioningResources(ProvisioningTestBase):
# The test bearer is granted only query:read; the PAT must not widen to the
# full ceiling even when the app's grantable set is broader.
token = self._get_bearer_token()
- app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)
+ app = self.partner
app.scopes = ["insight:read", "query:read"]
app.save(update_fields=["scopes"])
- self._post_signed_with_bearer(
+ self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
token=token,
)
pat = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()
@@ -172,13 +131,12 @@ class TestProvisioningResources(ProvisioningTestBase):
def test_create_resource_pat_excludes_optional_scopes_outside_grant(self):
token = self._get_bearer_token()
- app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)
+ app = self.partner
app.scopes = ["query:read"]
app.optional_scopes = ["insight:read"]
app.save(update_fields=["scopes", "optional_scopes"])
- self._post_signed_with_bearer(
+ self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
token=token,
)
pat = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()
@@ -187,13 +145,12 @@ class TestProvisioningResources(ProvisioningTestBase):
def test_create_resource_omits_pat_when_app_gate_off(self):
token = self._get_bearer_token()
- app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)
+ app = self.partner
app.provisioning_issues_personal_api_key = False
app.save(update_fields=["provisioning_issues_personal_api_key"])
before = PersonalAPIKey.objects.filter(user=self.user).count()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
token=token,
)
assert res.status_code == 200
@@ -225,17 +182,15 @@ class TestProvisioningResources(ProvisioningTestBase):
def test_create_resource_does_not_delete_existing_pats(self):
token = self._get_bearer_token()
- self._post_signed_with_bearer(
+ self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
token=token,
)
first_pat = PersonalAPIKey.objects.filter(user=self.user, label=self.team.name[:40]).first()
assert first_pat is not None
- self._post_signed_with_bearer(
+ self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
token=token,
)
provisioning_pats = PersonalAPIKey.objects.filter(user=self.user, label=self.team.name[:40])
@@ -251,9 +206,9 @@ class TestProvisioningResources(ProvisioningTestBase):
)
def test_create_resource_label_prefix_accepted(self, _name, label_prefix, expected_label_start_template):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "label_prefix": label_prefix},
+ data={"label_prefix": label_prefix},
token=token,
)
assert res.status_code == 200
@@ -274,9 +229,9 @@ class TestProvisioningResources(ProvisioningTestBase):
)
def test_create_resource_label_prefix_rejected(self, _name, label_prefix):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "label_prefix": label_prefix},
+ data={"label_prefix": label_prefix},
token=token,
)
assert res.status_code == 400
@@ -288,9 +243,9 @@ class TestProvisioningResources(ProvisioningTestBase):
self.team.name = long_team_name
self.team.save()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "label_prefix": "PartnerX"},
+ data={"label_prefix": "PartnerX"},
token=token,
)
assert res.status_code == 200
@@ -301,9 +256,9 @@ class TestProvisioningResources(ProvisioningTestBase):
def test_create_resource_with_project_id_creates_new_team(self):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "project_id": "proj_123"},
+ data={"project_id": "proj_123"},
token=token,
)
assert res.status_code == 200
@@ -315,37 +270,37 @@ class TestProvisioningResources(ProvisioningTestBase):
def test_create_resource_same_project_id_returns_same_team(self):
token = self._get_bearer_token()
- res1 = self._post_signed_with_bearer(
+ res1 = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "project_id": "proj_456"},
+ data={"project_id": "proj_456"},
token=token,
)
- res2 = self._post_signed_with_bearer(
+ res2 = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "project_id": "proj_456"},
+ data={"project_id": "proj_456"},
token=token,
)
assert res1.json()["id"] == res2.json()["id"]
def test_create_resource_different_project_ids_create_different_teams(self):
token = self._get_bearer_token()
- res1 = self._post_signed_with_bearer(
+ res1 = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "project_id": "proj_a"},
+ data={"project_id": "proj_a"},
token=token,
)
- res2 = self._post_signed_with_bearer(
+ res2 = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "project_id": "proj_b"},
+ data={"project_id": "proj_b"},
token=token,
)
assert res1.json()["id"] != res2.json()["id"]
def test_create_resource_with_project_id_adds_to_scoped_teams(self):
token = self._get_bearer_token()
- self._post_signed_with_bearer(
+ self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "project_id": "proj_scope"},
+ data={"project_id": "proj_scope"},
token=token,
)
access_token = OAuthAccessToken.objects.get(token=token)
@@ -381,9 +336,9 @@ class TestProvisioningResources(ProvisioningTestBase):
token = self._get_bearer_token()
with patch.object(TeamProvisioningConfig.objects, "update_or_create", side_effect=raise_once_then_passthrough):
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "project_id": "proj_shared"},
+ data={"project_id": "proj_shared"},
token=token,
)
@@ -424,9 +379,9 @@ class TestProvisioningResources(ProvisioningTestBase):
return original_update_or_create(*args, **kwargs)
with patch.object(TeamProvisioningConfig.objects, "update_or_create", side_effect=race_then_raise):
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "project_id": project_id},
+ data={"project_id": project_id},
token=token,
)
@@ -454,9 +409,9 @@ class TestProvisioningResources(ProvisioningTestBase):
)
assert access_token.scoped_teams == [self.team.id]
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "project_id": "proj_existing"},
+ data={"project_id": "proj_existing"},
token=token,
)
assert res.status_code == 200
@@ -499,9 +454,9 @@ class TestProvisioningResources(ProvisioningTestBase):
resource_id=str(restricted_team.id),
)
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "project_id": "proj_restricted"},
+ data={"project_id": "proj_restricted"},
token=token,
)
assert res.status_code == 404
@@ -541,9 +496,9 @@ class TestProvisioningResources(ProvisioningTestBase):
access_token = OAuthAccessToken.objects.get(token=token)
assert access_token.application_id != other_partner.id
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "project_id": "proj_shared_id"},
+ data={"project_id": "proj_shared_id"},
token=token,
)
# stripe_project_id is unique across all TPCs, so the create branch hits
@@ -602,9 +557,9 @@ class TestProvisioningResources(ProvisioningTestBase):
return original_update_or_create(*args, **kwargs)
with patch.object(TeamProvisioningConfig.objects, "update_or_create", side_effect=race_then_raise):
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "project_id": project_id},
+ data={"project_id": project_id},
token=token,
)
@@ -616,19 +571,17 @@ class TestProvisioningResources(ProvisioningTestBase):
def test_create_resource_without_project_id_returns_existing_team(self):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
token=token,
)
assert res.json()["id"] == str(self.team.id)
def test_create_resource_with_project_id_and_name(self):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
data={
- "service_id": "analytics",
"project_id": "proj_named",
"configuration": {"project_name": "My App"},
},
@@ -640,9 +593,9 @@ class TestProvisioningResources(ProvisioningTestBase):
def test_create_resource_new_team_belongs_to_same_org(self):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics", "project_id": "proj_org"},
+ data={"project_id": "proj_org"},
token=token,
)
new_team = Team.objects.get(id=int(res.json()["id"]))
@@ -650,7 +603,7 @@ class TestProvisioningResources(ProvisioningTestBase):
def test_get_resource_does_not_include_personal_api_key(self):
token = self._get_bearer_token()
- res = self._get_signed_with_bearer(
+ res = self._get_with_bearer(
f"/api/agentic/provisioning/resources/{self.team.id}",
token=token,
)
@@ -658,7 +611,6 @@ class TestProvisioningResources(ProvisioningTestBase):
assert "personal_api_key" not in res.json()["complete"]["access_configuration"]
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestProvisioningResourceRemove(ProvisioningTestBase):
def test_remove_strips_team_from_sibling_tokens(self):
# Removing a resource has to revoke the team from every live token
@@ -692,7 +644,7 @@ class TestProvisioningResourceRemove(ProvisioningTestBase):
scoped_teams=[self.team.id, 99999],
)
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
f"/api/agentic/provisioning/resources/{self.team.id}/remove",
token=token,
)
@@ -726,7 +678,7 @@ class TestProvisioningResourceRemove(ProvisioningTestBase):
)
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
f"/api/agentic/provisioning/resources/{self.team.id}/remove",
token=token,
)
@@ -739,10 +691,9 @@ class TestProvisioningResourceRemove(ProvisioningTestBase):
assert not OAuthAccessToken.objects.filter(token=token).exists()
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestCreateProvisionedPat(ProvisioningTestBase):
def _minting_app(self) -> OAuthApplication:
- app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)
+ app = self.partner
app.scopes = ["query:read"]
app.save(update_fields=["scopes"])
return app
@@ -777,8 +728,9 @@ class TestCreateProvisionedPat(ProvisioningTestBase):
def test_no_pat_when_ceiling_unseeded(self):
# A flag-on app without a scope ceiling must not fall back to ["*"] or
# mint an empty-scope key — skip the mint entirely.
- app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)
- assert app.scopes == []
+ app = self.partner
+ app.scopes = []
+ app.save(update_fields=["scopes"])
initial_count = PersonalAPIKey.objects.filter(user=self.user).count()
assert _maybe_create_provisioned_pat(self.user, self.team, app, "query:read") is None
assert PersonalAPIKey.objects.filter(user=self.user).count() == initial_count
diff --git a/ee/api/agentic_provisioning/test/test_rotate_credentials.py b/ee/api/agentic_provisioning/test/test_rotate_credentials.py
index b5fc0d88c720..5e88c432db17 100644
--- a/ee/api/agentic_provisioning/test/test_rotate_credentials.py
+++ b/ee/api/agentic_provisioning/test/test_rotate_credentials.py
@@ -1,22 +1,19 @@
from unittest.mock import patch
-from django.test import override_settings
-
from parameterized import parameterized
-from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.oauth import OAuthAccessToken
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team.team import Team
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, TEST_STRIPE_OAUTH_CLIENT_ID, ProvisioningTestBase
+from ee.api.agentic_provisioning.test.base import ProvisioningTestBase
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestProvisioningRotateCredentials(ProvisioningTestBase):
def test_rotate_returns_new_access_configuration(self):
token = self._get_bearer_token()
original_api_token = self.team.api_token
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials",
token=token,
)
@@ -32,7 +29,7 @@ class TestProvisioningRotateCredentials(ProvisioningTestBase):
def test_rotate_wrong_team_returns_403(self):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources/99999/rotate_credentials",
token=token,
)
@@ -40,14 +37,14 @@ class TestProvisioningRotateCredentials(ProvisioningTestBase):
def test_rotate_invalid_id_returns_400(self):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
"/api/agentic/provisioning/resources/not-a-number/rotate_credentials",
token=token,
)
assert res.status_code == 400
def test_rotate_missing_bearer_returns_401(self):
- res = self._post_signed(
+ res = self._post_api(
f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials",
)
assert res.status_code == 401
@@ -59,37 +56,15 @@ class TestProvisioningRotateCredentials(ProvisioningTestBase):
access_token.scoped_teams = [team_id]
access_token.save(update_fields=["scoped_teams"])
Team.objects.filter(id=team_id).delete()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
f"/api/agentic/provisioning/resources/{team_id}/rotate_credentials",
token=token,
)
assert res.status_code == 404
- def test_rotate_returns_service_id_from_create(self):
- token = self._get_bearer_token()
- self._post_signed_with_bearer(
- "/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
- token=token,
- )
- res = self._post_signed_with_bearer(
- f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials",
- token=token,
- )
- assert res.json()["service_id"] == "analytics"
-
- def test_rotate_defaults_service_id_to_posthog(self):
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials",
- token=token,
- )
- assert res.status_code == 200
- assert res.json()["service_id"] == "analytics"
-
def test_rotate_includes_new_personal_api_key(self):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials",
token=token,
)
@@ -99,10 +74,10 @@ class TestProvisioningRotateCredentials(ProvisioningTestBase):
def test_rotate_omits_pat_when_app_gate_off(self):
token = self._get_bearer_token()
- app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)
+ app = self.partner
app.provisioning_issues_personal_api_key = False
app.save(update_fields=["provisioning_issues_personal_api_key"])
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials",
token=token,
)
@@ -111,7 +86,7 @@ class TestProvisioningRotateCredentials(ProvisioningTestBase):
def test_rotate_pat_is_scoped_to_authorized_team(self):
token = self._get_bearer_token()
- self._post_signed_with_bearer(
+ self._post_with_bearer(
f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials",
token=token,
)
@@ -122,15 +97,14 @@ class TestProvisioningRotateCredentials(ProvisioningTestBase):
def test_rotate_preserves_existing_pats(self):
token = self._get_bearer_token()
- self._post_signed_with_bearer(
+ self._post_with_bearer(
"/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
token=token,
)
initial_pat = PersonalAPIKey.objects.filter(user=self.user, label=self.team.name[:40]).first()
assert initial_pat is not None
- self._post_signed_with_bearer(
+ self._post_with_bearer(
f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials",
token=token,
)
@@ -140,7 +114,7 @@ class TestProvisioningRotateCredentials(ProvisioningTestBase):
@patch("posthog.models.team.team.Team.reset_token_and_save", side_effect=Exception("db error"))
def test_rotate_returns_500_when_reset_token_fails(self, _mock_reset):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials",
token=token,
)
@@ -149,7 +123,7 @@ class TestProvisioningRotateCredentials(ProvisioningTestBase):
def test_rotate_with_label_prefix_uses_prefix_for_pat(self):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials",
data={"label_prefix": "Acme Co"},
token=token,
@@ -170,7 +144,7 @@ class TestProvisioningRotateCredentials(ProvisioningTestBase):
@patch("ee.api.agentic_provisioning.views._capture_provisioning_event")
def test_rotate_invalid_label_prefix_returns_400_and_captures_event(self, _name, label_prefix, mock_capture_event):
token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
+ res = self._post_with_bearer(
f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials",
data={"label_prefix": label_prefix},
token=token,
diff --git a/ee/api/agentic_provisioning/test/test_scope_hydration.py b/ee/api/agentic_provisioning/test/test_scope_hydration.py
index 9858ec412438..496365d77e0a 100644
--- a/ee/api/agentic_provisioning/test/test_scope_hydration.py
+++ b/ee/api/agentic_provisioning/test/test_scope_hydration.py
@@ -1,28 +1,56 @@
from io import StringIO
from django.core.management import call_command
-from django.test import override_settings
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase
+from posthog.constants import AvailableFeature
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.team.team import Team
+from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+from ee.api.agentic_provisioning.test.base import ProvisioningTestBase
+from ee.api.agentic_provisioning.views import _compute_partner_scoped_teams
+from ee.models.rbac.access_control import AccessControl
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
-class TestPartnerTokenScopeHydration(ProvisioningTestBase):
- def test_issuance_hydrates_with_previously_provisioned_teams(self):
- from posthog.models.oauth import OAuthAccessToken, OAuthApplication
- from posthog.models.team.team import Team
- from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+TOKEN_URL = "/api/agentic/oauth/token"
- stripe_app = OAuthApplication.objects.get(client_id="test_stripe_oauth_client_id")
- previously_provisioned = Team.objects.create_with_data(
+
+class TestPartnerTokenScopeHydration(ProvisioningTestBase):
+ def _provision_team(
+ self, application: OAuthApplication, name: str, project_id: str, organization: Organization | None = None
+ ) -> Team:
+ team = Team.objects.create_with_data(
initiating_user=self.user,
- organization=self.organization,
- name="Previously provisioned",
+ organization=organization or self.organization,
+ name=name,
)
TeamProvisioningConfig.objects.update_or_create(
- team=previously_provisioned,
- defaults={"stripe_project_id": "proj_existing", "application": stripe_app},
+ team=team,
+ defaults={"stripe_project_id": project_id, "application": application},
)
+ return team
+
+ def _restrict_team_access(self, team: Team) -> None:
+ AccessControl.objects.create(
+ team=team,
+ access_level="none",
+ resource="project",
+ resource_id=str(team.id),
+ )
+
+ def _enable_access_control_as_member(self) -> None:
+ 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()
+
+ def _refresh(self, refresh_token: str):
+ return self._post_api(TOKEN_URL, {"grant_type": "refresh_token", "refresh_token": refresh_token})
+
+ def test_issuance_hydrates_with_previously_provisioned_teams(self):
+ previously_provisioned = self._provision_team(self.partner, "Previously provisioned", "proj_existing")
token = self._get_bearer_token()
access_token = OAuthAccessToken.objects.get(token=token)
@@ -30,10 +58,6 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):
assert previously_provisioned.id in access_token.scoped_teams
def test_other_partner_teams_excluded(self):
- from posthog.models.oauth import OAuthAccessToken, OAuthApplication
- from posthog.models.team.team import Team
- from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
-
other_partner = OAuthApplication.objects.create(
name="Other Partner",
client_id="other_partner_client_id",
@@ -44,15 +68,7 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):
algorithm="RS256",
provisioning_partner_type="other_partner",
)
- other_partner_team = Team.objects.create_with_data(
- initiating_user=self.user,
- organization=self.organization,
- name="Other partner team",
- )
- TeamProvisioningConfig.objects.update_or_create(
- team=other_partner_team,
- defaults={"stripe_project_id": "proj_other", "application": other_partner},
- )
+ other_partner_team = self._provision_team(other_partner, "Other partner team", "proj_other")
token = self._get_bearer_token()
access_token = OAuthAccessToken.objects.get(token=token)
@@ -62,27 +78,13 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):
# Same partner provisions teams in two orgs the user belongs to.
# The token is granted under org A's authorization; org B's team must
# not leak in just because the user can access it via org B membership.
- from posthog.models.oauth import OAuthAccessToken, OAuthApplication
- from posthog.models.organization import Organization, OrganizationMembership
- from posthog.models.team.team import Team
- from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
-
- stripe_app = OAuthApplication.objects.get(client_id="test_stripe_oauth_client_id")
other_org = Organization.objects.create(name="Other org")
OrganizationMembership.objects.create(
organization=other_org,
user=self.user,
level=OrganizationMembership.Level.ADMIN,
)
- other_org_team = Team.objects.create_with_data(
- initiating_user=self.user,
- organization=other_org,
- name="Same partner, other org",
- )
- TeamProvisioningConfig.objects.update_or_create(
- team=other_org_team,
- defaults={"stripe_project_id": "proj_other_org", "application": stripe_app},
- )
+ other_org_team = self._provision_team(self.partner, "Same partner, other org", "proj_other_org", other_org)
token = self._get_bearer_token()
access_token = OAuthAccessToken.objects.get(token=token)
@@ -90,59 +92,18 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):
assert other_org_team.id not in access_token.scoped_teams
def test_cross_org_teams_excluded(self):
- from posthog.models.oauth import OAuthAccessToken, OAuthApplication
- from posthog.models.organization import Organization
- from posthog.models.team.team import Team
- from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
-
- stripe_app = OAuthApplication.objects.get(client_id="test_stripe_oauth_client_id")
other_org = Organization.objects.create(name="Other org")
- foreign_team = Team.objects.create_with_data(
- initiating_user=self.user,
- organization=other_org,
- name="Foreign team",
- )
- TeamProvisioningConfig.objects.update_or_create(
- team=foreign_team,
- defaults={"stripe_project_id": "proj_foreign", "application": stripe_app},
- )
+ foreign_team = self._provision_team(self.partner, "Foreign team", "proj_foreign", other_org)
token = self._get_bearer_token()
access_token = OAuthAccessToken.objects.get(token=token)
assert foreign_team.id not in access_token.scoped_teams
def test_team_with_revoked_access_excluded(self):
- from posthog.constants import AvailableFeature
- from posthog.models.oauth import OAuthAccessToken, OAuthApplication
- from posthog.models.organization import OrganizationMembership
- from posthog.models.team.team import Team
- from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
-
- from ee.models.rbac.access_control import AccessControl
-
- 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()
+ self._enable_access_control_as_member()
- stripe_app = OAuthApplication.objects.get(client_id="test_stripe_oauth_client_id")
- restricted_team = Team.objects.create_with_data(
- initiating_user=self.user,
- organization=self.organization,
- name="Restricted team",
- )
- TeamProvisioningConfig.objects.update_or_create(
- team=restricted_team,
- defaults={"stripe_project_id": "proj_restricted", "application": stripe_app},
- )
- AccessControl.objects.create(
- team=restricted_team,
- access_level="none",
- resource="project",
- resource_id=str(restricted_team.id),
- )
+ restricted_team = self._provision_team(self.partner, "Restricted team", "proj_restricted")
+ self._restrict_team_access(restricted_team)
token = self._get_bearer_token()
access_token = OAuthAccessToken.objects.get(token=token)
@@ -152,25 +113,8 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):
# When the base team is gone or the user lost access, _compute_partner_scoped_teams
# returns []. An empty scoped_teams is unrestricted under the standard permission
# check, so issuance must fail closed rather than mint a project-unrestricted token.
- from posthog.constants import AvailableFeature
- from posthog.models.oauth import OAuthAccessToken
- from posthog.models.organization import OrganizationMembership
-
- from ee.models.rbac.access_control import AccessControl
-
- 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()
-
- AccessControl.objects.create(
- team=self.team,
- access_level="none",
- resource="project",
- resource_id=str(self.team.id),
- )
+ self._enable_access_control_as_member()
+ self._restrict_team_access(self.team)
res = self._request_bearer_token()
assert res.status_code == 400, res.content
@@ -178,31 +122,14 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):
assert not OAuthAccessToken.objects.filter(user=self.user).exists()
def test_refresh_rehydrates_with_new_teams(self):
- from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
- from posthog.models.team.team import Team
- from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
-
token = self._get_bearer_token()
access_token = OAuthAccessToken.objects.get(token=token)
refresh_token = OAuthRefreshToken.objects.get(access_token=access_token)
assert access_token.scoped_teams == [self.team.id]
- stripe_app = OAuthApplication.objects.get(client_id="test_stripe_oauth_client_id")
- newly_provisioned = Team.objects.create_with_data(
- initiating_user=self.user,
- organization=self.organization,
- name="Newly provisioned",
- )
- TeamProvisioningConfig.objects.update_or_create(
- team=newly_provisioned,
- defaults={"stripe_project_id": "proj_new", "application": stripe_app},
- )
+ newly_provisioned = self._provision_team(self.partner, "Newly provisioned", "proj_new")
- res = self._post_signed(
- "/api/agentic/oauth/token",
- data={"grant_type": "refresh_token", "refresh_token": refresh_token.token},
- content_type="application/x-www-form-urlencoded",
- )
+ res = self._refresh(refresh_token.token)
assert res.status_code == 200, res.content
new_access_token = OAuthAccessToken.objects.get(token=res.json()["access_token"])
assert self.team.id in new_access_token.scoped_teams
@@ -212,33 +139,13 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):
# A refresh whose base team access was revoked recomputes to an empty scope.
# It must fail closed (not rotate into an unrestricted token) and, because the
# check runs before any token mutation, must leave the caller's refresh token intact.
- from posthog.constants import AvailableFeature
- from posthog.models.oauth import OAuthAccessToken, OAuthRefreshToken
- from posthog.models.organization import OrganizationMembership
-
- from ee.models.rbac.access_control import AccessControl
-
token = self._get_bearer_token()
refresh_token = OAuthRefreshToken.objects.get(access_token__token=token)
- 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()
- AccessControl.objects.create(
- team=self.team,
- access_level="none",
- resource="project",
- resource_id=str(self.team.id),
- )
+ self._enable_access_control_as_member()
+ self._restrict_team_access(self.team)
- res = self._post_signed(
- "/api/agentic/oauth/token",
- data={"grant_type": "refresh_token", "refresh_token": refresh_token.token},
- content_type="application/x-www-form-urlencoded",
- )
+ res = self._refresh(refresh_token.token)
assert res.status_code == 400, res.content
assert res.json()["error"] == "invalid_grant"
@@ -247,27 +154,12 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):
assert OAuthAccessToken.objects.filter(token=token).exists()
def test_backfill_rehydrates_stale_access_and_refresh_scope(self):
- from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
- from posthog.models.team.team import Team
- from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
-
token = self._get_bearer_token()
access_token = OAuthAccessToken.objects.get(token=token)
refresh_token = OAuthRefreshToken.objects.get(access_token=access_token)
assert access_token.scoped_teams == [self.team.id]
- stripe_app = OAuthApplication.objects.get(client_id="test_stripe_oauth_client_id")
- stripe_app.provisioning_partner_type = "stripe"
- stripe_app.save()
- newly_provisioned = Team.objects.create_with_data(
- initiating_user=self.user,
- organization=self.organization,
- name="Newly provisioned",
- )
- TeamProvisioningConfig.objects.update_or_create(
- team=newly_provisioned,
- defaults={"stripe_project_id": "proj_new", "application": stripe_app},
- )
+ newly_provisioned = self._provision_team(self.partner, "Newly provisioned", "proj_new")
call_command("backfill_agentic_provisioning_scope", stdout=StringIO())
@@ -283,33 +175,13 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):
# An empty scoped_teams is unrestricted under the standard permission check, so the
# backfill must NOT overwrite a restricted token with [] — it leaves the existing
# restriction intact and reports the token for re-authorization.
- from posthog.constants import AvailableFeature
- from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
- from posthog.models.organization import OrganizationMembership
-
- from ee.models.rbac.access_control import AccessControl
-
token = self._get_bearer_token()
access_token = OAuthAccessToken.objects.get(token=token)
refresh_token = OAuthRefreshToken.objects.get(access_token=access_token)
assert access_token.scoped_teams == [self.team.id]
- stripe_app = OAuthApplication.objects.get(client_id="test_stripe_oauth_client_id")
- stripe_app.provisioning_partner_type = "stripe"
- stripe_app.save()
-
- 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()
- AccessControl.objects.create(
- team=self.team,
- access_level="none",
- resource="project",
- resource_id=str(self.team.id),
- )
+ self._enable_access_control_as_member()
+ self._restrict_team_access(self.team)
out = StringIO()
call_command("backfill_agentic_provisioning_scope", stdout=out)
@@ -325,6 +197,4 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):
# NOT NULL and issuance always resolves an app), so this pins the helper's
# defensive branch: an unattributed token fails closed with no scope rather
# than silently retaining the base team.
- from ee.api.agentic_provisioning.views import _compute_partner_scoped_teams
-
assert _compute_partner_scoped_teams(None, self.user, self.team.id) == []
diff --git a/ee/api/agentic_provisioning/test/test_services.py b/ee/api/agentic_provisioning/test/test_services.py
deleted file mode 100644
index f6c0298b6e88..000000000000
--- a/ee/api/agentic_provisioning/test/test_services.py
+++ /dev/null
@@ -1,156 +0,0 @@
-# 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
-
-from django.test import override_settings
-
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase
-from ee.api.agentic_provisioning.views import SERVICES_CACHE_EXPIRES_KEY, SERVICES_CACHE_KEY
-
-MOCK_BILLING_PRODUCTS = {
- "products": [
- {
- "type": "product_analytics",
- "name": "Product analytics",
- "headline": "Product analytics with autocapture",
- "plans": [
- {"plan_key": "free-20230117", "price_id": None},
- {"plan_key": "paid-20240404", "price_id": "price_1PMG1IEuIatRXSdzht4rGlho"},
- ],
- },
- {
- "type": "session_replay",
- "name": "Session replay",
- "headline": "Watch how users experience your app",
- "plans": [
- {"plan_key": "free-20231218", "price_id": None},
- {"plan_key": "paid-20240402-5k-free", "price_id": "price_1P1EZoEuIatRXSdzakl5PcUF"},
- ],
- },
- {
- "type": "platform_and_support",
- "name": "Platform and support",
- "inclusion_only": True,
- "plans": [{"plan_key": "free-20230117", "price_id": None}],
- },
- ]
-}
-
-
-def _mock_billing_response():
- mock_resp = MagicMock()
- mock_resp.status_code = 200
- mock_resp.json.return_value = MOCK_BILLING_PRODUCTS
- mock_resp.raise_for_status.return_value = None
- return mock_resp
-
-
-def _mock_cache_empty():
- mock = MagicMock()
- mock.get.return_value = None
- return mock
-
-
-def _mock_cache_fresh(services):
- store = {
- SERVICES_CACHE_KEY: services,
- SERVICES_CACHE_EXPIRES_KEY: time.time() + 3600,
- }
- mock = MagicMock()
- mock.get.side_effect = lambda key: store.get(key)
- return mock
-
-
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
-class TestProvisioningServices(ProvisioningTestBase):
- @patch("ee.api.agentic_provisioning.views.requests.get", return_value=_mock_billing_response())
- @patch("ee.api.agentic_provisioning.views.cache", new_callable=_mock_cache_empty)
- def test_returns_three_services(self, mock_cache, mock_get):
- res = self._get_signed("/api/agentic/provisioning/services")
- assert res.status_code == 200
- data = res.json()
- services = data["data"]
- assert len(services) == 3
- assert "next_cursor" not in data
- ids = [s["id"] for s in services]
- assert ids == ["free", "pay_as_you_go", "analytics"]
-
- @patch("ee.api.agentic_provisioning.views.requests.get", return_value=_mock_billing_response())
- @patch("ee.api.agentic_provisioning.views.cache", new_callable=_mock_cache_empty)
- def test_analytics_deployable_description_from_billing(self, mock_cache, mock_get):
- res = self._get_signed("/api/agentic/provisioning/services")
- analytics = res.json()["data"][2]
- assert analytics["id"] == "analytics"
- assert analytics["kind"] == "deployable"
- assert "product analytics" in analytics["description"]
- assert "session replay" in analytics["description"]
- assert "platform and support" not in analytics["description"].lower()
-
- @patch("ee.api.agentic_provisioning.views.requests.get", return_value=_mock_billing_response())
- @patch("ee.api.agentic_provisioning.views.cache", new_callable=_mock_cache_empty)
- def test_analytics_deployable_allows_service_ref_updates(self, mock_cache, mock_get):
- res = self._get_signed("/api/agentic/provisioning/services")
- analytics = res.json()["data"][2]
- assert analytics["allowed_updates"] == ["service_ref"]
-
- @patch("ee.api.agentic_provisioning.views.requests.get", return_value=_mock_billing_response())
- @patch("ee.api.agentic_provisioning.views.cache", new_callable=_mock_cache_empty)
- def test_free_plan_can_upgrade_to_pay_as_you_go(self, mock_cache, mock_get):
- res = self._get_signed("/api/agentic/provisioning/services")
- free = res.json()["data"][0]
- assert free["id"] == "free"
- assert free["allowed_updates"] == ["pay_as_you_go"]
-
- @patch("ee.api.agentic_provisioning.views.requests.get", return_value=_mock_billing_response())
- @patch("ee.api.agentic_provisioning.views.cache", new_callable=_mock_cache_empty)
- def test_pay_as_you_go_plan_can_downgrade_to_free(self, mock_cache, mock_get):
- res = self._get_signed("/api/agentic/provisioning/services")
- payg = res.json()["data"][1]
- assert payg["id"] == "pay_as_you_go"
- assert payg["allowed_updates"] == ["free"]
-
- @patch("ee.api.agentic_provisioning.views.requests.get", return_value=_mock_billing_response())
- @patch("ee.api.agentic_provisioning.views.cache", new_callable=_mock_cache_empty)
- def test_pay_as_you_go_pricing_includes_rates(self, mock_cache, mock_get):
- res = self._get_signed("/api/agentic/provisioning/services")
- payg = res.json()["data"][1]
- freeform = payg["pricing"]["paid"]["freeform"]
- assert "$0/mo base" in freeform
- assert "posthog.com/pricing" in freeform
-
- @patch("ee.api.agentic_provisioning.views.requests.get", return_value=_mock_billing_response())
- @patch("ee.api.agentic_provisioning.views.cache", new_callable=_mock_cache_empty)
- def test_analytics_deployable_has_component_pricing(self, mock_cache, mock_get):
- res = self._get_signed("/api/agentic/provisioning/services")
- analytics = res.json()["data"][2]
- assert analytics["pricing"]["type"] == "component"
- options = analytics["pricing"]["component"]["options"]
- assert len(options) == 2
- assert options[0]["parent_service_ids"] == ["free"]
- assert options[0]["type"] == "free"
- assert options[1]["parent_service_ids"] == ["pay_as_you_go"]
- assert options[1]["type"] == "paid"
-
- @patch("ee.api.agentic_provisioning.views.requests.get")
- @patch("ee.api.agentic_provisioning.views.cache", new_callable=_mock_cache_empty)
- def test_billing_failure_returns_fallback(self, mock_cache, mock_get):
- mock_get.side_effect = Exception("connection error")
- res = self._get_signed("/api/agentic/provisioning/services")
- assert res.status_code == 200
- data = res.json()["data"]
- assert len(data) == 3
- ids = [s["id"] for s in data]
- assert ids == ["free", "pay_as_you_go", "analytics"]
- assert "PostHog" in data[2]["description"]
-
- @patch("ee.api.agentic_provisioning.views.requests.get", return_value=_mock_billing_response())
- @patch("ee.api.agentic_provisioning.views.cache", new_callable=_mock_cache_empty)
- def test_all_services_have_categories(self, mock_cache, mock_get):
- res = self._get_signed("/api/agentic/provisioning/services")
- for service in res.json()["data"]:
- assert "analytics" in service["categories"]
-
- def test_missing_signature_returns_401(self):
- res = self.client.get("/api/agentic/provisioning/services", headers={"api-version": "0.1d"})
- assert res.status_code == 401
diff --git a/ee/api/agentic_provisioning/test/test_signature.py b/ee/api/agentic_provisioning/test/test_signature.py
deleted file mode 100644
index e037baf6613c..000000000000
--- a/ee/api/agentic_provisioning/test/test_signature.py
+++ /dev/null
@@ -1,205 +0,0 @@
-# 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
-
-from django.http import HttpRequest
-from django.test import TestCase, override_settings
-
-from parameterized import parameterized
-from rest_framework.parsers import JSONParser
-from rest_framework.request import Request
-
-from ee.api.agentic_provisioning.signature import (
- _parse_signature_header,
- compute_signature,
- verify_provisioning_signature,
-)
-
-HMAC_SECRET = "test_hmac_secret"
-
-
-class TestParseSignatureHeader(TestCase):
- @parameterized.expand(
- [
- ("valid", f"t=1234567890,v1={'ab' * 32}", ("1234567890", "ab" * 32)),
- ("uppercase_hex", f"t=1234567890,v1={'AB' * 32}", ("1234567890", "AB" * 32)),
- ("missing_t", f"v1={'ab' * 32}", None),
- ("missing_v1", "t=1234567890", None),
- ("malformed_no_equals", "garbage", None),
- ("empty", "", None),
- ("short_hex", "t=1234567890,v1=abcd", None),
- ("non_numeric_timestamp", f"t=notanumber,v1={'ab' * 32}", None),
- ]
- )
- def test_parse(self, _name, header, expected):
- assert _parse_signature_header(header) == expected
-
-
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
-class TestComputeSignature(TestCase):
- @parameterized.expand(
- [
- ("basic_body", 1700000000, b'{"hello":"world"}'),
- ("empty_body", 1700000000, b""),
- ("binary_body", 1700000000, b"\x00\x01\x02"),
- ]
- )
- def test_deterministic(self, _name, ts, body):
- sig1 = compute_signature(HMAC_SECRET, ts, body)
- sig2 = compute_signature(HMAC_SECRET, ts, body)
- assert sig1 == sig2
- assert len(sig1) == 64
-
- def test_different_secret_different_sig(self):
- body = b"test"
- sig1 = compute_signature("secret1", 1700000000, body)
- sig2 = compute_signature("secret2", 1700000000, body)
- assert sig1 != sig2
-
- def test_different_timestamp_different_sig(self):
- body = b"test"
- sig1 = compute_signature(HMAC_SECRET, 1700000000, body)
- sig2 = compute_signature(HMAC_SECRET, 1700000001, body)
- assert sig1 != sig2
-
- def test_different_body_different_sig(self):
- sig1 = compute_signature(HMAC_SECRET, 1700000000, b"body1")
- sig2 = compute_signature(HMAC_SECRET, 1700000000, b"body2")
- assert sig1 != sig2
-
-
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
-class TestVerifySignatureAfterDRFParsing(TestCase):
- def _make_drf_request_with_consumed_stream(self, body: bytes) -> Request:
- django_request = HttpRequest()
- django_request.method = "POST"
- django_request.content_type = "application/json"
- django_request.META = {
- "REQUEST_METHOD": "POST",
- "CONTENT_TYPE": "application/json",
- "CONTENT_LENGTH": str(len(body)),
- }
- django_request._stream = io.BytesIO(body)
- django_request._read_started = False # type: ignore[attr-defined]
-
- drf_request = Request(django_request, parsers=[JSONParser()])
- _ = drf_request.data
-
- return cast(Request, drf_request)
-
- def test_returns_400_when_stream_consumed(self):
- body = b'{"email":"[email protected]"}'
- ts = int(time.time())
- sig = compute_signature(HMAC_SECRET, ts, body)
-
- drf_request = self._make_drf_request_with_consumed_stream(body)
- drf_request.META["HTTP_STRIPE_SIGNATURE"] = f"t={ts},v1={sig}"
-
- result = verify_provisioning_signature(drf_request)
- assert result is not None, "Body was consumed so signature can't be verified"
- assert result.status_code == 400
- assert result.data["error"]["code"] == "body_not_readable"
-
- def test_succeeds_when_stream_not_consumed(self):
- body = b'{"email":"[email protected]"}'
- ts = int(time.time())
- sig = compute_signature(HMAC_SECRET, ts, body)
-
- django_request = HttpRequest()
- django_request.method = "POST"
- django_request.content_type = "application/json"
- django_request.META = {
- "REQUEST_METHOD": "POST",
- "CONTENT_TYPE": "application/json",
- "CONTENT_LENGTH": str(len(body)),
- "HTTP_STRIPE_SIGNATURE": f"t={ts},v1={sig}",
- }
- django_request._stream = io.BytesIO(body)
- django_request._read_started = False # type: ignore[attr-defined]
-
- drf_request = Request(django_request, parsers=[JSONParser()])
- result = verify_provisioning_signature(drf_request)
- assert result is None
-
- def test_succeeds_when_body_cached_despite_stream_consumed(self):
- body = b'{"email":"[email protected]"}'
- ts = int(time.time())
- sig = compute_signature(HMAC_SECRET, ts, body)
-
- django_request = HttpRequest()
- django_request.method = "POST"
- django_request.content_type = "application/json"
- django_request.META = {
- "REQUEST_METHOD": "POST",
- "CONTENT_TYPE": "application/json",
- "CONTENT_LENGTH": str(len(body)),
- "HTTP_STRIPE_SIGNATURE": f"t={ts},v1={sig}",
- }
- django_request._body = body
- django_request._stream = io.BytesIO(b"")
- django_request._read_started = True # type: ignore[attr-defined]
-
- drf_request = Request(django_request, parsers=[JSONParser()])
- result = verify_provisioning_signature(drf_request)
- assert result is None
-
- def _make_request(self, body: bytes, sig_header: str) -> Request:
- django_request = HttpRequest()
- django_request.method = "POST"
- django_request.content_type = "application/json"
- django_request.META = {
- "REQUEST_METHOD": "POST",
- "CONTENT_TYPE": "application/json",
- "CONTENT_LENGTH": str(len(body)),
- "HTTP_STRIPE_SIGNATURE": sig_header,
- }
- django_request._stream = io.BytesIO(body)
- django_request._read_started = False # type: ignore[attr-defined]
- return cast(Request, Request(django_request, parsers=[JSONParser()]))
-
- def test_succeeds_with_multiple_signatures_during_rotation(self):
- # Stripe dual-signs while a signing-secret rotation is in flight, so the header
- # carries the stale (old secret) signature alongside the current one. The current
- # signature appears second here to guard against only checking the first v1.
- body = b'{"email":"[email protected]"}'
- ts = int(time.time())
- stale_sig = compute_signature("rotated_out_secret", ts, body)
- current_sig = compute_signature(HMAC_SECRET, ts, body)
-
- drf_request = self._make_request(body, f"t={ts},v1={stale_sig},v1={current_sig}")
- result = verify_provisioning_signature(drf_request)
- assert result is None
-
- @parameterized.expand(
- [
- (
- "no_signature_matches",
- lambda body, ts: (
- f"t={ts},v1={compute_signature('wrong_a', ts, body)},v1={compute_signature('wrong_b', ts, body)}"
- ),
- ),
- ("stale_timestamp", lambda body, ts: f"t={ts - 301},v1={compute_signature(HMAC_SECRET, ts - 301, body)}"),
- ("wrong_scheme_only", lambda body, ts: f"t={ts},v0={compute_signature(HMAC_SECRET, ts, body)}"),
- ("missing_header", lambda body, ts: ""),
- ]
- )
- def test_rejects_invalid_signature(self, _name, build_header):
- body = b'{"email":"[email protected]"}'
- ts = int(time.time())
-
- drf_request = self._make_request(body, build_header(body, ts))
- result = verify_provisioning_signature(drf_request)
- assert result is not None
- assert result.status_code == 401
- assert result.data["error"]["code"] == "invalid_signature"
-
- def test_non_utf8_body_is_a_bad_request_not_a_signature_failure(self):
- body = b"\xff\xfe not valid utf-8"
- ts = int(time.time())
-
- drf_request = self._make_request(body, f"t={ts},v1={'ab' * 32}")
- result = verify_provisioning_signature(drf_request)
- assert result is not None
- assert result.status_code == 400
- assert result.data["error"]["code"] == "body_not_decodable"
diff --git a/ee/api/agentic_provisioning/test/test_spt.py b/ee/api/agentic_provisioning/test/test_spt.py
deleted file mode 100644
index f90458622fa4..000000000000
--- a/ee/api/agentic_provisioning/test/test_spt.py
+++ /dev/null
@@ -1,160 +0,0 @@
-# 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
-
-from parameterized import parameterized
-
-from ee.api.agentic_provisioning.test.base import ProvisioningTestBase
-
-
-class TestSharedPaymentToken(ProvisioningTestBase):
- @patch("ee.api.agentic_provisioning.views.requests.post")
- @patch("ee.billing.billing_manager.build_billing_token", return_value="test_billing_token")
- @patch("posthog.cloud_utils.get_cached_instance_license")
- def test_provisioning_calls_billing_with_spt(self, mock_license, mock_build_token, mock_post):
- mock_license.return_value = MagicMock()
- mock_post.return_value = MagicMock(status_code=200)
-
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- "/api/agentic/provisioning/resources",
- data={
- "service_id": "analytics",
- "payment_credentials": {
- "type": "stripe_payment_token",
- "stripe_payment_token": "spt_test_123",
- },
- },
- token=token,
- )
- assert res.status_code == 200
- assert res.json()["status"] == "complete"
-
- mock_post.assert_called_once()
- call_args, call_kwargs = mock_post.call_args
- assert "/api/activate/authorize" in call_args[0]
- assert call_kwargs["json"] == {"shared_payment_token": "spt_test_123"}
- assert "Bearer test_billing_token" in call_kwargs["headers"]["Authorization"]
-
- def test_provisioning_works_without_spt(self):
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- "/api/agentic/provisioning/resources",
- data={"service_id": "analytics"},
- token=token,
- )
- assert res.status_code == 200
- assert res.json()["status"] == "complete"
-
- def test_provisioning_pay_as_you_go_without_spt_returns_error(self):
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- "/api/agentic/provisioning/resources",
- data={"service_id": "pay_as_you_go"},
- token=token,
- )
- assert res.status_code == 400
- body = res.json()
- assert body["status"] == "error"
- assert body["error"]["code"] == "requires_payment_credentials"
-
- @patch("ee.api.agentic_provisioning.views.requests.post")
- def test_provisioning_ignores_invalid_payment_credentials_type(self, mock_post):
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- "/api/agentic/provisioning/resources",
- data={
- "service_id": "analytics",
- "payment_credentials": {
- "type": "unknown_type",
- "token": "abc",
- },
- },
- token=token,
- )
- assert res.status_code == 200
- mock_post.assert_not_called()
-
- @parameterized.expand(
- [
- ("billing_inactive", False, 400, "requires_payment_credentials"),
- ("billing_already_active", True, 200, "complete"),
- ]
- )
- @patch("ee.api.agentic_provisioning.views.requests.get")
- @patch("ee.api.agentic_provisioning.views.requests.post")
- @patch("ee.billing.billing_manager.build_billing_token", return_value="test_billing_token")
- @patch("posthog.cloud_utils.get_cached_instance_license")
- def test_provisioning_spt_failure(
- self,
- _name,
- has_active_subscription,
- expected_status,
- expected_code,
- mock_license,
- mock_build_token,
- mock_post,
- mock_get,
- ):
- mock_license.return_value = MagicMock()
- mock_post.return_value = MagicMock(status_code=500)
- mock_get.return_value = MagicMock(
- status_code=200, json=lambda: {"customer": {"has_active_subscription": has_active_subscription}}
- )
-
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- "/api/agentic/provisioning/resources",
- data={
- "service_id": "analytics",
- "payment_credentials": {
- "type": "stripe_payment_token",
- "stripe_payment_token": "spt_test_123",
- },
- },
- token=token,
- )
- assert res.status_code == expected_status
- body = res.json()
- if expected_status == 400:
- assert body["error"]["code"] == expected_code
- else:
- assert body["status"] == expected_code
-
- def test_token_exchange_returns_orchestrator(self):
- """Token exchange should return payment_credentials: orchestrator so Stripe collects payment."""
- token_response = self._exchange_code_and_get_response()
- assert token_response["account"]["payment_credentials"] == "orchestrator"
-
- def _exchange_code_and_get_response(self) -> dict:
- import time
- from urllib.parse import urlencode
-
- from ee.api.agentic_provisioning.signature import compute_signature
- from ee.api.agentic_provisioning.test.base import HMAC_SECRET
- from ee.api.agentic_provisioning.views import AUTH_CODE_CACHE_PREFIX
-
- code = f"test_code_spt_{id(self)}"
- cache.set(
- f"{AUTH_CODE_CACHE_PREFIX}{code}",
- {
- "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",
- },
- timeout=300,
- )
- body = urlencode({"grant_type": "authorization_code", "code": code}).encode()
- ts = int(time.time())
- sig = compute_signature(HMAC_SECRET, ts, body)
- res = self.client.post(
- "/api/agentic/oauth/token",
- data=body,
- content_type="application/x-www-form-urlencoded",
- headers={"stripe-signature": f"t={ts},v1={sig}"},
- )
- return res.json()
diff --git a/ee/api/agentic_provisioning/test/test_update_service.py b/ee/api/agentic_provisioning/test/test_update_service.py
deleted file mode 100644
index e4aad78be669..000000000000
--- a/ee/api/agentic_provisioning/test/test_update_service.py
+++ /dev/null
@@ -1,189 +0,0 @@
-# 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
-
-from parameterized import parameterized
-
-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase
-
-
-@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
-class TestProvisioningUpdateService(ProvisioningTestBase):
- @patch("ee.api.agentic_provisioning.views.requests.post")
- @patch("ee.billing.billing_manager.build_billing_token", return_value="test_billing_token")
- @patch("posthog.cloud_utils.get_cached_instance_license")
- def test_update_service_with_spt_calls_billing(self, mock_license, mock_build_token, mock_post):
- mock_license.return_value = MagicMock()
- mock_post.return_value = MagicMock(status_code=200)
-
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- f"/api/agentic/provisioning/resources/{self.team.id}/update_service",
- data={
- "service_id": "pay_as_you_go",
- "payment_credentials": {
- "type": "stripe_payment_token",
- "stripe_payment_token": "spt_test_123",
- },
- },
- token=token,
- )
- assert res.status_code == 200
- assert res.json()["status"] == "complete"
- assert res.json()["service_id"] == "pay_as_you_go"
-
- mock_post.assert_called_once()
- call_args, call_kwargs = mock_post.call_args
- assert "/api/activate/authorize" in call_args[0]
- assert call_kwargs["json"] == {"shared_payment_token": "spt_test_123"}
-
- @parameterized.expand(
- [
- ("billing_inactive", False, 400, "billing_activation_failed"),
- ("billing_already_active", True, 200, "complete"),
- ]
- )
- @patch("ee.api.agentic_provisioning.views.requests.get")
- @patch("ee.api.agentic_provisioning.views.requests.post")
- @patch("ee.billing.billing_manager.build_billing_token", return_value="test_billing_token")
- @patch("posthog.cloud_utils.get_cached_instance_license")
- def test_update_service_spt_failure(
- self,
- _name,
- has_active_subscription,
- expected_status,
- expected_code,
- mock_license,
- mock_build_token,
- mock_post,
- mock_get,
- ):
- mock_license.return_value = MagicMock()
- mock_post.return_value = MagicMock(status_code=500)
- mock_get.return_value = MagicMock(
- status_code=200, json=lambda: {"customer": {"has_active_subscription": has_active_subscription}}
- )
-
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- f"/api/agentic/provisioning/resources/{self.team.id}/update_service",
- data={
- "service_id": "pay_as_you_go",
- "payment_credentials": {
- "type": "stripe_payment_token",
- "stripe_payment_token": "spt_test_123",
- },
- },
- token=token,
- )
- assert res.status_code == expected_status
- body = res.json()
- if expected_status == 400:
- assert body["error"]["code"] == expected_code
- else:
- assert body["status"] == expected_code
- assert body["service_id"] == "pay_as_you_go"
-
- def test_update_service_without_spt_to_free_succeeds(self):
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- f"/api/agentic/provisioning/resources/{self.team.id}/update_service",
- data={"service_id": "free"},
- token=token,
- )
- assert res.status_code == 200
- data = res.json()
- assert data["status"] == "complete"
- assert data["service_id"] == "free"
- assert "api_key" in data["complete"]["access_configuration"]
- assert "host" in data["complete"]["access_configuration"]
-
- def test_update_service_to_pay_as_you_go_without_spt_returns_error(self):
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- f"/api/agentic/provisioning/resources/{self.team.id}/update_service",
- data={"service_id": "pay_as_you_go"},
- token=token,
- )
- assert res.status_code == 400
- body = res.json()
- assert body["status"] == "error"
- assert body["error"]["code"] == "requires_payment_credentials"
-
- def test_update_service_rejects_unknown_service_id(self):
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- f"/api/agentic/provisioning/resources/{self.team.id}/update_service",
- data={"service_id": "unknown_service"},
- token=token,
- )
- assert res.status_code == 400
- assert res.json()["error"]["code"] == "unknown_service"
-
- def test_update_service_requires_service_id(self):
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- f"/api/agentic/provisioning/resources/{self.team.id}/update_service",
- data={},
- token=token,
- )
- assert res.status_code == 400
- assert res.json()["error"]["code"] == "missing_service_id"
-
- def test_update_service_wrong_team_returns_403(self):
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- "/api/agentic/provisioning/resources/99999/update_service",
- data={"service_id": "analytics"},
- token=token,
- )
- assert res.status_code == 403
-
- def test_update_service_missing_bearer_returns_401(self):
- res = self._post_signed(
- f"/api/agentic/provisioning/resources/{self.team.id}/update_service",
- data={"service_id": "analytics"},
- )
- assert res.status_code == 401
-
- def test_update_service_invalid_resource_id(self):
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- "/api/agentic/provisioning/resources/not-a-number/update_service",
- data={"service_id": "analytics"},
- token=token,
- )
- assert res.status_code == 400
-
- def test_update_service_rejects_config_owned_by_other_partner(self):
- # The base team is in the caller's scope, but its provisioning config
- # belongs to a different partner. The caller must not be able to mutate it.
- from posthog.models.oauth import OAuthApplication
- from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
-
- other_partner = OAuthApplication.objects.create(
- name="Other Partner",
- client_id="other_partner_update_client_id",
- client_secret="",
- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="https://localhost",
- algorithm="RS256",
- provisioning_partner_type="other_partner",
- )
- TeamProvisioningConfig.objects.update_or_create(
- team=self.team, defaults={"application": other_partner, "service_id": "analytics"}
- )
-
- token = self._get_bearer_token()
- res = self._post_signed_with_bearer(
- f"/api/agentic/provisioning/resources/{self.team.id}/update_service",
- data={"service_id": "free"},
- token=token,
- )
- assert res.status_code == 403, res.content
-
- config = TeamProvisioningConfig.objects.get(team=self.team)
- assert config.application_id == other_partner.id
- assert config.service_id == "analytics"
diff --git a/ee/api/agentic_provisioning/test/test_url_aliases.py b/ee/api/agentic_provisioning/test/test_url_aliases.py
index 0245db0155a8..7bf521734137 100644
--- a/ee/api/agentic_provisioning/test/test_url_aliases.py
+++ b/ee/api/agentic_provisioning/test/test_url_aliases.py
@@ -5,13 +5,10 @@ from ee.api.agentic_provisioning.test.base import ProvisioningTestBase
RESOURCE_ID = "res_placeholder"
PROVISIONING_ALIAS_URLS = [
- ("health", "/api/provisioning/health", "GET"),
- ("services", "/api/provisioning/services", "GET"),
("account_requests", "/api/provisioning/account_requests", "POST"),
("oauth_token", "/api/provisioning/oauth/token", "POST"),
("resources_create", "/api/provisioning/resources", "POST"),
("rotate_credentials", f"/api/provisioning/resources/{RESOURCE_ID}/rotate_credentials", "POST"),
- ("update_service", f"/api/provisioning/resources/{RESOURCE_ID}/update_service", "POST"),
("resource_remove", f"/api/provisioning/resources/{RESOURCE_ID}/remove", "POST"),
("resource_detail", f"/api/provisioning/resources/{RESOURCE_ID}", "GET"),
("deep_links", "/api/provisioning/deep_links", "POST"),
@@ -25,7 +22,7 @@ class TestProvisioningUrlAliases(ProvisioningTestBase):
@parameterized.expand(PROVISIONING_ALIAS_URLS)
def test_route_resolves(self, _name: str, url: str, method: str):
if method == "GET":
- res = self._get_signed(url)
+ res = self._get_api(url)
else:
- res = self._post_signed(url)
+ res = self._post_api(url)
assert res.status_code != 404, f"{method} {url} returned 404 — route not registered"
diff --git a/ee/api/agentic_provisioning/test/test_wizard_resource_actions.py b/ee/api/agentic_provisioning/test/test_wizard_resource_actions.py
index eaf9e1403eb3..a0a67e0785cc 100644
--- a/ee/api/agentic_provisioning/test/test_wizard_resource_actions.py
+++ b/ee/api/agentic_provisioning/test/test_wizard_resource_actions.py
@@ -10,13 +10,12 @@ import requests
from parameterized import parameterized
from posthog.models.integration import GitHubInstallationAccess, GitHubIntegration, GitHubUserAuthorization, Integration
-from posthog.models.oauth import OAuthApplication
from posthog.models.team.team import Team
from posthog.models.user import OnboardingSkippedReason
from posthog.models.user_integration import UserIntegration
from ee.api.agentic_provisioning import GITHUB_GRANT_CACHE_PREFIX, github_grants
-from ee.api.agentic_provisioning.test.base import TEST_STRIPE_OAUTH_CLIENT_ID, ProvisioningTestBase
+from ee.api.agentic_provisioning.test.base import ProvisioningTestBase
INSTALLATION_ID = "777"
@@ -44,18 +43,17 @@ class TestWizardResourceActions(ProvisioningTestBase):
def setUp(self):
super().setUp()
self.bearer = self._get_bearer_token()
- self.partner = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)
def _grant(self) -> github_grants.GitHubGrant:
return github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")
def _post_github_integration(self, team_id: int, body: dict):
- return self._post_signed_with_bearer(
+ return self._post_with_bearer(
f"/api/agentic/provisioning/resources/{team_id}/github_integration", body, token=self.bearer
)
def _post_wizard_runs(self, team_id: int, body: dict):
- return self._post_signed_with_bearer(
+ return self._post_with_bearer(
f"/api/agentic/provisioning/resources/{team_id}/wizard_runs", body, token=self.bearer
)
diff --git a/ee/api/agentic_provisioning/views.py b/ee/api/agentic_provisioning/views.py
index b84a72ced133..3d09034f9628 100644
--- a/ee/api/agentic_provisioning/views.py
+++ b/ee/api/agentic_provisioning/views.py
@@ -39,12 +39,7 @@ from posthog.api.email_verification import EmailVerifier
from posthog.api.github_callback.team_services import link_github_installation_for_user
from posthog.event_usage import report_user_signed_up
from posthog.exceptions_capture import capture_exception
-from posthog.models.integration import (
- GitHubInstallationAccessFetchError,
- GitHubIntegration,
- Integration,
- StripeIntegration,
-)
+from posthog.models.integration import GitHubInstallationAccessFetchError, GitHubIntegration, Integration
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken, find_oauth_access_token
from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
from posthog.models.team.team import Team
@@ -57,19 +52,16 @@ from posthog.models.utils import (
mask_key_value,
)
from posthog.rbac.user_access_control import UserAccessControl
-from posthog.scopes import narrow_scopes_to_ceiling, scopes_within_ceiling
+from posthog.scopes import effective_ceiling, narrow_scopes_to_ceiling, scopes_within_ceiling
from posthog.tasks.email import send_provisioning_welcome
from posthog.utils import get_instance_region
from products.tasks.backend.facade import api as tasks_facade
-from ee.settings import BILLING_SERVICE_URL
-
from . import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIX, github_grants
from .authentication import ProvisioningAuthentication
from .errors import error_response, typed_error_response
from .region_proxy import region_proxy
-from .signature import SUPPORTED_VERSIONS, verify_api_version, verify_provisioning_signature
logger = structlog.get_logger(__name__)
@@ -125,12 +117,6 @@ 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).
-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
@@ -142,180 +128,6 @@ ACCESS_TOKEN_EXPIRY_SECONDS = 365 * 24 * 3600
PARTNER_TOKEN_EXPIRY_SECONDS = 3600
-# ---------------------------------------------------------------------------
-# Service catalog — 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
-# 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"
-FREE_PLAN_SERVICE_ID = "free"
-PAY_AS_YOU_GO_SERVICE_ID = "pay_as_you_go"
-
-ALL_CATEGORIES: list[str] = ["analytics", "feature_flags", "ai", "observability"]
-
-SERVICES_CACHE_KEY = "agentic_provisioning:services"
-SERVICES_CACHE_TTL = 3600
-SERVICES_CACHE_RETRY_TTL = 300
-SERVICES_CACHE_EXPIRES_KEY = "agentic_provisioning:services:expires_at"
-SERVICES_CACHE_STORE_TTL = 86400
-
-_EXCLUDED_PRODUCT_TYPES = {"platform_and_support", "integrations"}
-
-_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"},
- )
- res.raise_for_status()
- products = res.json().get("products", [])
- except Exception:
- logger.exception("agentic_provisioning.services.billing_fetch_failed")
- return None
-
- 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("agentic_provisioning.services.serving_stale_cache")
- cache.set(SERVICES_CACHE_EXPIRES_KEY, now + SERVICES_CACHE_RETRY_TTL, SERVICES_CACHE_STORE_TTL)
- return cached
-
- logger.warning("agentic_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
-
-
-VALID_SERVICE_IDS: set[str] = {FREE_PLAN_SERVICE_ID, PAY_AS_YOU_GO_SERVICE_ID, ANALYTICS_SERVICE_ID}
-
-
-# ---------------------------------------------------------------------------
-# GET /provisioning/health — liveness probe, returns supported protocol versions
-# ---------------------------------------------------------------------------
-
-
-@api_view(["GET"])
-@authentication_classes([])
-@permission_classes([])
-def provisioning_health(request: Request) -> Response:
- error = verify_provisioning_signature(request)
- if error:
- return error
- if error := verify_api_version(request):
- return error
-
- return Response({"supported_versions": SUPPORTED_VERSIONS, "status": "ok"})
-
-
-# ---------------------------------------------------------------------------
-# GET /provisioning/services — returns the catalog of provisionable services
-# ---------------------------------------------------------------------------
-
-
-@api_view(["GET"])
-@authentication_classes([])
-@permission_classes([])
-def provisioning_services(request: Request) -> Response:
- error = verify_provisioning_signature(request)
- if error:
- return error
- if error := verify_api_version(request):
- return error
-
- return Response({"data": _get_services()})
-
-
# ---------------------------------------------------------------------------
# POST /provisioning/account_requests — onboard a new or existing user and
# return either an auth code (new user) or a redirect URL (existing user)
@@ -327,8 +139,6 @@ def provisioning_services(request: Request) -> Response:
@permission_classes([])
@region_proxy(strategy="body_region")
def account_requests(request: Request) -> Response:
- if error := verify_api_version(request):
- return error
if error := _enforce_cimd_registration_throttle(request):
return error
@@ -350,6 +160,9 @@ def account_requests(request: Request) -> Response:
status=202,
)
+ if partner is None:
+ return typed_error_response("unauthorized", "Authentication required", status=401)
+
# --- Parse request ---
data = request.data
request_id = data.get("id", "")
@@ -359,10 +172,13 @@ def account_requests(request: Request) -> Response:
return typed_error_response("invalid_request", "email is required")
scopes = data.get("scopes", [])
- confirmation_secret = data.get("confirmation_secret", "")
+ if not scopes:
+ # Resolve the default before any consent state is created, so the consent
+ # page displays exactly what the token exchange will later grant. Matches
+ # /authorize: an empty app ceiling resolves to the unprivileged set.
+ scopes = sorted(effective_ceiling(partner.ceiling_scopes))
expires_at_str = data.get("expires_at", "")
configuration = data.get("configuration") or {}
- orchestrator = data.get("orchestrator") or {}
if expires_at_str:
from django.utils.dateparse import parse_datetime
@@ -372,36 +188,11 @@ def account_requests(request: Request) -> Response:
_capture_provisioning_event("account_request", "error", error_code="expired")
return typed_error_response("expired", "Account request has expired")
- # Partner account ID: generic field, with Stripe backward compat
- 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", "")
-
- # 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)
-
- if not partner:
- if error := _verify_hmac_if_present(request):
- return error
-
- # Stripe Projects: require stripe account if no provisioning partner identified
- if not partner and not partner_account_id:
- _capture_provisioning_event("account_request", "error", error_code="missing_stripe_account")
- return typed_error_response("invalid_request", "orchestrator.stripe.account is required")
-
- # Check permission
- if partner and not partner.provisioning_can_create_accounts:
+ if not partner.provisioning_can_create_accounts:
_capture_provisioning_event("account_request", "error", error_code="account_creation_disabled")
return typed_error_response("forbidden", "Account creation is not enabled for this partner", status=403)
- if partner and (error := _enforce_partner_rate_limit(partner, "account_requests")):
+ if error := _enforce_partner_rate_limit(partner, "account_requests"):
return error
# PKCE: capture code_challenge for later verification
@@ -433,9 +224,7 @@ def account_requests(request: Request) -> Response:
return _handle_existing_user(
request_id,
existing_user,
- confirmation_secret,
scopes,
- partner_account_id,
region,
requested_team_id,
partner,
@@ -449,7 +238,6 @@ def account_requests(request: Request) -> Response:
data,
email,
scopes,
- partner_account_id,
region,
partner,
code_challenge,
@@ -458,29 +246,12 @@ def account_requests(request: Request) -> Response:
)
-def _user_has_existing_credentials_from_partner(user: User, partner: OAuthApplication) -> bool:
- """True if the user has any live OAuth credential issued to this partner.
-
- "Live" = unexpired access token or non-revoked refresh token. PersonalAPIKey has no
- partner attribution today, so it's excluded from this check; in practice PATs are
- minted alongside OAuth tokens at provisioning time, so the OAuth-only check matches.
- """
- now = timezone.now()
- if OAuthAccessToken.objects.filter(user=user, application=partner, expires__gt=now).exists():
- return True
- if OAuthRefreshToken.objects.filter(user=user, application=partner, revoked__isnull=True).exists():
- return True
- return False
-
-
def _caller_proved_existing_trust(partner: OAuthApplication, user: User, authenticated_user: User | None) -> bool:
"""True only when the caller proved a prior trust relationship with this user.
This is what lets a skip-consent partner re-mint silently for an existing user; without
it the request falls through to browser consent. The proof differs by auth method:
- - HMAC callers authenticate with a partner-level secret, so the partner already holding
- a live OAuth credential for the user is sufficient proof of an existing relationship.
- Bearer callers present a single user-scoped access token. That token proves a
relationship only with its own user, so it qualifies only when it belongs to the user
being re-linked — otherwise any user of the partner could ride another user's live
@@ -489,8 +260,6 @@ def _caller_proved_existing_trust(partner: OAuthApplication, user: User, authent
can send, so the request carries no proof the caller controls the partner. The "user
already holds a live credential" signal proves nothing, so these never qualify.
"""
- if partner.provisioning_auth_method == "hmac":
- return _user_has_existing_credentials_from_partner(user, partner)
if partner.provisioning_auth_method == "bearer":
return authenticated_user is not None and authenticated_user.id == user.id
return False
@@ -499,9 +268,7 @@ def _caller_proved_existing_trust(partner: OAuthApplication, user: User, authent
def _handle_existing_user(
request_id: str,
user: User,
- confirmation_secret: str,
scopes: list[str],
- partner_account_id: str = "",
region: str = "US",
team_id: int | None = None,
partner: OAuthApplication | None = None,
@@ -545,7 +312,6 @@ def _handle_existing_user(
request_id,
user,
scopes,
- partner_account_id,
region,
partner,
code_challenge,
@@ -567,7 +333,6 @@ def _handle_existing_user(
"user_id": user.id,
"org_id": str(team.organization_id),
"team_id": team.id,
- "stripe_account_id": partner_account_id,
"partner_id": str(partner.id) if partner else "",
"scopes": scopes,
"region": region,
@@ -586,7 +351,6 @@ def _require_user_consent(
request_id: str,
user: User,
scopes: list[str],
- partner_account_id: str,
region: str,
partner: OAuthApplication,
code_challenge: str,
@@ -608,7 +372,6 @@ def _require_user_consent(
{
"email": user.email,
"scopes": scopes,
- "stripe_account_id": partner_account_id,
"partner_id": str(partner.id),
"partner_name": partner.name,
"region": region,
@@ -670,7 +433,6 @@ def _handle_new_user(
data: dict,
email: str,
scopes: list[str],
- partner_account_id: str,
region: str,
partner: OAuthApplication | None = None,
code_challenge: str = "",
@@ -702,9 +464,7 @@ def _handle_new_user(
return _handle_existing_user(
request_id,
existing,
- data.get("confirmation_secret", ""),
scopes,
- partner_account_id,
region,
None,
partner,
@@ -773,7 +533,6 @@ def _handle_new_user(
"user_id": user.id,
"org_id": str(organization.id),
"team_id": team.id,
- "stripe_account_id": partner_account_id,
"partner_id": str(partner.id) if partner else "",
"scopes": scopes,
"region": region,
@@ -855,10 +614,10 @@ def _build_authorize_url(confirmation_secret: str, scopes: list[str], region: st
def _authenticate_provisioning_partner(request: Request) -> tuple[Response | None, OAuthApplication | None]:
- """Identify a provisioning partner, requiring proof-bearing auth (unlike
- account_requests' legacy Stripe fallback). Returns (error_response, partner).
+ """Identify a provisioning partner, requiring proof-bearing auth.
+ Returns (error_response, partner).
- Only HMAC and Bearer partners carry proof that the caller controls the partner.
+ Only Bearer partners carry proof that the caller controls the partner.
PKCE partners are identified solely by a public ``client_id`` anyone can send, so
they never qualify for these endpoints — they exchange GitHub OAuth codes and read
back GitHub account metadata, which must sit behind a real partner trust boundary.
@@ -874,7 +633,7 @@ def _authenticate_provisioning_partner(request: Request) -> tuple[Response | Non
typed_error_response("unauthorized", "Authentication required", status=401),
None,
)
- if partner.provisioning_auth_method not in ("hmac", "bearer"):
+ if partner.provisioning_auth_method != "bearer":
return (
typed_error_response("forbidden", "This endpoint requires a confidential partner", status=403),
None,
@@ -886,8 +645,6 @@ def _authenticate_provisioning_partner(request: Request) -> tuple[Response | Non
@authentication_classes([])
@permission_classes([])
def github_grants_create(request: Request) -> Response:
- if error := verify_api_version(request):
- return error
auth_error, partner = _authenticate_provisioning_partner(request)
if auth_error or partner is None:
@@ -965,8 +722,6 @@ def _enforce_grant_poll_rate_limit(grant_id: str) -> Response | None:
@authentication_classes([])
@permission_classes([])
def github_grant_repositories(request: Request, grant_id: str) -> Response:
- if error := verify_api_version(request):
- return error
auth_error, partner = _authenticate_provisioning_partner(request)
if auth_error or partner is None:
@@ -1038,7 +793,7 @@ def agentic_authorize(request: Any) -> HttpResponseBase:
# Re-check partner is still active (could have been deactivated since account_requests)
partner_id = pending.get("partner_id", "")
- is_trusted_partner = not partner_id
+ is_trusted_partner = False
if partner_id:
try:
partner_app = OAuthApplication.objects.get(id=partner_id)
@@ -1058,6 +813,11 @@ def agentic_authorize(request: Any) -> HttpResponseBase:
organization = memberships[0].organization
team = non_demo_teams[0]
+ callback_url = _get_callback_url(pending.get("partner_id", ""))
+ if callback_url is None:
+ _capture_provisioning_event("authorize", "missing_callback")
+ return HttpResponseRedirect(f"{settings.SITE_URL}?error=missing_callback")
+
code = secrets.token_urlsafe(32)
cache.set(
f"{AUTH_CODE_CACHE_PREFIX}{code}",
@@ -1066,7 +826,6 @@ def agentic_authorize(request: Any) -> HttpResponseBase:
"user_id": user.id,
"org_id": str(organization.id),
"team_id": team.id,
- "stripe_account_id": pending.get("stripe_account_id", ""),
"partner_id": pending.get("partner_id", ""),
"scopes": pending.get("scopes", []),
"region": pending.get("region", "US"),
@@ -1079,7 +838,6 @@ def agentic_authorize(request: Any) -> HttpResponseBase:
_capture_provisioning_event("authorize", "auto_redirect", team_id=team.id)
- callback_url = _get_callback_url(pending.get("partner_id", ""))
sanitized_state = re.sub(r"[^A-Za-z0-9_\-]", "", state)
params = urlencode({"code": code, "state": sanitized_state})
return HttpResponseRedirect(f"{callback_url}?{params}")
@@ -1164,6 +922,11 @@ def agentic_authorize_confirm(request: Request) -> Response:
except OAuthApplication.DoesNotExist:
pass
+ callback_url = _get_callback_url(pending.get("partner_id", ""))
+ if callback_url is None:
+ _capture_provisioning_event("authorize_confirm", "missing_callback", partner=confirm_partner)
+ return Response({"error": "missing_callback"}, status=400)
+
code = secrets.token_urlsafe(32)
# Set auth code BEFORE deleting pending state so a cache hiccup
# between the two doesn't leave the user with no recovery path.
@@ -1174,7 +937,6 @@ def agentic_authorize_confirm(request: Request) -> Response:
"user_id": user.id,
"org_id": str(team.organization_id),
"team_id": team.id,
- "stripe_account_id": pending.get("stripe_account_id", ""),
"partner_id": pending.get("partner_id", ""),
"scopes": pending.get("scopes", []),
"region": pending.get("region", "US"),
@@ -1185,7 +947,6 @@ def agentic_authorize_confirm(request: Request) -> Response:
)
cache.delete(pending_key)
- callback_url = _get_callback_url(pending.get("partner_id", ""))
sanitized_state = re.sub(r"[^A-Za-z0-9_\-]", "", state)
params = urlencode({"code": code, "state": sanitized_state})
redirect_url = f"{callback_url}?{params}"
@@ -1245,35 +1006,27 @@ def _exchange_authorization_code(request: Request) -> Response:
{"error": "invalid_grant", "error_description": "Invalid or expired authorization code"}, status=400
)
- # 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).
+ # Auth check: every code requires PKCE verification. 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")
- return Response(
- {"error": "invalid_request", "error_description": "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")
- return Response(
- {"error": "invalid_grant", "error_description": "PKCE code_verifier does not match"}, status=400
- )
- elif not has_hmac:
- _capture_provisioning_event("token_exchange", "missing_signature", grant_type="authorization_code")
+ if not stored_challenge:
+ _capture_provisioning_event("token_exchange", "missing_code_challenge", grant_type="authorization_code")
return Response({"error": "invalid_request", "error_description": "Authentication required"}, status=401)
- else:
- if error := _verify_hmac_if_present(request):
- return error
+
+ code_verifier = request.data.get("code_verifier", "")
+ if not code_verifier:
+ _capture_provisioning_event("token_exchange", "missing_code_verifier", grant_type="authorization_code")
+ return Response(
+ {"error": "invalid_request", "error_description": "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")
+ return Response(
+ {"error": "invalid_grant", "error_description": "PKCE code_verifier does not match"}, status=400
+ )
# Consume the code before rate limiting so a leaked auth code can't be replayed
# to burn the partner's bucket. Auth codes are single-use by spec, so the
@@ -1281,14 +1034,22 @@ def _exchange_authorization_code(request: Request) -> Response:
# re-initiate the OAuth flow if rate-limited.
cache.delete(cache_key)
+ oauth_app: OAuthApplication | None = None
partner_id = code_data.get("partner_id", "")
if partner_id:
try:
- partner = OAuthApplication.objects.get(id=partner_id)
- if error := _enforce_partner_rate_limit(partner, "token_exchanges"):
- return error
+ oauth_app = OAuthApplication.objects.get(id=partner_id)
except (OAuthApplication.DoesNotExist, ValidationError, ValueError):
- logger.warning("partner_rate_limit_app_missing", partner_id=partner_id)
+ logger.warning("token_exchange_app_missing", partner_id=partner_id)
+ if oauth_app is None:
+ _capture_provisioning_event("token_exchange", "oauth_app_missing", grant_type="authorization_code")
+ return Response(
+ {"error": "invalid_grant", "error_description": "Unknown application for this authorization code"},
+ status=400,
+ )
+
+ if error := _enforce_partner_rate_limit(oauth_app, "token_exchanges"):
+ return error
user_id = code_data["user_id"]
team_id = code_data["team_id"]
@@ -1300,15 +1061,6 @@ def _exchange_authorization_code(request: Request) -> Response:
_capture_provisioning_event("token_exchange", "user_not_found", grant_type="authorization_code")
return Response({"error": "invalid_grant", "error_description": "User not found"}, status=400)
- # Use partner's OAuth app if available, fall back to Stripe
- try:
- oauth_app = _get_oauth_app_for_code(code_data)
- except LegacyStripeOAuthAppMissingError:
- _capture_provisioning_event("token_exchange", "oauth_app_missing", grant_type="authorization_code")
- return Response(
- {"error": "server_error", "error_description": "OAuth application is not configured"}, status=500
- )
-
# 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
@@ -1316,7 +1068,7 @@ def _exchange_authorization_code(request: Request) -> Response:
# before `issued_at` shipped lack 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
+ locked_app = _lock_application(oauth_app.pk)
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")
@@ -1330,8 +1082,18 @@ def _exchange_authorization_code(request: Request) -> Response:
# Direct-mint bypasses /authorize's OAuthValidator, so the per-app scope
# ceiling has to be enforced here before the token is created by hand.
- requested_scopes = scopes if scopes else StripeIntegration.SCOPES.split()
app_scopes = locked_app.ceiling_scopes if locked_app else []
+ # Codes are minted with their scopes already resolved (account_requests
+ # defaults an omitted list to the app ceiling before consent), so an empty
+ # list means a stale or hand-crafted code. Defaulting at exchange time would
+ # grant scopes the consent screen never displayed.
+ if not scopes:
+ _capture_provisioning_event("token_exchange", "empty_scopes", grant_type="authorization_code")
+ return Response(
+ {"error": "invalid_scope", "error_description": "Authorization code carries no scopes; re-authorize."},
+ status=400,
+ )
+ requested_scopes = scopes
if not scopes_within_ceiling(requested_scopes, app_scopes):
_capture_provisioning_event("token_exchange", "scope_ceiling_exceeded", grant_type="authorization_code")
return Response(
@@ -1468,7 +1230,9 @@ def _exchange_refresh_token(request: Request) -> Response:
{"error": "invalid_grant", "error_description": "No accessible teams for this token; re-authorize."},
status=400,
)
- old_scope = old_refresh.access_token.scope if old_refresh.access_token else StripeIntegration.SCOPES
+ # A rotated-away access token leaves no scope to carry over; the refreshed
+ # token gets an empty scope rather than inheriting anything implicit.
+ old_scope = old_refresh.access_token.scope if old_refresh.access_token else ""
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:
@@ -1555,94 +1319,6 @@ 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
-
- 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("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(request: Request) -> str | None:
- payment_credentials = request.data.get("payment_credentials")
- 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(request: Request, 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(request)
- if not spt_token:
- return None
- if _team_has_active_billing(team, user):
- return True
- return _activate_billing_with_spt(team, user, spt_token)
-
-
class _InvalidLabelPrefixError(Exception):
"""Raised when a partner-supplied label_prefix fails validation."""
@@ -1917,21 +1593,6 @@ def _add_team_to_token_scopes(access_token: OAuthAccessToken, team_id: int) -> N
rt.save(update_fields=["scoped_teams"])
-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},
- )
-
-
# ---------------------------------------------------------------------------
# POST /provisioning/resources
# ---------------------------------------------------------------------------
@@ -1946,11 +1607,6 @@ def provisioning_resources_create(request: Request) -> Response:
if auth_error:
return auth_error
- if error := _verify_hmac_if_present(request):
- return error
- if error := verify_api_version(request):
- return error
-
app = access_token.application
if app and app.provisioning_partner_type:
if error := _enforce_partner_rate_limit(app, "resource_creates"):
@@ -1962,11 +1618,6 @@ def provisioning_resources_create(request: Request) -> Response:
response["Retry-After"] = retry_after
return response
- service_id = request.data.get("service_id", "")
- if service_id and service_id not in VALID_SERVICE_IDS:
- _capture_provisioning_event("resource_created", "error", partner=app, error_code="unknown_service")
- return error_response("unknown_service", f"Unknown service_id: {service_id}")
-
try:
label_prefix = _extract_label_prefix(request)
except _InvalidLabelPrefixError as exc:
@@ -2011,44 +1662,6 @@ def provisioning_resources_create(request: Request) -> Response:
)
return error_response("team_not_found", "Team not found", resource_id=str(team_id), status=404)
- resolved_service_id = service_id or ANALYTICS_SERVICE_ID
- _set_provisioning_service_id(team, resolved_service_id)
-
- billing_result = _try_activate_billing_with_spt(request, 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,
- )
- return Response(
- {
- "status": "error",
- "id": str(team.id),
- "error": {
- "code": "requires_payment_credentials",
- "message": "Billing activation failed",
- },
- },
- status=400,
- )
-
- 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,
- )
- return error_response("requires_payment_credentials", "Payment credentials required for paid plan")
-
region = get_instance_region() or "US"
host = _region_to_host(region)
@@ -2056,10 +1669,7 @@ def provisioning_resources_create(request: Request) -> Response:
"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] = {
@@ -2075,7 +1685,6 @@ def provisioning_resources_create(request: Request) -> Response:
{
"status": "complete",
"id": str(team.id),
- "service_id": resolved_service_id,
"complete": {
"access_configuration": access_configuration,
},
@@ -2110,11 +1719,6 @@ def provisioning_rotate_credentials(request: Request, resource_id: str) -> Respo
if auth_error:
return auth_error
- if error := _verify_hmac_if_present(request):
- return error
- if error := verify_api_version(request):
- return error
-
try:
label_prefix = _extract_label_prefix(request)
except _InvalidLabelPrefixError as exc:
@@ -2150,7 +1754,6 @@ def provisioning_rotate_credentials(request: Request, resource_id: str) -> Respo
_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)
@@ -2167,7 +1770,6 @@ def provisioning_rotate_credentials(request: Request, resource_id: str) -> Respo
{
"status": "complete",
"id": resource_id,
- "service_id": service_id,
"complete": {
"access_configuration": access_configuration,
},
@@ -2304,11 +1906,6 @@ def provisioning_github_integration(request: Request, resource_id: str) -> Respo
if auth_error:
return auth_error
- if error := _verify_hmac_if_present(request):
- return error
- if error := verify_api_version(request):
- return error
-
try:
team_id = int(resource_id)
except (ValueError, TypeError):
@@ -2473,11 +2070,6 @@ def provisioning_wizard_runs(request: Request, resource_id: str) -> Response:
if auth_error:
return auth_error
- if error := _verify_hmac_if_present(request):
- return error
- if error := verify_api_version(request):
- return error
-
try:
team_id = int(resource_id)
except (ValueError, TypeError):
@@ -2510,118 +2102,6 @@ def provisioning_wizard_runs(request: Request, resource_id: str) -> Response:
return Response({"status": "complete", "id": resource_id, "wizard_run": run_payload})
-# ---------------------------------------------------------------------------
-# 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/.
-# ---------------------------------------------------------------------------
-
-
-@api_view(["POST"])
-@authentication_classes([])
-@permission_classes([])
-@region_proxy(strategy="bearer_lookup")
-def provisioning_update_service(request: Request, resource_id: str) -> Response:
- auth_error, user, access_token = _authenticate_bearer(request)
- if auth_error:
- return auth_error
-
- error = verify_provisioning_signature(request)
- if error:
- return error
- if error := verify_api_version(request):
- return error
-
- scoped_teams = access_token.scoped_teams or []
-
- try:
- team_id = int(resource_id)
- except (ValueError, TypeError):
- return error_response("invalid_resource_id", "Invalid resource ID", resource_id=resource_id)
-
- if team_id not in scoped_teams:
- return error_response(
- "forbidden", "Resource not accessible with this token", resource_id=resource_id, status=403
- )
-
- try:
- team = Team.objects.get(id=team_id)
- except Team.DoesNotExist:
- return error_response("not_found", "Resource not found", resource_id=resource_id, status=404)
-
- # 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:
- return error_response(
- "forbidden", "Resource owned by a different provisioning partner", resource_id=resource_id, status=403
- )
-
- service_id = request.data.get("service_id", "")
- if not service_id:
- return error_response("missing_service_id", "service_id is required", resource_id=resource_id)
- if service_id not in VALID_SERVICE_IDS:
- return error_response("unknown_service", f"Unknown service_id: {service_id}", resource_id=resource_id)
-
- billing_result = _try_activate_billing_with_spt(request, 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,
- )
- return error_response(
- "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
- )
- return error_response(
- "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),
- )
-
- access_configuration: dict[str, str] = {
- "api_key": team.api_token,
- "host": host,
- }
-
- return Response(
- {
- "status": "complete",
- "id": resource_id,
- "service_id": service_id,
- "complete": {
- "access_configuration": access_configuration,
- },
- }
- )
-
-
# ---------------------------------------------------------------------------
# POST /provisioning/resources/:id/remove
# Detaches the resource from the orchestrator: removes it from the token's
@@ -2639,11 +2119,6 @@ def provisioning_resource_remove(request: Request, resource_id: str) -> Response
if auth_error:
return auth_error
- if error := _verify_hmac_if_present(request):
- return error
- if error := verify_api_version(request):
- return error
-
try:
team_id = int(resource_id)
except (ValueError, TypeError):
@@ -2756,11 +2231,6 @@ def _resolve_resource_response(request: Request, resource_id: str) -> Response:
if auth_error:
return auth_error
- if error := _verify_hmac_if_present(request):
- return error
- if error := verify_api_version(request):
- return error
-
scoped_teams = access_token.scoped_teams or []
try:
@@ -2793,7 +2263,6 @@ def _resolve_resource_response(request: Request, resource_id: str) -> Response:
status=404,
)
- service_id = _get_provisioning_service_id(team)
region = get_instance_region() or "US"
host = _region_to_host(region)
@@ -2801,7 +2270,6 @@ def _resolve_resource_response(request: Request, resource_id: str) -> Response:
{
"status": "complete",
"id": resource_id,
- "service_id": service_id,
"complete": {
"access_configuration": {
"api_key": team.api_token,
@@ -2826,25 +2294,6 @@ def deep_links(request: Request) -> Response:
if auth_error:
return auth_error
- # 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(
- "hmac_signature_required",
- "HMAC signature required for this partner",
- status=401,
- )
- if error := verify_provisioning_signature(request):
- return error
- elif error := _verify_hmac_if_present(request):
- return error
-
- if error := verify_api_version(request):
- return error
-
if not access_token.application.provisioning_can_issue_deep_links:
_capture_provisioning_event("deep_link_created", "not_enabled", partner=access_token.application)
return error_response(
@@ -2911,15 +2360,13 @@ 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 is None:
+ return "Partner"
if partner.provisioning_partner_type:
return partner.provisioning_partner_type.capitalize()
if partner.name:
return partner.name
- return "Stripe"
+ return "Partner"
def _enforce_partner_rate_limit(partner: OAuthApplication, endpoint: str) -> Response | None:
@@ -3020,24 +2467,10 @@ def _enforce_cimd_domain_rate_limit(client_id: str) -> Response | None:
return 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.
- For non-HMAC partners (wizard, Bearer-only), skip HMAC and rely on Bearer auth alone.
- """
- if request.headers.get("stripe-signature"):
- return verify_provisioning_signature(request)
- return None
-
-
def _authenticate_bearer(request: Request) -> tuple[Response | None, Any, Any]:
- """Authenticate via Bearer token. Returns (error_response, user, access_token).
+ """Authenticate via Bearer token issued to an active provisioning partner.
- Tries generic ProvisioningAuthentication first (any partner's token),
- then falls back to Stripe Projects HMAC auth.
+ Returns (error_response, user, access_token).
"""
auth_header = request.headers.get("authorization", "")
@@ -3058,6 +2491,12 @@ def _authenticate_bearer(request: Request) -> tuple[Response | None, Any, Any]:
# Check if token belongs to any active provisioning partner's app
app = access_token.application
if app and app.is_provisioning_partner:
+ # Only bearer/pkce partners are supported. An app configured with any other
+ # auth method (e.g. a leftover hmac partner row) must fail closed here, or its
+ # outstanding bearer tokens could still reach the resource and deep-link
+ # endpoints without the second factor that method implied.
+ if app.provisioning_auth_method not in ("bearer", "pkce"):
+ return (error_response("unauthorized", "Authentication failed", status=401), None, None)
if not app.provisioning_active:
return (error_response("unauthorized", "Partner is deactivated", status=401), None, None)
if not app.provisioning_can_provision_resources:
@@ -3068,61 +2507,9 @@ 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.
-
- Raised instead of fabricating an app on demand: a missing app is an
- operational misconfiguration, not something to paper over with a freshly
- created application that carries no scope ceiling.
- """
-
-
-def _seed_stripe_app_scopes(app: OAuthApplication) -> None:
- """Seed the Stripe Projects app's scope ceiling when it is unset.
-
- Region-agnostic by design: US and EU each hold their own OAuthApplication
- row, so this runs independently the first time the app is resolved in each
- region. Pre-seeding via the ops step in the slice notes avoids the on-request
- write, but this keeps the ceiling correct even if that step is missed.
- """
- if app.scopes:
- return
- app.scopes = list(STRIPE_CONTRACTED_SCOPES)
- app.save(update_fields=["scopes"])
-
-
-def _get_legacy_stripe_oauth_app() -> OAuthApplication:
- client_id = settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID
- if not client_id:
- error = LegacyStripeOAuthAppMissingError("STRIPE_POSTHOG_OAUTH_CLIENT_ID is not configured")
- capture_exception(error)
- raise error
-
- try:
- app = OAuthApplication.objects.get(client_id=client_id)
- except OAuthApplication.DoesNotExist as exc:
- error = LegacyStripeOAuthAppMissingError("Stripe Projects OAuth app not found for configured client_id")
- # Chain the DoesNotExist so the captured event keeps its traceback; the new
- # error was never raised, so it carries no traceback of its own.
- error.__cause__ = exc
- capture_exception(error, additional_properties={"client_id": client_id})
- raise error from None
-
- _seed_stripe_app_scopes(app)
- return app
-
-
def _get_available_teams_for_user(user: User) -> list[dict[str, Any]]:
"""Return the user's non-demo teams for inclusion in the token exchange response."""
org_ids = list(user.organization_memberships.values_list("organization_id", flat=True))
@@ -3138,38 +2525,22 @@ def _get_available_teams_for_user(user: User) -> list[dict[str, Any]]:
]
-def _get_callback_url(partner_id: str) -> str:
- """Get the callback URL from the partner's redirect_uris, falling back to the Stripe setting."""
- if partner_id:
- try:
- app = OAuthApplication.objects.get(id=partner_id)
- redirect_uris = app.redirect_uris.strip()
- if redirect_uris:
- return redirect_uris.split()[0]
- 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
-
+def _get_callback_url(partner_id: str) -> str | None:
+ """Get the callback URL from the partner's redirect_uris.
-def _get_oauth_app_for_code(code_data: dict) -> OAuthApplication:
- """Resolve the OAuthApplication for a token exchange.
-
- If the auth code was created by a provisioning partner, use that app.
- Otherwise fall back to the legacy Stripe Projects app lookup, which
- hard-fails (raising ``LegacyStripeOAuthAppMissingError``) if the configured
- app is missing rather than fabricating one.
+ Returns None when the partner cannot be resolved or has no redirect URI
+ registered; callers must fail the flow rather than redirect blindly.
"""
- partner_id = code_data.get("partner_id", "")
- if partner_id:
- try:
- return OAuthApplication.objects.get(id=partner_id)
- except OAuthApplication.DoesNotExist:
- pass
-
- return _get_legacy_stripe_oauth_app()
+ if not partner_id:
+ return None
+ try:
+ app = OAuthApplication.objects.get(id=partner_id)
+ except OAuthApplication.DoesNotExist:
+ return None
+ redirect_uris = app.redirect_uris.strip()
+ if not redirect_uris:
+ return None
+ return redirect_uris.split()[0]
def _region_to_host(region: str) -> str:
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.py
index 3a849ad7d057..5f44308e42c4 100644
--- a/ee/billing/billing_manager.py
+++ b/ee/billing/billing_manager.py
@@ -1,5 +1,7 @@
+import hmac
import json
import time
+import hashlib
from datetime import UTC, datetime, timedelta
from enum import Enum
from typing import Any, Optional, cast
@@ -21,7 +23,6 @@ from posthog.models import Organization
from posthog.models.organization import OrganizationMembership, OrganizationUsageInfo
from posthog.models.user import User
-from ee.api.agentic_provisioning.signature import compute_signature
from ee.billing.billing_types import BillingProvider, BillingStatus
from ee.billing.quota_limiting import set_org_usage_summary, update_org_billing_quotas
from ee.models import License
@@ -143,13 +144,21 @@ def build_billing_token(
return encoded_jwt
+def _compute_webhook_signature(secret: str, timestamp: int, body: bytes) -> str:
+ """HMAC-SHA256 over "<timestamp>.<body>", hex-encoded."""
+ mac = hmac.new(secret.encode(), digestmod=hashlib.sha256)
+ mac.update(f"{timestamp}.".encode())
+ mac.update(body)
+ return mac.digest().hex()
+
+
def build_billing_provider_webhook_signature_headers(body: bytes) -> dict[str, str]:
secret = getattr(settings, "BILLING_PROVIDER_WEBHOOK_SECRET", "")
if not secret:
raise ValueError("BILLING_PROVIDER_WEBHOOK_SECRET is not configured")
timestamp = int(time.time())
- digest = compute_signature(secret, timestamp, body)
+ digest = _compute_webhook_signature(secret, timestamp, body)
return {
BILLING_PROVIDER_WEBHOOK_SIGNATURE_HEADER: f"{BILLING_PROVIDER_WEBHOOK_SIGNATURE_VERSION}={digest}",
BILLING_PROVIDER_WEBHOOK_TIMESTAMP_HEADER: str(timestamp),
diff --git a/ee/urls.py b/ee/urls.py
index 407103abe538..dd85cc5cc139 100644
--- a/ee/urls.py
+++ b/ee/urls.py
@@ -275,24 +275,9 @@ urlpatterns: list[Any] = [
name="scim_resource_types",
),
path("scim/v2/<uuid:domain_id>/Schemas", csrf_exempt(scim_views.SCIMSchemasView.as_view()), name="scim_schemas"),
- # Stripe Projects provisioning (APP 0.1d) — the namespace the Stripe app
- # manifest points at (provisioning.base_url = .../api/partners/stripe/)
+ # Stripe Projects provisioning (APP 0.1d)
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),
- name="agentic_provisioning_health",
- ),
- path(
- "api/agentic/provisioning/services",
- csrf_exempt(agentic_provisioning_views.provisioning_services),
- name="agentic_provisioning_services",
- ),
path(
"api/agentic/provisioning/account_requests",
csrf_exempt(agentic_provisioning_views.account_requests),
@@ -328,11 +313,6 @@ urlpatterns: list[Any] = [
csrf_exempt(agentic_provisioning_views.provisioning_rotate_credentials),
name="agentic_provisioning_rotate_credentials",
),
- path(
- "api/agentic/provisioning/resources/<str:resource_id>/update_service",
- csrf_exempt(agentic_provisioning_views.provisioning_update_service),
- name="agentic_provisioning_update_service",
- ),
path(
"api/agentic/provisioning/resources/<str:resource_id>/remove",
csrf_exempt(agentic_provisioning_views.provisioning_resource_remove),
@@ -374,19 +354,6 @@ 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),
- name="provisioning_health",
- ),
- path(
- "api/provisioning/services",
- csrf_exempt(agentic_provisioning_views.provisioning_services),
- name="provisioning_services",
- ),
path(
"api/provisioning/account_requests",
csrf_exempt(agentic_provisioning_views.account_requests),
@@ -407,11 +374,6 @@ urlpatterns: list[Any] = [
csrf_exempt(agentic_provisioning_views.provisioning_rotate_credentials),
name="provisioning_rotate_credentials",
),
- path(
- "api/provisioning/resources/<str:resource_id>/update_service",
- csrf_exempt(agentic_provisioning_views.provisioning_update_service),
- name="provisioning_update_service",
- ),
path(
"api/provisioning/resources/<str:resource_id>/remove",
csrf_exempt(agentic_provisioning_views.provisioning_resource_remove),
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index cae2b96142c4..11e819855dfd 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -145,7 +145,7 @@ def _verify_stripe_install_signature(state: str, user_id: str, account_id: str,
separators=(",", ":"),
)
try:
- # 300s tolerance matches the agentic-provisioning HMAC check at ee/api/agentic_provisioning/signature.py.
+ # 300s tolerance matches the Stripe provisioning HMAC check at ee/partners/stripe/api/provisioning/signature.py.
stripe.WebhookSignature.verify_header(payload, install_signature, settings.STRIPE_SIGNING_SECRET, tolerance=300)
return True
except stripe.SignatureVerificationError:
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index 457caa991a62..a199af3b4072 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -107,7 +107,6 @@ STRIPE_APP_OVERRIDE_AUTHORIZE_URL = get_from_env("STRIPE_APP_OVERRIDE_AUTHORIZE_
STRIPE_APP_SECRET_KEY = get_from_env("STRIPE_APP_SECRET_KEY", "")
STRIPE_POSTHOG_OAUTH_CLIENT_ID = get_from_env("STRIPE_POSTHOG_OAUTH_CLIENT_ID", "")
STRIPE_SIGNING_SECRET = get_from_env("STRIPE_SIGNING_SECRET", "")
-STRIPE_ORCHESTRATOR_CALLBACK_URL = get_from_env("STRIPE_ORCHESTRATOR_CALLBACK_URL", "")
# WorkOS Radar (bot/fraud detection for auth flows)
WORKOS_RADAR_API_KEY = get_from_env("WORKOS_RADAR_API_KEY", "")