: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(agentic-provisioning): restructure into drf class-based views (#73935)
Rafael Audibert58dec4c4279b
diff --git a/ee/api/agentic_provisioning/__init__.py b/ee/api/agentic_provisioning/__init__.pyindex 98ed821f0cf9..a4e56ec1df4e 100644--- a/ee/api/agentic_provisioning/__init__.py+++ b/ee/api/agentic_provisioning/__init__.py@@ -1,3 +1 @@-AUTH_CODE_CACHE_PREFIX = "provisioning_auth_code:"-PENDING_AUTH_CACHE_PREFIX = "provisioning_pending_auth:"-GITHUB_GRANT_CACHE_PREFIX = "provisioning_github_grant:"+"""Agentic provisioning API: partner-facing account, resource, and wizard endpoints."""diff --git a/ee/api/agentic_provisioning/accounts.py b/ee/api/agentic_provisioning/accounts.pynew file mode 100644index 000000000000..04d27f9c23de--- /dev/null+++ b/ee/api/agentic_provisioning/accounts.py@@ -0,0 +1,419 @@+"""Account-request handling: onboarding new users, linking existing ones, and+the browser consent detour for partners that can't skip it."""++from __future__ import annotations++import secrets+from typing import Any+from urllib.parse import urlencode++from django.core.cache import cache+from django.db import IntegrityError+from django.utils import timezone++from posthog.api.authentication import password_reset_token_generator+from posthog.event_usage import report_user_signed_up+from posthog.exceptions_capture import capture_exception+from posthog.models.oauth import OAuthApplication+from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.scopes import scopes_within_ceiling+from posthog.tasks.email import send_provisioning_welcome++from ee.api.agentic_provisioning.analytics import capture_provisioning_event+from ee.api.agentic_provisioning.constants import (+ AUTH_CODE_CACHE_PREFIX,+ AUTH_CODE_TTL_SECONDS,+ PENDING_AUTH_CACHE_PREFIX,+ PENDING_AUTH_TTL_SECONDS,+)+from ee.api.agentic_provisioning.exceptions import ProvisioningError+from ee.api.agentic_provisioning.regions import region_to_host+from ee.api.agentic_provisioning.teams import resolve_team_for_existing_user+from ee.api.agentic_provisioning.wizard import create_wizard_run, link_github_grant_to_team+++def partner_label(partner: OAuthApplication | None) -> str:+ if partner is None:+ return "Partner"+ if partner.provisioning_partner_type:+ return partner.provisioning_partner_type.capitalize()+ if partner.name:+ return partner.name+ return "Partner"+++def get_callback_url(app: OAuthApplication | None) -> str | None:+ """Get the callback URL from the partner's redirect_uris.++ Returns None when the partner is gone or has no redirect URI registered;+ callers must fail the flow rather than redirect blindly.+ """+ if app is None:+ return None+ redirect_uris = app.redirect_uris.strip()+ if not redirect_uris:+ return None+ return redirect_uris.split()[0]+++def mint_auth_code(+ *,+ user_id: int,+ org_id: str,+ team_id: int,+ partner_id: str,+ scopes: list[str],+ region: str,+ code_challenge: str,+ code_challenge_method: str,+) -> str:+ """Mint a single-use authorization code in the cache and return it."""+ code = secrets.token_urlsafe(32)+ cache.set(+ f"{AUTH_CODE_CACHE_PREFIX}{code}",+ {+ "issued_at": timezone.now().isoformat(),+ "user_id": user_id,+ "org_id": org_id,+ "team_id": team_id,+ "partner_id": partner_id,+ "scopes": scopes,+ "region": region,+ "code_challenge": code_challenge,+ "code_challenge_method": code_challenge_method,+ },+ timeout=AUTH_CODE_TTL_SECONDS,+ )+ return code+++def mint_pending_auth_code(pending: dict[str, Any], *, user_id: int, org_id: str, team_id: int) -> str:+ """Mint an auth code carrying the parameters stored in a pending consent state."""+ return mint_auth_code(+ user_id=user_id,+ org_id=org_id,+ team_id=team_id,+ partner_id=pending.get("partner_id", ""),+ scopes=pending.get("scopes", []),+ region=pending.get("region", "US"),+ code_challenge=pending.get("code_challenge", ""),+ code_challenge_method=pending.get("code_challenge_method", "S256"),+ )+++def build_authorize_url(confirmation_secret: str, scopes: list[str], region: str = "") -> str:+ # region_to_host falls back to SITE_URL for an unknown/empty region.+ base = region_to_host(region).rstrip("/")+ params = urlencode({"state": confirmation_secret, "scope": " ".join(scopes)})+ return f"{base}/api/agentic/authorize?{params}"+++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:++ - 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+ credential to mint a code for that account.+ - PKCE callers are public: the partner is identified solely by a client_id that anyone+ 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 == "bearer":+ return authenticated_user is not None and authenticated_user.id == user.id+ return False+++def handle_existing_user(+ request_id: str,+ user: User,+ scopes: list[str],+ *,+ region: str,+ team_id: int | None,+ partner: OAuthApplication | None,+ code_challenge: str,+ code_challenge_method: str,+ authenticated_user: User | None,+) -> dict[str, Any]:+ # Account-takeover defense: a partner with skip_existing_user_consent=True may only mint+ # silently for an *existing* account when the caller proved a prior trust relationship with+ # that user (see caller_proved_existing_trust). Without proof we fall through to consent,+ # otherwise any caller could mint a code for an account they don't control. This holds+ # regardless of whether the user has reviewed their credentials: an unreviewed account is+ # still a pre-existing account, and the email may belong to a direct signup that never+ # touched provisioning — silently linking it is the takeover.+ silent_blocked = (+ partner is not None+ and partner.provisioning_skip_existing_user_consent+ and not caller_proved_existing_trust(partner, user, authenticated_user)+ )++ if silent_blocked:+ assert partner is not None # implied by silent_blocked+ capture_provisioning_event(+ "account_request",+ "silent_blocked_existing_user",+ partner=partner,+ )++ if partner and (not partner.provisioning_skip_existing_user_consent or silent_blocked):+ if not code_challenge:+ raise ProvisioningError(+ "invalid_request", "code_challenge is required for public clients", request_id=request_id+ )+ if not scopes_within_ceiling(scopes, partner.ceiling_scopes):+ raise ProvisioningError(+ "invalid_scope",+ "One or more requested scopes exceed the application's allowed scopes",+ request_id=request_id,+ )+ return require_user_consent(+ request_id,+ user,+ scopes,+ region,+ partner,+ code_challenge,+ code_challenge_method,+ )++ team = resolve_team_for_existing_user(user, team_id)+ if team is None:+ capture_provisioning_event("account_request", "error", error_code="team_resolution_failed")+ raise ProvisioningError(+ "team_resolution_failed", "Could not resolve a project for this user", request_id=request_id+ )++ code = mint_auth_code(+ user_id=user.id,+ org_id=str(team.organization_id),+ team_id=team.id,+ partner_id=str(partner.id) if partner else "",+ scopes=scopes,+ region=region,+ code_challenge=code_challenge,+ code_challenge_method=code_challenge_method,+ )++ capture_provisioning_event("account_request", "existing_user", partner=partner, region=region, team_id=team.id)++ return {"id": request_id, "type": "oauth", "oauth": {"code": code}}+++def require_user_consent(+ request_id: str,+ user: User,+ scopes: list[str],+ region: str,+ partner: OAuthApplication,+ code_challenge: str,+ code_challenge_method: str,+) -> dict[str, Any]:+ # Dedup: overwrite any prior pending state for same partner+email so+ # retries don't leave multiple live consent URLs.+ dedup_key = f"pending_auth_state:{partner.id}:{user.email}"+ old_state = cache.get(dedup_key)+ if old_state:+ cache.delete(f"{PENDING_AUTH_CACHE_PREFIX}{old_state}")++ state = secrets.token_urlsafe(32)+ cache.set(dedup_key, state, timeout=PENDING_AUTH_TTL_SECONDS)++ pending_key = f"{PENDING_AUTH_CACHE_PREFIX}{state}"+ cache.set(+ pending_key,+ {+ "email": user.email,+ "scopes": scopes,+ "partner_id": str(partner.id),+ "partner_name": partner.name,+ "region": region,+ "code_challenge": code_challenge,+ "code_challenge_method": code_challenge_method,+ # We only reach consent because the partner could not skip it for this user, so+ # the authorize step must require it too — never silently auto-approve this state.+ "consent_required": True,+ },+ timeout=PENDING_AUTH_TTL_SECONDS,+ )++ auth_url = build_authorize_url(state, scopes, region=region)++ capture_provisioning_event("account_request", "requires_auth", partner=partner, region=region)++ return {+ "id": request_id,+ "type": "requires_auth",+ "requires_auth": {"url": auth_url},+ }+++def handle_new_user(+ request_id: str,+ data: dict,+ email: str,+ scopes: list[str],+ *,+ region: str,+ partner: OAuthApplication | None,+ code_challenge: str,+ code_challenge_method: str,+ authenticated_user: User | None,+) -> dict[str, Any]:+ name = data.get("name", "")+ first_name = name.split(" ")[0] if name else ""++ configuration = data.get("configuration")+ if not isinstance(configuration, dict):+ configuration = {}++ label = partner_label(partner)+ org_name = configuration.get("organization_name") or f"{label} ({email})"++ try:+ organization, team, user = User.objects.bootstrap(+ organization_name=org_name,+ email=email,+ password=None,+ first_name=first_name,+ is_email_verified=False,+ )+ except IntegrityError:+ existing = User.objects.filter(email=email).first()+ if existing:+ capture_provisioning_event("account_request", "race_condition_existing_user", region=region)+ return handle_existing_user(+ request_id,+ existing,+ scopes,+ region=region,+ team_id=None,+ partner=partner,+ code_challenge=code_challenge,+ code_challenge_method=code_challenge_method,+ authenticated_user=authenticated_user,+ )+ capture_provisioning_event("account_request", "creation_failed", region=region)+ raise ProvisioningError(+ "account_creation_failed", "Failed to create account", request_id=request_id, status=500+ )++ capture_provisioning_event(+ "account_request",+ "new_user",+ partner=partner,+ region=region,+ team_id=team.id,+ )++ # Emit the standard signup event so provisioned accounts flow into the shared+ # signup / activation / billing analyses, segmentable by client. Vercel does the+ # same (ee/vercel/integration.py); the agentic path previously skipped it entirely.+ report_user_signed_up(+ user,+ is_instance_first_user=False,+ is_organization_first_user=True,+ backend_processor="AgenticProvisioning",+ social_provider=partner.name if partner else "",+ user_analytics_metadata=user.get_analytics_metadata(),+ org_analytics_metadata=organization.get_analytics_metadata(),+ )++ # Optional drop-flow wizard block: link the GitHub grant to the bootstrap team and+ # enqueue a cloud wizard run in the same call. A wizard failure never fails the+ # request — the account exists, so the partner gets the account plus a structured+ # wizard.error and retries via the granular resource actions. Partners that don't+ # send a wizard block are unaffected (no wizard key, unchanged email behavior).+ # Grants are region-local, so this request must hit the region that minted the grant.+ wizard_config = configuration.get("wizard")+ wizard_payload: dict[str, Any] | None = None+ wizard_repository: str | None = None+ if isinstance(wizard_config, dict) and partner is not None:+ wizard_payload = process_wizard_block(partner=partner, user=user, team=team, wizard_config=wizard_config)+ if "error" not in wizard_payload:+ wizard_repository = str(wizard_config.get("repository"))++ # Queued after the wizard block so the "we're setting up your repo" email only+ # sends once the run actually exists; the email still goes out (without the+ # repository paragraph) when the wizard block failed, since the account is real.+ try:+ reset_token = password_reset_token_generator.make_token(user)+ if wizard_repository:+ send_provisioning_welcome.delay(user.id, reset_token, label, repository=wizard_repository)+ else:+ send_provisioning_welcome.delay(user.id, reset_token, label)+ except Exception:+ capture_exception(additional_properties={"user_id": user.id, "step": "provisioning_welcome_email"})++ code = mint_auth_code(+ user_id=user.id,+ org_id=str(organization.id),+ team_id=team.id,+ partner_id=str(partner.id) if partner else "",+ scopes=scopes,+ region=region,+ code_challenge=code_challenge,+ code_challenge_method=code_challenge_method,+ )++ response_body: dict[str, Any] = {"id": request_id, "type": "oauth", "oauth": {"code": code}}+ if wizard_payload is not None:+ response_body["wizard"] = wizard_payload+ return response_body+++def process_wizard_block(*, partner: OAuthApplication, user: User, team: Team, wizard_config: dict) -> dict[str, Any]:+ """Run the bundled drop flow for a freshly bootstrapped account: link the GitHub+ grant to the team, then enqueue the cloud wizard run.++ Never raises — returns either the run payload ({task_id, run_id, status}) or+ {"error": {code, message}} for the partner to branch on and retry granularly.+ """+ try:+ grant_id = wizard_config.get("grant_id")+ installation_id = wizard_config.get("installation_id")+ repository = wizard_config.get("repository")+ if not grant_id or not installation_id or not repository:+ return {+ "error": {+ "code": "invalid_request",+ "message": "wizard requires grant_id, installation_id and repository",+ }+ }++ link_github_grant_to_team(+ partner=partner,+ user=user,+ team=team,+ grant_id=str(grant_id),+ installation_id=str(installation_id),+ )++ run_payload = create_wizard_run(+ partner=partner,+ user_id=user.id,+ team=team,+ repository=str(repository),+ branch=str(wizard_config.get("branch") or "") or None,+ )+ return dict(run_payload)+ except ProvisioningError as exc:+ return {"error": {"code": exc.code, "message": exc.message}}+ except Exception:+ capture_exception(additional_properties={"team_id": team.id, "step": "account_requests_wizard_block"})+ return {"error": {"code": "run_creation_failed", "message": "Unexpected error starting the wizard run"}}+++def resolve_pending_partner(partner_id: str) -> OAuthApplication | None:+ """Look up the partner referenced by a pending consent state; None when gone."""+ if not partner_id:+ return None+ try:+ return OAuthApplication.objects.get(id=partner_id)+ except OAuthApplication.DoesNotExist:+ return Nonediff --git a/ee/api/agentic_provisioning/analytics.py b/ee/api/agentic_provisioning/analytics.pynew file mode 100644index 000000000000..fea3095b276e--- /dev/null+++ b/ee/api/agentic_provisioning/analytics.py@@ -0,0 +1,61 @@+"""Product analytics events for the agentic provisioning API."""++from __future__ import annotations++import uuid++import posthoganalytics++from posthog.models.oauth import OAuthApplication+++def _anonymous_distinct_id() -> str:+ return f"agentic_provisioning_{uuid.uuid4().hex[:16]}"+++def capture_provisioning_event(+ event_type: str,+ outcome: str,+ *,+ partner: OAuthApplication | None = None,+ **extra: object,+) -> None:+ team_id = extra.get("team_id")+ distinct_id = f"agentic_provisioning_team_{team_id}" if team_id else _anonymous_distinct_id()+ properties: dict[str, object] = {"outcome": outcome, **extra}+ if partner is not None:+ properties.setdefault("partner_id", str(partner.id))+ properties.setdefault("client_name", partner.name)+ if partner.provisioning_partner_type:+ properties.setdefault("partner_type", partner.provisioning_partner_type)+ posthoganalytics.capture(+ f"agentic_provisioning {event_type}",+ distinct_id=distinct_id,+ properties=properties,+ )+++def capture_deep_link_event(outcome: str, **extra: object) -> None:+ capture_provisioning_event("deep link login", outcome, partner=None, **extra)+++def capture_auth_event(app: OAuthApplication, outcome: str, **extra: object) -> None:+ posthoganalytics.capture(+ "agentic_provisioning auth",+ distinct_id=_anonymous_distinct_id(),+ properties={+ "outcome": outcome,+ "partner_type": app.provisioning_partner_type,+ "auth_method": app.provisioning_auth_method,+ "app_id": str(app.id),+ **extra,+ },+ )+++def capture_region_proxy_event(outcome: str, **props: object) -> None:+ posthoganalytics.capture(+ "agentic_provisioning region_proxy",+ distinct_id=_anonymous_distinct_id(),+ properties={"outcome": outcome, **props},+ )diff --git a/ee/api/agentic_provisioning/authentication.py b/ee/api/agentic_provisioning/authentication.pyindex f730098aedae..cc860b4856de 100644--- a/ee/api/agentic_provisioning/authentication.py+++ b/ee/api/agentic_provisioning/authentication.py@@ -1,13 +1,12 @@from __future__ import annotations-import uuidimport hashlib+from django.contrib.auth.models import AnonymousUserfrom django.core.cache import cachefrom django.utils import timezoneimport structlog-import posthoganalyticsfrom rest_framework.authentication import BaseAuthenticationfrom rest_framework.exceptions import AuthenticationFailedfrom rest_framework.request import Request@@ -22,13 +21,47 @@ from posthog.api.oauth.cimd import (register_cimd_provisioning_application_task,)from posthog.exceptions_capture import capture_exception-from posthog.models.oauth import OAuthApplication, find_oauth_access_token+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, find_oauth_access_token+from posthog.models.user import User++from ee.api.agentic_provisioning.analytics import capture_auth_event+from ee.api.agentic_provisioning.exceptions import ProvisioningErrorlogger = structlog.get_logger(__name__)BEARER_PREFIX = "Bearer "+class BearerTokenError(Exception):+ """The bearer header is missing, unknown, or expired; the message is the+ wire-safe reason each authenticator maps into its own failure type."""+++def resolve_bearer_access_token(request: Request) -> OAuthAccessToken:+ """Parse the Authorization header and return the live access token it names.++ Shared by every bearer path in this module so token resolution (header+ parsing, lookup, expiry) can't drift between authenticators; policy checks+ (partner flags, app binding) stay with each caller.+ """+ auth_header = request.headers.get("authorization", "")+ if not auth_header.startswith(BEARER_PREFIX):+ raise BearerTokenError("Missing bearer token")++ token_value = auth_header[len(BEARER_PREFIX) :].strip()+ if not token_value:+ raise BearerTokenError("Missing bearer token")++ access_token = find_oauth_access_token(token_value)+ if access_token is None:+ raise BearerTokenError("Invalid access token")++ if access_token.expires and access_token.expires < timezone.now():+ raise BearerTokenError("Access token expired")++ return access_token++class ProvisioningAuthentication(BaseAuthentication):"""Authenticates provisioning requests from any registered partner.@@ -52,13 +85,13 @@ class ProvisioningAuthentication(BaseAuthentication):try:if app.provisioning_auth_method == "bearer":user = self._verify_bearer(request, app)- _capture_auth_event(app, "success", endpoint=request.path)+ capture_auth_event(app, "success", endpoint=request.path)return (user, app)elif app.provisioning_auth_method == "pkce":- _capture_auth_event(app, "success", endpoint=request.path)+ capture_auth_event(app, "success", endpoint=request.path)return self._verify_pkce(request, app)except AuthenticationFailed:- _capture_auth_event(app, "verification_failed", endpoint=request.path)+ capture_auth_event(app, "verification_failed", endpoint=request.path)raisereturn None@@ -67,9 +100,8 @@ class ProvisioningAuthentication(BaseAuthentication):app = None# 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)+ if request.headers.get("authorization", "").startswith(BEARER_PREFIX):+ app = self._identify_bearer_partner(request)# 2. Check for client_id in request body (PKCE public clients)if app is None:@@ -82,16 +114,10 @@ class ProvisioningAuthentication(BaseAuthentication):return app- def _identify_bearer_partner(self, auth_header: str) -> OAuthApplication | None:- token_value = auth_header[len(BEARER_PREFIX) :].strip()- if not token_value:- return None-- access_token = find_oauth_access_token(token_value)- if access_token is None:- return None-- if access_token.expires and access_token.expires < timezone.now():+ def _identify_bearer_partner(self, request: Request) -> OAuthApplication | None:+ try:+ access_token = resolve_bearer_access_token(request)+ except BearerTokenError:return Noneapp = access_token.application@@ -158,20 +184,10 @@ class ProvisioningAuthentication(BaseAuthentication):return Nonedef _verify_bearer(self, request: Request, app: OAuthApplication):- auth_header = request.META.get("HTTP_AUTHORIZATION", "")- if not auth_header.startswith(BEARER_PREFIX):- raise AuthenticationFailed("Missing bearer token")-- token_value = auth_header[len(BEARER_PREFIX) :].strip()- if not token_value:- raise AuthenticationFailed("Missing bearer token")-- access_token = find_oauth_access_token(token_value)- if access_token is None:- raise AuthenticationFailed("Invalid access token")-- if access_token.expires and access_token.expires < timezone.now():- raise AuthenticationFailed("Access token expired")+ try:+ access_token = resolve_bearer_access_token(request)+ except BearerTokenError as exc:+ raise AuthenticationFailed(str(exc))if access_token.application_id != app.id:raise AuthenticationFailed("Token not issued for this partner")@@ -182,15 +198,73 @@ class ProvisioningAuthentication(BaseAuthentication):return (None, app)-def _capture_auth_event(app: OAuthApplication, outcome: str, **extra: object) -> None:- posthoganalytics.capture(- "agentic_provisioning auth",- distinct_id=f"agentic_provisioning_{uuid.uuid4().hex[:16]}",- properties={- "outcome": outcome,- "partner_type": app.provisioning_partner_type,- "auth_method": app.provisioning_auth_method,- "app_id": str(app.id),- **extra,- },- )+class ProvisioningBearerAuthentication(BaseAuthentication):+ """Authenticate a provisioning partner via an OAuth bearer token, for the+ resource and deep-link endpoints.++ Returns ``(user, access_token)`` so views read the token off ``request.auth``.+ Raises :class:`ProvisioningError` (rendered in the view's envelope) on failure.+ """++ def authenticate(self, request: Request) -> tuple[User | None, OAuthAccessToken]:+ try:+ access_token = resolve_bearer_access_token(request)+ except BearerTokenError as exc:+ raise ProvisioningError("unauthorized", str(exc), status=401)++ # The token must belong to an active provisioning partner's app.+ app = access_token.application+ if app is None or not app.is_provisioning_partner:+ raise ProvisioningError("unauthorized", "Authentication failed", status=401)++ # 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"):+ raise ProvisioningError("unauthorized", "Authentication failed", status=401)+ if not app.provisioning_active:+ raise ProvisioningError("unauthorized", "Partner is deactivated", status=401)+ if not app.provisioning_can_provision_resources:+ raise ProvisioningError("forbidden", "Resource provisioning not enabled for this partner", status=403)++ return access_token.user, access_token++ def authenticate_header(self, request: Request) -> str:+ return "Bearer"+++def authenticate_confidential_partner(request: Request) -> OAuthApplication:+ """Identify a provisioning partner, requiring proof-bearing auth.++ 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.++ Raises :class:`ProvisioningError` when no qualifying partner is identified.+ """+ auth = ProvisioningAuthentication()+ try:+ result = auth.authenticate(request)+ except AuthenticationFailed:+ result = None+ partner = result[1] if result else None+ if partner is None:+ raise ProvisioningError("unauthorized", "Authentication required", status=401)+ if partner.provisioning_auth_method != "bearer":+ raise ProvisioningError("forbidden", "This endpoint requires a confidential partner", status=403)+ return partner+++class ConfidentialPartnerAuthentication(BaseAuthentication):+ """DRF form of :func:`authenticate_confidential_partner`, so confidential+ endpoints declare it in ``authentication_classes`` and can't ship without+ it. The partner rides ``request.auth``; these endpoints act for the partner,+ not an end user, so the user stays anonymous."""++ def authenticate(self, request: Request) -> tuple[AnonymousUser, OAuthApplication]:+ return AnonymousUser(), authenticate_confidential_partner(request)++ def authenticate_header(self, request: Request) -> str:+ return "Bearer"diff --git a/ee/api/agentic_provisioning/constants.py b/ee/api/agentic_provisioning/constants.pynew file mode 100644index 000000000000..2cf008ddfc6b--- /dev/null+++ b/ee/api/agentic_provisioning/constants.py@@ -0,0 +1,80 @@+"""Shared constants for the agentic provisioning API."""++from __future__ import annotations++import re++AUTH_CODE_CACHE_PREFIX = "provisioning_auth_code:"+PENDING_AUTH_CACHE_PREFIX = "provisioning_pending_auth:"+GITHUB_GRANT_CACHE_PREFIX = "provisioning_github_grant:"+DEEP_LINK_CACHE_PREFIX = "provisioning_deep_link:"++AUTH_CODE_TTL_SECONDS = 300+PENDING_AUTH_TTL_SECONDS = 600+DEEP_LINK_TTL_SECONDS = 600+DEEP_LINK_MAX_PATH_LENGTH = 2000+# Control chars, whitespace, and backslashes never appear in a legitimate in-app path; they are the+# building blocks of header-injection and backslash-host open-redirect tricks, so reject them outright.+DEEP_LINK_DISALLOWED_PATH_CHARS = re.compile(r"[\x00-\x20\x7f-\x9f\\]")++CIMD_DOMAIN_RATE_LIMIT_PREFIX = "cimd_registration_domain_rate:"+CIMD_DOMAIN_RATE_LIMIT_MAX = 5+CIMD_DOMAIN_RATE_LIMIT_WINDOW_SECONDS = 3600++PARTNER_RATE_LIMIT_PREFIX = "provisioning_partner_rate:"+PARTNER_RATE_LIMIT_WINDOW_SECONDS = 3600+PARTNER_RATE_LIMIT_DEFAULTS: dict[str, int] = {+ "account_requests": 10,+ "token_exchanges": 20,+ "resource_creates": 20,+ "github_grants": 10,+ "wizard_runs": 20,+}+PARTNER_RATE_LIMIT_EVENT_NAMES: dict[str, str] = {+ "account_requests": "account_request",+ "token_exchanges": "token_exchange",+ "resource_creates": "resource_created",+ "github_grants": "github_grant",+ "wizard_runs": "wizard_run",+}++# Per-user wizard-run budget matching the session endpoint's limits (2/hour, 5/day), which+# can't run here — the partner path has no session user on the request. Unlike the session+# endpoint's throttles, which count only non-failed/non-cancelled runs from the DB, this is a+# plain request counter: failed runs still consume partner quota. Aligning it with the+# outcome-aware counting is a pending follow-up.+WIZARD_RUN_USER_RATE_LIMIT_PREFIX = "provisioning_wizard_run_user:"+WIZARD_RUN_USER_RATE_LIMITS: list[tuple[str, int, int]] = [+ ("burst", 2, 3600),+ ("day", 5, 86400),+]++# Repo-picker polling budget per grant (the website polls while the visitor installs the+# GitHub App in another tab). Keyed per grant, so one stuck visitor can't starve others.+GITHUB_GRANT_POLL_RATE_LIMIT_PREFIX = "provisioning_github_grant_poll:"+GITHUB_GRANT_POLL_RATE_LIMIT_MAX = 120+GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS = 3600++# Per-IP ceiling on cross-region forwarding. The region proxy decides to forward before+# DRF authenticates or throttles anything, and each forwarded request occupies a worker+# until the other region answers, so this is the only limit an unauthenticated caller+# meets on that path. Two orders of magnitude above the peak per-IP forwarding rate real+# partner traffic reaches, so it leaves room for bulk provisioning while still bounding+# how many workers one caller can tie up.+REGION_PROXY_RATE_LIMIT = "300/minute"++# Matches the state parameter allowed by the auth endpoint's RFC 7636 spec.+SAFE_STATE_RE = re.compile(r"^[A-Za-z0-9_\-]{1,256}$")+CODE_CHALLENGE_RE = re.compile(r"[A-Za-z0-9_\-]+")++# Mirrors PersonalAPIKey.label's CharField(max_length=40) - keep in sync if that ever changes.+PROVISIONED_PAT_LABEL_MAX_LENGTH = 40++# Cap partner-supplied prefix below the full label length so " - {team_name}" still+# survives the truncation. A 37-char prefix would otherwise consume the whole label+# and the team name would disappear from the truncated result.+PROVISIONED_PAT_LABEL_PREFIX_MAX_LENGTH = 25++# Default access token expiry.+ACCESS_TOKEN_EXPIRY_SECONDS = 365 * 24 * 3600+PARTNER_TOKEN_EXPIRY_SECONDS = 3600diff --git a/ee/api/agentic_provisioning/credentials.py b/ee/api/agentic_provisioning/credentials.pynew file mode 100644index 000000000000..e3a0d4023567--- /dev/null+++ b/ee/api/agentic_provisioning/credentials.py@@ -0,0 +1,120 @@+"""Provisioned credentials: partner-labeled personal API keys."""++from __future__ import annotations++import unicodedata++from posthog.exceptions_capture import capture_exception+from posthog.models.oauth import OAuthApplication+from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value+from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.models.utils import generate_random_token_personal, mask_key_value+from posthog.scopes import narrow_scopes_to_ceiling++from ee.api.agentic_provisioning.analytics import capture_provisioning_event+from ee.api.agentic_provisioning.constants import (+ PROVISIONED_PAT_LABEL_MAX_LENGTH,+ PROVISIONED_PAT_LABEL_PREFIX_MAX_LENGTH,+)+from ee.api.agentic_provisioning.exceptions import ProvisioningError+++def validate_label_prefix(raw: object) -> str | None:+ """Validate the optional ``label_prefix`` request field.++ Returns ``None`` when the field is absent or empty (caller creates an+ unprefixed label). Raises an ``invalid_label_prefix``+ :class:`ProvisioningError` when the field is present but malformed (wrong+ type, too long, or contains control or format characters that would render+ badly in the user's PAT list).+ """+ if raw is None:+ return None+ if not isinstance(raw, str):+ raise ProvisioningError("invalid_label_prefix", "label_prefix must be a string")++ stripped = raw.strip()+ if not stripped:+ return None++ if len(stripped) > PROVISIONED_PAT_LABEL_PREFIX_MAX_LENGTH:+ raise ProvisioningError(+ "invalid_label_prefix",+ f"label_prefix must be {PROVISIONED_PAT_LABEL_PREFIX_MAX_LENGTH} characters or fewer",+ )++ # Reject Unicode control (Cc), format (Cf), and line/paragraph separators (Zl/Zp).+ # Cf is the important one - it includes bidi overrides (U+202A-U+202E) and+ # isolates (U+2066-U+2069), which a partner could use to re-order surrounding+ # text in the user's settings page (Trojan Source class). Cc covers C0 + DEL.+ if any(unicodedata.category(c) in {"Cc", "Cf", "Zl", "Zp"} for c in stripped):+ raise ProvisioningError("invalid_label_prefix", "label_prefix must not contain control or format characters")++ return stripped+++def maybe_create_provisioned_pat(+ user: User, team: Team, app: OAuthApplication | None, granted_scope: str | None, label_prefix: str | None = None+) -> str | None:+ """Create a Personal API Key for a provisioned user and return the raw key value.++ Gated by ``app.provisioning_issues_personal_api_key``: off by default, so most+ apps never receive a provisioned PAT (the OAuth token is the credential).+ Returns ``None`` when the gate is off, and the caller omits ``personal_api_key``+ from the response entirely.++ When enabled (the grandfathered legacy Stripe app), the key carries the granted+ OAuth token's scopes (``granted_scope``) narrowed to the app's current ceiling,+ so a provisioned PAT can exceed neither what the user granted nor what the app+ may hold. Minting from the ceiling alone would hand out optional scopes the+ grant never included. A flag-on app with an unseeded ceiling mints nothing: an+ empty-scope PAT fails every scope check, and widening to a wildcard would+ bypass the ceiling.++ scoped_teams is set to [team.id] so the PAT only grants access to the team+ being provisioned, matching the scoping of the OAuth token issued in the+ same flow. Without this, a provisioning call from an existing user would+ return a PAT that reaches across every team the user already belongs to.++ ``label_prefix`` should be pre-validated by ``validate_label_prefix``; pass+ ``None`` (or any falsy value) to label the key with just the team name.+ """+ if not app or not app.provisioning_issues_personal_api_key:+ return None+ if not app.ceiling_scopes:+ capture_provisioning_event("pat_mint", "skipped_unseeded_ceiling", partner=app, team_id=team.id)+ return None++ granted = (granted_scope or "").split()+ if "*" in granted:+ # A legacy wildcard token covers everything, so the ceiling is the cap.+ pat_scopes = app.ceiling_scopes+ else:+ pat_scopes = narrow_scopes_to_ceiling([s for s in granted if ":" in s], app.ceiling_scopes) or []++ if not pat_scopes:+ capture_provisioning_event("pat_mint", "skipped_no_granted_scopes", partner=app, team_id=team.id)+ return None++ try:+ api_key_value = generate_random_token_personal()+ label_base = f"{label_prefix} - {team.name}" if label_prefix else team.name+ # PersonalAPIKey.label is stored as a CharField(max_length=40); cap the+ # final string to match so we never violate the column constraint.+ label = label_base[:PROVISIONED_PAT_LABEL_MAX_LENGTH]++ PersonalAPIKey.objects.create(+ user=user,+ label=label,+ secure_value=hash_key_value(api_key_value),+ mask_value=mask_key_value(api_key_value),+ scopes=pat_scopes,+ scoped_teams=[team.id],+ scoped_organizations=[str(team.organization_id)],+ )++ return api_key_value+ except Exception:+ capture_exception(additional_properties={"user_id": user.id, "team_id": team.id})+ return Nonediff --git a/ee/api/agentic_provisioning/errors.py b/ee/api/agentic_provisioning/errors.pydeleted file mode 100644index 71ab92af9394..000000000000--- a/ee/api/agentic_provisioning/errors.py+++ /dev/null@@ -1,38 +0,0 @@-"""Error-envelope helpers for the agentic provisioning API.--Two helpers coexist because the provisioning views serve two distinct wire-contracts (plus OAuth endpoints, which follow RFC 6749's flat-{"error", "error_description"} shape and can't use either helper):--- `error_response` -> {"status": "error", "id": ..., "error": {...}} for the- resource endpoints, whose success envelope carries "status" (provisioning state)- and "id" (the partner's resource ID), so errors mirror that.-- `typed_error_response` -> {"type": "error", "error": {...}} for account- requests and GitHub grants, where "type" is the discriminator partners switch- on ("oauth" | "registering" | "error").--Collapsing them would break partner clients that branch on "status" vs "type".-"""--from __future__ import annotations--from typing import Any--import structlog-from rest_framework.response import Response--logger = structlog.get_logger(__name__)---def error_response(code: str, message: str, resource_id: str = "", status: int = 400) -> Response:- logger.warning("provisioning.error_response", code=code, message=message, resource_id=resource_id, status=status)- return Response({"status": "error", "id": resource_id, "error": {"code": code, "message": message}}, status=status)---def typed_error_response(code: str, message: str, request_id: str | None = None, status: int = 400) -> Response:- # No blanket warning log here: call sites already emit their own telemetry- # (_capture_provisioning_event / logger.warning) at the right granularity.- body: dict[str, Any] = {"type": "error", "error": {"code": code, "message": message}}- if request_id is not None:- body = {"id": request_id, **body}- return Response(body, status=status)diff --git a/ee/api/agentic_provisioning/exceptions.py b/ee/api/agentic_provisioning/exceptions.pynew file mode 100644index 000000000000..6da360fb80c3--- /dev/null+++ b/ee/api/agentic_provisioning/exceptions.py@@ -0,0 +1,92 @@+"""Error envelopes for the agentic provisioning API.++The provisioning views serve three distinct wire contracts, so DRF's default+error rendering can never leak out of these endpoints:++- ``typed``: ``{"type": "error", "error": {...}}`` — account requests and+ GitHub grants, where "type" is the discriminator partners switch on+ ("oauth" | "requires_auth" | "registering" | "error").+- ``status``: ``{"status": "error", "id": ..., "error": {...}}`` — the+ resource endpoints, whose success envelope carries "status" (provisioning+ state) and "id" (the partner's resource ID), so errors mirror that.+- ``oauth``: RFC 6749 ``{"error", "error_description"}`` — the token endpoint.++(The region proxy runs before DRF rendering exists, so it serializes+``provisioning_error_body`` itself. Its ``proxy_failed`` 502 keeps a flat+``{"error": {"code", "message"}}`` shape of its own.)++Collapsing them would break partner clients that branch on "status" vs "type".+Views raise :class:`ProvisioningError`; the base view's ``handle_exception``+renders it with the view's envelope (or the error's own override — e.g. a+partner rate limit raised inside the OAuth token exchange keeps the typed+shape).+"""++from __future__ import annotations++from typing import Any, Literal++import structlog+from rest_framework import status as http_status+from rest_framework.response import Response++logger = structlog.get_logger(__name__)++Envelope = Literal["typed", "status", "oauth"]+++class ProvisioningError(Exception):+ """An error with a wire-contract code, message, and envelope."""++ def __init__(+ self,+ code: str,+ message: str,+ *,+ status: int = http_status.HTTP_400_BAD_REQUEST,+ request_id: str | None = None,+ resource_id: str = "",+ envelope: Envelope | None = None,+ retry_after: int | None = None,+ ) -> None:+ super().__init__(message)+ self.code = code+ self.message = message+ self.status = status+ self.request_id = request_id+ self.resource_id = resource_id+ self.envelope = envelope+ self.retry_after = retry_after+++def provisioning_error_body(error: ProvisioningError, default_envelope: Envelope) -> dict[str, Any]:+ """The wire body for an error, without a DRF response around it, so the region+ proxy can render errors before DRF's renderers exist."""+ envelope = error.envelope or default_envelope+ body: dict[str, Any]+ if envelope == "typed":+ body = {"type": "error", "error": {"code": error.code, "message": error.message}}+ # "id" appears only when a request_id was threaded through; some call+ # sites carry "" (rendered as "id": "") and others no id at all.+ if error.request_id is not None:+ body = {"id": error.request_id, **body}+ elif envelope == "status":+ logger.warning(+ "provisioning.error_response",+ code=error.code,+ message=error.message,+ resource_id=error.resource_id,+ status=error.status,+ )+ body = {"status": "error", "id": error.resource_id, "error": {"code": error.code, "message": error.message}}+ else:+ body = {"error": error.code, "error_description": error.message}++ return body+++def render_provisioning_error(error: ProvisioningError, default_envelope: Envelope) -> Response:+ response = Response(provisioning_error_body(error, default_envelope), status=error.status)+ if error.retry_after is not None:+ response["Retry-After"] = str(error.retry_after)+ return responsediff --git a/ee/api/agentic_provisioning/github_grants.py b/ee/api/agentic_provisioning/github_grants.pyindex 2badaee88c1c..463de5aea7fd 100644--- a/ee/api/agentic_provisioning/github_grants.py+++ b/ee/api/agentic_provisioning/github_grants.py@@ -29,7 +29,7 @@ from posthog.helpers.encrypted_fields import EncryptedTextFieldfrom posthog.models.integration import GitHubUserAuthorizationfrom posthog.models.oauth import OAuthApplication-from . import GITHUB_GRANT_CACHE_PREFIX+from ee.api.agentic_provisioning.constants import GITHUB_GRANT_CACHE_PREFIXlogger = structlog.get_logger(__name__)diff --git a/ee/api/agentic_provisioning/region_proxy.py b/ee/api/agentic_provisioning/region_proxy.pyindex 55cdad851b45..ca2fe0b63492 100644--- a/ee/api/agentic_provisioning/region_proxy.py+++ b/ee/api/agentic_provisioning/region_proxy.py@@ -1,24 +1,44 @@+"""US/EU cross-region forwarding for the agentic provisioning API.++Partners call a single base URL, but the account or token they are acting on+may live in the other region. Each view declares a strategy for deciding+whether the request belongs to the other region:++- ``body_region``: proxy when ``configuration.region`` differs from the+ current region (account_requests).+- ``token_lookup``: proxy when the auth code / refresh token isn't found+ locally (oauth/token).+- ``bearer_lookup``: proxy when the bearer token isn't found locally (all+ resource endpoints).++Forwarding preserves the request path, so both regions must expose the same+routes (they deploy the same code). The decision happens before DRF+authenticates or throttles anything, so the forward carries its own per-IP cap+(:class:`~ee.api.agentic_provisioning.throttling.RegionProxyThrottle`).+"""+from __future__ import annotations-import uuid+import jsonimport hashlib-import functools+from typing import Any, ClassVarfrom urllib.parse import urlparse, urlunparsefrom django.conf import settingsfrom django.core.cache import cache+from django.http import HttpRequest, HttpResponseimport requestsimport structlog-import posthoganalytics-from rest_framework.request import Request-from rest_framework.response import Responsefrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.oauth import find_oauth_access_token, find_oauth_refresh_tokenfrom posthog.utils import get_instance_region-from . import AUTH_CODE_CACHE_PREFIX+from ee.api.agentic_provisioning.analytics import capture_region_proxy_event+from ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIX+from ee.api.agentic_provisioning.exceptions import Envelope, ProvisioningError, provisioning_error_body+from ee.api.agentic_provisioning.throttling import RegionProxyThrottlelogger = structlog.get_logger(__name__)@@ -35,15 +55,6 @@ BEARER_EXISTS_CACHE_PREFIX = "agentic_bearer_exists:"BEARER_EXISTS_POSITIVE_TTL = 300BEARER_EXISTS_NEGATIVE_TTL = 30--def _region_domains() -> tuple[str, str]:- """Read at call time, not import time, so @override_settings works in tests."""- return (- getattr(settings, "REGION_US_DOMAIN", DEFAULT_US_DOMAIN),- getattr(settings, "REGION_EU_DOMAIN", DEFAULT_EU_DOMAIN),- )--PROXY_HEADER_ALLOWLIST = frozenset({"content-type",@@ -53,6 +64,18 @@ PROXY_HEADER_ALLOWLIST = frozenset(})+# Match DRF's compact JSON rendering so proxied bodies read the same as+# locally rendered ones.+_JSON_SEPARATORS = (",", ":")+++def _region_domains() -> tuple[str, str]:+ """Read at call time, not import time, so @override_settings works in tests."""+ return (+ getattr(settings, "REGION_US_DOMAIN", DEFAULT_US_DOMAIN),+ getattr(settings, "REGION_EU_DOMAIN", DEFAULT_EU_DOMAIN),+ )+def _current_region() -> str | None:region = get_instance_region()@@ -68,7 +91,22 @@ def _other_region_domain(current: str) -> str:return us_domain-def _proxy_to_region(request: Request, target_domain: str) -> Response:+def _request_payload(request: HttpRequest) -> dict[str, Any]:+ """Parse the request body for the strategy checks without consuming the stream.++ Accessing ``request.body`` caches it, so DRF can still parse it downstream.+ """+ try:+ content_type = request.content_type or ""+ if "json" in content_type:+ parsed = json.loads(request.body.decode("utf-8")) if request.body else {}+ return parsed if isinstance(parsed, dict) else {}+ return dict(request.POST.items())+ except Exception:+ return {}+++def _proxy_to_region(request: HttpRequest, target_domain: str) -> HttpResponse:parsed_url = urlparse(request.build_absolute_uri())target_url = urlunparse(parsed_url._replace(netloc=target_domain))@@ -92,40 +130,62 @@ def _proxy_to_region(request: Request, target_domain: str) -> Response:)if response.status_code == 204:- return Response(status=204)+ return HttpResponse(status=204)try:data = response.json() if response.content else {}except ValueError:data = {"error": "Invalid response from alternate region"}- return Response(data=data, status=response.status_code)+ return HttpResponse(+ json.dumps(data, separators=_JSON_SEPARATORS),+ status=response.status_code,+ content_type="application/json",+ )except requests.exceptions.RequestException as e:capture_exception(e, {"target_url": target_url, "step": "provisioning.proxy.failed"})raise-def _should_proxy_body_region(request: Request, current_region: str) -> bool:- configuration = request.data.get("configuration")+def _error_response(error: ProvisioningError, envelope: Envelope) -> HttpResponse:+ """Serialize an error without DRF.++ ``dispatch`` runs outside ``APIView``'s exception handling and renderer+ negotiation, so a raised :class:`ProvisioningError` would surface as a 500+ and an unrendered DRF ``Response`` would blow up in middleware.+ """+ response = HttpResponse(+ json.dumps(provisioning_error_body(error, envelope), separators=_JSON_SEPARATORS),+ status=error.status,+ content_type="application/json",+ )+ if error.retry_after is not None:+ response["Retry-After"] = str(error.retry_after)+ return response+++def _should_proxy_body_region(request: HttpRequest, current_region: str) -> bool:+ configuration = _request_payload(request).get("configuration")if not isinstance(configuration, dict):configuration = {}requested_region = (configuration.get("region") or "US").upper()return requested_region != current_region-def _should_proxy_token_lookup(request: Request, current_region: str) -> bool:- grant_type = request.data.get("grant_type", "")+def _should_proxy_token_lookup(request: HttpRequest, current_region: str) -> bool:+ payload = _request_payload(request)+ grant_type = payload.get("grant_type", "")if grant_type == "authorization_code":- code = request.data.get("code", "")+ code = payload.get("code", "")if not code:return Falsecache_key = f"{AUTH_CODE_CACHE_PREFIX}{code}"return cache.get(cache_key) is Noneif grant_type == "refresh_token":- refresh_token_value = request.data.get("refresh_token", "")+ refresh_token_value = payload.get("refresh_token", "")if not refresh_token_value:return Falsereturn find_oauth_refresh_token(refresh_token_value) is None@@ -150,7 +210,7 @@ def _bearer_exists_locally(token_value: str) -> bool:return exists-def _should_proxy_bearer_lookup(request: Request, current_region: str) -> bool:+def _should_proxy_bearer_lookup(request: HttpRequest, current_region: str) -> bool:auth_header = request.META.get("HTTP_AUTHORIZATION", "")if not auth_header.startswith(BEARER_PREFIX):return False@@ -169,66 +229,85 @@ _STRATEGY_CHECKS = {}-REGION_PROXY_REGISTRY: dict[str, str] = {}---def region_proxy(strategy: str):- check_fn = _STRATEGY_CHECKS[strategy]-- def decorator(view_func):- REGION_PROXY_REGISTRY[view_func.__qualname__] = strategy-- @functools.wraps(view_func)- def wrapper(request: Request, *args, **kwargs) -> Response:- # 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.- _ = request.body-- current = _current_region()- if current is None or current in ("DEV", "LOCAL"):- return view_func(request, *args, **kwargs)-- if request.META.get(f"HTTP_{PROXY_LOOP_HEADER.upper().replace('-', '_')}"):- return view_func(request, *args, **kwargs)-- if check_fn(request, current):- target = _other_region_domain(current)- logger.info(- "provisioning.proxy.routing",- strategy=strategy,- current_region=current,- target_domain=target,+class RegionProxyMixin:+ """Forward the request to the other region when its resources live there.++ Set ``region_proxy_strategy`` on the view. Runs before authentication (a+ bearer that only exists in the other region must proxy, not 401 locally),+ which also means DRF's own throttles haven't run, hence the per-IP+ :class:`RegionProxyThrottle` guarding the forward itself.++ On proxy failure, ``body_region`` returns a flat ``proxy_failed`` 502 (the+ request can't be served locally at all); the lookup strategies fall through+ to local handling, which produces the appropriate auth error.+ """++ region_proxy_strategy: str | None = None+ # Declared by ProvisioningAPIView; the mixin reads it to render a 429 in the+ # endpoint's own wire envelope.+ error_envelope: ClassVar[Envelope]++ def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:+ strategy = self.region_proxy_strategy+ if strategy is None:+ return super().dispatch(request, *args, **kwargs) # type: ignore[misc]++ # Cache the raw body before the strategy checks touch it, so DRF's+ # parsers can still read it afterwards.+ _ = request.body++ current = _current_region()+ if current is None or current in ("DEV", "LOCAL"):+ return super().dispatch(request, *args, **kwargs) # type: ignore[misc]++ if request.META.get(f"HTTP_{PROXY_LOOP_HEADER.upper().replace('-', '_')}"):+ return super().dispatch(request, *args, **kwargs) # type: ignore[misc]++ if _STRATEGY_CHECKS[strategy](request, current):+ target = _other_region_domain(current)+ proxy_props = {+ "strategy": strategy,+ "from_region": current,+ "to_domain": target,+ "endpoint": request.path,+ }++ throttle = RegionProxyThrottle()+ if not throttle.allow_http_request(request):+ logger.warning("provisioning.proxy.rate_limited", **proxy_props)+ capture_region_proxy_event("proxy_rate_limited", **proxy_props)+ wait = throttle.wait()+ return _error_response(+ ProvisioningError(+ "rate_limited",+ RegionProxyThrottle.error_message,+ status=429,+ retry_after=max(1, int(wait)) if wait else None,+ ),+ self.error_envelope,)- proxy_props = {- "strategy": strategy,- "from_region": current,- "to_domain": target,- "endpoint": request.path,- }- try:- response = _proxy_to_region(request, target)- posthoganalytics.capture(- "agentic_provisioning region_proxy",- distinct_id=f"agentic_provisioning_{uuid.uuid4().hex[:16]}",- properties={"outcome": "proxied", **proxy_props},- )- return response- except requests.exceptions.RequestException:- posthoganalytics.capture(- "agentic_provisioning region_proxy",- distinct_id=f"agentic_provisioning_{uuid.uuid4().hex[:16]}",- properties={"outcome": "proxy_failed", **proxy_props},- )- if strategy == "body_region":- return Response(- {"error": {"code": "proxy_failed", "message": "Failed to route to correct region"}},- status=502,- )-- return view_func(request, *args, **kwargs)- return wrapper+ logger.info(+ "provisioning.proxy.routing",+ strategy=strategy,+ current_region=current,+ target_domain=target,+ )++ try:+ response = _proxy_to_region(request, target)+ capture_region_proxy_event("proxied", **proxy_props)+ return response+ except requests.exceptions.RequestException:+ capture_region_proxy_event("proxy_failed", **proxy_props)+ if strategy == "body_region":+ return HttpResponse(+ json.dumps(+ {"error": {"code": "proxy_failed", "message": "Failed to route to correct region"}},+ separators=_JSON_SEPARATORS,+ ),+ status=502,+ content_type="application/json",+ )- return decorator+ return super().dispatch(request, *args, **kwargs) # type: ignore[misc]diff --git a/ee/api/agentic_provisioning/regions.py b/ee/api/agentic_provisioning/regions.pynew file mode 100644index 000000000000..45f121195bdd--- /dev/null+++ b/ee/api/agentic_provisioning/regions.py@@ -0,0 +1,19 @@+from __future__ import annotations++from django.conf import settings++from posthog.utils import get_instance_region+++def current_region_host() -> str:+ """Host of the region this instance serves, for URLs handed to partners."""+ return region_to_host(get_instance_region() or "US")+++def region_to_host(region: str) -> str:+ region_lower = region.lower()+ if region_lower == "eu":+ return "https://eu.posthog.com"+ elif region_lower in ("us", "dev"):+ return "https://us.posthog.com"+ return settings.SITE_URLdiff --git a/ee/api/agentic_provisioning/serializers.py b/ee/api/agentic_provisioning/serializers.pynew file mode 100644index 000000000000..5ccfa8d1f054--- /dev/null+++ b/ee/api/agentic_provisioning/serializers.py@@ -0,0 +1,280 @@+"""Request serializers for the agentic provisioning endpoints.++Error codes, messages, and check order are part of the partner wire contract+(documented at posthog.com/docs/integrate/provisioning), not DRF's default+error shape, so validators raise :class:`ProvisioningError` (rendered by the+view in its envelope) instead of DRF ``ValidationError``.+"""++from __future__ import annotations++from typing import Any++from django.utils import timezone+from django.utils.dateparse import parse_datetime++from rest_framework import serializers++from ee.api.agentic_provisioning.analytics import capture_provisioning_event+from ee.api.agentic_provisioning.credentials import validate_label_prefix+from ee.api.agentic_provisioning.exceptions import ProvisioningError+++def first_error_message(errors: Any) -> str:+ """Flatten DRF field errors into a single wire-compatible message."""+ if isinstance(errors, dict):+ for field, messages in errors.items():+ nested = first_error_message(messages)+ return f"{field}: {nested}" if nested else str(field)+ if isinstance(errors, list) and errors:+ return first_error_message(errors[0])+ return str(errors)+++class AccountRequestSerializer(serializers.Serializer):+ """POST /provisioning/account_requests body."""++ # Optional fields carry allow_null=True: an explicit null is treated the+ # same as an omitted field (coerced to the declared default in validate)+ # rather than rejected with a 400.+ id = serializers.CharField(+ required=False,+ allow_blank=True,+ allow_null=True,+ default="",+ help_text="Partner-side account request id, echoed back for idempotency.",+ )+ email = serializers.CharField(+ required=False,+ allow_blank=True,+ allow_null=True,+ default=None,+ help_text="Email of the account to create or link. Required.",+ )+ name = serializers.CharField(+ required=False, allow_blank=True, allow_null=True, default="", help_text="Display name of the end user."+ )+ scopes = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ allow_null=True,+ default=list,+ help_text="OAuth scopes requested for the eventual access token. Defaults to the app's grantable set.",+ )+ expires_at = serializers.CharField(+ required=False,+ allow_blank=True,+ allow_null=True,+ default="",+ help_text="ISO-8601 expiry of the account request; expired requests are rejected.",+ )+ configuration = serializers.JSONField(+ required=False,+ allow_null=True,+ default=dict,+ help_text="Partner configuration: region (US/EU), organization_name, team_id, wizard block.",+ )+ code_challenge = serializers.CharField(+ required=False,+ allow_blank=True,+ allow_null=True,+ default="",+ help_text="PKCE code challenge (S256, base64url).",+ )+ code_challenge_method = serializers.CharField(+ required=False,+ allow_blank=True,+ allow_null=True,+ default="S256",+ help_text="PKCE challenge method; only S256 is supported.",+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ # Treat explicit null on optional fields as absent, so downstream code+ # sees the declared default rather than None.+ attrs["id"] = attrs.get("id") or ""+ attrs["scopes"] = attrs.get("scopes") or []+ attrs["code_challenge"] = attrs.get("code_challenge") or ""+ attrs["code_challenge_method"] = attrs.get("code_challenge_method") or "S256"++ if not attrs.get("email"):+ capture_provisioning_event("account_request", "error", error_code="missing_email")+ raise ProvisioningError("invalid_request", "email is required")++ expires_at_str = attrs.get("expires_at") or ""+ if expires_at_str:+ # parse_datetime returns None for non-ISO-8601 input but raises+ # ValueError for well-formed yet invalid values (e.g. month 13);+ # both count as unparseable and are ignored, matching the historic+ # "reject only when parseable and in the past" behavior.+ try:+ expires_at = parse_datetime(expires_at_str)+ except ValueError:+ expires_at = None+ if expires_at and expires_at < timezone.now():+ capture_provisioning_event("account_request", "error", error_code="expired")+ raise ProvisioningError("expired", "Account request has expired")++ if not isinstance(attrs.get("configuration"), dict):+ attrs["configuration"] = {}++ return attrs+++class GitHubGrantCreateSerializer(serializers.Serializer):+ """POST /provisioning/github/grants body."""++ code = serializers.JSONField(+ required=False,+ allow_null=True,+ default=None,+ help_text="GitHub OAuth authorization code to exchange server-side.",+ )+ redirect_uri = serializers.CharField(+ required=False,+ allow_blank=True,+ allow_null=True,+ default=None,+ help_text="redirect_uri used in the GitHub OAuth authorize step, when one was sent.",+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ code = attrs.get("code")+ if not code or not isinstance(code, str):+ capture_provisioning_event(+ "github_grant", "error", partner=self.context.get("partner"), error_code="missing_code"+ )+ raise ProvisioningError("invalid_request", "code is required")+ attrs["redirect_uri"] = attrs.get("redirect_uri") or None+ return attrs+++class ResourceCreateSerializer(serializers.Serializer):+ """POST /provisioning/resources body."""++ project_id = serializers.CharField(+ required=False,+ allow_blank=True,+ allow_null=True,+ default="",+ help_text="Partner-side project id; idempotency key for the provisioned project.",+ )+ configuration = serializers.JSONField(+ required=False, allow_null=True, default=dict, help_text="Partner configuration: project_name."+ )+ label_prefix = serializers.JSONField(+ required=False,+ allow_null=True,+ default=None,+ help_text="Optional prefix for the label of the provisioned personal API key (max 25 chars).",+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ try:+ attrs["label_prefix"] = validate_label_prefix(attrs.get("label_prefix"))+ except ProvisioningError:+ capture_provisioning_event(+ "resource_created", "error", partner=self.context.get("partner"), error_code="invalid_label_prefix"+ )+ raise++ attrs["project_id"] = attrs.get("project_id") or ""+ if not isinstance(attrs.get("configuration"), dict):+ attrs["configuration"] = {}++ return attrs+++class RotateCredentialsSerializer(serializers.Serializer):+ """POST /provisioning/resources/:id/rotate_credentials body."""++ label_prefix = serializers.JSONField(+ required=False,+ allow_null=True,+ default=None,+ help_text="Optional prefix for the label of the re-issued personal API key (max 25 chars).",+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ try:+ attrs["label_prefix"] = validate_label_prefix(attrs.get("label_prefix"))+ except ProvisioningError as exc:+ capture_provisioning_event("credential_rotation", "error", error_code="invalid_label_prefix")+ exc.resource_id = self.context.get("resource_id", "")+ raise++ return attrs+++class GitHubIntegrationSerializer(serializers.Serializer):+ """POST /provisioning/resources/:id/github_integration body."""++ grant_id = serializers.JSONField(+ required=False,+ allow_null=True,+ default=None,+ help_text="Opaque grant id returned by POST /provisioning/github/grants.",+ )+ installation_id = serializers.JSONField(+ required=False,+ allow_null=True,+ default=None,+ help_text="GitHub App installation id chosen by the user in the repo picker.",+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ if not attrs.get("grant_id") or not attrs.get("installation_id"):+ raise ProvisioningError(+ "invalid_request",+ "grant_id and installation_id are required",+ resource_id=self.context.get("resource_id", ""),+ )+ return attrs+++class WizardRunSerializer(serializers.Serializer):+ """POST /provisioning/resources/:id/wizard_runs body."""++ repository = serializers.JSONField(+ required=False,+ allow_null=True,+ default=None,+ help_text="Repository to run the setup wizard against, in 'owner/repo' form.",+ )+ branch = serializers.CharField(+ required=False,+ allow_blank=True,+ allow_null=True,+ default=None,+ help_text="Branch to base the wizard run on; defaults to the repository's default branch.",+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ if not attrs.get("repository"):+ raise ProvisioningError(+ "invalid_request", "repository is required", resource_id=self.context.get("resource_id", "")+ )+ attrs["branch"] = attrs.get("branch") or None+ return attrs+++class DeepLinkSerializer(serializers.Serializer):+ """POST /provisioning/deep_links body."""++ purpose = serializers.CharField(+ required=False,+ allow_blank=True,+ allow_null=True,+ default="dashboard",+ help_text="Free-form label retained for analytics (e.g. dashboard).",+ )+ path = serializers.JSONField(+ required=False,+ allow_null=True,+ default=None,+ help_text="Relative in-app path the user lands on after login; must start with a single '/'.",+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ attrs["purpose"] = attrs.get("purpose") or "dashboard"+ return attrsdiff --git a/ee/api/agentic_provisioning/teams.py b/ee/api/agentic_provisioning/teams.pynew file mode 100644index 000000000000..22aaa7f100d1--- /dev/null+++ b/ee/api/agentic_provisioning/teams.py@@ -0,0 +1,127 @@+"""Team resolution and creation for provisioning flows."""++from __future__ import annotations++from django.db import IntegrityError++from posthog.models.oauth import OAuthAccessToken+from posthog.models.team.team import Team+from posthog.models.team.team_provisioning_config import TeamProvisioningConfig+from posthog.models.user import User++from ee.api.agentic_provisioning.tokens import ensure_team_in_token_scopes, user_can_access_team+++class ProjectIdCollisionError(Exception):+ """Raised when a stripe_project_id is already in use by a team outside the caller's orgs."""++ def __init__(self, project_id: str) -> None:+ super().__init__(project_id)+ self.project_id = project_id+++def resolve_team_for_existing_user(user: User, requested_team_id: int | None = None) -> Team | None:+ """Pick a team for an existing user during email-based account linking.++ If requested_team_id is provided and the user has access, use it.+ Otherwise auto-select: single non-demo team → use it, only demo teams →+ create a new project, multiple teams → create a new project in the first org.+ """+ memberships = list(user.organization_memberships.select_related("organization").all())+ if not memberships:+ return None++ org_ids = [m.organization_id for m in memberships]++ if requested_team_id is not None:+ try:+ team = Team.objects.get(id=requested_team_id, is_demo=False)+ except Team.DoesNotExist:+ return None+ if team.organization_id not in org_ids:+ return None+ # Org membership alone is not access: a partner can name any team id in+ # the user's orgs, so a team the user is excluded from must not become+ # the scope of the minted code.+ if not user_can_access_team(user, team):+ return None+ return team++ non_demo_teams = [+ team+ for team in Team.objects.filter(organization_id__in=org_ids, is_demo=False)+ if user_can_access_team(user, team)+ ]++ if len(non_demo_teams) == 1:+ return non_demo_teams[0]++ organization = memberships[0].organization+ return Team.objects.create_with_data(initiating_user=user, organization=organization)+++def resolve_or_create_project_team(+ project_id: str,+ scoped_teams: list[int],+ user: User,+ configuration: dict,+ access_token: OAuthAccessToken,+) -> tuple[Team | None, list[int]]:+ """Look up or create a team for the given project_id.++ Uses TeamProvisioningConfig (DB-backed with unique constraint) for the+ project_id → team_id mapping. This ensures idempotency even across cache+ evictions and handles race conditions via IntegrityError.++ Returns (None, scoped_teams) when an existing team is resolved but the+ authenticated user lacks team-level access (honors advanced permissions+ / access controls on top of org membership).+ """+ existing = (+ TeamProvisioningConfig.objects.filter(+ stripe_project_id=project_id,+ application=access_token.application,+ team__organization_id__in=Team.objects.filter(id__in=scoped_teams).values("organization_id"),+ )+ .select_related("team")+ .first()+ )+ if existing:+ if not user_can_access_team(user, existing.team):+ return None, scoped_teams+ return ensure_team_in_token_scopes(access_token, scoped_teams, existing.team)++ base_team = Team.objects.get(id=scoped_teams[0])+ if not user_can_access_team(user, base_team):+ return None, scoped_teams++ project_name = configuration.get("project_name", "Default project")+ new_team = Team.objects.create_with_data(+ initiating_user=user,+ organization=base_team.organization,+ name=project_name,+ )++ try:+ TeamProvisioningConfig.objects.update_or_create(+ team=new_team,+ defaults={"stripe_project_id": project_id, "application": access_token.application},+ )+ except IntegrityError:+ new_team.delete()+ race_winner = (+ TeamProvisioningConfig.objects.filter(+ stripe_project_id=project_id,+ application=access_token.application,+ team__organization_id__in=Team.objects.filter(id__in=scoped_teams).values("organization_id"),+ )+ .select_related("team")+ .first()+ )+ if race_winner:+ if not user_can_access_team(user, race_winner.team):+ return None, scoped_teams+ return ensure_team_in_token_scopes(access_token, scoped_teams, race_winner.team)+ raise ProjectIdCollisionError(project_id)++ return ensure_team_in_token_scopes(access_token, scoped_teams, new_team)diff --git a/ee/api/agentic_provisioning/test/base.py b/ee/api/agentic_provisioning/test/base.pyindex 40a996febe67..0e00e292fcbf 100644--- a/ee/api/agentic_provisioning/test/base.py+++ b/ee/api/agentic_provisioning/test/base.py@@ -10,7 +10,12 @@ from django.utils import timezonefrom rest_framework.test import APIClient-from ee.api.agentic_provisioning.views import AUTH_CODE_CACHE_PREFIX+from posthog.constants import AvailableFeature+from posthog.models.organization import OrganizationMembership+from posthog.models.team.team import Team++from ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIX+from ee.models.rbac.access_control import AccessControlTEST_PARTNER_CLIENT_ID = "test_partner_client_id"@@ -117,3 +122,18 @@ class ProvisioningTestBase(APIBaseTest):def _get_bearer_token(self) -> str:return self._request_bearer_token().json()["access_token"]++ def _restrict_team_access(self, team: Team) -> None:+ """Make ``self.user`` an org member who is denied access to ``team``."""+ 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=team,+ access_level="none",+ resource="project",+ resource_id=str(team.id),+ )diff --git a/ee/api/agentic_provisioning/test/test_account_requests.py b/ee/api/agentic_provisioning/test/test_account_requests.pyindex 086ffd126068..3b12ca889db5 100644--- a/ee/api/agentic_provisioning/test/test_account_requests.py+++ b/ee/api/agentic_provisioning/test/test_account_requests.py@@ -5,20 +5,20 @@ from unittest.mock import patchfrom django.core.cache import cachefrom django.db import IntegrityError+from django.http import JsonResponsefrom django.test import override_settingsfrom django.utils import timezonefrom parameterized import parameterized-from rest_framework.response import Responsefrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshTokenfrom posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom posthog.models.user import User-from ee.api.agentic_provisioning import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIX+from ee.api.agentic_provisioning.analytics import capture_provisioning_event+from ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIXfrom ee.api.agentic_provisioning.test.base import ProvisioningTestBase-from ee.api.agentic_provisioning.views import _capture_provisioning_eventACCOUNT_REQUESTS_URL = "/api/agentic/provisioning/account_requests"VALID_CODE_CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"@@ -127,15 +127,33 @@ class TestAccountRequests(ProvisioningTestBase):assert res.status_code == 400assert res.json()["error"]["code"] == expected_code- def test_existing_user_with_inaccessible_team_id_returns_400(self):+ @parameterized.expand(["other_org", "restricted_in_own_org"])+ def test_existing_user_with_inaccessible_team_id_returns_400(self, case):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(email=self.user.email, configuration={"team_id": other_team.id})+ if case == "other_org":+ other_org = Organization.objects.create(name="Other Org")+ target = Team.objects.create(organization=other_org, name="Other Team")+ else:+ target = Team.objects.create_with_data(+ initiating_user=self.user, organization=self.organization, name="Restricted project"+ )+ self._restrict_team_access(target)++ payload = self._account_request_payload(email=self.user.email, configuration={"team_id": target.id})res = self._post_account_request(payload, token=token)assert res.status_code == 400assert res.json()["error"]["code"] == "team_resolution_failed"+ def test_existing_user_auto_select_skips_restricted_team(self):+ token = self._silent_partner_token_for(self.user)+ self._restrict_team_access(self.team)++ res = self._post_account_request(self._account_request_payload(email=self.user.email), token=token)++ assert res.status_code == 200+ code_data = cache.get(f"{AUTH_CODE_CACHE_PREFIX}{res.json()['oauth']['code']}")+ assert code_data["team_id"] != self.team.id+def test_existing_user_multi_team_creates_new_project(self):token = self._silent_partner_token_for(self.user)Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)@@ -184,7 +202,7 @@ class TestAccountRequests(ProvisioningTestBase):)@patch("ee.api.agentic_provisioning.region_proxy._proxy_to_region")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"}})+ mock_proxy.return_value = JsonResponse({"type": "oauth", "oauth": {"code": "proxied"}})payload = self._account_request_payload(configuration={"region": region})with override_settings(CLOUD_DEPLOYMENT=deployment):res = self._post_account_request(payload)@@ -199,7 +217,7 @@ class TestAccountRequests(ProvisioningTestBase):assert res.status_code == 200assert res.json()["type"] == "oauth"- @patch("ee.api.agentic_provisioning.views.User.objects.bootstrap", side_effect=IntegrityError)+ @patch("ee.api.agentic_provisioning.accounts.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"@@ -211,14 +229,14 @@ class TestAccountRequests(ProvisioningTestBase):# 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)+ @patch("ee.api.agentic_provisioning.accounts.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_account_request(payload)assert res.status_code == 500assert res.json()["error"]["code"] == "account_creation_failed"- @patch("ee.api.agentic_provisioning.views._capture_provisioning_event")+ @patch("ee.api.agentic_provisioning.accounts.capture_provisioning_event")def test_new_user_capture_includes_team_id(self, mock_capture_event):res = self._post_account_request(self._account_request_payload(email="[email protected]"))assert res.status_code == 200@@ -330,7 +348,7 @@ class TestPKCEPartnerExistingUserConsent(ProvisioningTestBase):assert data["type"] == "oauth"assert "code" in data["oauth"]- @patch("ee.api.agentic_provisioning.views._capture_provisioning_event")+ @patch("ee.api.agentic_provisioning.accounts.capture_provisioning_event")def test_pkce_partner_new_user_capture_attributes_client(self, mock_capture_event):payload = self._account_request_payload(email="[email protected]")res = self._post_as_pkce_partner(payload)@@ -342,7 +360,7 @@ class TestPKCEPartnerExistingUserConsent(ProvisioningTestBase):assert len(new_user_calls) == 1assert new_user_calls[0].kwargs["partner"] == self.pkce_partner- @patch("ee.api.agentic_provisioning.views.report_user_signed_up")+ @patch("ee.api.agentic_provisioning.accounts.report_user_signed_up")def test_pkce_partner_new_user_emits_signup_event_with_client(self, mock_signup):payload = self._account_request_payload(email="[email protected]")res = self._post_as_pkce_partner(payload)@@ -609,10 +627,10 @@ class TestCaptureProvisioningEvent(ProvisioningTestBase):("no_partner", None, False, None),])- @patch("ee.api.agentic_provisioning.views.posthoganalytics.capture")+ @patch("ee.api.agentic_provisioning.analytics.posthoganalytics.capture")def test_partner_attribution(self, _name, partner_type, expects_client, expected_partner_type, mock_capture):partner = None if partner_type is None else self._make_partner(partner_type=partner_type)- _capture_provisioning_event("account_request", "new_user", partner=partner, team_id=42)+ capture_provisioning_event("account_request", "new_user", partner=partner, team_id=42)props = mock_capture.call_args.kwargs["properties"]if expects_client:diff --git a/ee/api/agentic_provisioning/test/test_account_requests_wizard.py b/ee/api/agentic_provisioning/test/test_account_requests_wizard.pyindex 626a91d155f2..f679ea79b321 100644--- a/ee/api/agentic_provisioning/test/test_account_requests_wizard.py+++ b/ee/api/agentic_provisioning/test/test_account_requests_wizard.py@@ -9,7 +9,8 @@ from django.utils import timezonefrom posthog.models.integration import GitHubInstallationAccess, GitHubIntegration, GitHubUserAuthorizationfrom posthog.models.user import OnboardingSkippedReason, User-from ee.api.agentic_provisioning import GITHUB_GRANT_CACHE_PREFIX, github_grants+from ee.api.agentic_provisioning import github_grants+from ee.api.agentic_provisioning.constants import GITHUB_GRANT_CACHE_PREFIXfrom ee.api.agentic_provisioning.test.base import ProvisioningTestBaseACCOUNT_REQUESTS_URL = "/api/agentic/provisioning/account_requests"@@ -56,7 +57,7 @@ class TestAccountRequestsWizardBlock(ProvisioningTestBase):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:+ with patch("ee.api.agentic_provisioning.accounts.send_provisioning_welcome") as mock_email:response = self._post(self._payload("[email protected]"))assert response.status_code == 200, response.json()body = response.json()@@ -76,9 +77,9 @@ class TestAccountRequestsWizardBlock(ProvisioningTestBase):patch.object(GitHubIntegration, "fetch_installation_access", return_value=_installation_access()),patch.object(GitHubIntegration, "first_for_team_repository", return_value=MagicMock()),patch(- "ee.api.agentic_provisioning.views.tasks_facade.create_wizard_cloud_run", return_value=created+ "ee.api.agentic_provisioning.wizard.tasks_facade.create_wizard_cloud_run", return_value=created) as mock_create,- patch("ee.api.agentic_provisioning.views.send_provisioning_welcome") as mock_email,+ patch("ee.api.agentic_provisioning.accounts.send_provisioning_welcome") as mock_email,):manager.attach_mock(mock_create, "create_run")manager.attach_mock(mock_email.delay, "email_delay")@@ -113,7 +114,7 @@ class TestAccountRequestsWizardBlock(ProvisioningTestBase):assert call_names.index("create_run") < call_names.index("email_delay")def test_wizard_grant_not_found_returns_account_with_wizard_error(self):- with patch("ee.api.agentic_provisioning.views.send_provisioning_welcome") as mock_email:+ with patch("ee.api.agentic_provisioning.accounts.send_provisioning_welcome") as mock_email:response = self._post(self._payload(@@ -136,7 +137,7 @@ class TestAccountRequestsWizardBlock(ProvisioningTestBase):grant = self._grant("[email protected]")with (patch.object(GitHubIntegration, "verify_user_installation_access", return_value=False),- patch("ee.api.agentic_provisioning.views.send_provisioning_welcome"),+ patch("ee.api.agentic_provisioning.accounts.send_provisioning_welcome"),):response = self._post(self._payload(@@ -158,7 +159,7 @@ class TestAccountRequestsWizardBlock(ProvisioningTestBase):with (patch.object(GitHubIntegration, "verify_user_installation_access", return_value=True),patch.object(GitHubIntegration, "fetch_installation_access", return_value=_installation_access()),- patch("ee.api.agentic_provisioning.views.send_provisioning_welcome") as mock_email,+ patch("ee.api.agentic_provisioning.accounts.send_provisioning_welcome") as mock_email,):response = self._post(self._payload(diff --git a/ee/api/agentic_provisioning/test/test_authorize.py b/ee/api/agentic_provisioning/test/test_authorize.pyindex 7946c94d423e..4d440ddbb5cb 100644--- a/ee/api/agentic_provisioning/test/test_authorize.py+++ b/ee/api/agentic_provisioning/test/test_authorize.py@@ -10,7 +10,7 @@ from posthog.models import Organization, OrganizationMembership, Teamfrom posthog.models.oauth import OAuthApplicationfrom posthog.models.user import User-from ee.api.agentic_provisioning import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIX+from ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIXfrom ee.api.agentic_provisioning.test.base import TEST_PARTNER_SCOPES, ProvisioningTestBasePARTNER_CALLBACK = "https://partner.example.com/callback"@@ -97,6 +97,19 @@ class TestAgenticAuthorize(AuthorizeTestBase):assert code_data["partner_id"] == str(partner.id)assert cache.get(f"{PENDING_AUTH_CACHE_PREFIX}state_ok") is None+ def test_trusted_partner_auto_redirect_skips_restricted_team(self):+ partner = self._make_skip_consent_partner()+ self._restrict_team_access(self.team)+ self._set_pending_auth("state_restricted", self.user.email, partner=partner, consent_required=False)++ res = self.client.get("/api/agentic/authorize?state=state_restricted")++ assert res.status_code == 302+ assert res["Location"].startswith(PARTNER_CALLBACK)+ code = res["Location"].split("code=")[1].split("&")[0]+ code_data = cache.get(f"{AUTH_CODE_CACHE_PREFIX}{code}")+ assert code_data["team_id"] != self.team.id+@parameterized.expand([# consent_required=True forces the consent UI for a skip-consent partner whose request@@ -206,7 +219,7 @@ class TestAgenticAuthorizeConfirm(AgenticAuthorizeMultiOrgBase):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")+ @patch("ee.api.agentic_provisioning.views.authorize.capture_provisioning_event")def test_confirm_success_attributes_partner(self, mock_capture_event):partner = OAuthApplication.objects.create(client_id="confirm-attribution-partner",@@ -247,12 +260,19 @@ class TestAgenticAuthorizeConfirm(AgenticAuthorizeMultiOrgBase):assert res.status_code == 403assert res.json()["error"] == "email_mismatch"- def test_confirm_rejects_inaccessible_team(self):+ @parameterized.expand(["other_org", "restricted_in_own_org"])+ def test_confirm_rejects_inaccessible_team(self, case):self._set_pending_auth("state_no_access", self.user.email)- 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._confirm("state_no_access", other_team.id)+ if case == "other_org":+ other_org = Organization.objects.create(name="Other Org")+ target = Team.objects.create(organization=other_org, name="Other Project", api_token="token_other")+ else:+ target = Team.objects.create_with_data(+ initiating_user=self.user, organization=self.organization, name="Restricted project"+ )+ self._restrict_team_access(target)++ res = self._confirm("state_no_access", target.id)assert res.status_code == 403assert res.json()["error"] == "team_not_accessible"diff --git a/ee/api/agentic_provisioning/test/test_deep_links.py b/ee/api/agentic_provisioning/test/test_deep_links.pyindex 7b4f4ae5326d..6a9251132339 100644--- a/ee/api/agentic_provisioning/test/test_deep_links.py+++ b/ee/api/agentic_provisioning/test/test_deep_links.py@@ -4,8 +4,8 @@ from django.core.cache import cachefrom parameterized import parameterized+from ee.api.agentic_provisioning.constants import DEEP_LINK_CACHE_PREFIXfrom ee.api.agentic_provisioning.test.base import ProvisioningTestBase-from ee.api.agentic_provisioning.views import DEEP_LINK_CACHE_PREFIXclass TestDeepLinks(ProvisioningTestBase):@@ -33,7 +33,7 @@ class TestDeepLinks(ProvisioningTestBase):url = res.json()["url"]assert f"team_id={self.team.id}" in url- @patch("ee.api.agentic_provisioning.views._capture_provisioning_event")+ @patch("ee.api.agentic_provisioning.views.deep_links.capture_provisioning_event")def test_deep_link_capture_attributes_client(self, mock_capture_event):token = self._get_bearer_token()res = self._post_with_bearer(diff --git a/ee/api/agentic_provisioning/test/test_github_grants.py b/ee/api/agentic_provisioning/test/test_github_grants.pyindex bccc586811ba..6fb14c2e2196 100644--- a/ee/api/agentic_provisioning/test/test_github_grants.py+++ b/ee/api/agentic_provisioning/test/test_github_grants.py@@ -8,7 +8,8 @@ from parameterized import parameterizedfrom posthog.models.integration import GitHubUserAuthorizationfrom posthog.models.oauth import OAuthApplication-from ee.api.agentic_provisioning import GITHUB_GRANT_CACHE_PREFIX, github_grants+from ee.api.agentic_provisioning import github_grants+from ee.api.agentic_provisioning.constants import GITHUB_GRANT_CACHE_PREFIXfrom ee.api.agentic_provisioning.test.base import ProvisioningTestBaseACCESS_TOKEN = "gho_secret_user_token"@@ -72,7 +73,7 @@ class TestGitHubGrants(ProvisioningTestBase):def _create_grant_via_api(self):with (patch(- "ee.api.agentic_provisioning.views.GitHubIntegration.github_user_from_code",+ "ee.api.agentic_provisioning.views.github_grants.GitHubIntegration.github_user_from_code",return_value=AUTHORIZATION,),patch("ee.api.agentic_provisioning.github_grants.github_request", return_value=EMAILS_RESPONSE),@@ -84,7 +85,7 @@ class TestGitHubGrants(ProvisioningTestBase):def test_create_grant_happy_path(self):with (patch(- "ee.api.agentic_provisioning.views.GitHubIntegration.github_user_from_code",+ "ee.api.agentic_provisioning.views.github_grants.GitHubIntegration.github_user_from_code",return_value=AUTHORIZATION,) as mock_exchange,patch("ee.api.agentic_provisioning.github_grants.github_request", return_value=EMAILS_RESPONSE),@@ -123,7 +124,7 @@ class TestGitHubGrants(ProvisioningTestBase):def test_create_grant_exchange_failure_returns_502(self):with patch(- "ee.api.agentic_provisioning.views.GitHubIntegration.github_user_from_code",+ "ee.api.agentic_provisioning.views.github_grants.GitHubIntegration.github_user_from_code",return_value=None,):response = self._post_grants({"code": "bad_code"})@@ -132,7 +133,7 @@ class TestGitHubGrants(ProvisioningTestBase):def test_create_grant_github_request_failure_returns_502(self):with patch(- "ee.api.agentic_provisioning.views.GitHubIntegration.github_user_from_code",+ "ee.api.agentic_provisioning.views.github_grants.GitHubIntegration.github_user_from_code",side_effect=requests.RequestException("boom"),):response = self._post_grants({"code": "gh_code"})@@ -166,7 +167,7 @@ class TestGitHubGrants(ProvisioningTestBase):no_verified = _github_response(200, [{"email": "[email protected]", "primary": True, "verified": False}])with (patch(- "ee.api.agentic_provisioning.views.GitHubIntegration.github_user_from_code",+ "ee.api.agentic_provisioning.views.github_grants.GitHubIntegration.github_user_from_code",return_value=AUTHORIZATION,),patch("ee.api.agentic_provisioning.github_grants.github_request", return_value=no_verified),@@ -183,7 +184,7 @@ class TestGitHubGrants(ProvisioningTestBase):denied = _github_response(404, {"message": "Not Found"})with (patch(- "ee.api.agentic_provisioning.views.GitHubIntegration.github_user_from_code",+ "ee.api.agentic_provisioning.views.github_grants.GitHubIntegration.github_user_from_code",return_value=AUTHORIZATION,),patch("ee.api.agentic_provisioning.github_grants.github_request", return_value=denied),@@ -216,13 +217,22 @@ class TestGitHubGrants(ProvisioningTestBase):assert second.status_code == 429assert second["Retry-After"]- @parameterized.expand(- [- ("agentic_tree", "/api/agentic/provisioning/github/grants"),- ("alias_tree", "/api/provisioning/github/grants"),- ]- )- def test_repositories_happy_path(self, _name, base_url):+ def test_capability_refusal_does_not_spend_grant_budget(self):+ self.partner.provisioning_rate_limit_github_grants = 1+ self.partner.provisioning_can_create_accounts = False+ self.partner.save()++ for _ in range(3):+ refused = self._post_grants({"code": "gh_code"})+ assert refused.status_code == 403+ assert refused.json()["error"]["code"] == "forbidden"++ self.partner.provisioning_can_create_accounts = True+ self.partner.save()+ assert self._create_grant_via_api().status_code == 200++ def test_repositories_happy_path(self):+ base_url = "/api/agentic/provisioning/github/grants"grant = github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")def fake_github_request(method, url, **kwargs):@@ -251,8 +261,8 @@ class TestGitHubGrants(ProvisioningTestBase):assert response.status_code == 404assert response.json()["error"]["code"] == "grant_not_found"- def test_repositories_grant_of_other_partner_returns_404(self):- other_partner = OAuthApplication.objects.create(+ def _create_other_partner(self) -> OAuthApplication:+ return OAuthApplication.objects.create(name="Other Partner",client_id="other_partner_client_id",client_secret="",@@ -264,6 +274,9 @@ class TestGitHubGrants(ProvisioningTestBase):provisioning_active=True,provisioning_can_create_accounts=True,)++ def test_repositories_grant_of_other_partner_returns_404(self):+ other_partner = self._create_other_partner()grant = github_grants.create_grant(other_partner, AUTHORIZATION, "[email protected]")response = self._get_grants(f"/api/agentic/provisioning/github/grants/{grant.grant_id}/repositories")assert response.status_code == 404@@ -279,7 +292,7 @@ class TestGitHubGrants(ProvisioningTestBase):return REPOSITORIES_RESPONSEwith (- patch("ee.api.agentic_provisioning.views.GITHUB_GRANT_POLL_RATE_LIMIT_MAX", 1),+ patch("ee.api.agentic_provisioning.throttling.GITHUB_GRANT_POLL_RATE_LIMIT_MAX", 1),patch("ee.api.agentic_provisioning.github_grants.github_request", side_effect=fake_github_request),):first = self._get_grants(url)@@ -288,6 +301,27 @@ class TestGitHubGrants(ProvisioningTestBase):assert second.status_code == 429assert second["Retry-After"]+ def test_repositories_poll_budget_is_not_shared_across_partners(self):+ grant = github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")+ url = f"/api/agentic/provisioning/github/grants/{grant.grant_id}/repositories"+ other_partner = self._create_other_partner()+ other_bearer = self._request_bearer_token(partner=other_partner).json()["access_token"]++ def fake_github_request(method, request_url, **kwargs):+ if request_url.endswith("/user/installations"):+ return INSTALLATIONS_RESPONSE+ return REPOSITORIES_RESPONSE++ with (+ patch("ee.api.agentic_provisioning.throttling.GITHUB_GRANT_POLL_RATE_LIMIT_MAX", 1),+ patch("ee.api.agentic_provisioning.github_grants.github_request", side_effect=fake_github_request),+ ):+ foreign = self._get_with_bearer(url, other_bearer)+ owner = self._get_grants(url)++ assert foreign.status_code == 404+ assert owner.status_code == 200+def test_repositories_github_failure_returns_502(self):grant = github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")with patch(diff --git a/ee/api/agentic_provisioning/test/test_oauth_token.py b/ee/api/agentic_provisioning/test/test_oauth_token.pyindex 9ee5513eea5f..591417a09b0f 100644--- a/ee/api/agentic_provisioning/test/test_oauth_token.py+++ b/ee/api/agentic_provisioning/test/test_oauth_token.py@@ -6,10 +6,14 @@ from django.utils import timezonefrom parameterized import parameterized+from posthog.constants import AvailableFeaturefrom posthog.models.oauth import OAuthAccessToken, OAuthApplication+from posthog.models.organization import OrganizationMembership+from posthog.models.team.team import Team-from ee.api.agentic_provisioning import AUTH_CODE_CACHE_PREFIX+from ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIXfrom ee.api.agentic_provisioning.test.base import TEST_PARTNER_SCOPES, ProvisioningTestBase+from ee.models.rbac.access_control import AccessControlTOKEN_URL = "/api/agentic/oauth/token"@@ -55,6 +59,31 @@ class TestOAuthTokenExchange(ProvisioningTestBase):assert "name" in team_entryassert "organization_id" in team_entry+ def test_available_teams_exclude_acl_restricted_teams(self):+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ ]+ self.organization.save()+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()++ restricted_team = Team.objects.create_with_data(+ initiating_user=self.user, organization=self.organization, name="Restricted team"+ )+ AccessControl.objects.create(+ team=restricted_team,+ access_level="none",+ resource="project",+ resource_id=str(restricted_team.id),+ )++ data = self._request_bearer_token().json()+ listed = data["account"]["available_teams"]++ assert self.team.id in [team["id"] for team in listed]+ assert restricted_team.id not in [team["id"] for team in listed]+ assert restricted_team.name not in [team["name"] for team in listed]+def test_code_is_single_use(self):code, verifier = self._mint_auth_code()assert self._exchange_code(code, verifier).status_code == 200diff --git a/ee/api/agentic_provisioning/test/test_partner_rate_limits.py b/ee/api/agentic_provisioning/test/test_partner_rate_limits.pyindex 507fc8f979e4..92ee573b1384 100644--- a/ee/api/agentic_provisioning/test/test_partner_rate_limits.py+++ b/ee/api/agentic_provisioning/test/test_partner_rate_limits.py@@ -9,9 +9,10 @@ from rest_framework.test import APIClientfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken-from ee.api.agentic_provisioning import AUTH_CODE_CACHE_PREFIX+from ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIX, PARTNER_RATE_LIMIT_DEFAULTS+from ee.api.agentic_provisioning.exceptions import ProvisioningErrorfrom ee.api.agentic_provisioning.test.base import ProvisioningTestBase-from ee.api.agentic_provisioning.views import PARTNER_RATE_LIMIT_DEFAULTS+from ee.api.agentic_provisioning.throttling import enforce_partner_rate_limitPARTNER_CLIENT_ID = "partner_rate_limit_test"@@ -56,44 +57,36 @@ class TestPartnerRateLimits(ProvisioningTestBase):])def test_default_limit_applies_when_field_is_null(self, endpoint):- from ee.api.agentic_provisioning.views import _enforce_partner_rate_limit-assert getattr(self.partner_app, f"provisioning_rate_limit_{endpoint}") is Noneexpected_limit = PARTNER_RATE_LIMIT_DEFAULTS[endpoint]for _ in range(expected_limit):- assert _enforce_partner_rate_limit(self.partner_app, endpoint) is None+ enforce_partner_rate_limit(self.partner_app, endpoint)- response = _enforce_partner_rate_limit(self.partner_app, endpoint)- assert response is not None- assert response.status_code == 429+ with self.assertRaises(ProvisioningError) as ctx:+ enforce_partner_rate_limit(self.partner_app, endpoint)+ assert ctx.exception.status == 429def test_custom_override_respected(self):- from ee.api.agentic_provisioning.views import _enforce_partner_rate_limit-self.partner_app.provisioning_rate_limit_account_requests = 3self.partner_app.save(update_fields=["provisioning_rate_limit_account_requests"])for _ in range(3):- assert _enforce_partner_rate_limit(self.partner_app, "account_requests") is None+ enforce_partner_rate_limit(self.partner_app, "account_requests")- response = _enforce_partner_rate_limit(self.partner_app, "account_requests")- assert response is not None- assert response.status_code == 429- assert "Retry-After" in response+ with self.assertRaises(ProvisioningError) as ctx:+ enforce_partner_rate_limit(self.partner_app, "account_requests")+ assert ctx.exception.status == 429+ assert ctx.exception.retry_after is not Nonedef test_zero_override_disables_limiting(self):- from ee.api.agentic_provisioning.views import _enforce_partner_rate_limit-self.partner_app.provisioning_rate_limit_account_requests = 0self.partner_app.save(update_fields=["provisioning_rate_limit_account_requests"])for _ in range(100):- assert _enforce_partner_rate_limit(self.partner_app, "account_requests") is None+ enforce_partner_rate_limit(self.partner_app, "account_requests")def test_separate_buckets_per_endpoint(self):- from ee.api.agentic_provisioning.views import _enforce_partner_rate_limit-self.partner_app.provisioning_rate_limit_account_requests = 2self.partner_app.provisioning_rate_limit_resource_creates = 2self.partner_app.save(@@ -104,14 +97,13 @@ class TestPartnerRateLimits(ProvisioningTestBase):)for _ in range(2):- _enforce_partner_rate_limit(self.partner_app, "account_requests")+ enforce_partner_rate_limit(self.partner_app, "account_requests")- assert _enforce_partner_rate_limit(self.partner_app, "account_requests") is not None- assert _enforce_partner_rate_limit(self.partner_app, "resource_creates") is None+ with self.assertRaises(ProvisioningError):+ enforce_partner_rate_limit(self.partner_app, "account_requests")+ enforce_partner_rate_limit(self.partner_app, "resource_creates")def test_separate_buckets_per_partner(self):- from ee.api.agentic_provisioning.views import _enforce_partner_rate_limit-other_partner = OAuthApplication.objects.create(client_id="other_partner",name="Other Partner",@@ -130,10 +122,11 @@ class TestPartnerRateLimits(ProvisioningTestBase):self.partner_app.save(update_fields=["provisioning_rate_limit_account_requests"])for _ in range(2):- _enforce_partner_rate_limit(self.partner_app, "account_requests")+ enforce_partner_rate_limit(self.partner_app, "account_requests")- assert _enforce_partner_rate_limit(self.partner_app, "account_requests") is not None- assert _enforce_partner_rate_limit(other_partner, "account_requests") is None+ with self.assertRaises(ProvisioningError):+ enforce_partner_rate_limit(self.partner_app, "account_requests")+ enforce_partner_rate_limit(other_partner, "account_requests")# --- Integration: token exchange rate limiting ---diff --git a/ee/api/agentic_provisioning/test/test_provisioning_auth.py b/ee/api/agentic_provisioning/test/test_provisioning_auth.pyindex a842e208e9f5..dc541d822f7e 100644--- a/ee/api/agentic_provisioning/test/test_provisioning_auth.py+++ b/ee/api/agentic_provisioning/test/test_provisioning_auth.py@@ -595,7 +595,7 @@ class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):@patch("posthog.api.oauth.cimd.CIMD_THROTTLE_CLASSES", new=[])@patch("ee.api.agentic_provisioning.authentication.register_cimd_provisioning_application_task")def test_cimd_domain_rate_limit_blocks_excessive_registrations(self, mock_task, _url_mock):- from ee.api.agentic_provisioning.views import CIMD_DOMAIN_RATE_LIMIT_MAX+ from ee.api.agentic_provisioning.constants import CIMD_DOMAIN_RATE_LIMIT_MAXbase_domain = "evil.example.com"_, challenge = self._pkce_pair()@@ -633,7 +633,7 @@ class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):@patch("posthog.api.oauth.cimd.CIMD_THROTTLE_CLASSES", new=[])@patch("ee.api.agentic_provisioning.authentication.register_cimd_provisioning_application_task")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+ from ee.api.agentic_provisioning.constants import CIMD_DOMAIN_RATE_LIMIT_MAX_, challenge = self._pkce_pair()@@ -655,7 +655,7 @@ class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):@patch("posthog.api.oauth.cimd.CIMD_THROTTLE_CLASSES", new=[])@patch("posthog.api.oauth.cimd.refresh_cimd_metadata_task")def test_cimd_domain_rate_limit_skipped_for_existing_apps(self, mock_refresh, _url_mock):- from ee.api.agentic_provisioning.views import CIMD_DOMAIN_RATE_LIMIT_MAX+ from ee.api.agentic_provisioning.constants import CIMD_DOMAIN_RATE_LIMIT_MAXbase_domain = "existing.example.com"_, challenge = self._pkce_pair()diff --git a/ee/api/agentic_provisioning/test/test_region_proxy.py b/ee/api/agentic_provisioning/test/test_region_proxy.pyindex c6c082c3e4b1..6573fc917fd8 100644--- a/ee/api/agentic_provisioning/test/test_region_proxy.py+++ b/ee/api/agentic_provisioning/test/test_region_proxy.py@@ -2,14 +2,15 @@ from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patchfrom django.core.cache import cache+from django.http import JsonResponsefrom django.test import override_settings+from parameterized import parameterizedfrom rest_framework.parsers import JSONParserfrom rest_framework.request import Request-from rest_framework.response import Responsefrom rest_framework.test import APIRequestFactory-from ee.api.agentic_provisioning import AUTH_CODE_CACHE_PREFIX+from ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIXfrom ee.api.agentic_provisioning.region_proxy import (_proxy_to_region,_should_proxy_bearer_lookup,@@ -17,6 +18,7 @@ from ee.api.agentic_provisioning.region_proxy import (_should_proxy_token_lookup,)from ee.api.agentic_provisioning.test.base import ProvisioningTestBase+from ee.api.agentic_provisioning.throttling import RegionProxyThrottlefactory = APIRequestFactory()@@ -196,7 +198,7 @@ class TestDecoratorIntegration(ProvisioningTestBase):@override_settings(CLOUD_DEPLOYMENT="US")@patch("ee.api.agentic_provisioning.region_proxy._proxy_to_region")def test_proxy_success_returns_proxied_response(self, mock_proxy):- mock_proxy.return_value = Response({"type": "oauth", "oauth": {"code": "abc"}})+ mock_proxy.return_value = JsonResponse({"type": "oauth", "oauth": {"code": "abc"}})payload = {"email": "[email protected]", "configuration": {"region": "EU"}}res = self._post_api("/api/agentic/provisioning/account_requests", data=payload)assert mock_proxy.called@@ -270,7 +272,7 @@ class TestBearerLookupDecoratorCoverage(ProvisioningTestBase):@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)+ mock_proxy.return_value = JsonResponse({"status": "ok"}, status=200)for method, url in self._resource_endpoints():mock_proxy.reset_mock()@@ -291,38 +293,76 @@ class TestBearerLookupDecoratorCoverage(ProvisioningTestBase):assert not mock_proxy.called, f"{method} {url} should not proxy for a locally valid bearer token"-class TestDecoratorCoverageContract(BaseTest):- """Catches forgotten `@region_proxy` decorators on bearer-auth endpoints.+class TestRegionProxyThrottle(ProvisioningTestBase):+ def setUp(self):+ super().setUp()+ cache.clear()++ @parameterized.expand(+ [+ (+ "typed_envelope",+ "/api/agentic/provisioning/account_requests",+ {"email": "[email protected]", "configuration": {"region": "EU"}},+ "type",+ ),+ # Any resource id works: bearer_lookup proxies before the handler reads it.+ ("status_envelope", "/api/agentic/provisioning/resources/1", None, "status"),+ ]+ )+ @override_settings(CLOUD_DEPLOYMENT="US")+ @patch.object(RegionProxyThrottle, "rate", "1/minute")+ @patch("ee.api.agentic_provisioning.region_proxy._proxy_to_region")+ def test_forwarding_is_capped_per_ip(self, _name, url, data, envelope_key, mock_proxy):+ mock_proxy.return_value = JsonResponse({"status": "ok"})++ def call():+ if data is None:+ return self._get_with_bearer(url, token="unknown_token_from_the_other_region")+ return self._post_api(url, data=data)- If you add a new endpoint that accepts a bearer access token, either decorate it- with `region_proxy(strategy="bearer_lookup")` or add it to the allowlist here+ assert call().status_code == 200+ assert mock_proxy.called++ mock_proxy.reset_mock()+ rejected = call()++ assert not mock_proxy.called, "over-budget requests must not reach the other region"+ assert rejected.status_code == 429+ assert rejected["Retry-After"]+ body = rejected.json()+ assert body[envelope_key] == "error"+ assert body["error"]["code"] == "rate_limited"+++class TestRegionProxyCoverageContract(BaseTest):+ """Catches forgotten ``region_proxy_strategy`` on bearer-auth endpoints.++ If you add a new endpoint that accepts a bearer access token, either declare+ ``region_proxy_strategy = "bearer_lookup"`` on it (or build on+ BearerResourceAPIView, which carries it) or add it to the allowlist herewith a written reason."""REGION_AWARE_ENDPOINTS = {- "provisioning_resources_create": "bearer_lookup",- "provisioning_resource_detail": "bearer_lookup",- "provisioning_rotate_credentials": "bearer_lookup",- "provisioning_resource_remove": "bearer_lookup",- "deep_links": "bearer_lookup",- "account_requests": "body_region",- "oauth_token": "token_lookup",+ "ResourcesCreateView": "bearer_lookup",+ "ResourceDetailView": "bearer_lookup",+ "RotateCredentialsView": "bearer_lookup",+ "ResourceRemoveView": "bearer_lookup",+ "GitHubIntegrationView": "bearer_lookup",+ "WizardRunsView": "bearer_lookup",+ "DeepLinksView": "bearer_lookup",+ "AccountRequestsView": "body_region",+ "OAuthTokenView": "token_lookup",}- def test_all_region_aware_endpoints_have_proxy_decorator(self):+ def test_all_region_aware_endpoints_declare_proxy_strategy(self):from ee.api.agentic_provisioning import views- from ee.api.agentic_provisioning.region_proxy import REGION_PROXY_REGISTRYfor view_name, expected_strategy in self.REGION_AWARE_ENDPOINTS.items():- assert hasattr(views, view_name), f"View {view_name} is missing from views.py"- qualname = (- getattr(views, view_name).__qualname__- if hasattr(getattr(views, view_name), "__qualname__")- else view_name- )- registered_strategy = REGION_PROXY_REGISTRY.get(qualname) or REGION_PROXY_REGISTRY.get(view_name)- assert registered_strategy == expected_strategy, (- f"{view_name} must be decorated with @region_proxy(strategy={expected_strategy!r}) "- f"(registry has: {registered_strategy!r})"+ assert hasattr(views, view_name), f"View {view_name} is missing from the views package"+ declared_strategy = getattr(getattr(views, view_name), "region_proxy_strategy", None)+ assert declared_strategy == expected_strategy, (+ f"{view_name} must declare region_proxy_strategy = {expected_strategy!r} (found: {declared_strategy!r})")diff --git a/ee/api/agentic_provisioning/test/test_resources.py b/ee/api/agentic_provisioning/test/test_resources.pyindex 26e3afdf7a3b..f243acdae62b 100644--- a/ee/api/agentic_provisioning/test/test_resources.py+++ b/ee/api/agentic_provisioning/test/test_resources.py@@ -6,8 +6,8 @@ from posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team import Team+from ee.api.agentic_provisioning.credentials import maybe_create_provisioned_patfrom ee.api.agentic_provisioning.test.base import ProvisioningTestBase-from ee.api.agentic_provisioning.views import _maybe_create_provisioned_patclass TestProvisioningResources(ProvisioningTestBase):@@ -24,7 +24,25 @@ class TestProvisioningResources(ProvisioningTestBase):assert "api_key" in data["complete"]["access_configuration"]assert "host" in data["complete"]["access_configuration"]- @patch("ee.api.agentic_provisioning.views._capture_provisioning_event")+ def test_create_resource_rate_limited_uses_status_envelope(self):+ self.partner.provisioning_rate_limit_resource_creates = 1+ self.partner.save(update_fields=["provisioning_rate_limit_resource_creates"])+ token = self._get_bearer_token()++ assert self._post_with_bearer("/api/agentic/provisioning/resources", token=token).status_code == 200++ res = self._post_with_bearer("/api/agentic/provisioning/resources", token=token)+ assert res.status_code == 429+ assert res["Retry-After"]++ # Resource endpoints speak the "status" envelope, not the typed one.+ assert res.json() == {+ "status": "error",+ "id": "",+ "error": {"code": "rate_limited", "message": "Rate limit exceeded for this partner. Try again later."},+ }++ @patch("ee.api.agentic_provisioning.views.resources.capture_provisioning_event")def test_create_resource_capture_attributes_client(self, mock_capture_event):token = self._get_bearer_token()res = self._post_with_bearer(@@ -170,7 +188,7 @@ class TestProvisioningResources(ProvisioningTestBase):scopes=["insight:read"],provisioning_issues_personal_api_key=gate_on,)- result = _maybe_create_provisioned_pat(self.user, self.team, app, "insight:read")+ result = maybe_create_provisioned_pat(self.user, self.team, app, "insight:read")if gate_on:assert result is not Nonepat = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()@@ -706,7 +724,7 @@ class TestCreateProvisionedPat(ProvisioningTestBase):])def test_label_prefix_resolution(self, _name, label_prefix, expected_label_template):- api_key = _maybe_create_provisioned_pat(+ api_key = maybe_create_provisioned_pat(self.user, self.team, self._minting_app(), "query:read", label_prefix=label_prefix)assert api_key is not None@@ -717,7 +735,7 @@ class TestCreateProvisionedPat(ProvisioningTestBase):def test_label_is_truncated_to_40_chars(self):self.team.name = "A" * 60self.team.save()- _maybe_create_provisioned_pat(+ maybe_create_provisioned_pat(self.user, self.team, self._minting_app(), "query:read", label_prefix="LongPartnerName")pat = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()@@ -732,5 +750,5 @@ class TestCreateProvisionedPat(ProvisioningTestBase):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 maybe_create_provisioned_pat(self.user, self.team, app, "query:read") is Noneassert PersonalAPIKey.objects.filter(user=self.user).count() == initial_countdiff --git a/ee/api/agentic_provisioning/test/test_rotate_credentials.py b/ee/api/agentic_provisioning/test/test_rotate_credentials.pyindex 5e88c432db17..00d831bba497 100644--- a/ee/api/agentic_provisioning/test/test_rotate_credentials.py+++ b/ee/api/agentic_provisioning/test/test_rotate_credentials.py@@ -141,7 +141,7 @@ class TestProvisioningRotateCredentials(ProvisioningTestBase):("non_string", 123),])- @patch("ee.api.agentic_provisioning.views._capture_provisioning_event")+ @patch("ee.api.agentic_provisioning.serializers.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_with_bearer(diff --git a/ee/api/agentic_provisioning/test/test_scope_hydration.py b/ee/api/agentic_provisioning/test/test_scope_hydration.pyindex 496365d77e0a..217a59960da1 100644--- a/ee/api/agentic_provisioning/test/test_scope_hydration.py+++ b/ee/api/agentic_provisioning/test/test_scope_hydration.py@@ -9,7 +9,7 @@ from posthog.models.team.team import Teamfrom posthog.models.team.team_provisioning_config import TeamProvisioningConfigfrom ee.api.agentic_provisioning.test.base import ProvisioningTestBase-from ee.api.agentic_provisioning.views import _compute_partner_scoped_teams+from ee.api.agentic_provisioning.tokens import compute_partner_scoped_teamsfrom ee.models.rbac.access_control import AccessControlTOKEN_URL = "/api/agentic/oauth/token"@@ -110,7 +110,7 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):assert restricted_team.id not in access_token.scoped_teamsdef test_issuance_rejected_when_no_accessible_teams(self):- # When the base team is gone or the user lost access, _compute_partner_scoped_teams+ # 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.self._enable_access_control_as_member()@@ -171,7 +171,7 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):assert newly_provisioned.id in refresh_token.scoped_teamsdef test_backfill_leaves_scope_unchanged_when_recomputed_scope_is_empty(self):- # When the user has lost access, _compute_partner_scoped_teams returns [].+ # When the user has lost access, compute_partner_scoped_teams returns [].# An empty scoped_teams is unrestricted under the standard permission check, so the# backfill must NOT overwrite a restricted token with [] — it leaves the existing# restriction intact and reports the token for re-authorization.@@ -197,4 +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.- assert _compute_partner_scoped_teams(None, self.user, self.team.id) == []+ assert compute_partner_scoped_teams(None, self.user, self.team.id) == []diff --git a/ee/api/agentic_provisioning/test/test_url_aliases.py b/ee/api/agentic_provisioning/test/test_url_aliases.pydeleted file mode 100644index 7bf521734137..000000000000--- a/ee/api/agentic_provisioning/test/test_url_aliases.py+++ /dev/null@@ -1,28 +0,0 @@-from parameterized import parameterized--from ee.api.agentic_provisioning.test.base import ProvisioningTestBase--RESOURCE_ID = "res_placeholder"--PROVISIONING_ALIAS_URLS = [- ("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"),- ("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"),- ("github_grants_create", "/api/provisioning/github/grants", "POST"),- ("github_integration", f"/api/provisioning/resources/{RESOURCE_ID}/github_integration", "POST"),- ("wizard_runs", f"/api/provisioning/resources/{RESOURCE_ID}/wizard_runs", "POST"),-]---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_api(url)- else:- 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.pyindex a0a67e0785cc..a9a87a6344c6 100644--- a/ee/api/agentic_provisioning/test/test_wizard_resource_actions.py+++ b/ee/api/agentic_provisioning/test/test_wizard_resource_actions.py@@ -14,7 +14,8 @@ from posthog.models.team.team import Teamfrom posthog.models.user import OnboardingSkippedReasonfrom posthog.models.user_integration import UserIntegration-from ee.api.agentic_provisioning import GITHUB_GRANT_CACHE_PREFIX, github_grants+from ee.api.agentic_provisioning import github_grants+from ee.api.agentic_provisioning.constants import GITHUB_GRANT_CACHE_PREFIXfrom ee.api.agentic_provisioning.test.base import ProvisioningTestBaseINSTALLATION_ID = "777"@@ -178,7 +179,7 @@ class TestWizardResourceActions(ProvisioningTestBase):with (patch.object(GitHubIntegration, "first_for_team_repository", return_value=MagicMock()),patch(- "ee.api.agentic_provisioning.views.tasks_facade.create_wizard_cloud_run", return_value=created+ "ee.api.agentic_provisioning.wizard.tasks_facade.create_wizard_cloud_run", return_value=created) as mock_create,):response = self._post_wizard_runs(self.team.id, {"repository": "octocat/hello-world", "branch": "main"})@@ -209,7 +210,7 @@ class TestWizardResourceActions(ProvisioningTestBase):created = MagicMock(task_id="task-uuid", latest_run=None)with (patch.object(GitHubIntegration, "first_for_team_repository", return_value=MagicMock()),- patch("ee.api.agentic_provisioning.views.tasks_facade.create_wizard_cloud_run", return_value=created),+ patch("ee.api.agentic_provisioning.wizard.tasks_facade.create_wizard_cloud_run", return_value=created),):first = self._post_wizard_runs(self.team.id, {"repository": "octocat/one"})second = self._post_wizard_runs(self.team.id, {"repository": "octocat/two"})@@ -225,7 +226,7 @@ class TestWizardResourceActions(ProvisioningTestBase):# so a grant for one installation can't report success for an unrelated owner/repo.with (patch.object(GitHubIntegration, "first_for_team_repository", return_value=None),- patch("ee.api.agentic_provisioning.views.tasks_facade.create_wizard_cloud_run") as mock_create,+ patch("ee.api.agentic_provisioning.wizard.tasks_facade.create_wizard_cloud_run") as mock_create,):response = self._post_wizard_runs(self.team.id, {"repository": "octocat/hello-world"})assert response.status_code == 400diff --git a/ee/api/agentic_provisioning/throttling.py b/ee/api/agentic_provisioning/throttling.pynew file mode 100644index 000000000000..22ebcaba9b18--- /dev/null+++ b/ee/api/agentic_provisioning/throttling.py@@ -0,0 +1,297 @@+"""Rate limiting for the agentic provisioning API.++Fixed-window cache counters over one set of keys, reachable two ways:++- :class:`~rest_framework.throttling.BaseThrottle` subclasses, declared in+ ``partner_throttle_classes`` on the view, for limits whose key DRF already+ has when it calls ``check_throttles``: the partner on ``request.auth``, a+ grant id in the URL, a client_id in the body. The base view runs these on+ top of ``DEFAULT_THROTTLE_CLASSES`` and renders rejections in the view's+ wire envelope rather than DRF's ``{"detail": ...}``.+- ``enforce_*`` helpers, for limits that can't be spent as early as+ ``check_throttles`` runs: the token endpoint learns the partner only by+ decoding an auth code or refresh token; account_requests and github_grants+ must clear the partner's capability *before* charging quota, so a partner+ that is refused outright keeps its budget; and the wizard budget is shared+ with the bundled account_requests wizard block, which runs outside any view+ dispatch.+- :class:`RegionProxyThrottle`, checked by the region proxy in ``dispatch``,+ before DRF has authenticated the caller and before either of the above can+ run at all.++A caller can burst up to 2x a limit across a window boundary (``limit`` at+:59:59 plus ``limit`` at :00:00); switch to a sliding window if that matters.+"""++from __future__ import annotations++import time+from typing import ClassVar, cast+from urllib.parse import urlparse++from django.core.cache import cache+from django.http import HttpRequest++import structlog+from rest_framework.request import Request+from rest_framework.throttling import BaseThrottle+from rest_framework.views import APIView++from posthog.api.oauth import cimd+from posthog.models.oauth import OAuthAccessToken, OAuthApplication+from posthog.rate_limit import IPThrottle++from ee.api.agentic_provisioning.analytics import capture_provisioning_event+from ee.api.agentic_provisioning.constants import (+ CIMD_DOMAIN_RATE_LIMIT_MAX,+ CIMD_DOMAIN_RATE_LIMIT_PREFIX,+ CIMD_DOMAIN_RATE_LIMIT_WINDOW_SECONDS,+ GITHUB_GRANT_POLL_RATE_LIMIT_MAX,+ GITHUB_GRANT_POLL_RATE_LIMIT_PREFIX,+ GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS,+ PARTNER_RATE_LIMIT_DEFAULTS,+ PARTNER_RATE_LIMIT_EVENT_NAMES,+ PARTNER_RATE_LIMIT_PREFIX,+ PARTNER_RATE_LIMIT_WINDOW_SECONDS,+ REGION_PROXY_RATE_LIMIT,+ WIZARD_RUN_USER_RATE_LIMIT_PREFIX,+ WIZARD_RUN_USER_RATE_LIMITS,+)+from ee.api.agentic_provisioning.exceptions import Envelope, ProvisioningError++logger = structlog.get_logger(__name__)+++def _fixed_window_count(cache_key: str, window_seconds: int) -> int:+ try:+ cache.add(cache_key, 0, timeout=window_seconds)+ return cache.incr(cache_key)+ except (ValueError, ConnectionError, TimeoutError) as e:+ logger.warning("provisioning_rate_limit_cache_error", cache_key=cache_key, error=str(e))+ # cache.add preserves any counter a concurrent request already initialized,+ # so a transient cache error doesn't reset the window for a caller at the limit.+ cache.add(cache_key, 1, timeout=window_seconds)+ return 1+++def _window_retry_after(window_seconds: int) -> int:+ return window_seconds - (int(time.time()) % window_seconds)+++def _count_partner_request(partner: OAuthApplication, endpoint: str) -> tuple[int, int] | None:+ """Count one request against the partner's per-endpoint fixed window.++ Returns ``(count, limit)``, or None when rate limiting is disabled for the+ endpoint (model override of 0). The model's override field takes precedence+ over the conservative default; the window is keyed on partner id ++ window-of-epoch.+ """+ if endpoint not in PARTNER_RATE_LIMIT_DEFAULTS:+ raise ValueError(f"Unknown rate limit endpoint: {endpoint}")++ override = getattr(partner, f"provisioning_rate_limit_{endpoint}", None)+ limit = override if override is not None else PARTNER_RATE_LIMIT_DEFAULTS[endpoint]++ if limit <= 0:+ return None++ window_index = int(time.time()) // PARTNER_RATE_LIMIT_WINDOW_SECONDS+ cache_key = f"{PARTNER_RATE_LIMIT_PREFIX}{endpoint}:{partner.id}:{window_index}"+ return _fixed_window_count(cache_key, PARTNER_RATE_LIMIT_WINDOW_SECONDS), limit+++def _capture_partner_rate_limited(partner: OAuthApplication, endpoint: str, limit: int, count: int) -> None:+ capture_provisioning_event(+ PARTNER_RATE_LIMIT_EVENT_NAMES[endpoint], "rate_limited", partner=partner, limit=limit, count=count+ )+++def enforce_partner_rate_limit(+ partner: OAuthApplication,+ endpoint: str,+ *,+ message: str | None = None,+ envelope: Envelope | None = None,+) -> None:+ """Mid-flow form of :class:`PartnerRateThrottle`, sharing its counters, for+ flows that identify the partner only after dispatch (token exchange,+ account_requests, wizard runs).++ Raises a ``rate_limited`` :class:`ProvisioningError` when the limit is exceeded.+ """+ counted = _count_partner_request(partner, endpoint)+ if counted is None:+ return+ count, limit = counted++ if count > limit:+ _capture_partner_rate_limited(partner, endpoint, limit, count)+ raise ProvisioningError(+ "rate_limited",+ message or f"Rate limit exceeded for this partner ({endpoint}). Try again later.",+ status=429,+ envelope=envelope or "typed",+ retry_after=_window_retry_after(PARTNER_RATE_LIMIT_WINDOW_SECONDS),+ )+++class PartnerRateThrottle(BaseThrottle):+ """Per-partner fixed-window limit as a DRF throttle, for views whose+ partner is on ``request.auth`` after authentication."""++ endpoint: ClassVar[str]+ error_message: ClassVar[str]++ def get_partner(self, request: Request) -> OAuthApplication | None:+ auth = request.auth+ if isinstance(auth, OAuthAccessToken):+ return auth.application+ if isinstance(auth, OAuthApplication):+ return auth+ return None++ def allow_request(self, request: Request, view: APIView) -> bool:+ partner = self.get_partner(request)+ if partner is None:+ return True+ counted = _count_partner_request(partner, self.endpoint)+ if counted is None:+ return True+ count, limit = counted+ if count > limit:+ _capture_partner_rate_limited(partner, self.endpoint, limit, count)+ return False+ return True++ def wait(self) -> int:+ return _window_retry_after(PARTNER_RATE_LIMIT_WINDOW_SECONDS)+++class ResourceCreatesThrottle(PartnerRateThrottle):+ endpoint = "resource_creates"+ error_message = "Rate limit exceeded for this partner. Try again later."++ def get_partner(self, request: Request) -> OAuthApplication | None:+ partner = super().get_partner(request)+ # provisioning_partner_type is the stable partner marker; apps without+ # it (plain OAuth apps whose tokens reach this endpoint) are not+ # subject to partner quotas.+ if partner is None or not partner.provisioning_partner_type:+ return None+ return partner+++class GrantPollThrottle(BaseThrottle):+ """Cap repository-listing polls per grant while the visitor installs the GitHub App."""++ error_message: ClassVar[str] = "Too many repository listing requests for this grant"++ def allow_request(self, request: Request, view: APIView) -> bool:+ grant_id = getattr(view, "kwargs", {}).get("grant_id", "")+ if not grant_id:+ return True+ # DRF checks throttles before the handler loads the grant and rejects a+ # partner mismatch, so the key carries the caller's partner too. Without it a+ # partner that learns another partner's grant id could spend the owner's+ # budget on it. A grant only ever belongs to one partner, so scoping the key+ # this way does not split any legitimate caller's quota.+ partner_id = getattr(request.auth, "id", "unauthenticated")+ window_index = int(time.time()) // GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS+ key = f"{GITHUB_GRANT_POLL_RATE_LIMIT_PREFIX}{partner_id}:{grant_id}:{window_index}"+ count = _fixed_window_count(key, GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS)+ return count <= GITHUB_GRANT_POLL_RATE_LIMIT_MAX++ def wait(self) -> int:+ return _window_retry_after(GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS)+++class RegionProxyThrottle(IPThrottle):+ """Per-IP cap on forwarding a request to the other region.++ The region proxy decides to forward inside ``dispatch``, so DRF hasn't run+ ``initial()`` yet: no authentication, none of the throttles above. Without this,+ an unauthenticated caller sending a mismatched region or an unknown token+ turns each request into an outbound cross-region call that holds a worker+ until the other region answers.+ """++ scope = "agentic_provisioning_region_proxy"+ rate = REGION_PROXY_RATE_LIMIT+ error_message: ClassVar[str] = "Too many cross-region requests. Try again later."++ def allow_http_request(self, request: HttpRequest) -> bool:+ """Count a request from the proxy's ``dispatch``, where DRF's ``Request`` doesn't exist yet.++ The key comes from the IP alone, so the plain Django request carries+ everything this throttle reads, and the view argument goes unused.+ """+ return self.allow_request(cast(Request, request), cast(APIView, None))+++def enforce_wizard_run_user_rate_limit(user_id: int, resource_id: str = "") -> None:+ """Cache-counter equivalent of the session cloud_run endpoint's per-user throttles;+ shared across the granular wizard_runs action and the bundled account_requests path+ so retries can't double-spend the budget."""+ for label, limit, window_seconds in WIZARD_RUN_USER_RATE_LIMITS:+ window_index = int(time.time()) // window_seconds+ key = f"{WIZARD_RUN_USER_RATE_LIMIT_PREFIX}{label}:{user_id}:{window_index}"+ count = _fixed_window_count(key, window_seconds)+ if count > limit:+ raise ProvisioningError(+ "rate_limited",+ "Too many wizard runs for this user. Try later.",+ status=429,+ envelope="status",+ resource_id=resource_id,+ retry_after=_window_retry_after(window_seconds),+ )+++class CIMDRegistrationThrottle(BaseThrottle):+ """Rate-limit first-time CIMD app registration by IP and domain to match /authorize protections.++ Declared on the account_requests view, so it runs before the handler+ identifies the partner — keeping this check first, where an unregistered+ client_id can't spend anything else's quota.+ """++ error_message: str = "Too many new client registrations. Try again later."++ def allow_request(self, request: Request, view: APIView) -> bool:+ client_id = request.data.get("client_id") or request.query_params.get("client_id")+ if not cimd.is_cimd_client_id(client_id):+ return True+ if OAuthApplication.objects.filter(cimd_metadata_url=client_id).exists():+ return True++ # Attribute access (not a from-import) so tests patching+ # posthog.api.oauth.cimd.CIMD_THROTTLE_CLASSES take effect here.+ for throttle_cls in cimd.CIMD_THROTTLE_CLASSES:+ throttle = throttle_cls()+ if not throttle.allow_request(request, view):+ logger.warning("cimd_rate_limited", client_id=client_id, scope=throttle.scope, wait=throttle.wait())+ return False++ return self._allow_domain(cast(str, client_id))++ def _allow_domain(self, client_id: str) -> bool:+ """Prevent a single domain from registering unlimited CIMD apps via different URL paths."""+ domain = urlparse(client_id).hostname+ if not domain:+ return True++ window_index = int(time.time()) // CIMD_DOMAIN_RATE_LIMIT_WINDOW_SECONDS+ key = f"{CIMD_DOMAIN_RATE_LIMIT_PREFIX}{domain}:{window_index}"+ count = _fixed_window_count(key, CIMD_DOMAIN_RATE_LIMIT_WINDOW_SECONDS)++ if count > CIMD_DOMAIN_RATE_LIMIT_MAX:+ logger.warning("cimd_domain_rate_limited", client_id=client_id, domain=domain, count=count)+ capture_provisioning_event("account_request", "cimd_domain_rate_limited", domain=domain, count=count)+ self.error_message = "Too many new client registrations from this domain. Try again later."+ return False+ return True++ def wait(self) -> None:+ # CIMD registration 429s carry no Retry-After: the window is shared+ # across clients, so a per-caller hint would be misleading.+ return Nonediff --git a/ee/api/agentic_provisioning/tokens.py b/ee/api/agentic_provisioning/tokens.pynew file mode 100644index 000000000000..f061bd2a08bc--- /dev/null+++ b/ee/api/agentic_provisioning/tokens.py@@ -0,0 +1,210 @@+"""Partner OAuth token scoping: which teams a provisioning token can reach.++A partner token carries its restriction in ``scoped_teams`` alone — the+standard OAuth permission check treats an empty ``scoped_teams`` as+unrestricted — so every mutation here is deliberate about never leaving a+token empty-scoped by accident.+"""++from __future__ import annotations++import uuid++from django.db import transaction+from django.utils import timezone++from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken+from posthog.models.team.team import Team+from posthog.models.team.team_provisioning_config import TeamProvisioningConfig+from posthog.models.user import User+from posthog.rbac.user_access_control import UserAccessControl+++def user_can_access_team(user: User, team: Team) -> bool:+ """Verify the user has at least member-level access to the team.++ Org membership alone does not prove access for advanced-permissions+ orgs that restrict individual teams. Without this check the agentic+ provisioning resolve flow could grant scoped access to a private team+ as long as the user had any team in the same org.+ """+ return UserAccessControl(user=user, team=team).check_access_level_for_object(team, required_level="member")+++def lock_application(application_id: uuid.UUID) -> OAuthApplication | None:+ """Row-lock the OAuthApplication so direct-mint serializes with revoke_application_sessions.++ The revoke updates this row first and holds the lock for its whole transaction before+ sweeping tokens, so a mint that takes the same lock is forced into one of two safe orders:+ it holds the lock and its new tokens land before the revoke's sweep (which then catches+ them), or the revoke committed first and the caller reads the now-visible+ `sessions_revoked_at` and rejects. Must be called inside `transaction.atomic()`.+ """+ return OAuthApplication.objects.select_for_update().filter(pk=application_id).first()+++def compute_partner_scoped_teams(+ application: OAuthApplication | None,+ user: User,+ base_team_id: int,+) -> list[int]:+ """Compute the durable scope for a partner OAuth token at issuance/refresh.++ Returns the set of every team where ``TeamProvisioningConfig.application ==+ application`` (i.e. this partner provisioned the team for this user, attributed+ at create time) AND the team lives in the same organization as ``base_team_id``+ AND the user still has team-level access. This is partner-agnostic, not+ Stripe-specific: ``stripe_project_id`` is the (legacily named) external project+ id every partner sets, always written alongside ``application`` in+ ``resolve_or_create_project_team``, so the ``application`` filter already+ implies a provisioned team. The organization filter pins the token to the+ authorization context:+ a partner with OAuth grants in multiple orgs for the same user must not be+ able to reach an org-B team via an org-A token just because the user happens+ to be a member of both.++ Returns ``[]`` when ``application`` is None (legacy refresh tokens with no+ app binding). A partner-unattributed token cannot be safely scoped, so it+ gets no teams and the holder must re-authorize. Falling through would let+ ``filter(application=None)`` match every TPC row with NULL application+ across every partner.++ Returns ``[]`` if ``base_team_id`` no longer resolves to a team the user+ can access; stale scope must not grant ongoing access after ACL revocation+ or org removal.+ """+ if application is None:+ return []++ try:+ base_team = Team.objects.select_related("organization").get(id=base_team_id)+ except Team.DoesNotExist:+ return []+ if not user_can_access_team(user, base_team):+ return []++ candidate_team_ids = set(+ TeamProvisioningConfig.objects.filter(+ application=application,+ team__organization_id=base_team.organization_id,+ ).values_list("team_id", flat=True)+ )+ candidate_team_ids.add(base_team_id)++ granted: set[int] = {base_team_id}+ other_teams = Team.objects.select_related("organization").filter(+ id__in=candidate_team_ids - {base_team_id},+ )+ for team in other_teams:+ if user_can_access_team(user, team):+ granted.add(team.id)++ # sorted() only for deterministic test assertions and log diffs; scope order is not a correctness requirement+ return sorted(granted)+++def ensure_team_in_token_scopes(+ access_token: OAuthAccessToken, scoped_teams: list[int], team: Team+) -> tuple[Team, list[int]]:+ if team.id in scoped_teams:+ return team, scoped_teams+ add_team_to_token_scopes(access_token, team.id)+ return team, [*scoped_teams, team.id]+++def add_team_to_token_scopes(access_token: OAuthAccessToken, team_id: int) -> None:+ with transaction.atomic():+ locked_access_token = OAuthAccessToken.objects.select_for_update().get(pk=access_token.pk)+ teams = list(locked_access_token.scoped_teams or [])+ if team_id not in teams:+ teams.append(team_id)+ locked_access_token.scoped_teams = teams+ locked_access_token.save(update_fields=["scoped_teams"])+ access_token.scoped_teams = teams++ refresh_tokens = OAuthRefreshToken.objects.select_for_update().filter(access_token=locked_access_token)+ for rt in refresh_tokens:+ rt_teams = list(rt.scoped_teams or [])+ if team_id not in rt_teams:+ rt_teams.append(team_id)+ rt.scoped_teams = rt_teams+ rt.save(update_fields=["scoped_teams"])+++def remove_team_from_token_scopes(access_token: OAuthAccessToken, team_id: int) -> None:+ """Strip ``team_id`` from every access/refresh token for this partner+user combo.++ Removing a resource has to revoke access for any *other* live token the same+ partner installation might be holding for the same user (e.g. a separate+ bearer issued via a prior OAuth grant that still has the team in scope).+ Touching only the calling ``access_token`` would let the partner continue+ operating on the team via a sibling token after `remove` returned, since+ operational endpoints accept any team currently in ``scoped_teams``.++ Atomic so a refresh token can never be left with the removed team still in+ scope while the access token has it stripped — otherwise the orchestrator+ could refresh and replay the removed team right back into scope.+ """+ application = access_token.application+ user = access_token.user+ if application is None or user is None:+ # Defensive: a provisioning bearer token without an app/user shouldn't+ # exist in practice, but fall back to the single-token strip if it does.+ application_filter: dict[str, object] = {"pk": access_token.pk}+ user_filter: dict[str, object] = {}+ else:+ application_filter = {"application": application, "user": user}+ user_filter = {"application": application, "user": user}++ with transaction.atomic():+ access_tokens = list(+ OAuthAccessToken.objects.select_for_update()+ .filter(scoped_teams__contains=[team_id], **application_filter)+ .order_by("pk")+ )+ for at in access_tokens:+ remaining = [t for t in (at.scoped_teams or []) if t != team_id]+ refresh_tokens = OAuthRefreshToken.objects.select_for_update().filter(access_token=at)+ if not remaining:+ refresh_tokens.update(access_token=None, revoked=timezone.now(), scoped_teams=[])+ at.delete()+ continue+ at.scoped_teams = remaining+ at.save(update_fields=["scoped_teams"])+ for rt in refresh_tokens:+ rt.scoped_teams = [t for t in (rt.scoped_teams or []) if t != team_id]+ rt.save(update_fields=["scoped_teams"])++ if user_filter:+ # Orphan refresh tokens (where the access token was already rotated+ # or deleted) still carry scope. Strip the team from those too.+ orphan_refresh = OAuthRefreshToken.objects.select_for_update().filter(+ scoped_teams__contains=[team_id],+ access_token__isnull=True,+ revoked__isnull=True,+ **user_filter,+ )+ for rt in orphan_refresh:+ rt.scoped_teams = [t for t in (rt.scoped_teams or []) if t != team_id]+ rt.save(update_fields=["scoped_teams"])+++def get_available_teams_for_user(user: User) -> list[dict[str, object]]:+ """Return the user's non-demo teams for inclusion in the token exchange response.++ Access-checked per team like the scoping paths: org membership alone would+ otherwise expose the names of teams an advanced-permissions org restricts,+ and list teams the partner can never be scoped to.+ """+ org_ids = list(user.organization_memberships.values_list("organization_id", flat=True))+ teams = Team.objects.filter(organization_id__in=org_ids, is_demo=False).select_related("organization")+ return [+ {+ "id": team.id,+ "name": team.name,+ "organization_id": str(team.organization_id),+ "organization_name": team.organization.name if team.organization else "",+ }+ for team in teams+ if user_can_access_team(user, team)+ ]diff --git a/ee/api/agentic_provisioning/urls.py b/ee/api/agentic_provisioning/urls.pynew file mode 100644index 000000000000..6cc34670e66e--- /dev/null+++ b/ee/api/agentic_provisioning/urls.py@@ -0,0 +1,73 @@+"""Routes for the agentic provisioning namespace, included from ``ee/urls.py``.++Partner endpoints live under ``/api/agentic/`` and are ``csrf_exempt`` (they+authenticate with a bearer token or PKCE, never a session cookie). The consent+and login routes are browser-facing and keep CSRF protection.+"""++from django.urls import path+from django.views.decorators.csrf import csrf_exempt++from ee.api.agentic_provisioning import views++urlpatterns = [+ path(+ "api/agentic/provisioning/account_requests",+ csrf_exempt(views.AccountRequestsView.as_view()),+ name="agentic_provisioning_account_requests",+ ),+ path(+ "api/agentic/oauth/token",+ csrf_exempt(views.OAuthTokenView.as_view()),+ name="agentic_provisioning_oauth_token",+ ),+ path(+ "api/agentic/provisioning/resources",+ csrf_exempt(views.ResourcesCreateView.as_view()),+ name="agentic_provisioning_resources_create",+ ),+ path(+ "api/agentic/provisioning/resources/<str:resource_id>/rotate_credentials",+ csrf_exempt(views.RotateCredentialsView.as_view()),+ name="agentic_provisioning_rotate_credentials",+ ),+ path(+ "api/agentic/provisioning/resources/<str:resource_id>/remove",+ csrf_exempt(views.ResourceRemoveView.as_view()),+ name="agentic_provisioning_resource_remove",+ ),+ path(+ "api/agentic/provisioning/resources/<str:resource_id>/github_integration",+ csrf_exempt(views.GitHubIntegrationView.as_view()),+ name="agentic_provisioning_github_integration",+ ),+ path(+ "api/agentic/provisioning/resources/<str:resource_id>/wizard_runs",+ csrf_exempt(views.WizardRunsView.as_view()),+ name="agentic_provisioning_wizard_runs",+ ),+ path(+ "api/agentic/provisioning/resources/<str:resource_id>",+ csrf_exempt(views.ResourceDetailView.as_view()),+ name="agentic_provisioning_resource_detail",+ ),+ path(+ "api/agentic/provisioning/deep_links",+ csrf_exempt(views.DeepLinksView.as_view()),+ name="agentic_provisioning_deep_links",+ ),+ path(+ "api/agentic/provisioning/github/grants",+ csrf_exempt(views.GitHubGrantsCreateView.as_view()),+ name="agentic_provisioning_github_grants_create",+ ),+ path(+ "api/agentic/provisioning/github/grants/<str:grant_id>/repositories",+ csrf_exempt(views.GitHubGrantRepositoriesView.as_view()),+ name="agentic_provisioning_github_grant_repositories",+ ),+ path("api/agentic/authorize", views.agentic_authorize, name="agentic_authorize"),+ path("api/agentic/authorize/pending/", views.AuthorizePendingView.as_view(), name="agentic_authorize_pending"),+ path("api/agentic/authorize/confirm/", views.AuthorizeConfirmView.as_view(), name="agentic_authorize_confirm"),+ path("agentic/login", views.agentic_login, name="agentic_login"),+]diff --git a/ee/api/agentic_provisioning/views.py b/ee/api/agentic_provisioning/views.pydeleted file mode 100644index 3d09034f9628..000000000000--- a/ee/api/agentic_provisioning/views.py+++ /dev/null@@ -1,2689 +0,0 @@-from __future__ import annotations--import re-import time-import uuid-import base64-import hashlib-import secrets-import unicodedata-from datetime import datetime, timedelta-from typing import Any, cast-from urllib.parse import urlencode--from django.conf import settings-from django.contrib.auth import login as auth_login-from django.contrib.auth.decorators import login_required-from django.core.cache import cache-from django.core.exceptions import ValidationError-from django.db import IntegrityError, transaction-from django.http import HttpResponseRedirect-from django.http.response import HttpResponseBase-from django.utils import timezone-from django.utils.http import url_has_allowed_host_and_scheme--import requests-import structlog-import posthoganalytics-from rest_framework.decorators import api_view, authentication_classes, permission_classes-from rest_framework.exceptions import (- AuthenticationFailed,- ValidationError as DRFValidationError,-)-from rest_framework.permissions import IsAuthenticated-from rest_framework.request import Request-from rest_framework.response import Response--from posthog.api.authentication import password_reset_token_generator-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-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-from posthog.models.team.team_provisioning_config import TeamProvisioningConfig-from posthog.models.user import OnboardingSkippedReason, User-from posthog.models.utils import (- generate_random_oauth_access_token,- generate_random_oauth_refresh_token,- generate_random_token_personal,- mask_key_value,-)-from posthog.rbac.user_access_control import UserAccessControl-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 . 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--logger = structlog.get_logger(__name__)--AUTH_CODE_TTL_SECONDS = 300-PENDING_AUTH_TTL_SECONDS = 600-DEEP_LINK_TTL_SECONDS = 600-DEEP_LINK_CACHE_PREFIX = "provisioning_deep_link:"-DEEP_LINK_MAX_PATH_LENGTH = 2000-# Control chars, whitespace, and backslashes never appear in a legitimate in-app path; they are the-# building blocks of header-injection and backslash-host open-redirect tricks, so reject them outright.-DEEP_LINK_DISALLOWED_PATH_CHARS = re.compile(r"[\x00-\x20\x7f-\x9f\\]")-DEEP_LINK_RATE_LIMIT_PREFIX = "agentic_login_rate:"-DEEP_LINK_RATE_LIMIT_MAX_ATTEMPTS = 10-DEEP_LINK_RATE_LIMIT_WINDOW_SECONDS = 300--CIMD_DOMAIN_RATE_LIMIT_PREFIX = "cimd_registration_domain_rate:"-CIMD_DOMAIN_RATE_LIMIT_MAX = 5-CIMD_DOMAIN_RATE_LIMIT_WINDOW_SECONDS = 3600--PARTNER_RATE_LIMIT_PREFIX = "provisioning_partner_rate:"-PARTNER_RATE_LIMIT_WINDOW_SECONDS = 3600-PARTNER_RATE_LIMIT_DEFAULTS: dict[str, int] = {- "account_requests": 10,- "token_exchanges": 20,- "resource_creates": 20,- "github_grants": 10,- "wizard_runs": 20,-}-PARTNER_RATE_LIMIT_EVENT_NAMES: dict[str, str] = {- "account_requests": "account_request",- "token_exchanges": "token_exchange",- "resource_creates": "resource_created",- "github_grants": "github_grant",- "wizard_runs": "wizard_run",-}--# Per-user wizard-run budget matching the session endpoint's limits (2/hour, 5/day), which-# can't run here — the partner path has no session user on the request. Unlike the session-# endpoint's throttles, which count only non-failed/non-cancelled runs from the DB, this is a-# plain request counter: failed runs still consume partner quota. Aligning it with the-# outcome-aware counting is a pending follow-up.-WIZARD_RUN_USER_RATE_LIMIT_PREFIX = "provisioning_wizard_run_user:"-WIZARD_RUN_USER_RATE_LIMITS: list[tuple[str, int, int]] = [- ("burst", 2, 3600),- ("day", 5, 86400),-]--# Repo-picker polling budget per grant (the website polls while the visitor installs the-# GitHub App in another tab). Keyed per grant, so one stuck visitor can't starve others.-GITHUB_GRANT_POLL_RATE_LIMIT_PREFIX = "provisioning_github_grant_poll:"-GITHUB_GRANT_POLL_RATE_LIMIT_MAX = 120-GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS = 3600--_SAFE_STATE_RE = re.compile(r"^[A-Za-z0-9_\-]{1,256}$")--# Mirrors PersonalAPIKey.label's CharField(max_length=40) - keep in sync if that ever changes.-PROVISIONED_PAT_LABEL_MAX_LENGTH = 40-# Cap partner-supplied prefix below the full label length so " - {team_name}" still-# survives the truncation. A 37-char prefix would otherwise consume the whole label-# and the team name would disappear from the truncated result.-PROVISIONED_PAT_LABEL_PREFIX_MAX_LENGTH = 25--ACCESS_TOKEN_EXPIRY_SECONDS = 365 * 24 * 3600-PARTNER_TOKEN_EXPIRY_SECONDS = 3600---# ----------------------------------------------------------------------------# POST /provisioning/account_requests — onboard a new or existing user and-# return either an auth code (new user) or a redirect URL (existing user)-# ------------------------------------------------------------------------------@api_view(["POST"])-@authentication_classes([])-@permission_classes([])-@region_proxy(strategy="body_region")-def account_requests(request: Request) -> Response:-- if error := _enforce_cimd_registration_throttle(request):- return error-- # --- Identify partner ---- auth = ProvisioningAuthentication()- partner = None- authenticated_user = None- try:- result = auth.authenticate(request)- if result:- authenticated_user, partner = result- except AuthenticationFailed:- return typed_error_response("unauthorized", "Authentication failed", status=401)-- if partner is None and auth.cimd_registration_pending:- return Response(- {"type": "registering", "retry_after": 5},- 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", "")- email = data.get("email")- if not email:- _capture_provisioning_event("account_request", "error", error_code="missing_email")- return typed_error_response("invalid_request", "email is required")-- scopes = data.get("scopes", [])- 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 {}-- if expires_at_str:- from django.utils.dateparse import parse_datetime-- expires_at = parse_datetime(expires_at_str)- if expires_at and expires_at < timezone.now():- _capture_provisioning_event("account_request", "error", error_code="expired")- return typed_error_response("expired", "Account request has expired")-- 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 error := _enforce_partner_rate_limit(partner, "account_requests"):- return error-- # PKCE: capture code_challenge for later verification- code_challenge = data.get("code_challenge", "")- code_challenge_method = data.get("code_challenge_method", "S256")- if code_challenge and code_challenge_method != "S256":- return typed_error_response("invalid_request", "Only S256 code_challenge_method is supported")- if code_challenge and (- len(code_challenge) < 43 or len(code_challenge) > 128 or not re.fullmatch(r"[A-Za-z0-9_\-]+", code_challenge)- ):- return typed_error_response(- "invalid_request", "code_challenge must be 43-128 characters using base64url charset"- )-- region = (configuration.get("region") or "US").upper()-- requested_team_id = configuration.get("team_id")- if requested_team_id is not None:- try:- requested_team_id = int(requested_team_id)- except (ValueError, TypeError):- return typed_error_response(- "invalid_request", "configuration.team_id must be an integer", request_id=request_id- )-- existing_user = User.objects.filter(email=email).first()-- if existing_user:- return _handle_existing_user(- request_id,- existing_user,- scopes,- region,- requested_team_id,- partner,- code_challenge,- code_challenge_method,- authenticated_user,- )-- return _handle_new_user(- request_id,- data,- email,- scopes,- region,- partner,- code_challenge,- code_challenge_method,- authenticated_user,- )---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:-- - 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- credential to mint a code for that account.- - PKCE callers are public: the partner is identified solely by a client_id that anyone- 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 == "bearer":- return authenticated_user is not None and authenticated_user.id == user.id- return False---def _handle_existing_user(- request_id: str,- user: User,- scopes: list[str],- region: str = "US",- team_id: int | None = None,- partner: OAuthApplication | None = None,- code_challenge: str = "",- code_challenge_method: str = "S256",- authenticated_user: User | None = None,-) -> Response:- # Account-takeover defense: a partner with skip_existing_user_consent=True may only mint- # silently for an *existing* account when the caller proved a prior trust relationship with- # that user (see _caller_proved_existing_trust). Without proof we fall through to consent,- # otherwise any caller could mint a code for an account they don't control. This holds- # regardless of whether the user has reviewed their credentials: an unreviewed account is- # still a pre-existing account, and the email may belong to a direct signup that never- # touched provisioning — silently linking it is the takeover.- silent_blocked = (- partner is not None- and partner.provisioning_skip_existing_user_consent- and not _caller_proved_existing_trust(partner, user, authenticated_user)- )-- if silent_blocked:- assert partner is not None # implied by silent_blocked- _capture_provisioning_event(- "account_request",- "silent_blocked_existing_user",- partner=partner,- )-- if partner and (not partner.provisioning_skip_existing_user_consent or silent_blocked):- if not code_challenge:- return typed_error_response(- "invalid_request", "code_challenge is required for public clients", request_id=request_id- )- if not scopes_within_ceiling(scopes, partner.ceiling_scopes):- return typed_error_response(- "invalid_scope",- "One or more requested scopes exceed the application's allowed scopes",- request_id=request_id,- )- return _require_user_consent(- request_id,- user,- scopes,- region,- partner,- code_challenge,- code_challenge_method,- )-- team = _resolve_team_for_existing_user(user, team_id)- if team is None:- _capture_provisioning_event("account_request", "error", error_code="team_resolution_failed")- return typed_error_response(- "team_resolution_failed", "Could not resolve a project for this user", request_id=request_id- )-- code = secrets.token_urlsafe(32)- cache.set(- f"{AUTH_CODE_CACHE_PREFIX}{code}",- {- "issued_at": timezone.now().isoformat(),- "user_id": user.id,- "org_id": str(team.organization_id),- "team_id": team.id,- "partner_id": str(partner.id) if partner else "",- "scopes": scopes,- "region": region,- "code_challenge": code_challenge,- "code_challenge_method": code_challenge_method,- },- timeout=AUTH_CODE_TTL_SECONDS,- )-- _capture_provisioning_event("account_request", "existing_user", partner=partner, region=region, team_id=team.id)-- return Response({"id": request_id, "type": "oauth", "oauth": {"code": code}})---def _require_user_consent(- request_id: str,- user: User,- scopes: list[str],- region: str,- partner: OAuthApplication,- code_challenge: str,- code_challenge_method: str,-) -> Response:- # Dedup: overwrite any prior pending state for same partner+email so- # retries don't leave multiple live consent URLs.- dedup_key = f"pending_auth_state:{partner.id}:{user.email}"- old_state = cache.get(dedup_key)- if old_state:- cache.delete(f"{PENDING_AUTH_CACHE_PREFIX}{old_state}")-- state = secrets.token_urlsafe(32)- cache.set(dedup_key, state, timeout=PENDING_AUTH_TTL_SECONDS)-- pending_key = f"{PENDING_AUTH_CACHE_PREFIX}{state}"- cache.set(- pending_key,- {- "email": user.email,- "scopes": scopes,- "partner_id": str(partner.id),- "partner_name": partner.name,- "region": region,- "code_challenge": code_challenge,- "code_challenge_method": code_challenge_method,- # We only reach consent because the partner could not skip it for this user, so- # the authorize step must require it too — never silently auto-approve this state.- "consent_required": True,- },- timeout=PENDING_AUTH_TTL_SECONDS,- )-- auth_url = _build_authorize_url(state, scopes, region=region)-- _capture_provisioning_event("account_request", "requires_auth", partner=partner, region=region)-- return Response(- {- "id": request_id,- "type": "requires_auth",- "requires_auth": {"url": auth_url},- }- )---def _resolve_team_for_existing_user(user: User, requested_team_id: int | None = None) -> Team | None:- """Pick a team for an existing user during email-based account linking.-- If requested_team_id is provided and the user has access, use it.- Otherwise auto-select: single non-demo team → use it, only demo teams →- create a new project, multiple teams → create a new project in the first org.- """- memberships = list(user.organization_memberships.select_related("organization").all())- if not memberships:- return None-- org_ids = [m.organization_id for m in memberships]-- if requested_team_id is not None:- try:- team = Team.objects.get(id=requested_team_id, is_demo=False)- except Team.DoesNotExist:- return None- if team.organization_id not in org_ids:- return None- return team-- non_demo_teams = list(Team.objects.filter(organization_id__in=org_ids, is_demo=False))-- if len(non_demo_teams) == 1:- return non_demo_teams[0]-- organization = memberships[0].organization- return Team.objects.create_with_data(initiating_user=user, organization=organization)---def _handle_new_user(- request_id: str,- data: dict,- email: str,- scopes: list[str],- region: str,- partner: OAuthApplication | None = None,- code_challenge: str = "",- code_challenge_method: str = "S256",- authenticated_user: User | None = None,-) -> Response:- name = data.get("name", "")- first_name = name.split(" ")[0] if name else ""-- configuration = data.get("configuration")- if not isinstance(configuration, dict):- configuration = {}-- partner_label = _partner_label(partner)- org_name = configuration.get("organization_name") or f"{partner_label} ({email})"-- try:- organization, team, user = User.objects.bootstrap(- organization_name=org_name,- email=email,- password=None,- first_name=first_name,- is_email_verified=False,- )- except IntegrityError:- existing = User.objects.filter(email=email).first()- if existing:- _capture_provisioning_event("account_request", "race_condition_existing_user", region=region)- return _handle_existing_user(- request_id,- existing,- scopes,- region,- None,- partner,- code_challenge,- code_challenge_method,- authenticated_user,- )- _capture_provisioning_event("account_request", "creation_failed", region=region)- return typed_error_response(- "account_creation_failed", "Failed to create account", request_id=request_id, status=500- )-- _capture_provisioning_event(- "account_request",- "new_user",- partner=partner,- region=region,- team_id=team.id,- )-- # Emit the standard signup event so provisioned accounts flow into the shared- # signup / activation / billing analyses, segmentable by client. Vercel does the- # same (ee/vercel/integration.py); the agentic path previously skipped it entirely.- report_user_signed_up(- user,- is_instance_first_user=False,- is_organization_first_user=True,- backend_processor="AgenticProvisioning",- social_provider=partner.name if partner else "",- user_analytics_metadata=user.get_analytics_metadata(),- org_analytics_metadata=organization.get_analytics_metadata(),- )-- # Optional drop-flow wizard block: link the GitHub grant to the bootstrap team and- # enqueue a cloud wizard run in the same call. A wizard failure never fails the- # request — the account exists, so the partner gets the account plus a structured- # wizard.error and retries via the granular resource actions. Partners that don't- # send a wizard block are unaffected (no wizard key, unchanged email behavior).- # Grants are region-local, so this request must hit the region that minted the grant.- wizard_config = configuration.get("wizard")- wizard_payload: dict[str, Any] | None = None- if isinstance(wizard_config, dict) and partner is not None:- wizard_payload = _process_wizard_block(partner=partner, user=user, team=team, wizard_config=wizard_config)-- # Queued after the wizard block so the "we're setting up your repo" email only- # sends once the run actually exists; the email still goes out (without the- # repository paragraph) when the wizard block failed, since the account is real.- try:- reset_token = password_reset_token_generator.make_token(user)- wizard_repository: str | None = None- if wizard_payload is not None and "error" not in wizard_payload and isinstance(wizard_config, dict):- wizard_repository = str(wizard_config.get("repository"))- if wizard_repository:- send_provisioning_welcome.delay(user.id, reset_token, partner_label, repository=wizard_repository)- else:- send_provisioning_welcome.delay(user.id, reset_token, partner_label)- except Exception:- capture_exception(additional_properties={"user_id": user.id, "step": "provisioning_welcome_email"})-- code = secrets.token_urlsafe(32)- cache_key = f"{AUTH_CODE_CACHE_PREFIX}{code}"- cache.set(- cache_key,- {- "issued_at": timezone.now().isoformat(),- "user_id": user.id,- "org_id": str(organization.id),- "team_id": team.id,- "partner_id": str(partner.id) if partner else "",- "scopes": scopes,- "region": region,- "code_challenge": code_challenge,- "code_challenge_method": code_challenge_method,- },- timeout=AUTH_CODE_TTL_SECONDS,- )-- response_body: dict[str, Any] = {"id": request_id, "type": "oauth", "oauth": {"code": code}}- if wizard_payload is not None:- response_body["wizard"] = wizard_payload- return Response(response_body)---def _process_wizard_block(*, partner: OAuthApplication, user: User, team: Team, wizard_config: dict) -> dict[str, Any]:- """Run the bundled drop flow for a freshly bootstrapped account: link the GitHub- grant to the team, then enqueue the cloud wizard run.-- Never raises — returns either the run payload ({task_id, run_id, status}) or- {"error": {code, message}} for the partner to branch on and retry granularly.- """- try:- grant_id = wizard_config.get("grant_id")- installation_id = wizard_config.get("installation_id")- repository = wizard_config.get("repository")- if not grant_id or not installation_id or not repository:- return {- "error": {- "code": "invalid_request",- "message": "wizard requires grant_id, installation_id and repository",- }- }-- error, _integration, _already_linked = _link_github_grant_to_team(- partner=partner,- user=user,- team=team,- grant_id=str(grant_id),- installation_id=str(installation_id),- )- if error is not None:- return {"error": error.data.get("error", {"code": "invalid_request", "message": "GitHub link failed"})}-- error, run_payload = _create_wizard_run(- partner=partner,- user_id=user.id,- team=team,- repository=str(repository),- branch=str(wizard_config.get("branch") or "") or None,- )- if error is not None:- return {- "error": error.data.get(- "error", {"code": "run_creation_failed", "message": "Failed to start the wizard run"}- )- }- assert run_payload is not None- return dict(run_payload)- except Exception:- capture_exception(additional_properties={"team_id": team.id, "step": "account_requests_wizard_block"})- return {"error": {"code": "run_creation_failed", "message": "Unexpected error starting the wizard run"}}---def _build_authorize_url(confirmation_secret: str, scopes: list[str], region: str = "") -> str:- base = _region_to_host(region).rstrip("/") if region else settings.SITE_URL.rstrip("/")- params = urlencode({"state": confirmation_secret, "scope": " ".join(scopes)})- return f"{base}/api/agentic/authorize?{params}"---# ----------------------------------------------------------------------------# POST /provisioning/github/grants-# GET /provisioning/github/grants/:grant_id/repositories-# GitHub grants for drop-style partner flows: the partner forwards a GitHub OAuth-# code, we exchange and hold the user tokens server-side, and the partner only-# ever sees an opaque grant_id. No region proxy: grants are region-local (the-# partner must call the region that minted the grant).-# ------------------------------------------------------------------------------def _authenticate_provisioning_partner(request: Request) -> tuple[Response | None, OAuthApplication | None]:- """Identify a provisioning partner, requiring proof-bearing auth.- Returns (error_response, 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.- """- auth = ProvisioningAuthentication()- try:- result = auth.authenticate(request)- except AuthenticationFailed:- result = None- partner = result[1] if result else None- if partner is None:- return (- typed_error_response("unauthorized", "Authentication required", status=401),- None,- )- if partner.provisioning_auth_method != "bearer":- return (- typed_error_response("forbidden", "This endpoint requires a confidential partner", status=403),- None,- )- return None, partner---@api_view(["POST"])-@authentication_classes([])-@permission_classes([])-def github_grants_create(request: Request) -> Response:-- auth_error, partner = _authenticate_provisioning_partner(request)- if auth_error or partner is None:- return auth_error or Response(status=401)-- if not partner.provisioning_can_create_accounts:- _capture_provisioning_event("github_grant", "error", partner=partner, error_code="account_creation_disabled")- return typed_error_response("forbidden", "Account creation is not enabled for this partner", status=403)-- if error := _enforce_partner_rate_limit(partner, "github_grants"):- return error-- code = request.data.get("code")- redirect_uri = request.data.get("redirect_uri") or None- if not code or not isinstance(code, str):- _capture_provisioning_event("github_grant", "error", partner=partner, error_code="missing_code")- return typed_error_response("invalid_request", "code is required")-- try:- authorization = GitHubIntegration.github_user_from_code(code, redirect_uri=redirect_uri)- except requests.RequestException:- # Network failure or a non-JSON GitHub error body raising through .json() — retryable,- # distinct from a clean "bad code" exchange failure (which returns None below).- _capture_provisioning_event("github_grant", "error", partner=partner, error_code="github_unavailable")- return typed_error_response("github_unavailable", "GitHub request failed", status=502)- if authorization is None:- _capture_provisioning_event("github_grant", "error", partner=partner, error_code="github_exchange_failed")- return typed_error_response("github_exchange_failed", "Could not exchange the GitHub OAuth code", status=502)-- # A user with no verified email gets a grant with email=null — the partner- # collects an email inline instead. Only an access refusal (App permission- # misconfiguration) hard-fails, so it can't masquerade as that user state.- try:- email = github_grants.fetch_primary_email(authorization.access_token)- except github_grants.GitHubEmailAccessDenied:- _capture_provisioning_event("github_grant", "error", partner=partner, error_code="email_unavailable")- return typed_error_response("email_unavailable", "GitHub denied reading the user's email addresses", status=502)- except requests.RequestException:- _capture_provisioning_event("github_grant", "error", partner=partner, error_code="github_unavailable")- return typed_error_response("github_unavailable", "GitHub request failed", status=502)-- grant = github_grants.create_grant(partner, authorization, email)- _capture_provisioning_event("github_grant", "created", partner=partner, gh_login=grant.gh_login)- return Response(- {- "grant_id": grant.grant_id,- "gh_login": grant.gh_login,- "email": grant.email,- "expires_in": github_grants.GITHUB_GRANT_TTL_SECONDS,- }- )---def _enforce_grant_poll_rate_limit(grant_id: str) -> Response | None:- window_index = int(time.time()) // GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS- key = f"{GITHUB_GRANT_POLL_RATE_LIMIT_PREFIX}{grant_id}:{window_index}"- try:- cache.add(key, 0, timeout=GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS)- count = cache.incr(key)- except (ValueError, ConnectionError, TimeoutError):- count = 1- if count > GITHUB_GRANT_POLL_RATE_LIMIT_MAX:- response = typed_error_response(- "rate_limited", "Too many repository listing requests for this grant", status=429- )- response["Retry-After"] = str(- GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS- - (int(time.time()) % GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS)- )- return response- return None---@api_view(["GET"])-@authentication_classes([])-@permission_classes([])-def github_grant_repositories(request: Request, grant_id: str) -> Response:-- auth_error, partner = _authenticate_provisioning_partner(request)- if auth_error or partner is None:- return auth_error or Response(status=401)-- grant = github_grants.load_grant(grant_id, partner)- if grant is None:- return typed_error_response("grant_not_found", "Grant not found or expired", status=404)-- if error := _enforce_grant_poll_rate_limit(grant_id):- return error-- try:- listing = github_grants.list_installations_and_repositories(grant.access_token)- except requests.RequestException:- _capture_provisioning_event("github_grant", "listing_failed", partner=partner)- return typed_error_response("github_unavailable", "GitHub request failed", status=502)-- return Response({"gh_login": grant.gh_login, **listing})---# ----------------------------------------------------------------------------# GET /api/agentic/authorize-# Interactive OAuth consent for existing users (APP 0.1d §A1 "requires_auth").-# The orchestrator redirects the user here; on approval we issue an auth code-# and redirect back to the orchestrator callback.-# ------------------------------------------------------------------------------@login_required-def agentic_authorize(request: Any) -> HttpResponseBase:- state = request.GET.get("state", "")- if not state or not _SAFE_STATE_RE.match(state):- _capture_provisioning_event("authorize", "missing_state")- return HttpResponseRedirect(f"{settings.SITE_URL}?error=missing_state")-- pending_key = f"{PENDING_AUTH_CACHE_PREFIX}{state}"- pending = cache.get(pending_key)- if pending is None:- _capture_provisioning_event("authorize", "expired_state")- return HttpResponseRedirect(f"{settings.SITE_URL}?error=expired_or_invalid_state")-- if request.user.email != pending["email"]:- _capture_provisioning_event("authorize", "email_mismatch")- mismatch_params = urlencode(- {- "expected_email": pending["email"],- "current_email": request.user.email,- "partner_name": pending.get("partner_name", ""),- "state": state,- }- )- return HttpResponseRedirect(f"{settings.SITE_URL.rstrip('/')}/agentic/account-mismatch?{mismatch_params}")-- user = request.user- memberships = list(user.organization_memberships.select_related("organization").all())- if not memberships:- _capture_provisioning_event("authorize", "no_organization")- return HttpResponseRedirect(f"{settings.SITE_URL}?error=no_organization")-- org_ids = [m.organization_id for m in memberships]- non_demo_teams = list(Team.objects.filter(organization_id__in=org_ids, is_demo=False))-- if not non_demo_teams:- organization = memberships[0].organization- team = Team.objects.create_with_data(initiating_user=user, organization=organization)- non_demo_teams = [team]- _capture_provisioning_event("authorize", "auto_created_project", team_id=team.id)-- # Re-check partner is still active (could have been deactivated since account_requests)- partner_id = pending.get("partner_id", "")- is_trusted_partner = False- if partner_id:- try:- partner_app = OAuthApplication.objects.get(id=partner_id)- if not partner_app.provisioning_active:- cache.delete(pending_key)- _capture_provisioning_event("authorize", "partner_deactivated")- return HttpResponseRedirect(f"{settings.SITE_URL}?error=partner_deactivated")- # Fail closed: a partner-identified pending state missing the flag (e.g. created by an- # older pod mid-deploy) must still require consent, never silently auto-approve.- is_trusted_partner = partner_app.provisioning_skip_existing_user_consent and not pending.get(- "consent_required", True- )- except OAuthApplication.DoesNotExist:- pass-- if is_trusted_partner and len(memberships) == 1 and len(non_demo_teams) == 1:- 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}",- {- "issued_at": timezone.now().isoformat(),- "user_id": user.id,- "org_id": str(organization.id),- "team_id": team.id,- "partner_id": pending.get("partner_id", ""),- "scopes": pending.get("scopes", []),- "region": pending.get("region", "US"),- "code_challenge": pending.get("code_challenge", ""),- "code_challenge_method": pending.get("code_challenge_method", "S256"),- },- timeout=AUTH_CODE_TTL_SECONDS,- )- cache.delete(pending_key)-- _capture_provisioning_event("authorize", "auto_redirect", team_id=team.id)-- sanitized_state = re.sub(r"[^A-Za-z0-9_\-]", "", state)- params = urlencode({"code": code, "state": sanitized_state})- return HttpResponseRedirect(f"{callback_url}?{params}")-- _capture_provisioning_event("authorize", "selection_required")-- base = settings.SITE_URL.rstrip("/")- sanitized_state = re.sub(r"[^A-Za-z0-9_\-]", "", state)- params = urlencode({"state": sanitized_state})- return HttpResponseRedirect(f"{base}/agentic/authorize?{params}")---@api_view(["GET"])-@permission_classes([IsAuthenticated])-def agentic_authorize_pending(request: Request) -> Response:- """Return server-verified partner name and scopes for a pending auth state.-- The frontend calls this instead of reading from URL params, preventing- an attacker from spoofing the partner identity on the consent page.- """- state = request.query_params.get("state", "")- if not state or not _SAFE_STATE_RE.match(state):- return Response({"error": "invalid_state"}, status=400)-- pending = cache.get(f"{PENDING_AUTH_CACHE_PREFIX}{state}")- if pending is None:- return Response({"error": "expired_or_invalid_state"}, status=400)-- user = cast(User, request.user)- if user.email != pending["email"]:- return Response({"error": "email_mismatch"}, status=403)-- return Response(- {- "partner_name": pending.get("partner_name", "the requesting app"),- "scopes": pending.get("scopes", []),- }- )---@api_view(["POST"])-@permission_classes([IsAuthenticated])-def agentic_authorize_confirm(request: Request) -> Response:- state = request.data.get("state", "")- team_id = request.data.get("team_id")-- if not state or team_id is None or not _SAFE_STATE_RE.match(state):- _capture_provisioning_event("authorize_confirm", "invalid_request")- return Response({"error": "state and team_id are required"}, status=400)-- pending_key = f"{PENDING_AUTH_CACHE_PREFIX}{state}"- pending = cache.get(pending_key)- if pending is None:- _capture_provisioning_event("authorize_confirm", "expired_state")- return Response({"error": "expired_or_invalid_state"}, status=400)-- user = cast(User, request.user)-- if user.email != pending["email"]:- _capture_provisioning_event("authorize_confirm", "email_mismatch")- return Response({"error": "email_mismatch"}, status=403)-- try:- team = Team.objects.get(id=team_id, is_demo=False)- except Team.DoesNotExist:- _capture_provisioning_event("authorize_confirm", "team_not_found", team_id=team_id)- return Response({"error": "team_not_found"}, status=404)-- if not user.organization_memberships.filter(organization_id=team.organization_id).exists():- _capture_provisioning_event("authorize_confirm", "team_not_accessible", team_id=team_id)- return Response({"error": "team_not_accessible"}, status=403)-- confirm_partner_id = pending.get("partner_id", "")- confirm_partner: OAuthApplication | None = None- if confirm_partner_id:- try:- confirm_partner = OAuthApplication.objects.get(id=confirm_partner_id)- if not confirm_partner.provisioning_active:- cache.delete(pending_key)- _capture_provisioning_event("authorize_confirm", "partner_deactivated", partner=confirm_partner)- return Response({"error": "partner_deactivated"}, status=403)- 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.- cache.set(- f"{AUTH_CODE_CACHE_PREFIX}{code}",- {- "issued_at": timezone.now().isoformat(),- "user_id": user.id,- "org_id": str(team.organization_id),- "team_id": team.id,- "partner_id": pending.get("partner_id", ""),- "scopes": pending.get("scopes", []),- "region": pending.get("region", "US"),- "code_challenge": pending.get("code_challenge", ""),- "code_challenge_method": pending.get("code_challenge_method", "S256"),- },- timeout=AUTH_CODE_TTL_SECONDS,- )- cache.delete(pending_key)-- sanitized_state = re.sub(r"[^A-Za-z0-9_\-]", "", state)- params = urlencode({"code": code, "state": sanitized_state})- redirect_url = f"{callback_url}?{params}"-- _capture_provisioning_event("authorize_confirm", "success", partner=confirm_partner, team_id=team_id)-- return Response({"redirect_url": redirect_url})---# ----------------------------------------------------------------------------# POST /oauth/token — exchange auth codes or refresh tokens for access tokens-# ------------------------------------------------------------------------------@api_view(["POST"])-@authentication_classes([])-@permission_classes([])-@region_proxy(strategy="token_lookup")-def oauth_token(request: Request) -> Response:- grant_type = request.data.get("grant_type", "")-- if grant_type == "authorization_code":- return _exchange_authorization_code(request)- elif grant_type == "refresh_token":- return _exchange_refresh_token(request)- else:- _capture_provisioning_event("token_exchange", "unsupported_grant_type", grant_type=grant_type)- return Response(- {"error": "unsupported_grant_type", "error_description": f"Unsupported grant_type: {grant_type}"},- status=400,- )---def _lock_application(application_id: uuid.UUID) -> OAuthApplication | None:- """Row-lock the OAuthApplication so direct-mint serializes with revoke_application_sessions.-- The revoke updates this row first and holds the lock for its whole transaction before- sweeping tokens, so a mint that takes the same lock is forced into one of two safe orders:- it holds the lock and its new tokens land before the revoke's sweep (which then catches- them), or the revoke committed first and the caller reads the now-visible- `sessions_revoked_at` and rejects. Must be called inside `transaction.atomic()`.- """- return OAuthApplication.objects.select_for_update().filter(pk=application_id).first()---def _exchange_authorization_code(request: Request) -> Response:- code = request.data.get("code", "")- if not code:- _capture_provisioning_event("token_exchange", "missing_code", grant_type="authorization_code")- return Response({"error": "invalid_request", "error_description": "code is required"}, status=400)-- cache_key = f"{AUTH_CODE_CACHE_PREFIX}{code}"- code_data = cache.get(cache_key)- if code_data is None:- _capture_provisioning_event("token_exchange", "invalid_code", grant_type="authorization_code")- return Response(- {"error": "invalid_grant", "error_description": "Invalid or expired authorization code"}, status=400- )-- # 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", "")- 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)-- 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- # tradeoff (rate-limited client loses the code) is acceptable — clients can- # 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:- oauth_app = OAuthApplication.objects.get(id=partner_id)- except (OAuthApplication.DoesNotExist, ValidationError, ValueError):- 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"]- scopes = code_data.get("scopes", [])-- try:- user = User.objects.get(id=user_id)- except User.DoesNotExist:- _capture_provisioning_event("token_exchange", "user_not_found", grant_type="authorization_code")- return Response({"error": "invalid_grant", "error_description": "User not found"}, status=400)-- # Lock the app row before reading the revoke stamp and minting, so this serializes- # with revoke_application_sessions (see _lock_application). Provisioning auth codes- # live in the cache, not OAuthGrant, so the revoke's sweep can't reach them — the- # `issued_at` carried on the code is what a revoke is checked against. Codes minted- # 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)- sessions_revoked_at = locked_app.sessions_revoked_at if locked_app else None- if sessions_revoked_at is not None:- issued_at_raw = code_data.get("issued_at")- issued_at = datetime.fromisoformat(issued_at_raw) if issued_at_raw else None- if issued_at is None or issued_at < sessions_revoked_at:- _capture_provisioning_event("token_exchange", "sessions_revoked", grant_type="authorization_code")- return Response(- {"error": "invalid_grant", "error_description": "Application sessions were revoked; re-authorize."},- status=400,- )-- # Direct-mint bypasses /authorize's OAuthValidator, so the per-app scope- # ceiling has to be enforced here before the token is created by hand.- 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(- {- "error": "invalid_scope",- "error_description": "Requested scopes exceed the application's allowed scopes",- },- status=400,- )- scope_str = " ".join(requested_scopes)-- token_expiry = (- PARTNER_TOKEN_EXPIRY_SECONDS- if oauth_app and oauth_app.is_provisioning_partner- else ACCESS_TOKEN_EXPIRY_SECONDS- )-- scoped_teams = _compute_partner_scoped_teams(oauth_app, user, team_id)- # A partner token carries its restriction in scoped_teams alone, and the standard- # OAuth permission check treats an empty scoped_teams as unrestricted (permissions.py).- # _compute_partner_scoped_teams returns [] exactly when the base team is gone or the- # user lost access, so minting here would hand out a project-unrestricted bearer.- # Fail closed and force re-authorization.- if not scoped_teams:- _capture_provisioning_event("token_exchange", "no_accessible_teams", grant_type="authorization_code")- return Response(- {- "error": "invalid_grant",- "error_description": "No accessible teams for this authorization; re-authorize.",- },- status=400,- )-- access_token_value = generate_random_oauth_access_token(None)- access_token = OAuthAccessToken.objects.create(- application=oauth_app,- token=access_token_value,- user=user,- expires=timezone.now() + timedelta(seconds=token_expiry),- scope=scope_str,- scoped_teams=scoped_teams,- )-- refresh_token_value = generate_random_oauth_refresh_token(None)- OAuthRefreshToken.objects.create(- application=oauth_app,- token=refresh_token_value,- user=user,- access_token=access_token,- scoped_teams=scoped_teams,- )-- account_id = str(code_data.get("org_id", ""))-- available_teams = _get_available_teams_for_user(user)-- _capture_provisioning_event(- "token_exchange",- "success",- partner=oauth_app,- grant_type="authorization_code",- team_id=team_id,- user_id=user.id,- granted_team_count=len(scoped_teams),- )-- return Response(- {- "token_type": "bearer",- "access_token": access_token_value,- "refresh_token": refresh_token_value,- "expires_in": token_expiry,- "account": {- "id": account_id,- "payment_credentials": "orchestrator",- "available_teams": available_teams,- },- }- )---def _exchange_refresh_token(request: Request) -> Response:- refresh_token_value = request.data.get("refresh_token", "")- if not refresh_token_value:- _capture_provisioning_event("token_exchange", "missing_refresh_token", grant_type="refresh_token")- return Response({"error": "invalid_request", "error_description": "refresh_token is required"}, status=400)-- # Lock the app row first (revoke_application_sessions locks it before sweeping tokens),- # then re-read the refresh token under that lock, so the rotate-and-mint serializes with- # the revoke: either we hold the lock and our new tokens land before its sweep, or it- # committed first and we see the token already revoked (or the stamp) and reject. Looking- # the app up by id first (without locking the token row) keeps the lock order app→token,- # matching the revoke, so the two can't deadlock.- with transaction.atomic():- application_id = (- OAuthRefreshToken.objects.filter(token=refresh_token_value, revoked__isnull=True)- .values_list("application_id", flat=True)- .first()- )- locked_app = _lock_application(application_id) if application_id else None- old_refresh = (- OAuthRefreshToken.objects.select_related("user", "access_token")- .filter(token=refresh_token_value, revoked__isnull=True)- .first()- )- if old_refresh is None:- _capture_provisioning_event("token_exchange", "invalid_refresh_token", grant_type="refresh_token")- return Response(- {"error": "invalid_grant", "error_description": "Invalid or revoked refresh token"}, status=400- )-- oauth_app = locked_app- user = old_refresh.user- old_scoped_teams = old_refresh.scoped_teams or []- # base_team_id at refresh: the first team in the prior scope. The consent team- # (authorized at grant time) has the lowest id and sorts first at issuance;- # partner-provisioned teams are always created later, so they take higher ids- # and are only ever appended after it. [0] is therefore the consent team. This- # ordering is load-bearing: _compute_partner_scoped_teams re-adds the consent- # team only when it is base_team_id (it has no TeamProvisioningConfig for this- # app), so a lower-id provisioned team becoming [0] would silently drop the- # consent team from the refreshed scope. If the prior token was somehow empty-- # scoped, fall back to zero so the helper short-circuits without claiming a team.- base_team_id = old_scoped_teams[0] if old_scoped_teams else 0- scoped_teams = _compute_partner_scoped_teams(oauth_app, user, base_team_id)- # Same fail-closed rule as issuance: an empty scoped_teams is unrestricted under the- # standard permission check, so a refresh whose base team vanished or whose access was- # revoked must re-authorize rather than rotate into a project-unrestricted token.- # Checked before any token row is mutated so a rejected refresh never revokes the- # caller's only token.- if not scoped_teams:- _capture_provisioning_event("token_exchange", "no_accessible_teams", grant_type="refresh_token")- return Response(- {"error": "invalid_grant", "error_description": "No accessible teams for this token; re-authorize."},- status=400,- )- # 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:- _capture_provisioning_event("token_exchange", "sessions_revoked", grant_type="refresh_token")- return Response(- {"error": "invalid_grant", "error_description": "Application sessions were revoked; re-authorize."},- status=400,- )-- # Cap the refreshed scope at the app's current ceiling before touching any- # token rows — a since-tightened ceiling must drop the removed scopes, and a- # token now fully outside the ceiling has to re-authorize rather than refresh.- # Done up front so a rejected refresh never revokes the caller's only token.- app_scopes = oauth_app.ceiling_scopes if oauth_app else []- narrowed_scopes = narrow_scopes_to_ceiling(old_scope.split(), app_scopes)- if narrowed_scopes is None:- _capture_provisioning_event("token_exchange", "scope_ceiling_exceeded", grant_type="refresh_token")- return Response(- {- "error": "invalid_grant",- "error_description": "Token scopes are no longer within the application's allowed scopes; re-authorize.",- },- status=400,- )- new_scope = " ".join(narrowed_scopes)-- # provisioning_partner_type is a stable marker set at partner registration;- # checking it instead of is_provisioning_partner prevents a bypass when an admin- # clears provisioning_auth_method to disable a partner without revoking tokens.- if oauth_app and oauth_app.provisioning_partner_type:- if error := _enforce_partner_rate_limit(oauth_app, "token_exchanges"):- return error-- old_access = old_refresh.access_token- old_refresh.access_token = None- old_refresh.revoked = timezone.now()- old_refresh.save(update_fields=["access_token", "revoked"])-- if old_access:- old_access.delete()-- token_expiry = (- PARTNER_TOKEN_EXPIRY_SECONDS- if oauth_app and oauth_app.is_provisioning_partner- else ACCESS_TOKEN_EXPIRY_SECONDS- )-- new_access_value = generate_random_oauth_access_token(None)- new_access = OAuthAccessToken.objects.create(- application=oauth_app,- token=new_access_value,- user=user,- expires=timezone.now() + timedelta(seconds=token_expiry),- scope=new_scope,- scoped_teams=scoped_teams,- )-- new_refresh_value = generate_random_oauth_refresh_token(None)- OAuthRefreshToken.objects.create(- application=oauth_app,- token=new_refresh_value,- user=user,- access_token=new_access,- scoped_teams=scoped_teams,- )-- _capture_provisioning_event(- "token_exchange",- "success",- partner=oauth_app,- grant_type="refresh_token",- team_id=base_team_id,- user_id=user.id if user else None,- granted_team_count=len(scoped_teams),- )-- return Response(- {- "token_type": "bearer",- "access_token": new_access_value,- "refresh_token": new_refresh_value,- "expires_in": token_expiry,- }- )---class _InvalidLabelPrefixError(Exception):- """Raised when a partner-supplied label_prefix fails validation."""---def _extract_label_prefix(request: Request) -> str | None:- """Extract and validate the optional ``label_prefix`` from the request body.-- Returns ``None`` when the field is absent or empty (caller creates an- unprefixed label). Raises ``_InvalidLabelPrefixError`` when the field is- present but malformed (wrong type, too long, or contains control or format- characters that would render badly in the user's PAT list).- """- raw = request.data.get("label_prefix")- if raw is None:- return None- if not isinstance(raw, str):- raise _InvalidLabelPrefixError("label_prefix must be a string")-- stripped = raw.strip()- if not stripped:- return None-- if len(stripped) > PROVISIONED_PAT_LABEL_PREFIX_MAX_LENGTH:- raise _InvalidLabelPrefixError(- f"label_prefix must be {PROVISIONED_PAT_LABEL_PREFIX_MAX_LENGTH} characters or fewer"- )-- # Reject Unicode control (Cc), format (Cf), and line/paragraph separators (Zl/Zp).- # Cf is the important one - it includes bidi overrides (U+202A-U+202E) and- # isolates (U+2066-U+2069), which a partner could use to re-order surrounding- # text in the user's settings page (Trojan Source class). Cc covers C0 + DEL.- if any(unicodedata.category(c) in {"Cc", "Cf", "Zl", "Zp"} for c in stripped):- raise _InvalidLabelPrefixError("label_prefix must not contain control or format characters")-- return stripped---def _maybe_create_provisioned_pat(- user: User, team: Team, app: OAuthApplication | None, granted_scope: str | None, label_prefix: str | None = None-) -> str | None:- """Create a Personal API Key for a provisioned user and return the raw key value.-- Gated by ``app.provisioning_issues_personal_api_key``: off by default, so most- apps never receive a provisioned PAT (the OAuth token is the credential).- Returns ``None`` when the gate is off, and the caller omits ``personal_api_key``- from the response entirely.-- When enabled (the grandfathered legacy Stripe app), the key carries the granted- OAuth token's scopes (``granted_scope``) narrowed to the app's current ceiling,- so a provisioned PAT can exceed neither what the user granted nor what the app- may hold. Minting from the ceiling alone would hand out optional scopes the- grant never included. A flag-on app with an unseeded ceiling mints nothing: an- empty-scope PAT fails every scope check, and widening to a wildcard would- bypass the ceiling.-- scoped_teams is set to [team.id] so the PAT only grants access to the team- being provisioned, matching the scoping of the OAuth token issued in the- same flow. Without this, a provisioning call from an existing user would- return a PAT that reaches across every team the user already belongs to.-- ``label_prefix`` should be pre-validated by ``_extract_label_prefix``; pass- ``None`` (or any falsy value) to label the key with just the team name.- """- if not app or not app.provisioning_issues_personal_api_key:- return None- if not app.ceiling_scopes:- _capture_provisioning_event("pat_mint", "skipped_unseeded_ceiling", partner=app, team_id=team.id)- return None- granted = (granted_scope or "").split()- if "*" in granted:- # A legacy wildcard token covers everything, so the ceiling is the cap.- pat_scopes = app.ceiling_scopes- else:- pat_scopes = narrow_scopes_to_ceiling([s for s in granted if ":" in s], app.ceiling_scopes) or []- if not pat_scopes:- _capture_provisioning_event("pat_mint", "skipped_no_granted_scopes", partner=app, team_id=team.id)- return None- try:- api_key_value = generate_random_token_personal()- label_base = f"{label_prefix} - {team.name}" if label_prefix else team.name- # PersonalAPIKey.label is stored as a CharField(max_length=40); cap the- # final string to match so we never violate the column constraint.- label = label_base[:PROVISIONED_PAT_LABEL_MAX_LENGTH]-- PersonalAPIKey.objects.create(- user=user,- label=label,- secure_value=hash_key_value(api_key_value),- mask_value=mask_key_value(api_key_value),- scopes=pat_scopes,- scoped_teams=[team.id],- scoped_organizations=[str(team.organization_id)],- )-- return api_key_value- except Exception:- capture_exception(additional_properties={"user_id": user.id, "team_id": team.id})- return None---def _resolve_or_create_project_team(- project_id: str,- scoped_teams: list[int],- user: User,- configuration: dict,- access_token: OAuthAccessToken,-) -> tuple[Team | None, list[int]]:- """Look up or create a team for the given project_id.-- Uses TeamProvisioningConfig (DB-backed with unique constraint) for the- project_id → team_id mapping. This ensures idempotency even across cache- evictions and handles race conditions via IntegrityError.-- Returns (None, scoped_teams) when an existing team is resolved but the- authenticated user lacks team-level access (honors advanced permissions- / access controls on top of org membership).- """- existing = (- TeamProvisioningConfig.objects.filter(- stripe_project_id=project_id,- application=access_token.application,- team__organization_id__in=Team.objects.filter(id__in=scoped_teams).values("organization_id"),- )- .select_related("team")- .first()- )- if existing:- if not _user_can_access_team(user, existing.team):- return None, scoped_teams- return _ensure_team_in_token_scopes(access_token, scoped_teams, existing.team)-- base_team = Team.objects.get(id=scoped_teams[0])- if not _user_can_access_team(user, base_team):- return None, scoped_teams-- project_name = configuration.get("project_name", "Default project")- new_team = Team.objects.create_with_data(- initiating_user=user,- organization=base_team.organization,- name=project_name,- )-- try:- TeamProvisioningConfig.objects.update_or_create(- team=new_team,- defaults={"stripe_project_id": project_id, "application": access_token.application},- )- except IntegrityError:- new_team.delete()- race_winner = (- TeamProvisioningConfig.objects.filter(- stripe_project_id=project_id,- application=access_token.application,- team__organization_id__in=Team.objects.filter(id__in=scoped_teams).values("organization_id"),- )- .select_related("team")- .first()- )- if race_winner:- if not _user_can_access_team(user, race_winner.team):- return None, scoped_teams- return _ensure_team_in_token_scopes(access_token, scoped_teams, race_winner.team)- raise _ProjectIdCollisionError(project_id)-- return _ensure_team_in_token_scopes(access_token, scoped_teams, new_team)---class _ProjectIdCollisionError(Exception):- """Raised when a stripe_project_id is already in use by a team outside the caller's orgs."""-- def __init__(self, project_id: str) -> None:- super().__init__(project_id)- self.project_id = project_id---def _ensure_team_in_token_scopes(- access_token: OAuthAccessToken, scoped_teams: list[int], team: Team-) -> tuple[Team, list[int]]:- if team.id in scoped_teams:- return team, scoped_teams- _add_team_to_token_scopes(access_token, team.id)- return team, [*scoped_teams, team.id]---def _compute_partner_scoped_teams(- application: OAuthApplication | None,- user: User,- base_team_id: int,-) -> list[int]:- """Compute the durable scope for a partner OAuth token at issuance/refresh.-- Returns the set of every team where ``TeamProvisioningConfig.application ==- application`` (i.e. this partner provisioned the team for this user, attributed- at create time) AND the team lives in the same organization as ``base_team_id``- AND the user still has team-level access. This is partner-agnostic, not- Stripe-specific: ``stripe_project_id`` is the (legacily named) external project- id every partner sets, always written alongside ``application`` in- ``_resolve_or_create_project_team``, so the ``application`` filter already- implies a provisioned team. The organization filter pins the token to the- authorization context:- a partner with OAuth grants in multiple orgs for the same user must not be- able to reach an org-B team via an org-A token just because the user happens- to be a member of both.-- Returns ``[]`` when ``application`` is None (legacy refresh tokens with no- app binding). A partner-unattributed token cannot be safely scoped, so it- gets no teams and the holder must re-authorize. Falling through would let- ``filter(application=None)`` match every TPC row with NULL application- across every partner.-- Returns ``[]`` if ``base_team_id`` no longer resolves to a team the user- can access; stale scope must not grant ongoing access after ACL revocation- or org removal.- """- if application is None:- return []-- try:- base_team = Team.objects.select_related("organization").get(id=base_team_id)- except Team.DoesNotExist:- return []- if not _user_can_access_team(user, base_team):- return []-- candidate_team_ids = set(- TeamProvisioningConfig.objects.filter(- application=application,- team__organization_id=base_team.organization_id,- ).values_list("team_id", flat=True)- )- candidate_team_ids.add(base_team_id)-- granted: set[int] = {base_team_id}- other_teams = Team.objects.select_related("organization").filter(- id__in=candidate_team_ids - {base_team_id},- )- for team in other_teams:- if _user_can_access_team(user, team):- granted.add(team.id)-- # sorted() only for deterministic test assertions and log diffs; scope order is not a correctness requirement- return sorted(granted)---def _user_can_access_team(user: User, team: Team) -> bool:- """Verify the user has at least member-level access to the team.-- Org membership alone does not prove access for advanced-permissions- orgs that restrict individual teams. Without this check the agentic- provisioning resolve flow could grant scoped access to a private team- as long as the user had any team in the same org.- """- return UserAccessControl(user=user, team=team).check_access_level_for_object(team, required_level="member")---def _add_team_to_token_scopes(access_token: OAuthAccessToken, team_id: int) -> None:- with transaction.atomic():- locked_access_token = OAuthAccessToken.objects.select_for_update().get(pk=access_token.pk)- teams = list(locked_access_token.scoped_teams or [])- if team_id not in teams:- teams.append(team_id)- locked_access_token.scoped_teams = teams- locked_access_token.save(update_fields=["scoped_teams"])- access_token.scoped_teams = teams-- refresh_tokens = OAuthRefreshToken.objects.select_for_update().filter(access_token=locked_access_token)- for rt in refresh_tokens:- rt_teams = list(rt.scoped_teams or [])- if team_id not in rt_teams:- rt_teams.append(team_id)- rt.scoped_teams = rt_teams- rt.save(update_fields=["scoped_teams"])---# ----------------------------------------------------------------------------# POST /provisioning/resources-# ------------------------------------------------------------------------------@api_view(["POST"])-@authentication_classes([])-@permission_classes([])-@region_proxy(strategy="bearer_lookup")-def provisioning_resources_create(request: Request) -> Response:- auth_error, user, access_token = _authenticate_bearer(request)- if auth_error:- return auth_error-- app = access_token.application- if app and app.provisioning_partner_type:- if error := _enforce_partner_rate_limit(app, "resource_creates"):- # Resource endpoints use {"status": "error"} envelope, not {"type": "error"}- retry_after = error["Retry-After"] if "Retry-After" in error else "3600"- response = error_response(- "rate_limited", "Rate limit exceeded for this partner. Try again later.", status=429- )- response["Retry-After"] = retry_after- return response-- try:- label_prefix = _extract_label_prefix(request)- except _InvalidLabelPrefixError as exc:- _capture_provisioning_event("resource_created", "error", partner=app, error_code="invalid_label_prefix")- return error_response("invalid_label_prefix", str(exc))-- scoped_teams = access_token.scoped_teams or []-- if not scoped_teams:- _capture_provisioning_event("resource_created", "error", partner=app, error_code="no_team")- return error_response("no_team", "No team associated with this token")-- project_id = request.data.get("project_id", "")- configuration = request.data.get("configuration") or {}-- if project_id:- try:- team, scoped_teams = _resolve_or_create_project_team(- project_id, scoped_teams, user, configuration, access_token- )- except _ProjectIdCollisionError:- _capture_provisioning_event(- "resource_created", "error", partner=app, error_code="project_id_conflict", project_id=project_id- )- return error_response(- "project_id_conflict",- "Project ID already linked to another organization",- status=409,- )- if team is None:- _capture_provisioning_event(- "resource_created", "error", partner=app, error_code="not_found", project_id=project_id- )- return error_response("not_found", "Resource not found", status=404)- else:- team_id = scoped_teams[0]- try:- team = Team.objects.get(id=team_id)- except Team.DoesNotExist:- _capture_provisioning_event(- "resource_created", "error", partner=app, error_code="team_not_found", team_id=team_id- )- return error_response("team_not_found", "Team not found", resource_id=str(team_id), status=404)-- region = get_instance_region() or "US"- host = _region_to_host(region)-- _capture_provisioning_event(- "resource_created",- "success",- partner=app,- team_id=team.id,- )-- access_configuration: dict[str, str] = {- "api_key": team.api_token,- "host": host,- }- if personal_api_key := _maybe_create_provisioned_pat(- user, team, access_token.application, access_token.scope, label_prefix=label_prefix- ):- access_configuration["personal_api_key"] = personal_api_key-- return Response(- {- "status": "complete",- "id": str(team.id),- "complete": {- "access_configuration": access_configuration,- },- }- )---# ----------------------------------------------------------------------------# GET /provisioning/resources/:id-# ------------------------------------------------------------------------------@api_view(["GET"])-@authentication_classes([])-@permission_classes([])-@region_proxy(strategy="bearer_lookup")-def provisioning_resource_detail(request: Request, resource_id: str) -> Response:- return _resolve_resource_response(request, resource_id)---# ----------------------------------------------------------------------------# POST /provisioning/resources/:id/rotate_credentials-# ------------------------------------------------------------------------------@api_view(["POST"])-@authentication_classes([])-@permission_classes([])-@region_proxy(strategy="bearer_lookup")-def provisioning_rotate_credentials(request: Request, resource_id: str) -> Response:- auth_error, user, access_token = _authenticate_bearer(request)- if auth_error:- return auth_error-- try:- label_prefix = _extract_label_prefix(request)- except _InvalidLabelPrefixError as exc:- _capture_provisioning_event("credential_rotation", "error", error_code="invalid_label_prefix")- return error_response("invalid_label_prefix", str(exc), resource_id=resource_id)-- 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)-- try:- # Bearer flow resolves the token outside DRF, so read impersonation off the token directly.- team.reset_token_and_save(user=user, is_impersonated_session=access_token.impersonated_by_id is not None)- except Exception:- capture_exception(additional_properties={"team_id": team_id})- _capture_provisioning_event("credential_rotation", "failed", team_id=team_id)- return error_response(- "credential_rotation_failed", "Failed to rotate credentials", resource_id=resource_id, status=500- )-- _capture_provisioning_event("credential_rotation", "success", team_id=team_id)-- region = get_instance_region() or "US"- host = _region_to_host(region)-- access_configuration: dict[str, str] = {- "api_key": team.api_token,- "host": host,- }- if personal_api_key := _maybe_create_provisioned_pat(- user, team, access_token.application, access_token.scope, label_prefix=label_prefix- ):- access_configuration["personal_api_key"] = personal_api_key-- return Response(- {- "status": "complete",- "id": resource_id,- "complete": {- "access_configuration": access_configuration,- },- }- )---# ----------------------------------------------------------------------------# POST /provisioning/resources/:id/github_integration-# POST /provisioning/resources/:id/wizard_runs-# Drop-flow resource actions: link a GitHub installation to the team from a-# stored grant, then kick off a cloud wizard run against a repository.-# ------------------------------------------------------------------------------def _drf_validation_error_code(exc: DRFValidationError) -> str | None:- codes = exc.get_codes()- if isinstance(codes, list) and codes:- return str(codes[0])- if isinstance(codes, str):- return codes- return None---def _apply_provisioned_onboarding_flags(user: User, team: Team) -> None:- """Keep the app from routing a partner-provisioned account into onboarding on first- login. Only applied to unclaimed accounts (never logged in, no password set) so an- existing user going through the consent path keeps their onboarding state."""- # Bootstrapped accounts store password="" (create_user skips set_password when the- # password is None), which Django counts as *usable* — treat it as no password.- has_password = bool(user.password) and user.has_usable_password()- if user.last_login is not None or has_password:- return- if user.onboarding_skipped_at is None:- user.onboarding_skipped_at = timezone.now()- user.onboarding_skipped_reason = OnboardingSkippedReason.PROVISIONED- user.onboarding_skipped_organization_id = team.organization_id- user.save(- update_fields=["onboarding_skipped_at", "onboarding_skipped_reason", "onboarding_skipped_organization_id"]- )- if not team.completed_snippet_onboarding:- team.completed_snippet_onboarding = True- team.save(update_fields=["completed_snippet_onboarding"])---def _link_github_grant_to_team(- *, partner: OAuthApplication, user: User, team: Team, grant_id: str, installation_id: str-) -> tuple[Response | None, Integration | None, bool]:- """Shared core of the github_integration action and the account_requests wizard- block: validate the grant, verify installation ownership, create both GitHub- records, consume the grant. Returns (error_response, integration, already_linked).- """- grant = github_grants.load_grant(grant_id, partner)- if grant is None:- # Idempotent retry: the grant is consumed on success, so a retry after a lost- # response must not fail if the installation is already linked to this team.- existing = Integration.objects.first_github_for_team_installation(team.id, str(installation_id))- if existing is not None:- # Re-apply onboarding flags idempotently: the grant is consumed as the last step,- # so a crash between consume and the flag write would otherwise leave them unset- # on a retry (this branch runs only once the grant is already gone).- _apply_provisioned_onboarding_flags(user, team)- return None, existing, True- _capture_provisioning_event("github_integration", "error", partner=partner, error_code="grant_not_found")- return (- error_response("grant_not_found", "Grant not found or expired", resource_id=str(team.id), status=404),- None,- False,- )-- try:- integration = link_github_installation_for_user(- user=user, team_id=team.id, installation_id=str(installation_id), authorization=grant.to_authorization()- )- except DRFValidationError as exc:- code = _drf_validation_error_code(exc)- if code == "installation_access_denied":- _capture_provisioning_event("github_integration", "error", partner=partner, error_code=code)- return (- error_response(- "installation_access_denied",- "The GitHub user does not have access to this installation",- resource_id=str(team.id),- status=403,- ),- None,- False,- )- if code == "installation_verify_failed":- _capture_provisioning_event("github_integration", "error", partner=partner, error_code=code)- return (- error_response(- "installation_verify_failed",- "Could not verify installation access with GitHub",- resource_id=str(team.id),- status=502,- ),- None,- False,- )- _capture_provisioning_event("github_integration", "error", partner=partner, error_code="invalid_request")- return (- error_response("invalid_request", str(exc.detail), resource_id=str(team.id), status=400),- None,- False,- )- except GitHubInstallationAccessFetchError:- _capture_provisioning_event(- "github_integration", "error", partner=partner, error_code="integration_creation_failed"- )- return (- error_response(- "integration_creation_failed",- "Could not create the GitHub integration",- resource_id=str(team.id),- status=502,- ),- None,- False,- )-- github_grants.consume_grant(grant_id)- _apply_provisioned_onboarding_flags(user, team)- _capture_provisioning_event("github_integration", "success", partner=partner, team_id=team.id)- return None, integration, False---@api_view(["POST"])-@authentication_classes([])-@permission_classes([])-@region_proxy(strategy="bearer_lookup")-def provisioning_github_integration(request: Request, resource_id: str) -> Response:- auth_error, user, access_token = _authenticate_bearer(request)- if auth_error:- return auth_error-- 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 (access_token.scoped_teams or []):- 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)-- grant_id = request.data.get("grant_id")- installation_id = request.data.get("installation_id")- if not grant_id or not installation_id:- return error_response("invalid_request", "grant_id and installation_id are required", resource_id=resource_id)-- error, integration, already_linked = _link_github_grant_to_team(- partner=access_token.application,- user=user,- team=team,- grant_id=str(grant_id),- installation_id=str(installation_id),- )- if error:- return error- assert integration is not None-- return Response(- {- "status": "complete",- "id": resource_id,- "github_integration": {- "integration_id": str(integration.id),- "gh_login": (integration.config or {}).get("connecting_user_github_login"),- "already_linked": already_linked,- },- }- )---def _enforce_wizard_run_user_rate_limit(user_id: int) -> Response | None:- """Cache-counter equivalent of the session cloud_run endpoint's per-user throttles;- shared across the granular wizard_runs action and the bundled account_requests path- so retries can't double-spend the budget."""- for label, limit, window_seconds in WIZARD_RUN_USER_RATE_LIMITS:- window_index = int(time.time()) // window_seconds- key = f"{WIZARD_RUN_USER_RATE_LIMIT_PREFIX}{label}:{user_id}:{window_index}"- try:- cache.add(key, 0, timeout=window_seconds)- count = cache.incr(key)- except (ValueError, ConnectionError, TimeoutError):- count = 1- if count > limit:- response = Response(- {- "status": "error",- "error": {"code": "rate_limited", "message": "Too many wizard runs for this user. Try later."},- },- status=429,- )- response["Retry-After"] = str(window_seconds - (int(time.time()) % window_seconds))- return response- return None---def _create_wizard_run(- *, partner: OAuthApplication, user_id: int, team: Team, repository: str, branch: str | None-) -> tuple[Response | None, dict[str, str] | None]:- """Gate + throttle + create a cloud wizard run. Returns (error_response, run_payload)."""- if not bool(settings.WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID):- _capture_provisioning_event("wizard_run", "error", partner=partner, error_code="wizard_unavailable")- return (- error_response(- "wizard_unavailable",- "Running the setup wizard in the cloud is not available",- resource_id=str(team.id),- status=503,- ),- None,- )-- repository = (repository or "").strip()- parts = repository.split("/")- if len(parts) != 2 or not all(parts):- return (- error_response("invalid_request", "repository must be in 'owner/repo' format", resource_id=str(team.id)),- None,- )-- if error := _enforce_wizard_run_user_rate_limit(user_id):- return error, None- if error := _enforce_partner_rate_limit(partner, "wizard_runs"):- return error, None-- # Verifying the grant user owns the installation doesn't prove the installation can- # reach the requested repo — a valid grant for one installation could otherwise report- # wizard success for an owner/repo it can't operate on. Fail fast instead (after the- # rate limits, so this GitHub call can't be used as an unthrottled probe).- if GitHubIntegration.first_for_team_repository(team.id, repository, source="integration") is None:- _capture_provisioning_event(- "wizard_run", "error", partner=partner, error_code="github_integration_required", team_id=team.id- )- return (- error_response(- "github_integration_required",- "The team does not have a GitHub integration that can access this repository",- resource_id=str(team.id),- status=400,- ),- None,- )-- try:- created = tasks_facade.create_wizard_cloud_run(- team=team, user_id=user_id, repository=repository, branch=branch or None- )- except ValueError:- # The facade raises when the team has no usable GitHub integration.- _capture_provisioning_event(- "wizard_run", "error", partner=partner, error_code="github_integration_required", team_id=team.id- )- return (- error_response(- "github_integration_required",- "The team does not have a GitHub integration that can access this repository",- resource_id=str(team.id),- status=400,- ),- None,- )- except Exception:- capture_exception(additional_properties={"team_id": team.id, "step": "provisioning_wizard_run"})- _capture_provisioning_event(- "wizard_run", "error", partner=partner, error_code="run_creation_failed", team_id=team.id- )- return (- error_response(- "run_creation_failed", "Failed to start the wizard run", resource_id=str(team.id), status=500- ),- None,- )-- run = created.latest_run- _capture_provisioning_event("wizard_run", "success", partner=partner, team_id=team.id, task_id=str(created.task_id))- return None, {- "task_id": str(created.task_id),- "run_id": str(run.id) if run else "",- "status": str(run.status) if run else "queued",- }---@api_view(["POST"])-@authentication_classes([])-@permission_classes([])-@region_proxy(strategy="bearer_lookup")-def provisioning_wizard_runs(request: Request, resource_id: str) -> Response:- auth_error, user, access_token = _authenticate_bearer(request)- if auth_error:- return auth_error-- 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 (access_token.scoped_teams or []):- 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)-- repository = request.data.get("repository")- if not repository:- return error_response("invalid_request", "repository is required", resource_id=resource_id)-- error, run_payload = _create_wizard_run(- partner=access_token.application,- user_id=user.id,- team=team,- repository=str(repository),- branch=request.data.get("branch") or None,- )- if error:- return error-- return Response({"status": "complete", "id": resource_id, "wizard_run": run_payload})---# ----------------------------------------------------------------------------# POST /provisioning/resources/:id/remove-# Detaches the resource from the orchestrator: removes it from the token's-# scope and clears provisioning metadata. Preserves the underlying team and-# user data so the customer can still access PostHog directly.-# ------------------------------------------------------------------------------@api_view(["POST"])-@authentication_classes([])-@permission_classes([])-@region_proxy(strategy="bearer_lookup")-def provisioning_resource_remove(request: Request, resource_id: str) -> Response:- auth_error, user, access_token = _authenticate_bearer(request)- if auth_error:- return auth_error-- try:- team_id = int(resource_id)- except (ValueError, TypeError):- return Response(- {- "status": "error",- "id": resource_id,- "error": {"code": "invalid_resource_id", "message": "Invalid resource ID"},- },- status=400,- )-- scoped_teams = access_token.scoped_teams or []- if team_id not in scoped_teams:- return Response(- {- "status": "error",- "id": resource_id,- "error": {"code": "forbidden", "message": "Resource not accessible with this token"},- },- status=403,- )-- try:- # Clear the mapping only if it is unclaimed or owned by the caller's- # application; an in-scope partner must not delete another partner's- # provisioning mapping for the same team.- config = TeamProvisioningConfig.objects.filter(team_id=team_id).first()- if config is not None and config.application_id in (None, access_token.application_id):- config.delete()- except Exception:- capture_exception(additional_properties={"team_id": team_id, "step": "remove_provisioning_config"})- _capture_provisioning_event("resource_removed", "error", team_id=team_id, error_code="remove_config_failed")- return Response(- {- "status": "error",- "id": resource_id,- "error": {"code": "remove_failed", "message": "Failed to remove resource"},- },- status=500,- )-- _remove_team_from_token_scopes(access_token, team_id)-- _capture_provisioning_event("resource_removed", "success", team_id=team_id)-- return Response({"status": "removed", "id": resource_id})---def _remove_team_from_token_scopes(access_token: OAuthAccessToken, team_id: int) -> None:- """Strip ``team_id`` from every access/refresh token for this partner+user combo.-- Removing a resource has to revoke access for any *other* live token the same- partner installation might be holding for the same user (e.g. a separate- bearer issued via a prior OAuth grant that still has the team in scope).- Touching only the calling ``access_token`` would let the partner continue- operating on the team via a sibling token after `remove` returned, since- operational endpoints accept any team currently in ``scoped_teams``.-- Atomic so a refresh token can never be left with the removed team still in- scope while the access token has it stripped — otherwise the orchestrator- could refresh and replay the removed team right back into scope.- """- application = access_token.application- user = access_token.user- if application is None or user is None:- # Defensive: a provisioning bearer token without an app/user shouldn't- # exist in practice, but fall back to the single-token strip if it does.- application_filter: dict[str, object] = {"pk": access_token.pk}- user_filter: dict[str, object] = {}- else:- application_filter = {"application": application, "user": user}- user_filter = {"application": application, "user": user}-- with transaction.atomic():- access_tokens = list(- OAuthAccessToken.objects.select_for_update()- .filter(scoped_teams__contains=[team_id], **application_filter)- .order_by("pk")- )- for at in access_tokens:- remaining = [t for t in (at.scoped_teams or []) if t != team_id]- refresh_tokens = OAuthRefreshToken.objects.select_for_update().filter(access_token=at)- if not remaining:- refresh_tokens.update(access_token=None, revoked=timezone.now(), scoped_teams=[])- at.delete()- continue- at.scoped_teams = remaining- at.save(update_fields=["scoped_teams"])- for rt in refresh_tokens:- rt.scoped_teams = [t for t in (rt.scoped_teams or []) if t != team_id]- rt.save(update_fields=["scoped_teams"])-- if user_filter:- # Orphan refresh tokens (where the access token was already rotated- # or deleted) still carry scope. Strip the team from those too.- orphan_refresh = OAuthRefreshToken.objects.select_for_update().filter(- scoped_teams__contains=[team_id],- access_token__isnull=True,- revoked__isnull=True,- **user_filter,- )- for rt in orphan_refresh:- rt.scoped_teams = [t for t in (rt.scoped_teams or []) if t != team_id]- rt.save(update_fields=["scoped_teams"])---def _resolve_resource_response(request: Request, resource_id: str) -> Response:- auth_error, user, access_token = _authenticate_bearer(request)- if auth_error:- return auth_error-- scoped_teams = access_token.scoped_teams or []-- try:- team_id = int(resource_id)- except (ValueError, TypeError):- return Response(- {- "status": "error",- "id": resource_id,- "error": {"code": "invalid_resource_id", "message": "Invalid resource ID"},- },- status=400,- )-- if team_id not in scoped_teams:- return Response(- {- "status": "error",- "id": resource_id,- "error": {"code": "forbidden", "message": "Resource not accessible with this token"},- },- status=403,- )-- try:- team = Team.objects.get(id=team_id)- except Team.DoesNotExist:- return Response(- {"status": "error", "id": resource_id, "error": {"code": "not_found", "message": "Resource not found"}},- status=404,- )-- region = get_instance_region() or "US"- host = _region_to_host(region)-- return Response(- {- "status": "complete",- "id": resource_id,- "complete": {- "access_configuration": {- "api_key": team.api_token,- "host": host,- },- },- }- )---# ----------------------------------------------------------------------------# POST /provisioning/deep_links-# ------------------------------------------------------------------------------@api_view(["POST"])-@authentication_classes([])-@permission_classes([])-@region_proxy(strategy="bearer_lookup")-def deep_links(request: Request) -> Response:- auth_error, user, access_token = _authenticate_bearer(request)- if auth_error:- return auth_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(- "deep_links_not_enabled",- "Deep links are not enabled for this partner",- status=403,- )-- # `purpose` is a free-form label retained for analytics. `path` is the generic- # destination: any in-app path the partner wants the user to land on after login.- purpose = request.data.get("purpose", "dashboard")- path = request.data.get("path")- if path and not _is_safe_deep_link_path(path):- _capture_provisioning_event(- "deep_link_created", "invalid_path", partner=access_token.application, purpose=purpose- )- return error_response(- "invalid_path",- "path must be a relative in-app path beginning with a single '/'",- status=400,- )-- scoped_teams = access_token.scoped_teams or []- team_id = scoped_teams[0] if scoped_teams else None-- region = get_instance_region() or "US"- host = _region_to_host(region)-- token = secrets.token_urlsafe(32)- cache_key = f"{DEEP_LINK_CACHE_PREFIX}{token}"- cache.set(- cache_key,- {- "user_id": access_token.user_id,- "team_id": team_id,- "purpose": purpose,- "path": path or None,- },- timeout=DEEP_LINK_TTL_SECONDS,- )-- expires_at = timezone.now() + timedelta(seconds=DEEP_LINK_TTL_SECONDS)-- url = f"{host}/agentic/login?token={token}"- if team_id:- url += f"&team_id={team_id}"-- _capture_provisioning_event(- "deep_link_created", "success", partner=access_token.application, purpose=purpose, team_id=team_id- )-- return Response(- {- "purpose": purpose,- "url": url,- "expires_at": expires_at.isoformat(),- }- )---# ----------------------------------------------------------------------------# Helpers-# ------------------------------------------------------------------------------def _partner_label(partner: OAuthApplication | None) -> str:- if partner is None:- return "Partner"- if partner.provisioning_partner_type:- return partner.provisioning_partner_type.capitalize()- if partner.name:- return partner.name- return "Partner"---def _enforce_partner_rate_limit(partner: OAuthApplication, endpoint: str) -> Response | None:- """Enforce per-partner rate limit using the model's override or a conservative default.-- Returns a 429 Response if the limit is exceeded, or None if the request is allowed.- Setting the model field to 0 disables rate limiting for that endpoint.-- Uses a fixed-window counter keyed on partner id + window-of-epoch. A partner can- burst up to 2x the limit across a window boundary (`limit` at :59:59 plus `limit`- at :00:00); switch to a sliding window if that matters.- """- if endpoint not in PARTNER_RATE_LIMIT_DEFAULTS:- raise ValueError(f"Unknown rate limit endpoint: {endpoint}")-- field_name = f"provisioning_rate_limit_{endpoint}"- override = getattr(partner, field_name, None)-- if override is not None:- limit = override- else:- limit = PARTNER_RATE_LIMIT_DEFAULTS.get(endpoint, 10)-- if limit <= 0:- return None-- window_index = int(time.time()) // PARTNER_RATE_LIMIT_WINDOW_SECONDS- cache_key = f"{PARTNER_RATE_LIMIT_PREFIX}{endpoint}:{partner.id}:{window_index}"-- try:- cache.add(cache_key, 0, timeout=PARTNER_RATE_LIMIT_WINDOW_SECONDS)- count = cache.incr(cache_key)- except (ValueError, ConnectionError, TimeoutError) as e:- logger.warning("partner_rate_limit_cache_error", endpoint=endpoint, partner_id=str(partner.id), error=str(e))- # cache.add preserves any counter a concurrent request already initialized,- # so a transient cache error doesn't reset the window for a partner at the limit.- cache.add(cache_key, 1, timeout=PARTNER_RATE_LIMIT_WINDOW_SECONDS)- count = 1-- if count > limit:- event_name = PARTNER_RATE_LIMIT_EVENT_NAMES.get(endpoint, endpoint)- _capture_provisioning_event(event_name, "rate_limited", partner=partner, limit=limit, count=count)- retry_after = PARTNER_RATE_LIMIT_WINDOW_SECONDS - (int(time.time()) % PARTNER_RATE_LIMIT_WINDOW_SECONDS)- response = typed_error_response(- "rate_limited", f"Rate limit exceeded for this partner ({endpoint}). Try again later.", status=429- )- response["Retry-After"] = str(retry_after)- return response- return None---def _enforce_cimd_registration_throttle(request: Request) -> Response | None:- """Rate-limit first-time CIMD app registration by IP and domain to match /authorize protections."""- from posthog.api.oauth.cimd import CIMD_THROTTLE_CLASSES, is_cimd_client_id-- client_id = request.data.get("client_id") or request.query_params.get("client_id")- if not is_cimd_client_id(client_id):- return None- if OAuthApplication.objects.filter(cimd_metadata_url=client_id).exists():- return None-- for throttle_cls in CIMD_THROTTLE_CLASSES:- throttle = throttle_cls()- if not throttle.allow_request(request, view=None): # type: ignore[arg-type]- logger.warning("cimd_rate_limited", client_id=client_id, scope=throttle.scope, wait=throttle.wait())- return typed_error_response(- "rate_limited", "Too many new client registrations. Try again later.", status=429- )-- if error := _enforce_cimd_domain_rate_limit(cast(str, client_id)):- return error-- return None---def _enforce_cimd_domain_rate_limit(client_id: str) -> Response | None:- """Prevent a single domain from registering unlimited CIMD apps via different URL paths."""- from urllib.parse import urlparse-- domain = urlparse(client_id).hostname- if not domain:- return None-- window_index = int(time.time()) // CIMD_DOMAIN_RATE_LIMIT_WINDOW_SECONDS- key = f"{CIMD_DOMAIN_RATE_LIMIT_PREFIX}{domain}:{window_index}"- try:- count = cache.incr(key)- except ValueError:- cache.add(key, 0, timeout=CIMD_DOMAIN_RATE_LIMIT_WINDOW_SECONDS)- count = cache.incr(key)-- if count > CIMD_DOMAIN_RATE_LIMIT_MAX:- logger.warning("cimd_domain_rate_limited", client_id=client_id, domain=domain, count=count)- _capture_provisioning_event("account_request", "cimd_domain_rate_limited", domain=domain, count=count)- return typed_error_response(- "rate_limited", "Too many new client registrations from this domain. Try again later.", status=429- )- return None---def _authenticate_bearer(request: Request) -> tuple[Response | None, Any, Any]:- """Authenticate via Bearer token issued to an active provisioning partner.-- Returns (error_response, user, access_token).- """-- auth_header = request.headers.get("authorization", "")- if not auth_header.startswith("Bearer "):- return (error_response("unauthorized", "Missing bearer token", status=401), None, None)-- token_value = auth_header[len("Bearer ") :].strip()- if not token_value:- return (error_response("unauthorized", "Missing bearer token", status=401), None, None)-- access_token = find_oauth_access_token(token_value)- if access_token is None:- return (error_response("unauthorized", "Invalid access token", status=401), None, None)-- if access_token.expires and access_token.expires < timezone.now():- return (error_response("unauthorized", "Access token expired", status=401), None, None)-- # 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:- return (- error_response("forbidden", "Resource provisioning not enabled for this partner", status=403),- None,- None,- )- return None, access_token.user, access_token-- return (error_response("unauthorized", "Authentication failed", status=401), None, None)---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))- teams = Team.objects.filter(organization_id__in=org_ids, is_demo=False).select_related("organization")- return [- {- "id": team.id,- "name": team.name,- "organization_id": str(team.organization_id),- "organization_name": team.organization.name if team.organization else "",- }- for team in teams- ]---def _get_callback_url(partner_id: str) -> str | None:- """Get the callback URL from the partner's redirect_uris.-- Returns None when the partner cannot be resolved or has no redirect URI- registered; callers must fail the flow rather than redirect blindly.- """- 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:- region_lower = region.lower()- if region_lower == "eu":- return "https://eu.posthog.com"- elif region_lower in ("us", "dev"):- return "https://us.posthog.com"- return settings.SITE_URL---# ----------------------------------------------------------------------------# GET /agentic/login — deep link login for agentic provisioning users-# ------------------------------------------------------------------------------def agentic_login(request: Any) -> HttpResponseBase:- token = request.GET.get("token", "")- if not token:- _capture_deep_link_event("missing_token")- logger.warning("agentic_login.missing_token")- return HttpResponseRedirect("/?error=missing_token")-- cache_key = f"{DEEP_LINK_CACHE_PREFIX}{token}"-- try:- link_data = cache.get(cache_key)- except Exception:- capture_exception(additional_properties={"cache_key": cache_key})- return HttpResponseRedirect("/?error=service_unavailable")-- if link_data is None:- _capture_deep_link_event("expired_or_invalid_token")- logger.warning("agentic_login.expired_or_invalid_token")- return HttpResponseRedirect("/?error=expired_or_invalid_token")-- # Atomic delete — if another request already consumed this token, reject- if not cache.delete(cache_key):- _capture_deep_link_event("expired_or_invalid_token")- logger.warning("agentic_login.token_already_consumed")- return HttpResponseRedirect("/?error=expired_or_invalid_token")-- if not isinstance(link_data, dict):- _capture_deep_link_event("invalid_token_data")- logger.warning("agentic_login.invalid_token_data")- return HttpResponseRedirect("/?error=invalid_token_data")-- user_id = link_data.get("user_id")- team_id = link_data.get("team_id")- purpose = link_data.get("purpose", "dashboard")- path = link_data.get("path")-- if not user_id:- _capture_deep_link_event("invalid_token_data")- logger.warning("agentic_login.missing_user_id")- return HttpResponseRedirect("/?error=invalid_token_data")-- try:- user = User.objects.get(id=user_id)- except User.DoesNotExist:- _capture_deep_link_event("user_not_found", user_id=user_id)- capture_exception(- Exception("Deep link login user not found"),- {"user_id": user_id, "team_id": team_id},- )- return HttpResponseRedirect("/?error=user_not_found")-- if not user.is_active:- _capture_deep_link_event("user_inactive", user_id=user_id)- logger.warning("agentic_login.user_inactive", user_id=user_id)- return HttpResponseRedirect("/?error=user_inactive")-- # Deep-link login has no password challenge and no SSO step, so partner-asserted- # email ownership is the only thing standing between an attacker and a session.- # Require explicit is_email_verified=True - don't trust the legacy None passthrough- # or the org-level email-verification-disabled flag.- if user.is_email_verified is not True:- try:- EmailVerifier.create_token_and_send_email_verification(user)- except Exception:- # Intentionally swallowed: the login must stay blocked regardless of email delivery.- # EmailVerifier captures the exception internally; the verify_email page has a resend button.- logger.warning("agentic_login.verification_email_failed", user_id=user.id)- _capture_deep_link_event("email_unverified", user_id=user_id)- logger.warning("agentic_login.email_unverified", user_id=user_id)- return HttpResponseRedirect(f"/verify_email/{user.uuid}")-- auth_login(request, user, backend="django.contrib.auth.backends.ModelBackend")-- _capture_deep_link_event("success", user_id=user_id, team_id=team_id, purpose=purpose)- logger.info("agentic_login.success", user_id=user_id, team_id=team_id, purpose=purpose)-- redirect_path = _deep_link_redirect_path(purpose, team_id, path)- return HttpResponseRedirect(redirect_path)---def _is_safe_deep_link_path(path: object) -> bool:- """Allow only relative, same-origin in-app paths so a deep link can't become an open redirect."""- return (- isinstance(path, str)- and 0 < len(path) <= DEEP_LINK_MAX_PATH_LENGTH- # Reject control chars, whitespace, and backslashes (the `/\` backslash-host form included).- and not DEEP_LINK_DISALLOWED_PATH_CHARS.search(path)- and path.startswith("/")- # Reject protocol-relative (`//`) forms; a single leading `/` keeps it same-origin.- and not path.startswith("//")- and url_has_allowed_host_and_scheme(path, allowed_hosts=None)- )---def _deep_link_redirect_path(purpose: str, team_id: int | None, path: str | None = None) -> str:- if path and _is_safe_deep_link_path(path):- return path- if path:- # Unreachable in normal operation (mint-time validation already ran); a hit here means- # cache tampering or a mint-side regression.- logger.warning("agentic_login.unsafe_path_in_cache", path=path)- if team_id and Team.objects.filter(id=team_id).exists():- return f"/project/{team_id}"- return "/"---def _capture_provisioning_event(- event_type: str,- outcome: str,- *,- partner: OAuthApplication | None = None,- **extra: object,-) -> None:- team_id = extra.get("team_id")- distinct_id = f"agentic_provisioning_team_{team_id}" if team_id else f"agentic_provisioning_{uuid.uuid4().hex[:16]}"- properties: dict[str, object] = {"outcome": outcome, **extra}- if partner is not None:- properties.setdefault("partner_id", str(partner.id))- properties.setdefault("client_name", partner.name)- if partner.provisioning_partner_type:- properties.setdefault("partner_type", partner.provisioning_partner_type)- posthoganalytics.capture(- f"agentic_provisioning {event_type}",- distinct_id=distinct_id,- properties=properties,- )---def _capture_deep_link_event(outcome: str, **extra: object) -> None:- _capture_provisioning_event("deep link login", outcome, partner=None, **extra)diff --git a/ee/api/agentic_provisioning/views/__init__.py b/ee/api/agentic_provisioning/views/__init__.pynew file mode 100644index 000000000000..08b50f415c8c--- /dev/null+++ b/ee/api/agentic_provisioning/views/__init__.py@@ -0,0 +1,31 @@+from ee.api.agentic_provisioning.views.account_requests import AccountRequestsView+from ee.api.agentic_provisioning.views.authorize import AuthorizeConfirmView, AuthorizePendingView, agentic_authorize+from ee.api.agentic_provisioning.views.deep_links import DeepLinksView, agentic_login+from ee.api.agentic_provisioning.views.github_grants import GitHubGrantRepositoriesView, GitHubGrantsCreateView+from ee.api.agentic_provisioning.views.oauth_token import OAuthTokenView+from ee.api.agentic_provisioning.views.resources import (+ GitHubIntegrationView,+ ResourceDetailView,+ ResourceRemoveView,+ ResourcesCreateView,+ RotateCredentialsView,+ WizardRunsView,+)++__all__ = [+ "AccountRequestsView",+ "AuthorizeConfirmView",+ "AuthorizePendingView",+ "DeepLinksView",+ "GitHubGrantRepositoriesView",+ "GitHubGrantsCreateView",+ "GitHubIntegrationView",+ "OAuthTokenView",+ "ResourceDetailView",+ "ResourceRemoveView",+ "ResourcesCreateView",+ "RotateCredentialsView",+ "WizardRunsView",+ "agentic_authorize",+ "agentic_login",+]diff --git a/ee/api/agentic_provisioning/views/account_requests.py b/ee/api/agentic_provisioning/views/account_requests.pynew file mode 100644index 000000000000..049f358e9956--- /dev/null+++ b/ee/api/agentic_provisioning/views/account_requests.py@@ -0,0 +1,127 @@+"""POST /provisioning/account_requests — onboard a new or existing user and+return either an auth code (new user) or a redirect URL (existing user).++The check order here is part of the observable wire behavior (which error a+request with several problems gets, and whether it consumes partner quota), so+the checks run explicitly in the handler rather than via DRF's auth/permission+hooks: CIMD throttle → partner identification → body validation → partner+capability → partner rate limit → PKCE validation.+"""++from __future__ import annotations++from rest_framework.exceptions import AuthenticationFailed+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.models.user import User+from posthog.scopes import effective_ceiling++from ee.api.agentic_provisioning.accounts import handle_existing_user, handle_new_user+from ee.api.agentic_provisioning.analytics import capture_provisioning_event+from ee.api.agentic_provisioning.authentication import ProvisioningAuthentication+from ee.api.agentic_provisioning.constants import CODE_CHALLENGE_RE+from ee.api.agentic_provisioning.exceptions import ProvisioningError+from ee.api.agentic_provisioning.serializers import AccountRequestSerializer+from ee.api.agentic_provisioning.throttling import CIMDRegistrationThrottle, enforce_partner_rate_limit+from ee.api.agentic_provisioning.views.base import ProvisioningAPIView+++class AccountRequestsView(ProvisioningAPIView):+ region_proxy_strategy = "body_region"+ partner_throttle_classes = [CIMDRegistrationThrottle]++ def post(self, request: Request) -> Response:+ # --- Identify partner ---+ auth = ProvisioningAuthentication()+ partner = None+ authenticated_user = None+ try:+ result = auth.authenticate(request)+ if result:+ authenticated_user, partner = result+ except AuthenticationFailed:+ raise ProvisioningError("unauthorized", "Authentication failed", status=401)++ if partner is None and auth.cimd_registration_pending:+ return Response(+ {"type": "registering", "retry_after": 5},+ status=202,+ )++ if partner is None:+ raise ProvisioningError("unauthorized", "Authentication required", status=401)++ # --- Parse request ---+ data = self.validated_body(AccountRequestSerializer, request)++ request_id = data["id"]+ email = data["email"]++ scopes = data["scopes"]+ 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))+ configuration = data["configuration"]++ if not partner.provisioning_can_create_accounts:+ capture_provisioning_event("account_request", "error", error_code="account_creation_disabled")+ raise ProvisioningError("forbidden", "Account creation is not enabled for this partner", status=403)++ enforce_partner_rate_limit(partner, "account_requests")++ # PKCE: capture code_challenge for later verification+ code_challenge = data["code_challenge"]+ code_challenge_method = data["code_challenge_method"]+ if code_challenge and code_challenge_method != "S256":+ raise ProvisioningError("invalid_request", "Only S256 code_challenge_method is supported")+ if code_challenge and (+ len(code_challenge) < 43 or len(code_challenge) > 128 or not CODE_CHALLENGE_RE.fullmatch(code_challenge)+ ):+ raise ProvisioningError(+ "invalid_request", "code_challenge must be 43-128 characters using base64url charset"+ )++ region = (configuration.get("region") or "US").upper()++ requested_team_id = configuration.get("team_id")+ if requested_team_id is not None:+ try:+ requested_team_id = int(requested_team_id)+ except (ValueError, TypeError):+ raise ProvisioningError(+ "invalid_request", "configuration.team_id must be an integer", request_id=request_id+ )++ existing_user = User.objects.filter(email=email).first()++ if existing_user:+ return Response(+ handle_existing_user(+ request_id,+ existing_user,+ scopes,+ region=region,+ team_id=requested_team_id,+ partner=partner,+ code_challenge=code_challenge,+ code_challenge_method=code_challenge_method,+ authenticated_user=authenticated_user,+ )+ )++ return Response(+ handle_new_user(+ request_id,+ data,+ email,+ scopes,+ region=region,+ partner=partner,+ code_challenge=code_challenge,+ code_challenge_method=code_challenge_method,+ authenticated_user=authenticated_user,+ )+ )diff --git a/ee/api/agentic_provisioning/views/authorize.py b/ee/api/agentic_provisioning/views/authorize.pynew file mode 100644index 000000000000..472f52f833eb--- /dev/null+++ b/ee/api/agentic_provisioning/views/authorize.py@@ -0,0 +1,216 @@+"""Interactive OAuth consent for existing users.++The orchestrator redirects the user to GET /api/agentic/authorize; on approval+(automatic for trusted partners, via the in-app consent page otherwise) we+issue an auth code and redirect back to the orchestrator callback. The+pending/confirm endpoints back the in-app consent page, so unlike the rest of+this package they authenticate the browser session and speak the frontend's+plain error shapes, not the partner envelopes.+"""++from __future__ import annotations++import re+from typing import Any, cast+from urllib.parse import urlencode++from django.conf import settings+from django.contrib.auth.decorators import login_required+from django.core.cache import cache+from django.http import HttpResponseRedirect+from django.http.response import HttpResponseBase++from rest_framework.permissions import IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.views import APIView++from posthog.models.oauth import OAuthApplication+from posthog.models.team.team import Team+from posthog.models.user import User++from ee.api.agentic_provisioning.accounts import get_callback_url, mint_pending_auth_code, resolve_pending_partner+from ee.api.agentic_provisioning.analytics import capture_provisioning_event+from ee.api.agentic_provisioning.constants import PENDING_AUTH_CACHE_PREFIX, SAFE_STATE_RE+from ee.api.agentic_provisioning.tokens import user_can_access_team+++def _sanitize_state(state: str) -> str:+ return re.sub(r"[^A-Za-z0-9_\-]", "", state)+++@login_required+def agentic_authorize(request: Any) -> HttpResponseBase:+ state = request.GET.get("state", "")+ if not state or not SAFE_STATE_RE.match(state):+ capture_provisioning_event("authorize", "missing_state")+ return HttpResponseRedirect(f"{settings.SITE_URL}?error=missing_state")++ pending_key = f"{PENDING_AUTH_CACHE_PREFIX}{state}"+ pending = cache.get(pending_key)+ if pending is None:+ capture_provisioning_event("authorize", "expired_state")+ return HttpResponseRedirect(f"{settings.SITE_URL}?error=expired_or_invalid_state")++ if request.user.email != pending["email"]:+ capture_provisioning_event("authorize", "email_mismatch")+ mismatch_params = urlencode(+ {+ "expected_email": pending["email"],+ "current_email": request.user.email,+ "partner_name": pending.get("partner_name", ""),+ "state": state,+ }+ )+ return HttpResponseRedirect(f"{settings.SITE_URL.rstrip('/')}/agentic/account-mismatch?{mismatch_params}")++ user = request.user+ memberships = list(user.organization_memberships.select_related("organization").all())+ if not memberships:+ capture_provisioning_event("authorize", "no_organization")+ return HttpResponseRedirect(f"{settings.SITE_URL}?error=no_organization")++ # Only teams the user can actually reach are eligible: the auto-approve path+ # below mints a code for non_demo_teams[0] without further checks.+ org_ids = [m.organization_id for m in memberships]+ non_demo_teams = [+ team+ for team in Team.objects.filter(organization_id__in=org_ids, is_demo=False)+ if user_can_access_team(user, team)+ ]++ if not non_demo_teams:+ organization = memberships[0].organization+ team = Team.objects.create_with_data(initiating_user=user, organization=organization)+ non_demo_teams = [team]+ capture_provisioning_event("authorize", "auto_created_project", team_id=team.id)++ # Re-check partner is still active (could have been deactivated since account_requests)+ partner_id = pending.get("partner_id", "")+ is_trusted_partner = False+ partner_app = resolve_pending_partner(partner_id)+ if partner_app is not None:+ if not partner_app.provisioning_active:+ cache.delete(pending_key)+ capture_provisioning_event("authorize", "partner_deactivated")+ return HttpResponseRedirect(f"{settings.SITE_URL}?error=partner_deactivated")+ # Fail closed: a partner-identified pending state missing the flag (e.g. created by an+ # older pod mid-deploy) must still require consent, never silently auto-approve.+ is_trusted_partner = partner_app.provisioning_skip_existing_user_consent and not pending.get(+ "consent_required", True+ )++ if is_trusted_partner and len(memberships) == 1 and len(non_demo_teams) == 1:+ organization = memberships[0].organization+ team = non_demo_teams[0]++ callback_url = get_callback_url(partner_app)+ if callback_url is None:+ capture_provisioning_event("authorize", "missing_callback")+ return HttpResponseRedirect(f"{settings.SITE_URL}?error=missing_callback")++ code = mint_pending_auth_code(pending, user_id=user.id, org_id=str(organization.id), team_id=team.id)+ cache.delete(pending_key)++ capture_provisioning_event("authorize", "auto_redirect", team_id=team.id)++ params = urlencode({"code": code, "state": _sanitize_state(state)})+ return HttpResponseRedirect(f"{callback_url}?{params}")++ capture_provisioning_event("authorize", "selection_required")++ base = settings.SITE_URL.rstrip("/")+ params = urlencode({"state": _sanitize_state(state)})+ return HttpResponseRedirect(f"{base}/agentic/authorize?{params}")+++class AuthorizePendingView(APIView):+ """Return server-verified partner name and scopes for a pending auth state.++ The frontend calls this instead of reading from URL params, preventing+ an attacker from spoofing the partner identity on the consent page.+ """++ permission_classes = [IsAuthenticated]++ def get(self, request: Request) -> Response:+ state = request.query_params.get("state", "")+ if not state or not SAFE_STATE_RE.match(state):+ return Response({"error": "invalid_state"}, status=400)++ pending = cache.get(f"{PENDING_AUTH_CACHE_PREFIX}{state}")+ if pending is None:+ return Response({"error": "expired_or_invalid_state"}, status=400)++ user = cast(User, request.user)+ if user.email != pending["email"]:+ return Response({"error": "email_mismatch"}, status=403)++ return Response(+ {+ "partner_name": pending.get("partner_name", "the requesting app"),+ "scopes": pending.get("scopes", []),+ }+ )+++class AuthorizeConfirmView(APIView):+ permission_classes = [IsAuthenticated]++ def post(self, request: Request) -> Response:+ state = request.data.get("state", "")+ team_id = request.data.get("team_id")++ if not state or team_id is None or not SAFE_STATE_RE.match(state):+ capture_provisioning_event("authorize_confirm", "invalid_request")+ return Response({"error": "state and team_id are required"}, status=400)++ pending_key = f"{PENDING_AUTH_CACHE_PREFIX}{state}"+ pending = cache.get(pending_key)+ if pending is None:+ capture_provisioning_event("authorize_confirm", "expired_state")+ return Response({"error": "expired_or_invalid_state"}, status=400)++ user = cast(User, request.user)++ if user.email != pending["email"]:+ capture_provisioning_event("authorize_confirm", "email_mismatch")+ return Response({"error": "email_mismatch"}, status=403)++ try:+ team = Team.objects.get(id=team_id, is_demo=False)+ except Team.DoesNotExist:+ capture_provisioning_event("authorize_confirm", "team_not_found", team_id=team_id)+ return Response({"error": "team_not_found"}, status=404)++ # The user picks the team here, so consent does not imply access: check+ # team level too, or an org member excluded from a private project could+ # approve a code scoped to it.+ in_org = user.organization_memberships.filter(organization_id=team.organization_id).exists()+ if not in_org or not user_can_access_team(user, team):+ capture_provisioning_event("authorize_confirm", "team_not_accessible", team_id=team_id)+ return Response({"error": "team_not_accessible"}, status=403)++ confirm_partner_id = pending.get("partner_id", "")+ confirm_partner: OAuthApplication | None = resolve_pending_partner(confirm_partner_id)+ if confirm_partner is not None and not confirm_partner.provisioning_active:+ cache.delete(pending_key)+ capture_provisioning_event("authorize_confirm", "partner_deactivated", partner=confirm_partner)+ return Response({"error": "partner_deactivated"}, status=403)++ callback_url = get_callback_url(confirm_partner)+ if callback_url is None:+ capture_provisioning_event("authorize_confirm", "missing_callback", partner=confirm_partner)+ return Response({"error": "missing_callback"}, status=400)++ # Mint the auth code BEFORE deleting pending state so a cache hiccup+ # between the two doesn't leave the user with no recovery path.+ code = mint_pending_auth_code(pending, user_id=user.id, org_id=str(team.organization_id), team_id=team.id)+ cache.delete(pending_key)++ params = urlencode({"code": code, "state": _sanitize_state(state)})+ redirect_url = f"{callback_url}?{params}"++ capture_provisioning_event("authorize_confirm", "success", partner=confirm_partner, team_id=team_id)++ return Response({"redirect_url": redirect_url})diff --git a/ee/api/agentic_provisioning/views/base.py b/ee/api/agentic_provisioning/views/base.pynew file mode 100644index 000000000000..ca526e5e51c5--- /dev/null+++ b/ee/api/agentic_provisioning/views/base.py@@ -0,0 +1,128 @@+"""Base views for the agentic provisioning API.++Every endpoint in this namespace is a DRF class-based view built on+:class:`ProvisioningAPIView`. Errors raised as :class:`ProvisioningError`+(from views, serializers, authentication, or throttling helpers) render in the+view's declared wire envelope, so DRF's default error shape never leaks out of+these partner-facing endpoints.+"""++from __future__ import annotations++from typing import Any, ClassVar++from rest_framework import serializers+from rest_framework.authentication import BaseAuthentication+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.throttling import BaseThrottle+from rest_framework.views import APIView++from posthog.models.oauth import OAuthAccessToken+from posthog.models.team.team import Team++from ee.api.agentic_provisioning.authentication import (+ ConfidentialPartnerAuthentication,+ ProvisioningBearerAuthentication,+)+from ee.api.agentic_provisioning.exceptions import Envelope, ProvisioningError, render_provisioning_error+from ee.api.agentic_provisioning.region_proxy import RegionProxyMixin+from ee.api.agentic_provisioning.serializers import first_error_message+++class ProvisioningAPIView(RegionProxyMixin, APIView):+ """Base for every endpoint in this namespace.++ Unauthenticated by default (each endpoint declares its own partner auth);+ errors raised as :class:`ProvisioningError` render in the view's envelope.+ """++ authentication_classes: list[type[BaseAuthentication]] = []+ permission_classes: list = []+ error_envelope: ClassVar[Envelope] = "typed"++ # Provisioning throttles keyed on something DRF has by the time it calls+ # check_throttles (the partner on request.auth, a URL kwarg). Additive to+ # DEFAULT_THROTTLE_CLASSES, which still guards these endpoints per IP.+ # Flows whose key only appears mid-handler (token exchange, account+ # request partner quota, wizard runs) call the throttling helpers instead.+ partner_throttle_classes: ClassVar[list[type[BaseThrottle]]] = []++ def get_throttles(self) -> list[BaseThrottle]:+ return [*super().get_throttles(), *(throttle() for throttle in self.partner_throttle_classes)]++ def check_throttles(self, request: Request) -> None:+ """Reject on the first throttle that refuses, in the view's wire envelope.++ Short-circuiting means a request already refused by the global per-IP+ limit doesn't also spend partner quota, and partners get the documented+ ``rate_limited`` shape rather than DRF's ``{"detail": ...}``.+ """+ for throttle in self.get_throttles():+ if throttle.allow_request(request, self):+ continue++ wait = throttle.wait()+ raise ProvisioningError(+ "rate_limited",+ getattr(throttle, "error_message", "Rate limit exceeded. Try again later."),+ status=429,+ retry_after=int(wait) if wait else None,+ )++ def handle_exception(self, exc: Exception) -> Response:+ if isinstance(exc, ProvisioningError):+ return render_provisioning_error(exc, self.error_envelope)+ return super().handle_exception(exc)++ def validated_body(+ self,+ serializer_class: type[serializers.Serializer],+ request: Request,+ *,+ resource_id: str = "",+ context: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ """Parse the request body, raising the wire-contract ``invalid_request``+ error (never DRF's default shape) when validation fails."""+ serializer = serializer_class(data=request.data, context=context or {})+ if not serializer.is_valid():+ raise ProvisioningError("invalid_request", first_error_message(serializer.errors), resource_id=resource_id)+ return serializer.validated_data+++class ConfidentialPartnerAPIView(ProvisioningAPIView):+ """Base for confidential-partner endpoints (GitHub grants): the bearer-authed+ partner rides ``request.auth``; typed envelope."""++ authentication_classes = [ConfidentialPartnerAuthentication]+++class BearerResourceAPIView(ProvisioningAPIView):+ """Base for the bearer-authenticated resource endpoints (status envelope)."""++ error_envelope = "status"+ region_proxy_strategy = "bearer_lookup"+ authentication_classes = [ProvisioningBearerAuthentication]++ def parse_resource_team_id(self, resource_id: str, access_token: OAuthAccessToken) -> int:+ try:+ team_id = int(resource_id)+ except (ValueError, TypeError):+ raise ProvisioningError("invalid_resource_id", "Invalid resource ID", resource_id=resource_id)++ if team_id not in (access_token.scoped_teams or []):+ raise ProvisioningError(+ "forbidden", "Resource not accessible with this token", resource_id=resource_id, status=403+ )+ return team_id++ def get_team(self, team_id: int, resource_id: str) -> Team:+ try:+ return Team.objects.get(id=team_id)+ except Team.DoesNotExist:+ raise ProvisioningError("not_found", "Resource not found", resource_id=resource_id, status=404)++ def get_scoped_team(self, resource_id: str, access_token: OAuthAccessToken) -> Team:+ """Resolve the resource id to its team, enforcing the token's team scope."""+ return self.get_team(self.parse_resource_team_id(resource_id, access_token), resource_id)diff --git a/ee/api/agentic_provisioning/views/deep_links.py b/ee/api/agentic_provisioning/views/deep_links.pynew file mode 100644index 000000000000..139471f5a3fd--- /dev/null+++ b/ee/api/agentic_provisioning/views/deep_links.py@@ -0,0 +1,211 @@+"""Deep links: POST /provisioning/deep_links mints a single-use login URL for+the partner's user; GET /agentic/login consumes it and mints a session."""++from __future__ import annotations++import secrets+from datetime import timedelta+from typing import Any, cast++from django.contrib.auth import login as auth_login+from django.core.cache import cache+from django.http import HttpResponseRedirect+from django.http.response import HttpResponseBase+from django.utils import timezone+from django.utils.http import url_has_allowed_host_and_scheme++import structlog+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.email_verification import EmailVerifier+from posthog.exceptions_capture import capture_exception+from posthog.models.oauth import OAuthAccessToken+from posthog.models.team.team import Team+from posthog.models.user import User++from ee.api.agentic_provisioning.analytics import capture_deep_link_event, capture_provisioning_event+from ee.api.agentic_provisioning.constants import (+ DEEP_LINK_CACHE_PREFIX,+ DEEP_LINK_DISALLOWED_PATH_CHARS,+ DEEP_LINK_MAX_PATH_LENGTH,+ DEEP_LINK_TTL_SECONDS,+)+from ee.api.agentic_provisioning.exceptions import ProvisioningError+from ee.api.agentic_provisioning.regions import current_region_host+from ee.api.agentic_provisioning.serializers import DeepLinkSerializer+from ee.api.agentic_provisioning.views.base import BearerResourceAPIView++logger = structlog.get_logger(__name__)+++def is_safe_deep_link_path(path: object) -> bool:+ """Allow only relative, same-origin in-app paths so a deep link can't become an open redirect."""+ return (+ isinstance(path, str)+ and 0 < len(path) <= DEEP_LINK_MAX_PATH_LENGTH+ # Reject control chars, whitespace, and backslashes (the `/\` backslash-host form included).+ and not DEEP_LINK_DISALLOWED_PATH_CHARS.search(path)+ and path.startswith("/")+ # Reject protocol-relative (`//`) forms; a single leading `/` keeps it same-origin.+ and not path.startswith("//")+ and url_has_allowed_host_and_scheme(path, allowed_hosts=None)+ )+++class DeepLinksView(BearerResourceAPIView):+ def post(self, request: Request) -> Response:+ access_token = cast(OAuthAccessToken, request.auth)++ if not access_token.application.provisioning_can_issue_deep_links:+ capture_provisioning_event("deep_link_created", "not_enabled", partner=access_token.application)+ raise ProvisioningError(+ "deep_links_not_enabled",+ "Deep links are not enabled for this partner",+ status=403,+ )++ data = self.validated_body(DeepLinkSerializer, request)++ # `purpose` is a free-form label retained for analytics. `path` is the generic+ # destination: any in-app path the partner wants the user to land on after login.+ purpose = data["purpose"]+ path = data["path"]+ if path and not is_safe_deep_link_path(path):+ capture_provisioning_event(+ "deep_link_created", "invalid_path", partner=access_token.application, purpose=purpose+ )+ raise ProvisioningError(+ "invalid_path",+ "path must be a relative in-app path beginning with a single '/'",+ status=400,+ )++ scoped_teams = access_token.scoped_teams or []+ team_id = scoped_teams[0] if scoped_teams else None++ host = current_region_host()++ token = secrets.token_urlsafe(32)+ cache_key = f"{DEEP_LINK_CACHE_PREFIX}{token}"+ cache.set(+ cache_key,+ {+ "user_id": access_token.user_id,+ "team_id": team_id,+ "purpose": purpose,+ "path": path or None,+ },+ timeout=DEEP_LINK_TTL_SECONDS,+ )++ expires_at = timezone.now() + timedelta(seconds=DEEP_LINK_TTL_SECONDS)++ url = f"{host}/agentic/login?token={token}"+ if team_id:+ url += f"&team_id={team_id}"++ capture_provisioning_event(+ "deep_link_created", "success", partner=access_token.application, purpose=purpose, team_id=team_id+ )++ return Response(+ {+ "purpose": purpose,+ "url": url,+ "expires_at": expires_at.isoformat(),+ }+ )+++def agentic_login(request: Any) -> HttpResponseBase:+ """GET /agentic/login — deep link login for agentic provisioning users."""+ token = request.GET.get("token", "")+ if not token:+ capture_deep_link_event("missing_token")+ logger.warning("agentic_login.missing_token")+ return HttpResponseRedirect("/?error=missing_token")++ cache_key = f"{DEEP_LINK_CACHE_PREFIX}{token}"++ try:+ link_data = cache.get(cache_key)+ except Exception:+ capture_exception(additional_properties={"cache_key": cache_key})+ return HttpResponseRedirect("/?error=service_unavailable")++ if link_data is None:+ capture_deep_link_event("expired_or_invalid_token")+ logger.warning("agentic_login.expired_or_invalid_token")+ return HttpResponseRedirect("/?error=expired_or_invalid_token")++ # Atomic delete — if another request already consumed this token, reject+ if not cache.delete(cache_key):+ capture_deep_link_event("expired_or_invalid_token")+ logger.warning("agentic_login.token_already_consumed")+ return HttpResponseRedirect("/?error=expired_or_invalid_token")++ if not isinstance(link_data, dict):+ capture_deep_link_event("invalid_token_data")+ logger.warning("agentic_login.invalid_token_data")+ return HttpResponseRedirect("/?error=invalid_token_data")++ user_id = link_data.get("user_id")+ team_id = link_data.get("team_id")+ purpose = link_data.get("purpose", "dashboard")+ path = link_data.get("path")++ if not user_id:+ capture_deep_link_event("invalid_token_data")+ logger.warning("agentic_login.missing_user_id")+ return HttpResponseRedirect("/?error=invalid_token_data")++ try:+ user = User.objects.get(id=user_id)+ except User.DoesNotExist:+ capture_deep_link_event("user_not_found", user_id=user_id)+ capture_exception(+ Exception("Deep link login user not found"),+ {"user_id": user_id, "team_id": team_id},+ )+ return HttpResponseRedirect("/?error=user_not_found")++ if not user.is_active:+ capture_deep_link_event("user_inactive", user_id=user_id)+ logger.warning("agentic_login.user_inactive", user_id=user_id)+ return HttpResponseRedirect("/?error=user_inactive")++ # Deep-link login has no password challenge and no SSO step, so partner-asserted+ # email ownership is the only thing standing between an attacker and a session.+ # Require explicit is_email_verified=True - don't trust the legacy None passthrough+ # or the org-level email-verification-disabled flag.+ if user.is_email_verified is not True:+ try:+ EmailVerifier.create_token_and_send_email_verification(user)+ except Exception:+ # Intentionally swallowed: the login must stay blocked regardless of email delivery.+ # EmailVerifier captures the exception internally; the verify_email page has a resend button.+ logger.warning("agentic_login.verification_email_failed", user_id=user.id)+ capture_deep_link_event("email_unverified", user_id=user_id)+ logger.warning("agentic_login.email_unverified", user_id=user_id)+ return HttpResponseRedirect(f"/verify_email/{user.uuid}")++ auth_login(request, user, backend="django.contrib.auth.backends.ModelBackend")++ capture_deep_link_event("success", user_id=user_id, team_id=team_id, purpose=purpose)+ logger.info("agentic_login.success", user_id=user_id, team_id=team_id, purpose=purpose)++ redirect_path = _deep_link_redirect_path(purpose, team_id, path)+ return HttpResponseRedirect(redirect_path)+++def _deep_link_redirect_path(purpose: str, team_id: int | None, path: str | None = None) -> str:+ if path and is_safe_deep_link_path(path):+ return path+ if path:+ # Unreachable in normal operation (mint-time validation already ran); a hit here means+ # cache tampering or a mint-side regression.+ logger.warning("agentic_login.unsafe_path_in_cache", path=path)+ if team_id and Team.objects.filter(id=team_id).exists():+ return f"/project/{team_id}"+ return "/"diff --git a/ee/api/agentic_provisioning/views/github_grants.py b/ee/api/agentic_provisioning/views/github_grants.pynew file mode 100644index 000000000000..f8da75634b56--- /dev/null+++ b/ee/api/agentic_provisioning/views/github_grants.py@@ -0,0 +1,98 @@+"""GitHub grants for drop-style partner flows: the partner forwards a GitHub+OAuth code, we exchange and hold the user tokens server-side, and the partner+only ever sees an opaque grant_id. No region proxy: grants are region-local+(the partner must call the region that minted the grant).++Grant creation enforces its partner quota inline rather than through+``partner_throttle_classes``, so the capability check runs first: a partner+without ``provisioning_can_create_accounts`` is refused for free instead of+burning its hourly grant budget on requests it can never complete.+"""++from __future__ import annotations++from typing import cast++import requests+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.models.integration import GitHubIntegration+from posthog.models.oauth import OAuthApplication++from ee.api.agentic_provisioning import github_grants+from ee.api.agentic_provisioning.analytics import capture_provisioning_event+from ee.api.agentic_provisioning.exceptions import ProvisioningError+from ee.api.agentic_provisioning.serializers import GitHubGrantCreateSerializer+from ee.api.agentic_provisioning.throttling import GrantPollThrottle, enforce_partner_rate_limit+from ee.api.agentic_provisioning.views.base import ConfidentialPartnerAPIView+++class GitHubGrantsCreateView(ConfidentialPartnerAPIView):+ def post(self, request: Request) -> Response:+ partner = cast(OAuthApplication, request.auth)++ if not partner.provisioning_can_create_accounts:+ capture_provisioning_event("github_grant", "error", partner=partner, error_code="account_creation_disabled")+ raise ProvisioningError("forbidden", "Account creation is not enabled for this partner", status=403)++ enforce_partner_rate_limit(partner, "github_grants")++ data = self.validated_body(GitHubGrantCreateSerializer, request, context={"partner": partner})+ code = data["code"]+ redirect_uri = data["redirect_uri"]++ try:+ authorization = GitHubIntegration.github_user_from_code(code, redirect_uri=redirect_uri)+ except requests.RequestException:+ # Network failure or a non-JSON GitHub error body raising through .json() — retryable,+ # distinct from a clean "bad code" exchange failure (which returns None below).+ capture_provisioning_event("github_grant", "error", partner=partner, error_code="github_unavailable")+ raise ProvisioningError("github_unavailable", "GitHub request failed", status=502)+ if authorization is None:+ capture_provisioning_event("github_grant", "error", partner=partner, error_code="github_exchange_failed")+ raise ProvisioningError("github_exchange_failed", "Could not exchange the GitHub OAuth code", status=502)++ # A user with no verified email gets a grant with email=null — the partner+ # collects an email inline instead. Only an access refusal (App permission+ # misconfiguration) hard-fails, so it can't masquerade as that user state.+ try:+ email = github_grants.fetch_primary_email(authorization.access_token)+ except github_grants.GitHubEmailAccessDenied:+ capture_provisioning_event("github_grant", "error", partner=partner, error_code="email_unavailable")+ raise ProvisioningError("email_unavailable", "GitHub denied reading the user's email addresses", status=502)+ except requests.RequestException:+ capture_provisioning_event("github_grant", "error", partner=partner, error_code="github_unavailable")+ raise ProvisioningError("github_unavailable", "GitHub request failed", status=502)++ grant = github_grants.create_grant(partner, authorization, email)+ capture_provisioning_event("github_grant", "created", partner=partner, gh_login=grant.gh_login)+ return Response(+ {+ "grant_id": grant.grant_id,+ "gh_login": grant.gh_login,+ "email": grant.email,+ "expires_in": github_grants.GITHUB_GRANT_TTL_SECONDS,+ }+ )+++class GitHubGrantRepositoriesView(ConfidentialPartnerAPIView):+ # Keyed per calling partner and grant id, so polls against an id the caller does+ # not own can only exhaust the caller's own budget.+ partner_throttle_classes = [GrantPollThrottle]++ def get(self, request: Request, grant_id: str) -> Response:+ partner = cast(OAuthApplication, request.auth)++ grant = github_grants.load_grant(grant_id, partner)+ if grant is None:+ raise ProvisioningError("grant_not_found", "Grant not found or expired", status=404)++ try:+ listing = github_grants.list_installations_and_repositories(grant.access_token)+ except requests.RequestException:+ capture_provisioning_event("github_grant", "listing_failed", partner=partner)+ raise ProvisioningError("github_unavailable", "GitHub request failed", status=502)++ return Response({"gh_login": grant.gh_login, **listing})diff --git a/ee/api/agentic_provisioning/views/oauth_token.py b/ee/api/agentic_provisioning/views/oauth_token.pynew file mode 100644index 000000000000..521ea20b5946--- /dev/null+++ b/ee/api/agentic_provisioning/views/oauth_token.py@@ -0,0 +1,349 @@+"""POST /oauth/token — exchange auth codes or refresh tokens for access tokens.++Follows RFC 6749's flat ``{"error", "error_description"}`` error shape, except+for partner rate limits, which keep the typed envelope (their historical wire+shape on this endpoint).+"""++from __future__ import annotations++import base64+import hashlib+from datetime import datetime, timedelta++from django.core.cache import cache+from django.core.exceptions import ValidationError+from django.db import transaction+from django.utils import timezone++import structlog+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken+from posthog.models.user import User+from posthog.models.utils import generate_random_oauth_access_token, generate_random_oauth_refresh_token+from posthog.scopes import narrow_scopes_to_ceiling, scopes_within_ceiling++from ee.api.agentic_provisioning.analytics import capture_provisioning_event+from ee.api.agentic_provisioning.constants import (+ ACCESS_TOKEN_EXPIRY_SECONDS,+ AUTH_CODE_CACHE_PREFIX,+ PARTNER_TOKEN_EXPIRY_SECONDS,+)+from ee.api.agentic_provisioning.exceptions import ProvisioningError+from ee.api.agentic_provisioning.throttling import enforce_partner_rate_limit+from ee.api.agentic_provisioning.tokens import (+ compute_partner_scoped_teams,+ get_available_teams_for_user,+ lock_application,+)+from ee.api.agentic_provisioning.views.base import ProvisioningAPIView++logger = structlog.get_logger(__name__)+++class OAuthTokenView(ProvisioningAPIView):+ error_envelope = "oauth"+ region_proxy_strategy = "token_lookup"++ def post(self, request: Request) -> Response:+ grant_type = request.data.get("grant_type", "")++ if grant_type == "authorization_code":+ return self._exchange_authorization_code(request)+ elif grant_type == "refresh_token":+ return self._exchange_refresh_token(request)++ capture_provisioning_event("token_exchange", "unsupported_grant_type", grant_type=grant_type)+ raise ProvisioningError("unsupported_grant_type", f"Unsupported grant_type: {grant_type}")++ def _exchange_authorization_code(self, request: Request) -> Response:+ code = request.data.get("code", "")+ if not code:+ capture_provisioning_event("token_exchange", "missing_code", grant_type="authorization_code")+ raise ProvisioningError("invalid_request", "code is required")++ cache_key = f"{AUTH_CODE_CACHE_PREFIX}{code}"+ code_data = cache.get(cache_key)+ if code_data is None:+ capture_provisioning_event("token_exchange", "invalid_code", grant_type="authorization_code")+ raise ProvisioningError("invalid_grant", "Invalid or expired authorization code")++ # 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", "")+ if not stored_challenge:+ capture_provisioning_event("token_exchange", "missing_code_challenge", grant_type="authorization_code")+ raise ProvisioningError("invalid_request", "Authentication required", status=401)++ code_verifier = request.data.get("code_verifier", "")+ if not code_verifier:+ capture_provisioning_event("token_exchange", "missing_code_verifier", grant_type="authorization_code")+ raise ProvisioningError("invalid_request", "code_verifier is required for PKCE", status=401)+ computed = (+ base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode("ascii")).digest())+ .rstrip(b"=")+ .decode("ascii")+ )+ if computed != stored_challenge:+ capture_provisioning_event("token_exchange", "pkce_mismatch", grant_type="authorization_code")+ raise ProvisioningError("invalid_grant", "PKCE code_verifier does not match")++ # 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+ # tradeoff (rate-limited client loses the code) is acceptable — clients can+ # 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:+ oauth_app = OAuthApplication.objects.get(id=partner_id)+ except (OAuthApplication.DoesNotExist, ValidationError, ValueError):+ 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")+ raise ProvisioningError("invalid_grant", "Unknown application for this authorization code")++ enforce_partner_rate_limit(oauth_app, "token_exchanges")++ user_id = code_data["user_id"]+ team_id = code_data["team_id"]+ scopes = code_data.get("scopes", [])++ try:+ user = User.objects.get(id=user_id)+ except User.DoesNotExist:+ capture_provisioning_event("token_exchange", "user_not_found", grant_type="authorization_code")+ raise ProvisioningError("invalid_grant", "User not found")++ # Lock the app row before reading the revoke stamp and minting, so this serializes+ # with revoke_application_sessions (see lock_application). Provisioning auth codes+ # live in the cache, not OAuthGrant, so the revoke's sweep can't reach them — the+ # `issued_at` carried on the code is what a revoke is checked against. Codes minted+ # 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)+ sessions_revoked_at = locked_app.sessions_revoked_at if locked_app else None+ if sessions_revoked_at is not None:+ issued_at_raw = code_data.get("issued_at")+ issued_at = datetime.fromisoformat(issued_at_raw) if issued_at_raw else None+ if issued_at is None or issued_at < sessions_revoked_at:+ capture_provisioning_event("token_exchange", "sessions_revoked", grant_type="authorization_code")+ raise ProvisioningError("invalid_grant", "Application sessions were revoked; re-authorize.")++ # Direct-mint bypasses /authorize's OAuthValidator, so the per-app scope+ # ceiling has to be enforced here before the token is created by hand.+ 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")+ raise ProvisioningError("invalid_scope", "Authorization code carries no scopes; re-authorize.")+ requested_scopes = scopes+ if not scopes_within_ceiling(requested_scopes, app_scopes):+ capture_provisioning_event("token_exchange", "scope_ceiling_exceeded", grant_type="authorization_code")+ raise ProvisioningError("invalid_scope", "Requested scopes exceed the application's allowed scopes")+ scope_str = " ".join(requested_scopes)++ token_expiry = (+ PARTNER_TOKEN_EXPIRY_SECONDS+ if oauth_app and oauth_app.is_provisioning_partner+ else ACCESS_TOKEN_EXPIRY_SECONDS+ )++ scoped_teams = compute_partner_scoped_teams(oauth_app, user, team_id)+ # A partner token carries its restriction in scoped_teams alone, and the standard+ # OAuth permission check treats an empty scoped_teams as unrestricted (permissions.py).+ # compute_partner_scoped_teams returns [] exactly when the base team is gone or the+ # user lost access, so minting here would hand out a project-unrestricted bearer.+ # Fail closed and force re-authorization.+ if not scoped_teams:+ capture_provisioning_event("token_exchange", "no_accessible_teams", grant_type="authorization_code")+ raise ProvisioningError("invalid_grant", "No accessible teams for this authorization; re-authorize.")++ access_token_value = generate_random_oauth_access_token(None)+ access_token = OAuthAccessToken.objects.create(+ application=oauth_app,+ token=access_token_value,+ user=user,+ expires=timezone.now() + timedelta(seconds=token_expiry),+ scope=scope_str,+ scoped_teams=scoped_teams,+ )++ refresh_token_value = generate_random_oauth_refresh_token(None)+ OAuthRefreshToken.objects.create(+ application=oauth_app,+ token=refresh_token_value,+ user=user,+ access_token=access_token,+ scoped_teams=scoped_teams,+ )++ account_id = str(code_data.get("org_id", ""))++ available_teams = get_available_teams_for_user(user)++ capture_provisioning_event(+ "token_exchange",+ "success",+ partner=oauth_app,+ grant_type="authorization_code",+ team_id=team_id,+ user_id=user.id,+ granted_team_count=len(scoped_teams),+ )++ return Response(+ {+ "token_type": "bearer",+ "access_token": access_token_value,+ "refresh_token": refresh_token_value,+ "expires_in": token_expiry,+ "account": {+ "id": account_id,+ "payment_credentials": "orchestrator",+ "available_teams": available_teams,+ },+ }+ )++ def _exchange_refresh_token(self, request: Request) -> Response:+ refresh_token_value = request.data.get("refresh_token", "")+ if not refresh_token_value:+ capture_provisioning_event("token_exchange", "missing_refresh_token", grant_type="refresh_token")+ raise ProvisioningError("invalid_request", "refresh_token is required")++ # Lock the app row first (revoke_application_sessions locks it before sweeping tokens),+ # then re-read the refresh token under that lock, so the rotate-and-mint serializes with+ # the revoke: either we hold the lock and our new tokens land before its sweep, or it+ # committed first and we see the token already revoked (or the stamp) and reject. Looking+ # the app up by id first (without locking the token row) keeps the lock order app→token,+ # matching the revoke, so the two can't deadlock.+ with transaction.atomic():+ application_id = (+ OAuthRefreshToken.objects.filter(token=refresh_token_value, revoked__isnull=True)+ .values_list("application_id", flat=True)+ .first()+ )+ locked_app = lock_application(application_id) if application_id else None+ old_refresh = (+ OAuthRefreshToken.objects.select_related("user", "access_token")+ .filter(token=refresh_token_value, revoked__isnull=True)+ .first()+ )+ if old_refresh is None:+ capture_provisioning_event("token_exchange", "invalid_refresh_token", grant_type="refresh_token")+ raise ProvisioningError("invalid_grant", "Invalid or revoked refresh token")++ oauth_app = locked_app+ user = old_refresh.user+ old_scoped_teams = old_refresh.scoped_teams or []++ # base_team_id at refresh: the first team in the prior scope. The consent team+ # (authorized at grant time) has the lowest id and sorts first at issuance;+ # partner-provisioned teams are always created later, so they take higher ids+ # and are only ever appended after it. [0] is therefore the consent team. This+ # ordering is load-bearing: compute_partner_scoped_teams re-adds the consent+ # team only when it is base_team_id (it has no TeamProvisioningConfig for this+ # app), so a lower-id provisioned team becoming [0] would silently drop the+ # consent team from the refreshed scope. If the prior token was somehow empty-+ # scoped, fall back to zero so the helper short-circuits without claiming a team.+ base_team_id = old_scoped_teams[0] if old_scoped_teams else 0+ scoped_teams = compute_partner_scoped_teams(oauth_app, user, base_team_id)++ # Same fail-closed rule as issuance: an empty scoped_teams is unrestricted under the+ # standard permission check, so a refresh whose base team vanished or whose access was+ # revoked must re-authorize rather than rotate into a project-unrestricted token.+ # Checked before any token row is mutated so a rejected refresh never revokes the+ # caller's only token.+ if not scoped_teams:+ capture_provisioning_event("token_exchange", "no_accessible_teams", grant_type="refresh_token")+ raise ProvisioningError("invalid_grant", "No accessible teams for this token; re-authorize.")++ # 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:+ capture_provisioning_event("token_exchange", "sessions_revoked", grant_type="refresh_token")+ raise ProvisioningError("invalid_grant", "Application sessions were revoked; re-authorize.")++ # Cap the refreshed scope at the app's current ceiling before touching any+ # token rows — a since-tightened ceiling must drop the removed scopes, and a+ # token now fully outside the ceiling has to re-authorize rather than refresh.+ # Done up front so a rejected refresh never revokes the caller's only token.+ app_scopes = oauth_app.ceiling_scopes if oauth_app else []+ narrowed_scopes = narrow_scopes_to_ceiling(old_scope.split(), app_scopes)+ if narrowed_scopes is None:+ capture_provisioning_event("token_exchange", "scope_ceiling_exceeded", grant_type="refresh_token")+ raise ProvisioningError(+ "invalid_grant",+ "Token scopes are no longer within the application's allowed scopes; re-authorize.",+ )+ new_scope = " ".join(narrowed_scopes)++ # provisioning_partner_type is a stable marker set at partner registration;+ # checking it instead of is_provisioning_partner prevents a bypass when an admin+ # clears provisioning_auth_method to disable a partner without revoking tokens.+ if oauth_app and oauth_app.provisioning_partner_type:+ enforce_partner_rate_limit(oauth_app, "token_exchanges")++ old_access = old_refresh.access_token+ old_refresh.access_token = None+ old_refresh.revoked = timezone.now()+ old_refresh.save(update_fields=["access_token", "revoked"])++ if old_access:+ old_access.delete()++ token_expiry = (+ PARTNER_TOKEN_EXPIRY_SECONDS+ if oauth_app and oauth_app.is_provisioning_partner+ else ACCESS_TOKEN_EXPIRY_SECONDS+ )++ new_access_value = generate_random_oauth_access_token(None)+ new_access = OAuthAccessToken.objects.create(+ application=oauth_app,+ token=new_access_value,+ user=user,+ expires=timezone.now() + timedelta(seconds=token_expiry),+ scope=new_scope,+ scoped_teams=scoped_teams,+ )++ new_refresh_value = generate_random_oauth_refresh_token(None)+ OAuthRefreshToken.objects.create(+ application=oauth_app,+ token=new_refresh_value,+ user=user,+ access_token=new_access,+ scoped_teams=scoped_teams,+ )++ capture_provisioning_event(+ "token_exchange",+ "success",+ partner=oauth_app,+ grant_type="refresh_token",+ team_id=base_team_id,+ user_id=user.id if user else None,+ granted_team_count=len(scoped_teams),+ )++ return Response(+ {+ "token_type": "bearer",+ "access_token": new_access_value,+ "refresh_token": new_refresh_value,+ "expires_in": token_expiry,+ }+ )diff --git a/ee/api/agentic_provisioning/views/resources.py b/ee/api/agentic_provisioning/views/resources.pynew file mode 100644index 000000000000..741b6cda1fda--- /dev/null+++ b/ee/api/agentic_provisioning/views/resources.py@@ -0,0 +1,271 @@+"""Resource endpoints — bearer-authenticated, status envelope.++A "resource" is a provisioned team, addressed by the partner as an opaque+resource id. All endpoints proxy cross-region on bearer lookup and read the+authenticated token off ``request.auth``.+"""++from __future__ import annotations++from typing import cast++from rest_framework.request import Request+from rest_framework.response import Response++from posthog.exceptions_capture import capture_exception+from posthog.models.oauth import OAuthAccessToken+from posthog.models.team.team import Team+from posthog.models.team.team_provisioning_config import TeamProvisioningConfig+from posthog.models.user import User++from ee.api.agentic_provisioning.analytics import capture_provisioning_event+from ee.api.agentic_provisioning.credentials import maybe_create_provisioned_pat+from ee.api.agentic_provisioning.exceptions import ProvisioningError+from ee.api.agentic_provisioning.regions import current_region_host+from ee.api.agentic_provisioning.serializers import (+ GitHubIntegrationSerializer,+ ResourceCreateSerializer,+ RotateCredentialsSerializer,+ WizardRunSerializer,+)+from ee.api.agentic_provisioning.teams import ProjectIdCollisionError, resolve_or_create_project_team+from ee.api.agentic_provisioning.throttling import ResourceCreatesThrottle+from ee.api.agentic_provisioning.tokens import remove_team_from_token_scopes+from ee.api.agentic_provisioning.views.base import BearerResourceAPIView+from ee.api.agentic_provisioning.wizard import create_wizard_run, link_github_grant_to_team+++def _access_configuration_response(+ *,+ resource_id: str,+ team: Team,+ user: User,+ access_token: OAuthAccessToken,+ label_prefix: str | None,+ mint_pat: bool = True,+) -> Response:+ access_configuration: dict[str, str] = {+ "api_key": team.api_token,+ "host": current_region_host(),+ }+ if mint_pat and (+ personal_api_key := maybe_create_provisioned_pat(+ user, team, access_token.application, access_token.scope, label_prefix=label_prefix+ )+ ):+ access_configuration["personal_api_key"] = personal_api_key++ return Response(+ {+ "status": "complete",+ "id": resource_id,+ "complete": {+ "access_configuration": access_configuration,+ },+ }+ )+++class ResourcesCreateView(BearerResourceAPIView):+ partner_throttle_classes = [ResourceCreatesThrottle]++ def post(self, request: Request) -> Response:+ user = cast(User, request.user)+ access_token = cast(OAuthAccessToken, request.auth)++ app = access_token.application++ data = self.validated_body(ResourceCreateSerializer, request, context={"partner": app})+ label_prefix = data["label_prefix"]++ scoped_teams = access_token.scoped_teams or []++ if not scoped_teams:+ capture_provisioning_event("resource_created", "error", partner=app, error_code="no_team")+ raise ProvisioningError("no_team", "No team associated with this token")++ project_id = data["project_id"]+ configuration = data["configuration"]++ if project_id:+ try:+ team, scoped_teams = resolve_or_create_project_team(+ project_id, scoped_teams, user, configuration, access_token+ )+ except ProjectIdCollisionError:+ capture_provisioning_event(+ "resource_created", "error", partner=app, error_code="project_id_conflict", project_id=project_id+ )+ raise ProvisioningError(+ "project_id_conflict",+ "Project ID already linked to another organization",+ status=409,+ )+ if team is None:+ capture_provisioning_event(+ "resource_created", "error", partner=app, error_code="not_found", project_id=project_id+ )+ raise ProvisioningError("not_found", "Resource not found", status=404)+ else:+ team_id = scoped_teams[0]+ try:+ team = Team.objects.get(id=team_id)+ except Team.DoesNotExist:+ capture_provisioning_event(+ "resource_created", "error", partner=app, error_code="team_not_found", team_id=team_id+ )+ raise ProvisioningError("team_not_found", "Team not found", resource_id=str(team_id), status=404)++ capture_provisioning_event(+ "resource_created",+ "success",+ partner=app,+ team_id=team.id,+ )++ return _access_configuration_response(+ resource_id=str(team.id),+ team=team,+ user=user,+ access_token=access_token,+ label_prefix=label_prefix,+ )+++class ResourceDetailView(BearerResourceAPIView):+ def get(self, request: Request, resource_id: str) -> Response:+ user = cast(User, request.user)+ access_token = cast(OAuthAccessToken, request.auth)+ team = self.get_scoped_team(resource_id, access_token)++ return _access_configuration_response(+ resource_id=resource_id,+ team=team,+ user=user,+ access_token=access_token,+ label_prefix=None,+ # A read never mints a personal API key; rotation/creation do.+ mint_pat=False,+ )+++class RotateCredentialsView(BearerResourceAPIView):+ def post(self, request: Request, resource_id: str) -> Response:+ user = cast(User, request.user)+ access_token = cast(OAuthAccessToken, request.auth)++ data = self.validated_body(+ RotateCredentialsSerializer, request, resource_id=resource_id, context={"resource_id": resource_id}+ )+ label_prefix = data["label_prefix"]++ team = self.get_scoped_team(resource_id, access_token)++ try:+ # Bearer flow resolves the token outside DRF's session machinery,+ # so read impersonation off the token directly.+ team.reset_token_and_save(user=user, is_impersonated_session=access_token.impersonated_by_id is not None)+ except Exception:+ capture_exception(additional_properties={"team_id": team.id})+ capture_provisioning_event("credential_rotation", "failed", team_id=team.id)+ raise ProvisioningError(+ "credential_rotation_failed", "Failed to rotate credentials", resource_id=resource_id, status=500+ )++ capture_provisioning_event("credential_rotation", "success", team_id=team.id)++ return _access_configuration_response(+ resource_id=resource_id,+ team=team,+ user=user,+ access_token=access_token,+ label_prefix=label_prefix,+ )+++class ResourceRemoveView(BearerResourceAPIView):+ """Detaches the resource from the orchestrator: removes it from the token's+ scope and clears provisioning metadata. Preserves the underlying team and+ user data so the customer can still access PostHog directly."""++ def post(self, request: Request, resource_id: str) -> Response:+ access_token = cast(OAuthAccessToken, request.auth)++ team_id = self.parse_resource_team_id(resource_id, access_token)++ try:+ # Clear the mapping only if it is unclaimed or owned by the caller's+ # application; an in-scope partner must not delete another partner's+ # provisioning mapping for the same team.+ config = TeamProvisioningConfig.objects.filter(team_id=team_id).first()+ if config is not None and config.application_id in (None, access_token.application_id):+ config.delete()+ except Exception:+ capture_exception(additional_properties={"team_id": team_id, "step": "remove_provisioning_config"})+ capture_provisioning_event("resource_removed", "error", team_id=team_id, error_code="remove_config_failed")+ raise ProvisioningError("remove_failed", "Failed to remove resource", resource_id=resource_id, status=500)++ remove_team_from_token_scopes(access_token, team_id)++ capture_provisioning_event("resource_removed", "success", team_id=team_id)++ return Response({"status": "removed", "id": resource_id})+++class GitHubIntegrationView(BearerResourceAPIView):+ """Link a GitHub installation to the team from a stored grant."""++ def post(self, request: Request, resource_id: str) -> Response:+ user = cast(User, request.user)+ access_token = cast(OAuthAccessToken, request.auth)++ team = self.get_scoped_team(resource_id, access_token)++ data = self.validated_body(+ GitHubIntegrationSerializer, request, resource_id=resource_id, context={"resource_id": resource_id}+ )++ integration, already_linked = link_github_grant_to_team(+ partner=access_token.application,+ user=user,+ team=team,+ grant_id=str(data["grant_id"]),+ installation_id=str(data["installation_id"]),+ )++ return Response(+ {+ "status": "complete",+ "id": resource_id,+ "github_integration": {+ "integration_id": str(integration.id),+ "gh_login": (integration.config or {}).get("connecting_user_github_login"),+ "already_linked": already_linked,+ },+ }+ )+++class WizardRunsView(BearerResourceAPIView):+ """Kick off a cloud wizard run against a repository the team's GitHub+ integration can reach."""++ def post(self, request: Request, resource_id: str) -> Response:+ user = cast(User, request.user)+ access_token = cast(OAuthAccessToken, request.auth)++ team = self.get_scoped_team(resource_id, access_token)++ data = self.validated_body(+ WizardRunSerializer, request, resource_id=resource_id, context={"resource_id": resource_id}+ )++ run_payload = create_wizard_run(+ partner=access_token.application,+ user_id=user.id,+ team=team,+ repository=str(data["repository"]),+ branch=data["branch"],+ )++ return Response({"status": "complete", "id": resource_id, "wizard_run": run_payload})diff --git a/ee/api/agentic_provisioning/wizard.py b/ee/api/agentic_provisioning/wizard.pynew file mode 100644index 000000000000..c9ceee741d06--- /dev/null+++ b/ee/api/agentic_provisioning/wizard.py@@ -0,0 +1,184 @@+"""Drop-flow actions: linking a stored GitHub grant to a team and starting+cloud wizard runs against a repository."""++from __future__ import annotations++from django.conf import settings+from django.utils import timezone++from rest_framework.exceptions import ValidationError as DRFValidationError++from posthog.api.github_callback.team_services import link_github_installation_for_user+from posthog.exceptions_capture import capture_exception+from posthog.models.integration import GitHubInstallationAccessFetchError, GitHubIntegration, Integration+from posthog.models.oauth import OAuthApplication+from posthog.models.team.team import Team+from posthog.models.user import OnboardingSkippedReason, User++from products.tasks.backend.facade import api as tasks_facade++from ee.api.agentic_provisioning import github_grants+from ee.api.agentic_provisioning.analytics import capture_provisioning_event+from ee.api.agentic_provisioning.exceptions import ProvisioningError+from ee.api.agentic_provisioning.throttling import enforce_partner_rate_limit, enforce_wizard_run_user_rate_limit+++def _drf_validation_error_code(exc: DRFValidationError) -> str | None:+ codes = exc.get_codes()+ if isinstance(codes, list) and codes:+ return str(codes[0])+ if isinstance(codes, str):+ return codes+ return None+++def apply_provisioned_onboarding_flags(user: User, team: Team) -> None:+ """Keep the app from routing a partner-provisioned account into onboarding on first+ login. Only applied to unclaimed accounts (never logged in, no password set) so an+ existing user going through the consent path keeps their onboarding state."""+ # Bootstrapped accounts store password="" (create_user skips set_password when the+ # password is None), which Django counts as *usable* — treat it as no password.+ has_password = bool(user.password) and user.has_usable_password()+ if user.last_login is not None or has_password:+ return+ if user.onboarding_skipped_at is None:+ user.onboarding_skipped_at = timezone.now()+ user.onboarding_skipped_reason = OnboardingSkippedReason.PROVISIONED+ user.onboarding_skipped_organization_id = team.organization_id+ user.save(+ update_fields=["onboarding_skipped_at", "onboarding_skipped_reason", "onboarding_skipped_organization_id"]+ )+ if not team.completed_snippet_onboarding:+ team.completed_snippet_onboarding = True+ team.save(update_fields=["completed_snippet_onboarding"])+++def link_github_grant_to_team(+ *, partner: OAuthApplication, user: User, team: Team, grant_id: str, installation_id: str+) -> tuple[Integration, bool]:+ """Shared core of the github_integration action and the account_requests wizard+ block: validate the grant, verify installation ownership, create both GitHub+ records, consume the grant. Returns (integration, already_linked); raises+ :class:`ProvisioningError` on failure.+ """+ grant = github_grants.load_grant(grant_id, partner)+ if grant is None:+ # Idempotent retry: the grant is consumed on success, so a retry after a lost+ # response must not fail if the installation is already linked to this team.+ existing = Integration.objects.first_github_for_team_installation(team.id, str(installation_id))+ if existing is not None:+ # Re-apply onboarding flags idempotently: the grant is consumed as the last step,+ # so a crash between consume and the flag write would otherwise leave them unset+ # on a retry (this branch runs only once the grant is already gone).+ apply_provisioned_onboarding_flags(user, team)+ return existing, True+ capture_provisioning_event("github_integration", "error", partner=partner, error_code="grant_not_found")+ raise ProvisioningError("grant_not_found", "Grant not found or expired", resource_id=str(team.id), status=404)++ try:+ integration = link_github_installation_for_user(+ user=user, team_id=team.id, installation_id=str(installation_id), authorization=grant.to_authorization()+ )+ except DRFValidationError as exc:+ code = _drf_validation_error_code(exc)+ if code == "installation_access_denied":+ capture_provisioning_event("github_integration", "error", partner=partner, error_code=code)+ raise ProvisioningError(+ "installation_access_denied",+ "The GitHub user does not have access to this installation",+ resource_id=str(team.id),+ status=403,+ )+ if code == "installation_verify_failed":+ capture_provisioning_event("github_integration", "error", partner=partner, error_code=code)+ raise ProvisioningError(+ "installation_verify_failed",+ "Could not verify installation access with GitHub",+ resource_id=str(team.id),+ status=502,+ )+ capture_provisioning_event("github_integration", "error", partner=partner, error_code="invalid_request")+ raise ProvisioningError("invalid_request", str(exc.detail), resource_id=str(team.id), status=400)+ except GitHubInstallationAccessFetchError:+ capture_provisioning_event(+ "github_integration", "error", partner=partner, error_code="integration_creation_failed"+ )+ raise ProvisioningError(+ "integration_creation_failed",+ "Could not create the GitHub integration",+ resource_id=str(team.id),+ status=502,+ )++ github_grants.consume_grant(grant_id)+ apply_provisioned_onboarding_flags(user, team)+ capture_provisioning_event("github_integration", "success", partner=partner, team_id=team.id)+ return integration, False+++def _github_integration_required_error(partner: OAuthApplication, team: Team) -> ProvisioningError:+ capture_provisioning_event(+ "wizard_run", "error", partner=partner, error_code="github_integration_required", team_id=team.id+ )+ return ProvisioningError(+ "github_integration_required",+ "The team does not have a GitHub integration that can access this repository",+ resource_id=str(team.id),+ status=400,+ )+++def create_wizard_run(+ *, partner: OAuthApplication, user_id: int, team: Team, repository: str, branch: str | None+) -> dict[str, str]:+ """Gate + throttle + create a cloud wizard run. Returns the run payload;+ raises :class:`ProvisioningError` on failure."""+ if not bool(settings.WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID):+ capture_provisioning_event("wizard_run", "error", partner=partner, error_code="wizard_unavailable")+ raise ProvisioningError(+ "wizard_unavailable",+ "Running the setup wizard in the cloud is not available",+ resource_id=str(team.id),+ status=503,+ )++ repository = (repository or "").strip()+ parts = repository.split("/")+ if len(parts) != 2 or not all(parts):+ raise ProvisioningError(+ "invalid_request", "repository must be in 'owner/repo' format", resource_id=str(team.id)+ )++ enforce_wizard_run_user_rate_limit(user_id, resource_id=str(team.id))+ enforce_partner_rate_limit(partner, "wizard_runs")++ # Verifying the grant user owns the installation doesn't prove the installation can+ # reach the requested repo — a valid grant for one installation could otherwise report+ # wizard success for an owner/repo it can't operate on. Fail fast instead (after the+ # rate limits, so this GitHub call can't be used as an unthrottled probe).+ if GitHubIntegration.first_for_team_repository(team.id, repository, source="integration") is None:+ raise _github_integration_required_error(partner, team)++ try:+ created = tasks_facade.create_wizard_cloud_run(+ team=team, user_id=user_id, repository=repository, branch=branch or None+ )+ except ValueError:+ # The facade raises when the team has no usable GitHub integration.+ raise _github_integration_required_error(partner, team)+ except Exception:+ capture_exception(additional_properties={"team_id": team.id, "step": "provisioning_wizard_run"})+ capture_provisioning_event(+ "wizard_run", "error", partner=partner, error_code="run_creation_failed", team_id=team.id+ )+ raise ProvisioningError(+ "run_creation_failed", "Failed to start the wizard run", resource_id=str(team.id), status=500+ )++ run = created.latest_run+ capture_provisioning_event("wizard_run", "success", partner=partner, team_id=team.id, task_id=str(created.task_id))+ return {+ "task_id": str(created.task_id),+ "run_id": str(run.id) if run else "",+ "status": str(run.status) if run else "queued",+ }diff --git a/ee/urls.py b/ee/urls.pyindex dd85cc5cc139..db36090b8e34 100644--- a/ee/urls.py+++ b/ee/urls.py@@ -18,7 +18,6 @@ from products.cdp.backend.api import hooksfrom ee.admin.loginas_views import loginas_user, upgrade_impersonationfrom ee.admin.oauth_views import admin_auth_check, admin_oauth_successfrom ee.api import integration-from ee.api.agentic_provisioning import views as agentic_provisioning_viewsfrom ee.api.vercel import vercel_connect, vercel_sso, vercel_webhooksfrom ee.middleware import admin_oauth2_callbackfrom ee.support_sidebar_max.views import MaxChatViewSet@@ -277,137 +276,7 @@ urlpatterns: list[Any] = [path("scim/v2/<uuid:domain_id>/Schemas", csrf_exempt(scim_views.SCIMSchemasView.as_view()), name="scim_schemas"),# Stripe Projects provisioning (APP 0.1d)path("api/partners/stripe/", include("ee.partners.stripe.api.provisioning.urls")),- # Account Provisioning- path(- "api/agentic/provisioning/account_requests",- csrf_exempt(agentic_provisioning_views.account_requests),- name="agentic_provisioning_account_requests",- ),- path(- "api/agentic/authorize",- agentic_provisioning_views.agentic_authorize,- name="agentic_authorize",- ),- path(- "api/agentic/authorize/pending/",- agentic_provisioning_views.agentic_authorize_pending,- name="agentic_authorize_pending",- ),- path(- "api/agentic/authorize/confirm/",- agentic_provisioning_views.agentic_authorize_confirm,- name="agentic_authorize_confirm",- ),- path(- "api/agentic/oauth/token",- csrf_exempt(agentic_provisioning_views.oauth_token),- name="agentic_provisioning_oauth_token",- ),- path(- "api/agentic/provisioning/resources",- csrf_exempt(agentic_provisioning_views.provisioning_resources_create),- name="agentic_provisioning_resources_create",- ),- path(- "api/agentic/provisioning/resources/<str:resource_id>/rotate_credentials",- csrf_exempt(agentic_provisioning_views.provisioning_rotate_credentials),- name="agentic_provisioning_rotate_credentials",- ),- path(- "api/agentic/provisioning/resources/<str:resource_id>/remove",- csrf_exempt(agentic_provisioning_views.provisioning_resource_remove),- name="agentic_provisioning_resource_remove",- ),- path(- "api/agentic/provisioning/resources/<str:resource_id>/github_integration",- csrf_exempt(agentic_provisioning_views.provisioning_github_integration),- name="agentic_provisioning_github_integration",- ),- path(- "api/agentic/provisioning/resources/<str:resource_id>/wizard_runs",- csrf_exempt(agentic_provisioning_views.provisioning_wizard_runs),- name="agentic_provisioning_wizard_runs",- ),- path(- "api/agentic/provisioning/resources/<str:resource_id>",- csrf_exempt(agentic_provisioning_views.provisioning_resource_detail),- name="agentic_provisioning_resource_detail",- ),- path(- "api/agentic/provisioning/deep_links",- csrf_exempt(agentic_provisioning_views.deep_links),- name="agentic_provisioning_deep_links",- ),- path(- "api/agentic/provisioning/github/grants",- csrf_exempt(agentic_provisioning_views.github_grants_create),- name="agentic_provisioning_github_grants_create",- ),- path(- "api/agentic/provisioning/github/grants/<str:grant_id>/repositories",- csrf_exempt(agentic_provisioning_views.github_grant_repositories),- name="agentic_provisioning_github_grant_repositories",- ),- path(- "agentic/login",- agentic_provisioning_views.agentic_login,- name="agentic_login",- ),- # Generic provisioning URL aliases (keep /api/agentic/... for backward compat)- path(- "api/provisioning/account_requests",- csrf_exempt(agentic_provisioning_views.account_requests),- name="provisioning_account_requests",- ),- path(- "api/provisioning/oauth/token",- csrf_exempt(agentic_provisioning_views.oauth_token),- name="provisioning_oauth_token",- ),- path(- "api/provisioning/resources",- csrf_exempt(agentic_provisioning_views.provisioning_resources_create),- name="provisioning_resources_create",- ),- path(- "api/provisioning/resources/<str:resource_id>/rotate_credentials",- csrf_exempt(agentic_provisioning_views.provisioning_rotate_credentials),- name="provisioning_rotate_credentials",- ),- path(- "api/provisioning/resources/<str:resource_id>/remove",- csrf_exempt(agentic_provisioning_views.provisioning_resource_remove),- name="provisioning_resource_remove",- ),- path(- "api/provisioning/resources/<str:resource_id>/github_integration",- csrf_exempt(agentic_provisioning_views.provisioning_github_integration),- name="provisioning_github_integration",- ),- path(- "api/provisioning/resources/<str:resource_id>/wizard_runs",- csrf_exempt(agentic_provisioning_views.provisioning_wizard_runs),- name="provisioning_wizard_runs",- ),- path(- "api/provisioning/resources/<str:resource_id>",- csrf_exempt(agentic_provisioning_views.provisioning_resource_detail),- name="provisioning_resource_detail",- ),- path(- "api/provisioning/deep_links",- csrf_exempt(agentic_provisioning_views.deep_links),- name="provisioning_deep_links",- ),- path(- "api/provisioning/github/grants",- csrf_exempt(agentic_provisioning_views.github_grants_create),- name="provisioning_github_grants_create",- ),- path(- "api/provisioning/github/grants/<str:grant_id>/repositories",- csrf_exempt(agentic_provisioning_views.github_grant_repositories),- name="provisioning_github_grant_repositories",- ),+ # Agentic provisioning (partner account/resource provisioning + deep-link login)+ path("", include("ee.api.agentic_provisioning.urls")),*admin_urlpatterns,]diff --git a/posthog/management/commands/backfill_agentic_provisioning_scope.py b/posthog/management/commands/backfill_agentic_provisioning_scope.pyindex 158aafb68d5c..ff293e3c70e5 100644--- a/posthog/management/commands/backfill_agentic_provisioning_scope.py+++ b/posthog/management/commands/backfill_agentic_provisioning_scope.py@@ -13,7 +13,7 @@ class Command(BaseCommand):help = ("Rehydrate scoped_teams on existing agentic provisioning OAuth tokens. ""Walks live access + refresh tokens for partner OAuth applications and "- "recomputes scoped_teams via _compute_partner_scoped_teams. Idempotent."+ "recomputes scoped_teams via compute_partner_scoped_teams. Idempotent.")def add_arguments(self, parser):@@ -30,9 +30,11 @@ class Command(BaseCommand):def handle(self, *args, **options):# Local import so the import graph stays small for the management command- # registry; views.py pulls in a much larger dependency surface than the- # rest of the command suite.- from ee.api.agentic_provisioning.views import _compute_partner_scoped_teams+ # registry; the provisioning package pulls in a much larger dependency+ # surface than the rest of the command suite.+ from ee.api.agentic_provisioning.tokens import (+ compute_partner_scoped_teams, # noqa: PLC0415 — keeps the heavy dep off the import path+ )application_id = options.get("application_id")dry_run: bool = options["dry_run"]@@ -67,8 +69,8 @@ class Command(BaseCommand):continueold_scope = list(access_token.scoped_teams or [])base_team_id = old_scope[0] if old_scope else 0- new_scope = _compute_partner_scoped_teams(application, user, base_team_id)- # _compute_partner_scoped_teams returns [] when the base team is gone or the+ new_scope = compute_partner_scoped_teams(application, user, base_team_id)+ # compute_partner_scoped_teams returns [] when the base team is gone or the# user lost access. An empty scoped_teams is treated as unrestricted by the# OAuth permission check (permissions.py), so writing [] here would strip the# project restriction from a live token. Leave the existing scope intact and@@ -108,7 +110,7 @@ class Command(BaseCommand):continueold_scope = list(refresh_token.scoped_teams or [])base_team_id = old_scope[0] if old_scope else 0- new_scope = _compute_partner_scoped_teams(application, user, base_team_id)+ new_scope = compute_partner_scoped_teams(application, user, base_team_id)# Same fail-closed rule as access tokens: never overwrite a restricted scope# with an empty (unrestricted) one. Leave it for re-authorization.if not new_scope: