: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
chore(provisioning): remove github grants and wizard runs from provisioning (#115808)
Rafael Audibertc52be6770425
diff --git a/ee/api/agentic_provisioning/__init__.py b/ee/api/agentic_provisioning/__init__.pyindex a4e56ec1df4e..1848cd7d3788 100644--- a/ee/api/agentic_provisioning/__init__.py+++ b/ee/api/agentic_provisioning/__init__.py@@ -1 +1 @@-"""Agentic provisioning API: partner-facing account, resource, and wizard endpoints."""+"""Agentic provisioning API: partner-facing account and resource endpoints."""diff --git a/ee/api/agentic_provisioning/accounts.py b/ee/api/agentic_provisioning/accounts.pyindex 936eaa396756..20433656142f 100644--- a/ee/api/agentic_provisioning/accounts.py+++ b/ee/api/agentic_provisioning/accounts.py@@ -20,7 +20,7 @@ from posthog.models.oauth import OAuthApplicationfrom posthog.models.organization_provisioning import OrganizationProvisioningfrom posthog.models.team.team import Teamfrom posthog.models.team.team_provisioning_config import TeamProvisioningConfig-from posthog.models.user import User+from posthog.models.user import OnboardingSkippedReason, Userfrom posthog.scopes import scopes_within_ceilingfrom posthog.tasks.email import send_provisioning_welcome@@ -35,11 +35,6 @@ from ee.api.agentic_provisioning.constants import ()from ee.api.agentic_provisioning.exceptions import ProvisioningErrorfrom ee.api.agentic_provisioning.regions import region_to_host-from ee.api.agentic_provisioning.wizard import (- apply_provisioned_onboarding_flags,- create_wizard_run,- link_github_grant_to_team,-)def partner_label(partner: OAuthApplication | None) -> str:@@ -217,6 +212,27 @@ def require_user_consent(}+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 handle_new_user(request_id: str,data: dict,@@ -283,9 +299,6 @@ def handle_new_user(team_id=team.id,)- # Every provisioned account is treated as already onboarded — apply the flags at- # bootstrap so the account is covered regardless of which follow-up blocks (if any)- # run, rather than only on the GitHub wizard path.apply_provisioned_onboarding_flags(user, team)# Emit the standard signup event so provisioned accounts flow into the shared@@ -301,29 +314,9 @@ def handle_new_user(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):- 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)+ send_provisioning_welcome.delay(user.id, reset_token, label)except Exception:capture_exception(additional_properties={"user_id": user.id, "step": "provisioning_welcome_email"})@@ -338,63 +331,7 @@ def handle_new_user(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:- # create_wizard_run refuses an ungranted partner anyway, but checking before the grant- # is linked keeps a refused request from consuming a single-use grant the partner- # would then have to mint again.- if not partner.provisioning.can_start_wizard_runs:- return {- "error": {- "code": "forbidden",- "message": "Starting wizard runs is not enabled for this partner",- }- }-- 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"}}+ return {"id": request_id, "type": "oauth", "oauth": {"code": code}}def resolve_pending_partner(partner_id: str) -> OAuthApplication | None:diff --git a/ee/api/agentic_provisioning/authentication.py b/ee/api/agentic_provisioning/authentication.pyindex 127038e061ff..243418752c5b 100644--- a/ee/api/agentic_provisioning/authentication.py+++ b/ee/api/agentic_provisioning/authentication.py@@ -2,7 +2,6 @@ from __future__ import annotationsfrom typing import NoReturn-from django.contrib.auth.models import AnonymousUserfrom django.utils import timezoneimport structlog@@ -256,61 +255,3 @@ class ProvisioningBearerAuthentication(ActivityCredentialMixin, BaseAuthenticatidef authenticate_header(self, request: Request) -> str:return "Bearer"---def authenticate_confidential_partner(request: Request, *, capability: str) -> OAuthApplication:- """Identify a provisioning partner, requiring proof-bearing auth and an explicitly granted- capability.-- Only confidential partners carry proof that the caller controls the partner. Public- partners are identified solely by a ``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.-- Authenticating is necessary but not sufficient. A CIMD client self-registers by publishing- a metadata document, and one that declares ``private_key_jwt`` becomes a confidential- client whose assertions it can sign with its own published key, so it would clear a- confidential-only gate without any PostHog involvement. ``capability`` names the- ``provisioning`` flag an admin has to grant on top, which self-registration never sets.-- Raises :class:`ProvisioningError` when no qualifying partner is identified.- """- auth = ProvisioningAuthentication()- try:- result = auth.authenticate(request)- except AuthenticationFailed as exc:- # Keep the reason: "this client must authenticate" and "this client is not registered"- # call for different fixes, and a flat 401 tells the partner neither.- raise ProvisioningError("unauthorized", str(exc.detail), status=401)- partner = result[1] if result else None- if partner is None:- raise ProvisioningError("unauthorized", CLIENT_NOT_REGISTERED_MESSAGE, status=401)- if not partner.requires_client_authentication:- raise ProvisioningError("forbidden", "This endpoint requires a confidential partner", status=403)- if not getattr(partner.provisioning, capability):- raise ProvisioningError("forbidden", "This endpoint is not enabled for this partner", status=403)- return partner---class ConfidentialPartnerAuthentication(ActivityCredentialMixin, 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.-- Subclassed per capability rather than parameterized, because DRF instantiates- authentication classes with no arguments."""-- # `ProvisioningAuthentication` records the partner, because this class authenticates through it.- activity_credential_type = "partner"- capability: str-- def authenticate(self, request: Request) -> tuple[AnonymousUser, OAuthApplication]:- return AnonymousUser(), authenticate_confidential_partner(request, capability=self.capability)-- def authenticate_header(self, request: Request) -> str:- return "Basic"---class GitHubGrantsAuthentication(ConfidentialPartnerAuthentication):- capability = "can_use_github_grants"diff --git a/ee/api/agentic_provisioning/constants.py b/ee/api/agentic_provisioning/constants.pyindex d569f0a5a45a..25956301f7f8 100644--- a/ee/api/agentic_provisioning/constants.py+++ b/ee/api/agentic_provisioning/constants.py@@ -6,7 +6,6 @@ import reAUTH_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@@ -39,17 +38,6 @@ CLIENT_REGISTRATION_IP_RATE_LIMIT_MAX = 120# Per-partner endpoint budgets live in ee/api/agentic_provisioning/ratelimits.py,# declared on each handler with @rate_limited.-# 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),-]-# 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 callerdiff --git a/ee/api/agentic_provisioning/exceptions.py b/ee/api/agentic_provisioning/exceptions.pyindex 4ab4a83b158e..e89f5d501d50 100644--- a/ee/api/agentic_provisioning/exceptions.py+++ b/ee/api/agentic_provisioning/exceptions.py@@ -3,8 +3,8 @@The provisioning views serve three distinct wire contracts, so DRF's defaulterror 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+- ``typed``: ``{"type": "error", "error": {...}}`` — account requests,+ where "type" is the discriminator partners switch on("oauth" | "requires_auth" | "registering" | "error").- ``status``: ``{"status": "error", "id": ..., "error": {...}}`` — theresource endpoints, whose success envelope carries "status" (provisioningdiff --git a/ee/api/agentic_provisioning/github_grants.py b/ee/api/agentic_provisioning/github_grants.pydeleted file mode 100644index 9d5018ea5d4f..000000000000--- a/ee/api/agentic_provisioning/github_grants.py+++ /dev/null@@ -1,286 +0,0 @@-"""Server-side store for GitHub user authorizations minted during a partner drop flow.--A partner (e.g. posthog.com) exchanges a GitHub OAuth code via the provisioning API and-receives only an opaque ``grant_id`` — the GitHub user-to-server tokens never leave-PostHog. The grant is later consumed when the GitHub installation is linked to a team-(the ``github_integration`` resource action or the ``configuration.wizard`` block in-``account_requests``).--Grants are region-local: they live in this region's cache, so every follow-up call that-references a ``grant_id`` must hit the region that minted it. v1 partners are US-only.-"""--from __future__ import annotations--import json-import secrets-import dataclasses-from dataclasses import dataclass, field-from typing import Any--from django.core.cache import cache-from django.utils import timezone--import requests-import structlog-from cryptography.fernet import InvalidToken--from posthog.egress.github.transport import github_request-from posthog.egress.limiter.policies import Priority-from posthog.helpers.encrypted_fields import EncryptedTextField-from posthog.models.integration import GitHubUserAuthorization-from posthog.models.oauth import OAuthApplication--from ee.api.agentic_provisioning.constants import GITHUB_GRANT_CACHE_PREFIX--logger = structlog.get_logger(__name__)--# Long enough to survive the existing-user consent detour (login + in-app approval),-# short enough that a stored user token goes stale quickly if never used.-GITHUB_GRANT_TTL_SECONDS = 3600--# The payload holds GitHub user-to-server tokens, so it is encrypted at rest in the-# cache with the same MultiFernet keys that back EncryptedJSONField columns.-_grant_cipher = EncryptedTextField()---class GitHubEmailAccessDenied(Exception):- """GitHub refused the /user/emails read — almost always the App missing the- "Email addresses (read)" account permission, i.e. our misconfiguration.-- Kept distinct from "the user has no verified email" (a legitimate state the- partner recovers from by collecting an email inline) so the misconfiguration- stays a loud error instead of silently degrading every drop."""---@dataclass(frozen=True)-class GitHubGrant:- """A stored GitHub user authorization, bound to the partner that created it."""-- grant_id: str- partner_id: str- gh_id: int- gh_login: str- email: str | None- access_token: str = field(repr=False)- refresh_token: str | None = field(repr=False)- access_token_expires_in: int | None- refresh_token_expires_in: int | None- created_at: str- # None only for grants cached before the field existed.- identity_verified_at: int | None = None-- def to_authorization(self) -> GitHubUserAuthorization:- authorization = GitHubUserAuthorization(- gh_id=self.gh_id,- gh_login=self.gh_login,- access_token=self.access_token,- refresh_token=self.refresh_token,- access_token_expires_in=self.access_token_expires_in,- refresh_token_expires_in=self.refresh_token_expires_in,- )- if self.identity_verified_at is None:- return authorization- return dataclasses.replace(authorization, identity_verified_at=self.identity_verified_at)-- def cache_payload(self) -> dict[str, Any]:- return {- "partner_id": self.partner_id,- "gh_id": self.gh_id,- "gh_login": self.gh_login,- "email": self.email,- "access_token": self.access_token,- "refresh_token": self.refresh_token,- "access_token_expires_in": self.access_token_expires_in,- "refresh_token_expires_in": self.refresh_token_expires_in,- "created_at": self.created_at,- "identity_verified_at": self.identity_verified_at,- }-- @classmethod- def from_cache(cls, grant_id: str, payload: dict[str, Any]) -> GitHubGrant:- return cls(- grant_id=grant_id,- partner_id=payload["partner_id"],- gh_id=payload["gh_id"],- gh_login=payload["gh_login"],- email=payload["email"],- access_token=payload["access_token"],- refresh_token=payload.get("refresh_token"),- access_token_expires_in=payload.get("access_token_expires_in"),- refresh_token_expires_in=payload.get("refresh_token_expires_in"),- created_at=payload["created_at"],- identity_verified_at=payload.get("identity_verified_at"),- )---def create_grant(partner: OAuthApplication, authorization: GitHubUserAuthorization, email: str | None) -> GitHubGrant:- grant = GitHubGrant(- grant_id=secrets.token_urlsafe(32),- partner_id=str(partner.id),- gh_id=authorization.gh_id,- gh_login=authorization.gh_login,- email=email,- access_token=authorization.access_token,- refresh_token=authorization.refresh_token,- access_token_expires_in=authorization.access_token_expires_in,- refresh_token_expires_in=authorization.refresh_token_expires_in,- created_at=timezone.now().isoformat(),- identity_verified_at=authorization.identity_verified_at,- )- cache.set(- f"{GITHUB_GRANT_CACHE_PREFIX}{grant.grant_id}",- _grant_cipher.encrypt(json.dumps(grant.cache_payload())),- timeout=GITHUB_GRANT_TTL_SECONDS,- )- return grant---def load_grant(grant_id: str, partner: OAuthApplication) -> GitHubGrant | None:- """Load a grant if it exists and was created by ``partner``, else None.-- Partner mismatch deliberately looks identical to a missing grant so the endpoint- can't be used as an existence oracle for other partners' grants.- """- if not grant_id:- return None- raw = cache.get(f"{GITHUB_GRANT_CACHE_PREFIX}{grant_id}")- if raw is None:- return None- try:- payload = json.loads(_grant_cipher.decrypt(raw))- grant = GitHubGrant.from_cache(grant_id, payload)- except (InvalidToken, ValueError, KeyError, TypeError):- logger.warning("github_grant.corrupt_payload", grant_id=grant_id)- return None- if grant.partner_id != str(partner.id):- logger.warning("github_grant.partner_mismatch", grant_id=grant_id, partner_id=str(partner.id))- return None- return grant---def consume_grant(grant_id: str) -> None:- cache.delete(f"{GITHUB_GRANT_CACHE_PREFIX}{grant_id}")---def fetch_primary_email(access_token: str) -> str | None:- """Fetch the user's primary verified email with a user-to-server token.-- Returns None when the user simply has no verified email (the partner collects one- inline instead). Raises ``GitHubEmailAccessDenied`` when GitHub refuses the read- (missing App permission) and ``requests.RequestException`` on network errors or- GitHub 5xx so callers can distinguish "retry" from "won't work".- """- # Identity-blind: user OAuth token, metered against the user's budget.- response = github_request(- "GET",- "https://api.github.com/user/emails",- source="integration",- headers={"Authorization": f"Bearer {access_token}"},- params={"per_page": 100},- timeout=10,- priority=Priority.CRITICAL,- )- if response.status_code >= 500:- raise requests.RequestException(f"Unexpected status {response.status_code} listing user emails")- if response.status_code != 200:- logger.warning("github_grant.user_emails_denied", status_code=response.status_code)- raise GitHubEmailAccessDenied(f"GitHub returned {response.status_code} listing user emails")- emails = response.json()- if not isinstance(emails, list):- return None- verified = [e for e in emails if isinstance(e, dict) and e.get("verified") and e.get("email")]- for entry in verified:- if entry.get("primary"):- return str(entry["email"])- if verified:- return str(verified[0]["email"])- return None---# A single page covers the overwhelmingly common case; the cap bounds request fan-out-# for users with huge installations so the endpoint stays cheap to poll.-_REPOSITORY_PAGE_SIZE = 100-_REPOSITORY_MAX_PAGES = 3---def list_installations_and_repositories(access_token: str) -> dict[str, Any]:- """List the user's installations of our GitHub App and the repos each grants.-- A user-to-server token only ever sees installations of the App that minted it,- so no app filtering is needed. Raises ``requests.RequestException`` on failure.- """- # Identity-blind: user OAuth token, metered against the user's budget.- response = github_request(- "GET",- "https://api.github.com/user/installations",- source="integration",- headers={"Authorization": f"Bearer {access_token}"},- params={"per_page": 100},- timeout=10,- priority=Priority.CRITICAL,- )- if response.status_code != 200:- logger.warning("github_grant.list_installations_failed", status_code=response.status_code)- raise requests.RequestException(f"Unexpected status {response.status_code} listing user installations")-- installations: list[dict[str, Any]] = []- repositories: list[dict[str, Any]] = []- raw_installations = response.json().get("installations", [])- if not isinstance(raw_installations, list):- raw_installations = []-- for installation in raw_installations:- if not isinstance(installation, dict) or installation.get("id") is None:- continue- installation_id = str(installation["id"])- installations.append(- {- "id": installation_id,- "account_login": (installation.get("account") or {}).get("login"),- "repository_selection": installation.get("repository_selection"),- }- )- repositories.extend(_list_installation_repositories(access_token, installation_id))-- return {"installations": installations, "repositories": repositories}---def _list_installation_repositories(access_token: str, installation_id: str) -> list[dict[str, Any]]:- repositories: list[dict[str, Any]] = []- for page in range(1, _REPOSITORY_MAX_PAGES + 1):- response = github_request(- "GET",- f"https://api.github.com/user/installations/{installation_id}/repositories",- source="integration",- headers={"Authorization": f"Bearer {access_token}"},- params={"per_page": _REPOSITORY_PAGE_SIZE, "page": page},- timeout=10,- priority=Priority.CRITICAL,- )- if response.status_code != 200:- logger.warning(- "github_grant.list_repositories_failed",- status_code=response.status_code,- installation_id=installation_id,- )- raise requests.RequestException(- f"Unexpected status {response.status_code} listing installation repositories"- )- raw_repositories = response.json().get("repositories", [])- if not isinstance(raw_repositories, list):- break- for repository in raw_repositories:- if not isinstance(repository, dict) or not repository.get("full_name"):- continue- repositories.append(- {- "installation_id": installation_id,- "full_name": repository["full_name"],- "default_branch": repository.get("default_branch"),- "private": repository.get("private"),- }- )- if len(raw_repositories) < _REPOSITORY_PAGE_SIZE:- break- return repositoriesdiff --git a/ee/api/agentic_provisioning/ratelimits.py b/ee/api/agentic_provisioning/ratelimits.pyindex 00abd49f7454..956a51da61b9 100644--- a/ee/api/agentic_provisioning/ratelimits.py+++ b/ee/api/agentic_provisioning/ratelimits.py@@ -15,9 +15,7 @@ Charging happens two ways, mirroring where the partner becomes known:those refuse spends no partner quota.- ``charge="manual"``: the handler calls ``self.charge_rate_limit(...)`` onceit has resolved its partner (the token endpoint decodes a grant first,- account_requests must clear the capability check before spending quota), or- a flow outside any view (the bundled account-request wizard block) calls- :func:`charge_partner_by_name`.+ account_requests must clear the capability check before spending quota).A charge is refunded in ``handle_exception`` when the request provably did nowork (the error code is in the declaration's ``refund_on``), so a partner@@ -79,10 +77,9 @@ FLAT_MULTIPLIERS: dict[PartnerTier, int] = dict.fromkeys(TIER_MULTIPLIERS, 1)# Error codes whose requests provably did no work: rejections raised before the# endpoint writes anything or calls out. Any invalid_* code counts as no-work too-# (see _did_no_work), so validation codes need no entry here. Codes like-# github_unavailable are deliberately absent because the outbound call already-# happened, and so is not_found: the endpoints that raise it do so only after-# resolving the resource, so refunding it would make repeated probes free. An+# (see _did_no_work), so validation codes need no entry here. not_found is+# deliberately absent: the endpoints that raise it do so only after resolving+# the resource, so refunding it would make repeated probes free. An# endpoint that rejects before resolving anything can name its own code in# refund_on.DID_NO_WORK_CODES: frozenset[str] = frozenset(@@ -91,9 +88,7 @@ DID_NO_WORK_CODES: frozenset[str] = frozenset("unauthorized","no_team","team_not_found",- "grant_not_found","deep_links_not_enabled",- "wizard_unavailable",})@@ -319,25 +314,6 @@ def charge_partner(DECISIONS_COUNTER.labels(endpoint=declaration.endpoint, tier=tier, outcome="allowed").inc()-def charge_partner_by_name(- endpoint: str, partner: OAuthApplication, *, request: Request | None = None, resource_id: str = ""-) -> None:- """Charge by registry name, for flows that run outside any view dispatch- (the bundled account-request wizard block)."""- declaration = _REGISTRY.get(endpoint)- if declaration is None:- # Declarations register when the view modules import. Web processes load- # them through the URLconf; anything else (a test importing accounts.py- # directly) gets them here. Function-local to break the views->ratelimits- # import cycle.- from ee.api.agentic_provisioning import views # noqa: F401, PLC0415-- declaration = _REGISTRY.get(endpoint)- if declaration is None:- raise ImproperlyConfigured(f"No rate limit declared for endpoint {endpoint!r}")- charge_partner(declaration, partner, request=request, resource_id=resource_id)--def _did_no_work(error_code: str, refund_on: frozenset[str]) -> bool:# invalid_* is the convention every validation rejection follows, including# per-endpoint serializer codes (invalid_label_prefix, invalid_path, ...), sodiff --git a/ee/api/agentic_provisioning/serializers.py b/ee/api/agentic_provisioning/serializers.pyindex 73efb456c8fb..e2c01764368a 100644--- a/ee/api/agentic_provisioning/serializers.py+++ b/ee/api/agentic_provisioning/serializers.py@@ -74,7 +74,7 @@ class AccountRequestSerializer(serializers.Serializer):required=False,allow_null=True,default=dict,- help_text="Partner configuration: region (US/EU), organization_name, wizard block.",+ help_text="Partner configuration: region (US/EU), organization_name.",)code_challenge = serializers.CharField(required=False,@@ -123,34 +123,6 @@ class AccountRequestSerializer(serializers.Serializer):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."""@@ -208,58 +180,6 @@ class RotateCredentialsSerializer(serializers.Serializer):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."""diff --git a/ee/api/agentic_provisioning/test/base.py b/ee/api/agentic_provisioning/test/base.pyindex 5025c3468eaa..621407e70a74 100644--- a/ee/api/agentic_provisioning/test/base.py+++ b/ee/api/agentic_provisioning/test/base.py@@ -45,14 +45,12 @@ TEST_PARTNER_SCOPES = [# A partner granted everything, so a test narrows to the one capability it is about rather-# than restating the other eight. `provisioning_config(can_start_wizard_runs=False)` reads as-# the thing under test; a literal dict at each call site does not.+# than restating the rest. `provisioning_config(can_issue_deep_links=False)` reads as the+# thing under test; a literal dict at each call site does not.TEST_PARTNER_PROVISIONING: dict[str, bool] = {"active": True,"can_create_accounts": True,"can_provision_resources": True,- "can_use_github_grants": True,- "can_start_wizard_runs": True,"can_issue_deep_links": True,# Stands in for the one grandfathered app that still mints a provisioned PAT."issues_personal_api_key": True,diff --git a/ee/api/agentic_provisioning/test/test_account_requests.py b/ee/api/agentic_provisioning/test/test_account_requests.pyindex dc7154781a91..aee3b280dad1 100644--- a/ee/api/agentic_provisioning/test/test_account_requests.py+++ b/ee/api/agentic_provisioning/test/test_account_requests.py@@ -15,7 +15,7 @@ from posthog.models.oauth import OAuthApplicationfrom posthog.models.organization import Organizationfrom posthog.models.organization_provisioning import OrganizationProvisioningfrom posthog.models.team.team_provisioning_config import TeamProvisioningConfig-from posthog.models.user import User+from posthog.models.user import OnboardingSkippedReason, Userfrom posthog.test.authentication_checks import covers_authenticationfrom ee.api.agentic_provisioning.analytics import capture_provisioning_event@@ -72,6 +72,10 @@ class TestAccountRequests(ProvisioningTestBase):assert user.organization is not Noneassert user.team is not Noneassert TeamProvisioningConfig.objects.get(team=user.team).application_id == self.partner.id+ assert user.onboarding_skipped_reason == OnboardingSkippedReason.PROVISIONED+ assert user.onboarding_skipped_at is not None+ assert user.onboarding_skipped_organization_id == user.organization.id+ assert user.team.completed_snippet_onboarding is Truerecord = OrganizationProvisioning.objects.get(organization=user.organization)assert (record.partner, record.application_id) == ("provisioning_api", self.partner.id)diff --git a/ee/api/agentic_provisioning/test/test_account_requests_wizard.py b/ee/api/agentic_provisioning/test/test_account_requests_wizard.pydeleted file mode 100644index 17fa08e030f8..000000000000--- a/ee/api/agentic_provisioning/test/test_account_requests_wizard.py+++ /dev/null@@ -1,202 +0,0 @@-from datetime import timedelta--from unittest.mock import MagicMock, patch--from django.core.cache import cache-from django.test import override_settings-from django.utils import timezone--from posthog.models.integration import GitHubInstallationAccess, GitHubIntegration, GitHubUserAuthorization-from posthog.models.user import OnboardingSkippedReason, User--from ee.api.agentic_provisioning import github_grants-from ee.api.agentic_provisioning.constants import GITHUB_GRANT_CACHE_PREFIX-from ee.api.agentic_provisioning.test.base import ProvisioningTestBase--ACCOUNT_REQUESTS_URL = "/api/agentic/provisioning/account_requests"-INSTALLATION_ID = "777"-CODE_CHALLENGE = "a" * 43--AUTHORIZATION = GitHubUserAuthorization(- gh_id=12345,- gh_login="octocat",- access_token="gho_secret_user_token",- refresh_token="ghr_refresh_token",- access_token_expires_in=28800,- refresh_token_expires_in=15897600,-)---def _installation_access() -> GitHubInstallationAccess:- return GitHubInstallationAccess(- installation_id=INSTALLATION_ID,- installation_info={"account": {"type": "User", "login": "octocat"}},- access_token="ghs_installation_token",- token_expires_at=(timezone.now() + timedelta(hours=1)).isoformat(),- repository_selection="selected",- )---@override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")-class TestAccountRequestsWizardBlock(ProvisioningTestBase):- def _payload(self, email: str, wizard: dict | None = None) -> dict:- configuration: dict = {"region": "US"}- if wizard is not None:- configuration["wizard"] = wizard- return {- "id": "acctreq_wizard123",- "email": email,- "code_challenge": CODE_CHALLENGE,- "configuration": configuration,- }-- def _grant(self, email: str) -> github_grants.GitHubGrant:- return github_grants.create_grant(self.partner, AUTHORIZATION, email)-- def _post(self, payload: dict):- return self._post_with_client_secret(ACCOUNT_REQUESTS_URL, payload)-- def test_without_wizard_block_response_and_email_unchanged(self):- 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()- assert body["type"] == "oauth"- assert "wizard" not in body- assert mock_email.delay.call_count == 1- args, kwargs = mock_email.delay.call_args- assert len(args) == 3- assert kwargs == {}-- user = User.objects.get(email="[email protected]")- team = user.teams.get()- assert user.onboarding_skipped_reason == OnboardingSkippedReason.PROVISIONED- assert user.onboarding_skipped_at is not None- assert user.onboarding_skipped_organization_id == team.organization_id- assert team.completed_snippet_onboarding is True-- def test_bundled_happy_path_runs_wizard_then_emails(self):- grant = self._grant("[email protected]")- created = MagicMock(task_id="task-uuid", latest_run=MagicMock(id="run-uuid", status="queued"))- manager = MagicMock()- with (- patch.object(GitHubIntegration, "verify_user_installation_access", return_value=True),- 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.wizard.tasks_facade.create_wizard_cloud_run", return_value=created- ) as mock_create,- 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")- response = self._post(- self._payload(- "[email protected]",- wizard={- "grant_id": grant.grant_id,- "installation_id": INSTALLATION_ID,- "repository": "octocat/hello-world",- "branch": "main",- },- )- )-- assert response.status_code == 200, response.json()- body = response.json()- assert body["type"] == "oauth"- assert body["wizard"] == {"task_id": "task-uuid", "run_id": "run-uuid", "status": "queued"}-- user = User.objects.get(email="[email protected]")- team = user.teams.get()- mock_create.assert_called_once_with(team=team, user_id=user.id, repository="octocat/hello-world", branch="main")-- assert cache.get(f"{GITHUB_GRANT_CACHE_PREFIX}{grant.grant_id}") is None- assert user.onboarding_skipped_reason == OnboardingSkippedReason.PROVISIONED- team.refresh_from_db()- assert team.completed_snippet_onboarding is True-- assert mock_email.delay.call_args.kwargs == {"repository": "octocat/hello-world"}- call_names = [name for name, _args, _kwargs in manager.mock_calls]- 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.accounts.send_provisioning_welcome") as mock_email:- response = self._post(- self._payload(- "[email protected]",- wizard={- "grant_id": "nonexistent",- "installation_id": INSTALLATION_ID,- "repository": "octocat/hello-world",- },- )- )- assert response.status_code == 200, response.json()- body = response.json()- assert body["type"] == "oauth"- assert "code" in body["oauth"]- assert body["wizard"]["error"]["code"] == "grant_not_found"- assert User.objects.filter(email="[email protected]").exists()- assert mock_email.delay.call_args.kwargs == {}-- def test_wizard_ownership_denied_preserves_grant(self):- grant = self._grant("[email protected]")- with (- patch.object(GitHubIntegration, "verify_user_installation_access", return_value=False),- patch("ee.api.agentic_provisioning.accounts.send_provisioning_welcome"),- ):- response = self._post(- self._payload(- "[email protected]",- wizard={- "grant_id": grant.grant_id,- "installation_id": INSTALLATION_ID,- "repository": "octocat/hello-world",- },- )- )- assert response.status_code == 200- assert response.json()["wizard"]["error"]["code"] == "installation_access_denied"- assert cache.get(f"{GITHUB_GRANT_CACHE_PREFIX}{grant.grant_id}") is not None-- @override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="")- def test_wizard_unavailable_when_cloud_run_not_configured(self):- grant = self._grant("[email protected]")- 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.accounts.send_provisioning_welcome") as mock_email,- ):- response = self._post(- self._payload(- "[email protected]",- wizard={- "grant_id": grant.grant_id,- "installation_id": INSTALLATION_ID,- "repository": "octocat/hello-world",- },- )- )- assert response.status_code == 200- assert response.json()["wizard"]["error"]["code"] == "wizard_unavailable"- assert mock_email.delay.call_args.kwargs == {}-- def test_existing_user_with_wizard_block_gets_requires_auth_and_grant_survives(self):- User.objects.create_user(email="[email protected]", password="hunter2!!", first_name="Ex")- grant = self._grant("[email protected]")- response = self._post(- self._payload(- "[email protected]",- wizard={- "grant_id": grant.grant_id,- "installation_id": INSTALLATION_ID,- "repository": "octocat/hello-world",- },- )- )- assert response.status_code == 200, response.json()- body = response.json()- assert body["type"] == "requires_auth"- assert "wizard" not in body- assert cache.get(f"{GITHUB_GRANT_CACHE_PREFIX}{grant.grant_id}") is not Nonediff --git a/ee/api/agentic_provisioning/test/test_client_registration.py b/ee/api/agentic_provisioning/test/test_client_registration.pyindex 9e517e95e350..67e4830a9948 100644--- a/ee/api/agentic_provisioning/test/test_client_registration.py+++ b/ee/api/agentic_provisioning/test/test_client_registration.py@@ -11,7 +11,7 @@ import jwtfrom cryptography.hazmat.primitives.asymmetric import rsafrom parameterized import parameterized-from posthog.api.oauth.cimd import CIMDFetchError, apply_provisioning_defaults+from posthog.api.oauth.cimd import apply_provisioning_defaultsfrom posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARER, ClientAssertionErrorfrom posthog.models.oauth import OAuthApplication@@ -116,8 +116,8 @@ class TestClientRegistration(ProvisioningTestBase):"_provisioning_config": provisioning_config(active=True,can_create_accounts=True,- can_use_github_grants=False,- can_start_wizard_runs=False,+ can_issue_deep_links=False,+ issues_personal_api_key=False,),}return OAuthApplication.objects.create(**{**defaults, **overrides})@@ -157,10 +157,7 @@ class TestClientRegistration(ProvisioningTestBase):assert body["registered"] is Trueassert body["client_id"] == CIMD_URLassert body["token_endpoint_auth_method"] == "private_key_jwt"- # Signing assertions with a key it published itself proves only that it controls its- # own metadata document, which anyone can do, so it is not yet a partner PostHog- # vouched for.- assert body["capabilities"]["github_grants"] is False+ assert body["capabilities"] == {"account_requests": True}checks = {check["name"]: check for check in body["checks"]}assert checks["jwks"]["ok"] is Trueassert KID in checks["jwks"]["detail"]@@ -217,27 +214,6 @@ class TestClientRegistration(ProvisioningTestBase):assert app.client_type == OAuthApplication.CLIENT_PUBLICassert app.is_provisioning_partner is False- def test_partner_registered_by_an_admin_can_use_github_grants(self):- self._make_partner(_provisioning_config=provisioning_config(can_use_github_grants=True))-- res = self._register({"client_id": CIMD_URL})-- assert res.status_code == 200, res.json()- assert res.json()["capabilities"]["github_grants"] is True-- def test_public_client_is_told_it_cannot_use_github_grants(self):- self._make_partner(client_type=OAuthApplication.CLIENT_PUBLIC, jwks_uri=None)-- # A document declaring no auth method keeps the refresh from re-promoting it.- res = self._register({"client_id": CIMD_URL}, metadata_error=CIMDFetchError("offline"))-- assert res.status_code == 200, res.json()- body = res.json()- assert body["token_endpoint_auth_method"] == "none"- # The reason a public client gets 403 on the grant endpoints is not derivable from its- # own metadata document, so the diagnostics have to state it.- assert body["capabilities"]["github_grants"] is False-def test_opts_an_existing_cimd_oauth_app_into_provisioning(self):# A CIMD app registered through the ordinary OAuth flow carries no provisioning# config. Opting it in used to happen implicitly on the auth path; it is now this@@ -382,14 +358,8 @@ class TestUnregisteredClientsFailClosed(ProvisioningTestBase):endpoint, instead of the old behavior where an unknown CIMD client_id silently kicked offa background registration and answered "retry shortly"."""- @parameterized.expand(- [- ("account_requests", ACCOUNT_REQUESTS_URL, {"id": "r1", "email": "[email protected]"}),- ("github_grants", "/api/agentic/provisioning/github/grants", {"code": "gh-code"}),- ]- )- def test_unknown_client_id_is_pointed_at_the_registration_endpoint(self, _name, url, body):- res = self._post_api(url, {**body, "client_id": CIMD_URL})+ def test_unknown_client_id_is_pointed_at_the_registration_endpoint(self):+ res = self._post_api(ACCOUNT_REQUESTS_URL, {"id": "r1", "email": "[email protected]", "client_id": CIMD_URL})assert res.status_code == 401message = res.json()["error"]["message"]diff --git a/ee/api/agentic_provisioning/test/test_github_grants.py b/ee/api/agentic_provisioning/test/test_github_grants.pydeleted file mode 100644index b47363bf47f7..000000000000--- a/ee/api/agentic_provisioning/test/test_github_grants.py+++ /dev/null@@ -1,379 +0,0 @@-import dataclasses--from unittest.mock import MagicMock, patch--from django.core.cache import cache--import requests-from parameterized import parameterized--from posthog.models.integration import GitHubUserAuthorization-from posthog.models.oauth import OAuthApplication-from posthog.test.authentication_checks import covers_authentication-from posthog.token_bucket import Budget--from ee.api.agentic_provisioning import github_grants-from ee.api.agentic_provisioning.authentication import ConfidentialPartnerAuthentication, GitHubGrantsAuthentication-from ee.api.agentic_provisioning.constants import GITHUB_GRANT_CACHE_PREFIX-from ee.api.agentic_provisioning.test.base import (- TEST_PARTNER_CLIENT_SECRET,- ProvisioningTestBase,- patched_budget,- provisioning_config,-)-from ee.api.agentic_provisioning.views.github_grants import GitHubGrantRepositoriesView--ACCESS_TOKEN = "gho_secret_user_token"--AUTHORIZATION = GitHubUserAuthorization(- gh_id=12345,- gh_login="octocat",- access_token=ACCESS_TOKEN,- refresh_token="ghr_refresh_token",- access_token_expires_in=28800,- refresh_token_expires_in=15897600,-)---def _github_response(status_code: int, payload: object) -> MagicMock:- response = MagicMock()- response.status_code = status_code- response.json.return_value = payload- return response---EMAILS_RESPONSE = _github_response(- 200,- [- {"email": "[email protected]", "primary": False, "verified": True},- {"email": "[email protected]", "primary": True, "verified": True},- {"email": "[email protected]", "primary": False, "verified": False},- ],-)--INSTALLATIONS_RESPONSE = _github_response(- 200,- {- "installations": [- {"id": 777, "account": {"login": "octocat"}, "repository_selection": "selected"},- ]- },-)--REPOSITORIES_RESPONSE = _github_response(- 200,- {- "repositories": [- {"full_name": "octocat/hello-world", "default_branch": "main", "private": False},- ]- },-)---class TestGitHubGrants(ProvisioningTestBase):- def _post_grants(self, body: dict):- return self._post_with_client_secret("/api/agentic/provisioning/github/grants", body)-- def _get_grants(self, url: str):- # A GET has no body to carry the credentials, so these endpoints need Basic auth.- return self._get_api(url, HTTP_AUTHORIZATION=self._basic_auth_header())-- def _create_grant_via_api(self):- with (- patch(- "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),- ):- return self._post_grants(- {"code": "gh_code", "redirect_uri": "https://posthog.com/api/wizard/github/callback"},- )-- @covers_authentication(ConfidentialPartnerAuthentication, GitHubGrantsAuthentication)- def test_create_grant_happy_path(self):- with (- patch(- "ee.api.agentic_provisioning.views.github_grants.GitHubIntegration.github_user_from_code",- return_value=dataclasses.replace(AUTHORIZATION, identity_verified_at=1_700_000_000),- ) as mock_exchange,- patch("ee.api.agentic_provisioning.github_grants.github_request", return_value=EMAILS_RESPONSE),- ):- response = self._post_grants(- {"code": "gh_code", "redirect_uri": "https://posthog.com/api/wizard/github/callback"},- )-- assert response.status_code == 200, response.json()- body = response.json()- assert body["gh_login"] == "octocat"- assert body["email"] == "[email protected]"- assert body["grant_id"]- # The redirect_uri must flow into the exchange — GitHub rejects mismatches.- mock_exchange.assert_called_once_with("gh_code", redirect_uri="https://posthog.com/api/wizard/github/callback")-- # Tokens are encrypted at rest in the cache; the loaded grant round-trips them.- raw = cache.get(f"{GITHUB_GRANT_CACHE_PREFIX}{body['grant_id']}")- assert isinstance(raw, str)- assert ACCESS_TOKEN not in raw- grant = github_grants.load_grant(body["grant_id"], self.partner)- assert grant is not None- assert grant.access_token == ACCESS_TOKEN- assert grant.email == "[email protected]"- assert grant.to_authorization().identity_verified_at == 1_700_000_000-- @parameterized.expand(- [- ("missing_code", {}, 400, "invalid_request"),- ("blank_code", {"code": ""}, 400, "invalid_request"),- ]- )- def test_create_grant_requires_code(self, _name, body, expected_status, expected_code):- response = self._post_grants(body)- assert response.status_code == expected_status- assert response.json()["error"]["code"] == expected_code-- def test_create_grant_exchange_failure_returns_502(self):- with patch(- "ee.api.agentic_provisioning.views.github_grants.GitHubIntegration.github_user_from_code",- return_value=None,- ):- response = self._post_grants({"code": "bad_code"})- assert response.status_code == 502- assert response.json()["error"]["code"] == "github_exchange_failed"-- def test_create_grant_github_request_failure_returns_502(self):- with patch(- "ee.api.agentic_provisioning.views.github_grants.GitHubIntegration.github_user_from_code",- side_effect=requests.RequestException("boom"),- ):- response = self._post_grants({"code": "gh_code"})- assert response.status_code == 502- assert response.json()["error"]["code"] == "github_unavailable"-- def test_create_grant_rejects_pkce_partner(self):- # PKCE partners are identified only by a public client_id, so they carry no proof- # of controlling the partner and must not reach the GitHub code exchange.- pkce_partner = OAuthApplication.objects.create(- name="PKCE Partner",- client_id="pkce_partner_client_id",- client_secret="",- client_type=OAuthApplication.CLIENT_PUBLIC,- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,- redirect_uris="https://pkce.example.com",- algorithm="RS256",- is_provisioning_partner=True,- _provisioning_config=provisioning_config(active=True, can_create_accounts=True),- )- response = self.client.post(- "/api/agentic/provisioning/github/grants",- data={"client_id": pkce_partner.client_id, "code": "gh_code"},- format="json",- )- assert response.status_code == 403- assert response.json()["error"]["code"] == "forbidden"-- def test_create_grant_without_verified_email_returns_null_email(self):- no_verified = _github_response(200, [{"email": "[email protected]", "primary": True, "verified": False}])- with (- patch(- "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),- ):- response = self._post_grants({"code": "gh_code"})- assert response.status_code == 200, response.json()- body = response.json()- assert body["email"] is None- grant = github_grants.load_grant(body["grant_id"], self.partner)- assert grant is not None- assert grant.email is None-- def test_create_grant_email_access_denied_returns_502(self):- denied = _github_response(404, {"message": "Not Found"})- with (- patch(- "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),- ):- response = self._post_grants({"code": "gh_code"})- assert response.status_code == 502- assert response.json()["error"]["code"] == "email_unavailable"-- def test_create_grant_requires_partner_auth(self):- response = self.client.post(- "/api/agentic/provisioning/github/grants",- data={"code": "gh_code"},- format="json",- )- assert response.status_code == 401-- def test_create_grant_requires_account_creation_permission(self):- self.partner.update_provisioning(can_create_accounts=False)- self.partner.save()- response = self._post_grants({"code": "gh_code"})- assert response.status_code == 403- assert response.json()["error"]["code"] == "forbidden"-- def test_create_grant_partner_rate_limited(self):- self.partner.update_provisioning_rate_limits(github_grants=1)- self.partner.save()- first = self._create_grant_via_api()- assert first.status_code == 200- second = self._create_grant_via_api()- assert second.status_code == 429- assert second["Retry-After"]-- def test_capability_refusal_does_not_spend_grant_budget(self):- self.partner.update_provisioning(can_create_accounts=False)- self.partner.update_provisioning_rate_limits(github_grants=1)- 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.update_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):- if url.endswith("/user/installations"):- return INSTALLATIONS_RESPONSE- return REPOSITORIES_RESPONSE-- with patch("ee.api.agentic_provisioning.github_grants.github_request", side_effect=fake_github_request):- response = self._get_grants(f"{base_url}/{grant.grant_id}/repositories")-- assert response.status_code == 200, response.json()- body = response.json()- assert body["gh_login"] == "octocat"- assert body["installations"] == [{"id": "777", "account_login": "octocat", "repository_selection": "selected"}]- assert body["repositories"] == [- {- "installation_id": "777",- "full_name": "octocat/hello-world",- "default_branch": "main",- "private": False,- }- ]-- def test_repositories_unknown_grant_returns_404(self):- response = self._get_grants("/api/agentic/provisioning/github/grants/nonexistent/repositories")- assert response.status_code == 404- assert response.json()["error"]["code"] == "grant_not_found"-- def _create_other_partner(- self, *, can_use_github_grants: bool = True, is_cimd_client: bool = False- ) -> OAuthApplication:- return OAuthApplication.objects.create(- name="Other Partner",- is_cimd_client=is_cimd_client,- client_id="other_partner_client_id",- client_secret=TEST_PARTNER_CLIENT_SECRET,- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,- redirect_uris="https://other.example.com",- algorithm="RS256",- is_provisioning_partner=True,- _provisioning_config=provisioning_config(- active=True, can_create_accounts=True, can_use_github_grants=can_use_github_grants- ),- )-- 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- assert response.json()["error"]["code"] == "grant_not_found"-- def test_repositories_poll_rate_limited(self):- grant = github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")- url = f"/api/agentic/provisioning/github/grants/{grant.grant_id}/repositories"-- def fake_github_request(method, request_url, **kwargs):- if request_url.endswith("/user/installations"):- return INSTALLATIONS_RESPONSE- return REPOSITORIES_RESPONSE-- with (- patched_budget(GitHubGrantRepositoriesView, "get", "grant_repo_polls", Budget(burst=1, per_hour=1)),- patch("ee.api.agentic_provisioning.github_grants.github_request", side_effect=fake_github_request),- ):- first = self._get_grants(url)- second = self._get_grants(url)- assert first.status_code == 200- assert second.status_code == 429- assert 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()-- def fake_github_request(method, request_url, **kwargs):- if request_url.endswith("/user/installations"):- return INSTALLATIONS_RESPONSE- return REPOSITORIES_RESPONSE-- with (- patched_budget(GitHubGrantRepositoriesView, "get", "grant_repo_polls", Budget(burst=1, per_hour=1)),- patch("ee.api.agentic_provisioning.github_grants.github_request", side_effect=fake_github_request),- ):- foreign = self._get_api(url, HTTP_AUTHORIZATION=self._basic_auth_header(other_partner))- owner = self._get_grants(url)-- assert foreign.status_code == 404- assert owner.status_code == 200-- def test_repositories_rejects_a_partner_without_the_capability(self):- # A CIMD client self-registers by publishing a metadata document and becomes confidential- # by declaring private_key_jwt, so authenticating cannot be the only gate here. The- # capability is granted by an admin, and self-registration never grants it.- grant = github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")- unvouched = self._create_other_partner(can_use_github_grants=False, is_cimd_client=True)- response = self._get_api(- f"/api/agentic/provisioning/github/grants/{grant.grant_id}/repositories",- HTTP_AUTHORIZATION=self._basic_auth_header(unvouched),- )- assert response.status_code == 403- assert response.json()["error"]["code"] == "forbidden"-- def test_repositories_allows_a_partner_granted_the_capability(self):- # The other half of the gate: the capability is what admits a partner, whether or not it- # is a CIMD client.- grant = github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")- admin_registered = self._create_other_partner(can_use_github_grants=True)-- 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.github_grants.github_request", side_effect=fake_github_request):- response = self._get_api(- f"/api/agentic/provisioning/github/grants/{grant.grant_id}/repositories",- HTTP_AUTHORIZATION=self._basic_auth_header(admin_registered),- )- # 404 rather than 200: it authenticated and passed the gate, then failed ownership on a- # grant belonging to another partner, which is the next check and the correct one.- assert response.status_code == 404- assert response.json()["error"]["code"] == "grant_not_found"-- def test_repositories_github_failure_returns_502(self):- grant = github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")- with patch(- "ee.api.agentic_provisioning.github_grants.github_request",- return_value=_github_response(500, {}),- ):- response = self._get_grants(f"/api/agentic/provisioning/github/grants/{grant.grant_id}/repositories")- assert response.status_code == 502- assert response.json()["error"]["code"] == "github_unavailable"diff --git a/ee/api/agentic_provisioning/test/test_limits.py b/ee/api/agentic_provisioning/test/test_limits.pyindex a8574ead08a3..577a47378ce7 100644--- a/ee/api/agentic_provisioning/test/test_limits.py+++ b/ee/api/agentic_provisioning/test/test_limits.py@@ -41,7 +41,7 @@ class TestLimitsEndpoint(ProvisioningTestBase):assert res["RateLimit-Limit"]def test_client_authenticated_partner_sees_its_overrides(self):- self.partner.update_provisioning_rate_limits(resource_creates=7, wizard_runs=-1)+ self.partner.update_provisioning_rate_limits(resource_creates=7, deep_links=-1)res = self.client.post(LIMITS_URL,@@ -51,7 +51,7 @@ class TestLimitsEndpoint(ProvisioningTestBase):assert res.status_code == 200body = res.json()assert body["endpoints"]["resource_creates"]["per_hour"] == 7- assert body["endpoints"]["wizard_runs"] == {"unlimited": True}+ assert body["endpoints"]["deep_links"] == {"unlimited": True}@parameterized.expand([diff --git a/ee/api/agentic_provisioning/test/test_partner_rate_limits.py b/ee/api/agentic_provisioning/test/test_partner_rate_limits.pyindex 645e6f5a7d86..33cd3daebadd 100644--- a/ee/api/agentic_provisioning/test/test_partner_rate_limits.py+++ b/ee/api/agentic_provisioning/test/test_partner_rate_limits.py@@ -16,7 +16,7 @@ from posthog.token_bucket import Budget, TEST_reset_scriptsfrom ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIXfrom ee.api.agentic_provisioning.exceptions import ProvisioningError-from ee.api.agentic_provisioning.ratelimits import FLAT_MULTIPLIERS, charge_partner_by_name+from ee.api.agentic_provisioning.ratelimits import FLAT_MULTIPLIERS, charge_partner, registered_budgetsfrom ee.api.agentic_provisioning.test.base import (TEST_PARTNER_CLIENT_SECRET,ProvisioningTestBase,@@ -24,10 +24,14 @@ from ee.api.agentic_provisioning.test.base import (provisioning_config,)from ee.api.agentic_provisioning.views.resources import RotateCredentialsView-from ee.api.agentic_provisioning.wizard import create_wizard_runPARTNER_CLIENT_ID = "partner_rate_limit_test"++def _charge(endpoint: str, partner: OAuthApplication) -> None:+ charge_partner(registered_budgets()[endpoint], partner)++# account_requests declares Budget(burst=5, per_hour=10); the tier grid scales it.ACCOUNT_REQUESTS_BURST_BY_TIER = {PartnerTier.PUBLIC: 5,@@ -96,10 +100,10 @@ class TestPartnerRateLimits(ProvisioningTestBase):with time_machine.travel("2026-01-01 00:00:00", tick=False):for _ in range(burst):- charge_partner_by_name("account_requests", partner)+ _charge("account_requests", partner)with self.assertRaises(ProvisioningError) as ctx:- charge_partner_by_name("account_requests", partner)+ _charge("account_requests", partner)assert ctx.exception.status == 429assert ctx.exception.retry_after is not None@@ -112,10 +116,10 @@ class TestPartnerRateLimits(ProvisioningTestBase):with time_machine.travel("2026-01-01 00:00:00", tick=False):for _ in range(2):- charge_partner_by_name("account_requests", self.partner_app)+ _charge("account_requests", self.partner_app)with self.assertRaises(ProvisioningError) as ctx:- charge_partner_by_name("account_requests", self.partner_app)+ _charge("account_requests", self.partner_app)assert ctx.exception.status == 429assert ctx.exception.retry_after is not None@@ -124,16 +128,16 @@ class TestPartnerRateLimits(ProvisioningTestBase):with time_machine.travel("2026-01-01 00:00:00", tick=False):for _ in range(100):- charge_partner_by_name("account_requests", self.partner_app)+ _charge("account_requests", self.partner_app)def test_separate_buckets_per_endpoint(self):self.partner_app.update_provisioning_rate_limits(account_requests=1, resource_creates=1)with time_machine.travel("2026-01-01 00:00:00", tick=False):- charge_partner_by_name("account_requests", self.partner_app)+ _charge("account_requests", self.partner_app)with self.assertRaises(ProvisioningError):- charge_partner_by_name("account_requests", self.partner_app)- charge_partner_by_name("resource_creates", self.partner_app)+ _charge("account_requests", self.partner_app)+ _charge("resource_creates", self.partner_app)def test_separate_buckets_per_partner(self):other_partner = self._partner_at_tier(PartnerTier.JWKS)@@ -141,11 +145,11 @@ class TestPartnerRateLimits(ProvisioningTestBase):other_partner.update_provisioning_rate_limits(account_requests=1)with time_machine.travel("2026-01-01 00:00:00", tick=False):- charge_partner_by_name("account_requests", self.partner_app)+ _charge("account_requests", self.partner_app)with self.assertRaises(ProvisioningError):- charge_partner_by_name("account_requests", self.partner_app)- charge_partner_by_name("account_requests", other_partner)+ _charge("account_requests", self.partner_app)+ _charge("account_requests", other_partner)# --- Integration: token endpoint ---@@ -265,36 +269,8 @@ class TestPartnerRateLimits(ProvisioningTestBase):def test_blocked_tier_cannot_use_deep_links(self):public_partner = self._partner_at_tier(PartnerTier.PUBLIC)with self.assertRaises(ProvisioningError) as ctx:- charge_partner_by_name("deep_links", public_partner)+ _charge("deep_links", public_partner)assert ctx.exception.status == 403# The JWKS tiers keep their budget.- charge_partner_by_name("deep_links", self._partner_at_tier(PartnerTier.JWKS))-- def test_failed_repository_probe_keeps_the_charge(self):- # The repository check is an authenticated GitHub call, so a rejected run has- # already done outbound work. With a budget of 1, a second attempt must be- # rate limited rather than probing GitHub again for free.- self.partner_app.update_provisioning(can_start_wizard_runs=True)- self.partner_app.update_provisioning_rate_limits(wizard_runs=1)-- with self.settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client"):- with self.assertRaises(ProvisioningError) as ctx:- create_wizard_run(- partner=self.partner_app,- user_id=self.user.id,- team=self.team,- repository="acme/widgets",- branch=None,- )- assert ctx.exception.code == "github_integration_required"-- with self.assertRaises(ProvisioningError) as ctx:- create_wizard_run(- partner=self.partner_app,- user_id=self.user.id,- team=self.team,- repository="acme/other",- branch=None,- )- assert ctx.exception.code == "rate_limited"+ _charge("deep_links", self._partner_at_tier(PartnerTier.JWKS))diff --git a/ee/api/agentic_provisioning/test/test_private_key_jwt_partner.py b/ee/api/agentic_provisioning/test/test_private_key_jwt_partner.pyindex 72cb7b77e275..0fdbcf892f86 100644--- a/ee/api/agentic_provisioning/test/test_private_key_jwt_partner.py+++ b/ee/api/agentic_provisioning/test/test_private_key_jwt_partner.py@@ -210,32 +210,3 @@ class TestPrivateKeyJwtPartner(ProvisioningTestBase):)assert res.status_code == 200, res.json()mock_refresh.assert_called_once_with(PARTNER_CLIENT_ID)-- def test_github_grant_listing_authenticates_from_the_query_string(self):- # The listing endpoint is a GET, so there is no body to carry the assertion. Without- # the query-string fallback a private_key_jwt partner would be locked out of it while- # a client_secret partner sailed through on the Basic header.- with patch("posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=(self.jwks, None)):- res = self.client.get(- "/api/agentic/provisioning/github/grants/unknown-grant/repositories",- data={- "client_assertion": self._assertion(jti_suffix="listing"),- "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER,- },- )-- # 404 for a grant that does not exist means authentication was accepted; 401/403 would- # mean it was not.- assert res.status_code == 404, res.json()- assert res.json()["error"]["code"] == "grant_not_found"-- def test_github_grants_accepts_a_private_key_jwt_partner(self):- # These endpoints require a confidential partner. private_key_jwt qualifies, since the- # assertion proves control of the client just as a secret would.- res = self._post(- "/api/agentic/provisioning/github/grants",- {"code": "", **self._assertion_body()},- )- # An empty GitHub code fails validation, which means auth was accepted.- assert res.status_code == 400- assert res.json()["error"]["code"] == "invalid_request"diff --git a/ee/api/agentic_provisioning/test/test_region_proxy.py b/ee/api/agentic_provisioning/test/test_region_proxy.pyindex 9d0a46124ec7..92fe90b09f06 100644--- a/ee/api/agentic_provisioning/test/test_region_proxy.py+++ b/ee/api/agentic_provisioning/test/test_region_proxy.py@@ -345,8 +345,6 @@ class TestRegionProxyCoverageContract(SimpleTestCase):"ResourceDetailView": "bearer_lookup","RotateCredentialsView": "bearer_lookup","ResourceRemoveView": "bearer_lookup",- "GitHubIntegrationView": "bearer_lookup",- "WizardRunsView": "bearer_lookup","DeepLinksView": "bearer_lookup","LimitsView": "bearer_lookup","AccountRequestsView": "body_region",diff --git a/ee/api/agentic_provisioning/test/test_wizard_resource_actions.py b/ee/api/agentic_provisioning/test/test_wizard_resource_actions.pydeleted file mode 100644index cb3c55b0caeb..000000000000--- a/ee/api/agentic_provisioning/test/test_wizard_resource_actions.py+++ /dev/null@@ -1,233 +0,0 @@-from datetime import timedelta--from unittest.mock import MagicMock, patch--from django.core.cache import cache-from django.test import override_settings-from django.utils import timezone--import requests-from parameterized import parameterized--from posthog.models.integration import GitHubInstallationAccess, GitHubIntegration, GitHubUserAuthorization, Integration-from posthog.models.team.team import Team-from posthog.models.user_integration import UserIntegration--from ee.api.agentic_provisioning import github_grants-from ee.api.agentic_provisioning.constants import GITHUB_GRANT_CACHE_PREFIX-from ee.api.agentic_provisioning.test.base import ProvisioningTestBase--INSTALLATION_ID = "777"--AUTHORIZATION = GitHubUserAuthorization(- gh_id=12345,- gh_login="octocat",- access_token="gho_secret_user_token",- refresh_token="ghr_refresh_token",- access_token_expires_in=28800,- refresh_token_expires_in=15897600,-)---def _installation_access() -> GitHubInstallationAccess:- return GitHubInstallationAccess(- installation_id=INSTALLATION_ID,- installation_info={"account": {"type": "User", "login": "octocat"}},- access_token="ghs_installation_token",- token_expires_at=(timezone.now() + timedelta(hours=1)).isoformat(),- repository_selection="selected",- )---class TestWizardResourceActions(ProvisioningTestBase):- def setUp(self):- super().setUp()- self.bearer = self._get_bearer_token()-- def _grant(self) -> github_grants.GitHubGrant:- return github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")-- def _post_github_integration(self, team_id: int, body: dict):- return self._post_with_bearer(- f"/api/agentic/provisioning/resources/{team_id}/github_integration", body, token=self.bearer- )-- def _post_wizard_runs(self, team_id: int, body: dict):- return self._post_with_bearer(- f"/api/agentic/provisioning/resources/{team_id}/wizard_runs", body, token=self.bearer- )-- def _mark_user_unclaimed(self):- self.user.set_unusable_password()- self.user.last_login = None- self.user.save()-- def test_github_integration_happy_path_links_and_consumes_grant(self):- self._mark_user_unclaimed()- grant = self._grant()- with (- patch.object(GitHubIntegration, "verify_user_installation_access", return_value=True),- patch.object(GitHubIntegration, "fetch_installation_access", return_value=_installation_access()),- ):- response = self._post_github_integration(- self.team.id, {"grant_id": grant.grant_id, "installation_id": INSTALLATION_ID}- )-- assert response.status_code == 200, response.json()- body = response.json()- assert body["status"] == "complete"- assert body["github_integration"]["gh_login"] == "octocat"- assert body["github_integration"]["already_linked"] is False-- integration = Integration.objects.get(team_id=self.team.id, kind="github", integration_id=INSTALLATION_ID)- assert integration.config["connecting_user_github_login"] == "octocat"- assert UserIntegration.objects.filter(- user=self.user, kind=UserIntegration.IntegrationKind.GITHUB, integration_id=INSTALLATION_ID- ).exists()-- assert cache.get(f"{GITHUB_GRANT_CACHE_PREFIX}{grant.grant_id}") is None-- # Onboarding flags are set at account bootstrap, never on the GitHub linking path,- # so linking a grant must not touch them.- self.user.refresh_from_db()- self.team.refresh_from_db()- assert self.user.onboarding_skipped_reason is None- assert self.user.onboarding_skipped_at is None- assert self.user.onboarding_skipped_organization_id is None- assert self.team.completed_snippet_onboarding is False-- def test_github_integration_unknown_grant_returns_404(self):- response = self._post_github_integration(- self.team.id, {"grant_id": "nonexistent", "installation_id": INSTALLATION_ID}- )- assert response.status_code == 404- assert response.json()["error"]["code"] == "grant_not_found"-- def test_github_integration_idempotent_retry_after_grant_consumed(self):- self._mark_user_unclaimed()- Integration.objects.create(- team_id=self.team.id,- kind="github",- integration_id=INSTALLATION_ID,- config={"installation_id": INSTALLATION_ID},- sensitive_config={},- )- response = self._post_github_integration(- self.team.id, {"grant_id": "already-consumed", "installation_id": INSTALLATION_ID}- )- assert response.status_code == 200- assert response.json()["github_integration"]["already_linked"] is True-- # The GitHub linking path never touches onboarding flags; they are set at bootstrap.- self.user.refresh_from_db()- assert self.user.onboarding_skipped_reason is None- assert self.user.onboarding_skipped_at is None-- @parameterized.expand(- [- ("access_denied", {"return_value": False}, 403, "installation_access_denied"),- (- "verify_error",- {"side_effect": requests.RequestException("boom")},- 502,- "installation_verify_failed",- ),- ]- )- def test_github_integration_ownership_failures_preserve_grant(self, _name, verify_kwargs, status, code):- grant = self._grant()- with patch.object(GitHubIntegration, "verify_user_installation_access", **verify_kwargs):- response = self._post_github_integration(- self.team.id, {"grant_id": grant.grant_id, "installation_id": INSTALLATION_ID}- )- assert response.status_code == status- assert response.json()["error"]["code"] == code- assert cache.get(f"{GITHUB_GRANT_CACHE_PREFIX}{grant.grant_id}") is not None-- def test_github_integration_team_outside_token_scope_returns_403(self):- other_team = Team.objects.create(organization=self.organization, name="other")- grant = self._grant()- response = self._post_github_integration(- other_team.id, {"grant_id": grant.grant_id, "installation_id": INSTALLATION_ID}- )- assert response.status_code == 403- assert response.json()["error"]["code"] == "forbidden"-- @override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")- def test_wizard_runs_rejects_a_partner_without_the_capability(self):- # Starting a coding-agent run in a customer's repository takes its own grant, which- # self-registration never gives out - a bearer token for an active partner is not enough.- self.partner.update_provisioning(can_start_wizard_runs=False)-- with 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 == 403- assert response.json()["error"]["code"] == "forbidden"- mock_create.assert_not_called()-- @override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="")- def test_wizard_runs_unavailable_without_oauth_client_id(self):- response = self._post_wizard_runs(self.team.id, {"repository": "octocat/hello-world"})- assert response.status_code == 503- assert response.json()["error"]["code"] == "wizard_unavailable"-- @override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")- def test_wizard_runs_happy_path(self):- created = MagicMock(task_id="task-uuid", latest_run=MagicMock(id="run-uuid", status="queued"))- with (- patch.object(GitHubIntegration, "first_for_team_repository", return_value=MagicMock()),- patch(- "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"})-- assert response.status_code == 200, response.json()- body = response.json()- assert body["status"] == "complete"- assert body["wizard_run"] == {"task_id": "task-uuid", "run_id": "run-uuid", "status": "queued"}- mock_create.assert_called_once_with(- team=self.team, user_id=self.user.id, repository="octocat/hello-world", branch="main"- )-- @parameterized.expand(- [- ("missing_repository", {}, "invalid_request"),- ("bad_format", {"repository": "not-a-repo"}, "invalid_request"),- ("too_many_parts", {"repository": "a/b/c"}, "invalid_request"),- ]- )- @override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")- def test_wizard_runs_rejects_invalid_repository(self, _name, body, code):- response = self._post_wizard_runs(self.team.id, body)- assert response.status_code == 400- assert response.json()["error"]["code"] == code-- @override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")- def test_wizard_runs_per_user_burst_limit(self):- 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.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"})- third = self._post_wizard_runs(self.team.id, {"repository": "octocat/three"})- assert first.status_code == 200- assert second.status_code == 200- assert third.status_code == 429- assert third["Retry-After"]-- @override_settings(WIZARD_CLOUD_RUN_OAUTH_CLIENT_ID="wizard-client-id")- def test_wizard_runs_rejects_repository_the_installation_cannot_access(self):- # No team integration can reach the repo -> fail fast without ever creating a run,- # 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.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 == 400- assert response.json()["error"]["code"] == "github_integration_required"- mock_create.assert_not_called()diff --git a/ee/api/agentic_provisioning/throttling.py b/ee/api/agentic_provisioning/throttling.pyindex 24e11c2fe2d8..099bffb1b7ac 100644--- a/ee/api/agentic_provisioning/throttling.py+++ b/ee/api/agentic_provisioning/throttling.py@@ -6,8 +6,6 @@ limits keyed on something other than a partner:- :class:`ClientRegistrationThrottle` and :class:`CIMDRegistrationThrottle`,per client_id / IP / domain, screening callers that are not partners yet.-- ``enforce_wizard_run_user_rate_limit``, per end user, shared between the- granular wizard_runs action and the bundled account_requests wizard block.- :class:`RegionProxyThrottle`, per IP, checked by the region proxy in``dispatch`` before DRF has authenticated the caller.@@ -46,10 +44,7 @@ from ee.api.agentic_provisioning.constants import (CLIENT_REGISTRATION_RATE_LIMIT_PREFIX,CLIENT_REGISTRATION_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 ProvisioningErrorlogger = structlog.get_logger(__name__)@@ -104,28 +99,6 @@ class RegionProxyThrottle(IPThrottle):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:- capture_provisioning_event(- "rate_limited", "rate_limited", endpoint="wizard_runs_user", limit=limit, window=label- )- 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 ClientRegistrationThrottle(BaseThrottle):"""Cap client_registration calls per client_id.diff --git a/ee/api/agentic_provisioning/urls.py b/ee/api/agentic_provisioning/urls.pyindex 7b43108a75d2..48bf85a81d06 100644--- a/ee/api/agentic_provisioning/urls.py+++ b/ee/api/agentic_provisioning/urls.py@@ -42,16 +42,6 @@ urlpatterns = [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()),@@ -67,16 +57,6 @@ urlpatterns = [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"),diff --git a/ee/api/agentic_provisioning/views/__init__.py b/ee/api/agentic_provisioning/views/__init__.pyindex 94693ba5cffd..e1c8b8fc0666 100644--- a/ee/api/agentic_provisioning/views/__init__.py+++ b/ee/api/agentic_provisioning/views/__init__.py@@ -2,16 +2,13 @@ from ee.api.agentic_provisioning.views.account_requests import AccountRequestsVifrom ee.api.agentic_provisioning.views.authorize import AuthorizeConfirmView, AuthorizePendingView, agentic_authorizefrom ee.api.agentic_provisioning.views.client_registration import ClientRegistrationViewfrom ee.api.agentic_provisioning.views.deep_links import DeepLinksView, agentic_login-from ee.api.agentic_provisioning.views.github_grants import GitHubGrantRepositoriesView, GitHubGrantsCreateViewfrom ee.api.agentic_provisioning.views.limits import LimitsViewfrom ee.api.agentic_provisioning.views.oauth_token import OAuthTokenViewfrom ee.api.agentic_provisioning.views.resources import (- GitHubIntegrationView,ResourceDetailView,ResourceRemoveView,ResourcesCreateView,RotateCredentialsView,- WizardRunsView,)__all__ = [@@ -20,16 +17,12 @@ __all__ = ["AuthorizePendingView","ClientRegistrationView","DeepLinksView",- "GitHubGrantRepositoriesView",- "GitHubGrantsCreateView",- "GitHubIntegrationView","LimitsView","OAuthTokenView","ResourceDetailView","ResourceRemoveView","ResourcesCreateView","RotateCredentialsView",- "WizardRunsView","agentic_authorize","agentic_login",]diff --git a/ee/api/agentic_provisioning/views/base.py b/ee/api/agentic_provisioning/views/base.pyindex bc7fe5d49898..e4f8c635e023 100644--- a/ee/api/agentic_provisioning/views/base.py+++ b/ee/api/agentic_provisioning/views/base.py@@ -23,7 +23,7 @@ from rest_framework.views import APIViewfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.team.team import Team-from ee.api.agentic_provisioning.authentication import GitHubGrantsAuthentication, ProvisioningBearerAuthentication+from ee.api.agentic_provisioning.authentication import ProvisioningBearerAuthenticationfrom ee.api.agentic_provisioning.exceptions import Envelope, ProvisioningError, render_provisioning_errorfrom ee.api.agentic_provisioning.ratelimits import (BudgetDeclaration,@@ -72,7 +72,7 @@ class ProvisioningAPIView(RegionProxyMixin, APIView):raise TypeError(f"{cls.__name__} declares no authentication_classes. Provisioning endpoints are ""partner-facing, so set authentication_classes (for example to "- "GitHubGrantsAuthentication) or, if it must authenticate inside the "+ "ProvisioningBearerAuthentication) or, if it must authenticate inside the ""handler, set authenticates_in_handler = True.")@@ -83,7 +83,7 @@ class ProvisioningAPIView(RegionProxyMixin, APIView):# skips authenticated requests that carry no personal API key, which is# every bearer-authenticated provisioning call.# Flows whose key only appears mid-handler (token exchange, account- # request partner quota, wizard runs) call the throttling helpers instead.+ # request partner quota) call the throttling helpers instead.partner_throttle_classes: ClassVar[list[type[BaseThrottle]]] = []def get_throttles(self) -> list[BaseThrottle]:@@ -179,18 +179,6 @@ class ProvisioningAPIView(RegionProxyMixin, APIView):return serializer.validated_data-class GitHubGrantsAPIView(ProvisioningAPIView):- """Base for the GitHub grant endpoints.-- The partner rides ``request.auth``, having proven itself with either a signed- ``private_key_jwt`` assertion or a verified client secret. A public partner is identified- only by a client_id anyone can send, so it never reaches these endpoints, and a confidential- one still needs ``can_use_github_grants`` granted.- """-- authentication_classes = [GitHubGrantsAuthentication]--class BearerResourceAPIView(ProvisioningAPIView):"""Base for the bearer-authenticated resource endpoints (status envelope)."""diff --git a/ee/api/agentic_provisioning/views/client_registration.py b/ee/api/agentic_provisioning/views/client_registration.pyindex ca6352fb7f72..47dffb6724ed 100644--- a/ee/api/agentic_provisioning/views/client_registration.py+++ b/ee/api/agentic_provisioning/views/client_registration.py@@ -84,18 +84,8 @@ class ClientRegistrationView(ProvisioningAPIView):"can_create_accounts": app.provisioning.can_create_accounts,"can_provision_resources": app.provisioning.can_provision_resources,},- # Spelled out because "why can't I call github/grants" is the question this- # endpoint exists to answer, and the rule (a confidential client PostHog granted- # the capability to) is not something a partner can infer from its own metadata- # document."capabilities": {"account_requests": app.provisioning.active and app.provisioning.can_create_accounts,- "github_grants": (- app.requires_client_authentication- and app.provisioning.can_use_github_grants- and app.provisioning.can_create_accounts- ),- "wizard_runs": app.provisioning.active and app.provisioning.can_start_wizard_runs,},"checks": checks,}@@ -160,7 +150,7 @@ class ClientRegistrationView(ProvisioningAPIView):checks,"jwks",True,- "No jwks_uri, so this client authenticates with PKCE only and cannot use the GitHub grant endpoints",+ "No jwks_uri, so this client authenticates with PKCE only",)returndiff --git a/ee/api/agentic_provisioning/views/github_grants.py b/ee/api/agentic_provisioning/views/github_grants.pydeleted file mode 100644index ad98a1976f4d..000000000000--- a/ee/api/agentic_provisioning/views/github_grants.py+++ /dev/null@@ -1,100 +0,0 @@-"""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 is charged automatically but the capability refusal is in the-budget's refund set, so a partner without ``can_create_accounts`` still spends-nothing 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.ratelimits import FLAT_MULTIPLIERS, rate_limited-from ee.api.agentic_provisioning.serializers import GitHubGrantCreateSerializer-from ee.api.agentic_provisioning.views.base import GitHubGrantsAPIView---class GitHubGrantsCreateView(GitHubGrantsAPIView):- @rate_limited("github_grants")- 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)-- 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(GitHubGrantsAPIView):- # 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. Flat multipliers: how fast a- # visitor's repo picker polls has nothing to do with the partner's trust tier.- @rate_limited(- "grant_repo_polls",- multipliers=FLAT_MULTIPLIERS,- key=lambda request, view: str(getattr(view, "kwargs", {}).get("grant_id", "")),- )- 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/resources.py b/ee/api/agentic_provisioning/views/resources.pyindex 7663e83c3dcb..c028c014aaf1 100644--- a/ee/api/agentic_provisioning/views/resources.py+++ b/ee/api/agentic_provisioning/views/resources.py@@ -23,16 +23,10 @@ from ee.api.agentic_provisioning.credentials import maybe_create_provisioned_patfrom ee.api.agentic_provisioning.exceptions import ProvisioningErrorfrom ee.api.agentic_provisioning.ratelimits import Budget, rate_limitedfrom 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.serializers import ResourceCreateSerializer, RotateCredentialsSerializerfrom ee.api.agentic_provisioning.teams import ProjectIdCollisionError, resolve_or_create_project_teamfrom ee.api.agentic_provisioning.tokens import remove_team_from_token_scopesfrom ee.api.agentic_provisioning.views.base import BearerResourceAPIView-from ee.api.agentic_provisioning.wizard import create_wizard_run, link_github_grant_to_teamdef _access_configuration_response(@@ -215,73 +209,3 @@ class ResourceRemoveView(BearerResourceAPIView):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."""-- @rate_limited("github_integrations")- 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.-- Starting a coding-agent run inside a customer's repository reaches a long way past- provisioning a project, so it needs its own grant rather than following from a partner- being allowed to provision resources at all. ``create_wizard_run`` enforces that, for- this endpoint and the account-request wizard block alike.- """-- # charge="manual": the charge lives inside create_wizard_run, which the bundled- # account-request wizard block also calls, so retries can't double-spend and the- # capability check runs before any quota is spent on either path.- @rate_limited("wizard_runs", charge="manual")- 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.pydeleted file mode 100644index d509e594d2e5..000000000000--- a/ee/api/agentic_provisioning/wizard.py+++ /dev/null@@ -1,204 +0,0 @@-"""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.egress.limiter.policies import Priority-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.ratelimits import charge_partner_by_name-from ee.api.agentic_provisioning.throttling import 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:- 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)- 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."""- # Checked here rather than in each caller: the resource endpoint and the account-request- # wizard block both land on this function, so this is the one place a new caller cannot- # forget. Before the rate limits, so a partner without the grant can't spend its quota.- if not partner.provisioning.can_start_wizard_runs:- capture_provisioning_event("wizard_run", "error", partner=partner, error_code="forbidden")- raise ProvisioningError(- "forbidden",- "Starting wizard runs is not enabled for this partner",- resource_id=str(team.id),- status=403,- )-- 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))- # By registry name because the budget is declared on WizardRunsView, and this- # function is also reached by the bundled account-request wizard block, which- # runs outside any view dispatch.- # Not refunded past this point: the repository check below is an authenticated- # GitHub call, so a partner cycling inaccessible repository names would otherwise- # generate unbounded egress for free.- charge_partner_by_name("wizard_runs", partner, resource_id=str(team.id))-- # 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", priority=Priority.CRITICAL- )- 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/partners/stripe/api/provisioning/test/test_account_requests.py b/ee/partners/stripe/api/provisioning/test/test_account_requests.pyindex 445e52b5685b..593c0daa991e 100644--- a/ee/partners/stripe/api/provisioning/test/test_account_requests.py+++ b/ee/partners/stripe/api/provisioning/test/test_account_requests.py@@ -118,20 +118,6 @@ class TestAccountRequests(StripeProvisioningTestBase):assert res.status_code == 200assert res.json()["type"] == "oauth"- def test_wizard_configuration_block_is_ignored(self):- res = self._post_signed(- URL,- data=_account_request(- "[email protected]",- configuration={- "region": "US",- "wizard": {"grant_id": "g", "installation_id": "i", "repository": "o/r"},- },- ),- )- assert res.status_code == 200- assert "wizard" not in res.json()-def test_missing_signature_is_unauthorized(self):res = self.client.post(URL, data=_account_request("[email protected]"), format="json", HTTP_API_VERSION="0.1d")assert res.status_code == 401diff --git a/posthog/admin/admins/oauth_admin.py b/posthog/admin/admins/oauth_admin.pyindex e4b3ae450fe6..3559a3532bd6 100644--- a/posthog/admin/admins/oauth_admin.py+++ b/posthog/admin/admins/oauth_admin.py@@ -344,9 +344,8 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne"authenticates follows from the fields above: a confidential client with a ""jwks_uri signs an assertion with its own key (preferred), a confidential client ""without one presents a client secret, and a public client is identified by "- "client_id and relies on PKCE. The GitHub grant endpoints additionally require a "- "confidential client. Use the 'Generate a new client secret' action to issue a "- "secret. Leave a rate limit blank to use the endpoint's default."+ "client_id and relies on PKCE. Use the 'Generate a new client secret' action to "+ "issue a secret. Leave a rate limit blank to use the endpoint's default."),"fields": tuple(provisioning_fields),},diff --git a/posthog/admin/test_oauth_admin.py b/posthog/admin/test_oauth_admin.pyindex 51d0ac17ac33..579119b2e0c5 100644--- a/posthog/admin/test_oauth_admin.py+++ b/posthog/admin/test_oauth_admin.py@@ -46,17 +46,17 @@ class TestOAuthApplicationAdmin(BaseTest):redirect_uris="https://example.com/callback",algorithm="RS256",)- assert app.provisioning.can_use_github_grants is False+ assert app.provisioning.can_issue_deep_links is False- form = self._provisioning_form(app, provisioning_can_use_github_grants="on")+ form = self._provisioning_form(app, provisioning_can_issue_deep_links="on")assert form.is_valid(), form.errorsform.save()app.refresh_from_db()granted = app.provisioning- assert granted.can_use_github_grants is True+ assert granted.can_issue_deep_links is True# Unticked boxes stay off rather than picking up a default.- assert granted.can_start_wizard_runs is False+ assert granted.skip_existing_user_consent is Falsedef _rate_limit_app(self) -> OAuthApplication:return OAuthApplication.objects.create(diff --git a/posthog/api/github_callback/team_services.py b/posthog/api/github_callback/team_services.pyindex babf83513401..16bd3e93c6da 100644--- a/posthog/api/github_callback/team_services.py+++ b/posthog/api/github_callback/team_services.py@@ -41,7 +41,6 @@ from posthog.models.integration import (GitHubInstallationAccess,GitHubInstallationAccessFetchError,GitHubIntegration,- GitHubUserAuthorization,Integration,defer_repository_cache_fields,invalidate_github_repository_caches_for_installation,@@ -113,24 +112,6 @@ def create_team_github_integration_from_oauth_code(if authorization is None:raise ValidationError("Failed to exchange the OAuth code — ensure GITHUB_APP_CLIENT_SECRET is configured")- return link_github_installation_for_user(- user=user, team_id=team_id, installation_id=installation_id, authorization=authorization- )---def link_github_installation_for_user(- *,- user: User,- team_id: int,- installation_id: str,- authorization: "GitHubUserAuthorization",-) -> Integration:- """Verify the user controls the installation, then create both GitHub records:- the team-scoped Integration and the personal UserIntegration.-- Request-free core of the team GitHub link, shared with flows that hold an- already-exchanged authorization (e.g. agentic provisioning GitHub grants).- """if not is_valid_github_installation_id(installation_id):raise ValidationError("Invalid installation_id")audit = GitHubAudit(diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.pyindex b1453e23650e..26957775bcc4 100644--- a/posthog/api/oauth/cimd.py+++ b/posthog/api/oauth/cimd.py@@ -983,8 +983,7 @@ def _cimd_provisioning_defaults_for(app: OAuthApplication) -> "ProvisioningConfiDeliberately narrow. Creating accounts and provisioning resources is the whole point ofself-serve registration, so those are turned on; no other capability is, because a partnerthat vouched for itself by publishing a document is not the same as one PostHog decided to- trust. GitHub grants, wizard runs, deep links and skipped consent are granted by an admin or- not at all.+ trust. Deep links and skipped consent are granted by an admin or not at all.No rate limits are written here: budgets are derived per request from the partner's tier(auth method x verification), so registration and verification change what the partnerdiff --git a/posthog/api/oauth/client_assertion.py b/posthog/api/oauth/client_assertion.pyindex d3b3345f175f..830f10d9d2a1 100644--- a/posthog/api/oauth/client_assertion.py+++ b/posthog/api/oauth/client_assertion.py@@ -73,18 +73,9 @@ class UnknownSigningKeyError(ClientAssertionError):def _request_field(request: Any, name: str) -> str:- """Read a field from the request body, falling back to the query string.-- RFC 7523 section 2.2 sends these as form parameters, which a GET has nowhere to put. The- GitHub grant listing endpoint is a GET, so without the query-string fallback a- private_key_jwt client could not authenticate there at all, while a client_secret one- could (its credentials ride the Basic header). An assertion is single-use and capped at- MAX_ASSERTION_LIFETIME_SECONDS, so one appearing in an access log is already spent.- """+ """Read a field from the request body, where RFC 7523 section 2.2 sends it as a form parameter."""from_body = request.data.get(name) if hasattr(request, "data") else None- if from_body:- return str(from_body)- return str(request.query_params.get(name) or "") if hasattr(request, "query_params") else ""+ return str(from_body or "")def extract_client_assertion(request: Any) -> ResolvedClientAssertion | None:diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.pyindex c2b06c8dacd6..5b04e5b0e925 100644--- a/posthog/api/oauth/test_cimd.py+++ b/posthog/api/oauth/test_cimd.py@@ -684,14 +684,14 @@ class TestApplyProvisioningDefaults(APIBaseTest):mock_get.return_value = _mock_response(_make_metadata(), headers={})existing = fetch_and_upsert_cimd_application(VALID_CIMD_URL)assert existing is not None- existing.update_provisioning(can_use_github_grants=True)- OAuthApplication.objects.get(pk=existing.pk).update_provisioning(can_use_github_grants=False)+ existing.update_provisioning(can_issue_deep_links=True)+ OAuthApplication.objects.get(pk=existing.pk).update_provisioning(can_issue_deep_links=False)app = apply_provisioning_defaults(existing)- self.assertFalse(app.provisioning.can_use_github_grants)+ self.assertFalse(app.provisioning.can_issue_deep_links)app.refresh_from_db()- self.assertFalse(app.provisioning.can_use_github_grants)+ self.assertFalse(app.provisioning.can_issue_deep_links)# The self-serve defaults still land - only the admin's revocation survives on top.self.assertTrue(app.provisioning.can_create_accounts)diff --git a/posthog/models/oauth_provisioning.py b/posthog/models/oauth_provisioning.pyindex c7319ed28765..2ab109b06a37 100644--- a/posthog/models/oauth_provisioning.py+++ b/posthog/models/oauth_provisioning.py@@ -68,10 +68,6 @@ class ProvisioningConfig(BaseModel):can_create_accounts: bool = Falsecan_provision_resources: bool = False- # Exchanging GitHub OAuth codes and starting cloud wizard runs both act well beyond ordinary- # provisioning, so neither follows from being a partner - each is granted on its own.- can_use_github_grants: bool = False- can_start_wizard_runs: bool = False# Only for partners trusted enough that the blast radius of the app being compromised is# understood: a deep link mints a full web session, and skipping consent links an existingdiff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 625f21796638..c742a565c708 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -588,7 +588,7 @@ def send_member_join(invitee_uuid: str, organization_id: str) -> None:@shared_task(**EMAIL_TASK_KWARGS)@skip_team_scope_audit-def send_provisioning_welcome(user_id: int, token: str, partner_name: str = "", repository: str | None = None) -> None:+def send_provisioning_welcome(user_id: int, token: str, partner_name: str = "") -> None:user = User.objects.get(pk=user_id)message = EmailMessage(use_http=True,@@ -601,7 +601,6 @@ def send_provisioning_welcome(user_id: int, token: str, partner_name: str = "","cloud": is_cloud(),"site_url": settings.SITE_URL,"partner_name": partner_name,- "repository": repository or "",},)message.add_user_recipient(user)diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.pyindex 36a521379954..5143f8e4d46b 100644--- a/posthog/tasks/test/test_email.py+++ b/posthog/tasks/test/test_email.py@@ -433,17 +433,6 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):assert "Set your password" in mocked_email_messages[0].html_bodyassert "Wizard" in mocked_email_messages[0].html_body- def test_send_provisioning_welcome_with_repository(self, MockEmailMessage: MagicMock) -> None:- mocked_email_messages = mock_email_messages(MockEmailMessage)- org, user = create_org_team_and_user("2022-01-02 00:00:00", "[email protected]")- token = password_reset_token_generator.make_token(self.user)-- send_provisioning_welcome(user.id, token, "posthog.com", repository="octocat/hello-world")-- assert len(mocked_email_messages) == 1- assert "octocat/hello-world" in mocked_email_messages[0].html_body- assert "pull request" in mocked_email_messages[0].html_body-def test_send_provisioning_welcome_without_partner(self, MockEmailMessage: MagicMock) -> None:mocked_email_messages = mock_email_messages(MockEmailMessage)org, user = create_org_team_and_user("2022-01-02 00:00:00", "[email protected]")diff --git a/posthog/templates/email/provisioning_welcome.html b/posthog/templates/email/provisioning_welcome.htmlindex 4154bbcf1b36..c0bc6b4ff312 100644--- a/posthog/templates/email/provisioning_welcome.html+++ b/posthog/templates/email/provisioning_welcome.html@@ -1,11 +1,6 @@{% extends "email/base.html" %}{% block section %}<p>Welcome to PostHog! Your account was created{% if partner_name %} via {{ partner_name }}{% endif %}.</p>- {% if repository %}- <p>- We're setting up PostHog in <strong>{{ repository }}</strong> in the background — a pull request will appear on the repository shortly.- </p>- {% endif %}<p>Set a password to log in to PostHog directly.</p><div class="mb mt text-center"><a class="button" href="{% absolute_uri link %}">Set your password</a>