: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
feat(agentic-provisioning): authenticate partners as oauth clients (#74089)
Rafael Audibert702eca064c7f
diff --git a/ee/api/agentic_provisioning/accounts.py b/ee/api/agentic_provisioning/accounts.pyindex 04d27f9c23de..45165f1dbeaf 100644--- a/ee/api/agentic_provisioning/accounts.py+++ b/ee/api/agentic_provisioning/accounts.py@@ -29,7 +29,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.teams import resolve_team_for_existing_userfrom ee.api.agentic_provisioning.wizard import create_wizard_run, link_github_grant_to_team@@ -109,101 +108,56 @@ def build_authorize_url(confirmation_secret: str, scopes: list[str], region: strreturn f"{base}/api/agentic/authorize?{params}"-def caller_proved_existing_trust(partner: OAuthApplication, user: User, authenticated_user: User | None) -> bool:- """True only when the caller proved a prior trust relationship with this user.-- This is what lets a skip-consent partner re-mint silently for an existing user; without- it the request falls through to browser consent. The proof differs by auth method:-- - Bearer callers present a single user-scoped access token. That token proves a- relationship only with its own user, so it qualifies only when it belongs to the user- being re-linked — otherwise any user of the partner could ride another user's live- credential to mint a code for that account.- - PKCE callers are public: the partner is identified solely by a client_id that anyone- can send, so the request carries no proof the caller controls the partner. The "user- already holds a live credential" signal proves nothing, so these never qualify.- """- if partner.provisioning_auth_method == "bearer":- return authenticated_user is not None and authenticated_user.id == user.id- return False--def handle_existing_user(request_id: str,user: User,scopes: list[str],*,region: str,- team_id: int | None,- partner: OAuthApplication | None,+ partner: OAuthApplication,code_challenge: str,code_challenge_method: str,- authenticated_user: User | None,) -> dict[str, Any]:- # Account-takeover defense: a partner with skip_existing_user_consent=True may only mint- # silently for an *existing* account when the caller proved a prior trust relationship with- # that user (see caller_proved_existing_trust). Without proof we fall through to consent,- # otherwise any caller could mint a code for an account they don't control. This holds- # regardless of whether the user has reviewed their credentials: an unreviewed account is- # still a pre-existing account, and the email may belong to a direct signup that never- # touched provisioning — silently linking it is the takeover.- silent_blocked = (- partner is not None- and partner.provisioning_skip_existing_user_consent- and not caller_proved_existing_trust(partner, user, authenticated_user)- )-- if silent_blocked:- assert partner is not None # implied by silent_blocked+ """Send an account request that matched an existing account to browser consent.++ Account-takeover defense: no partner may mint silently for an *existing* account, not+ even one with skip_existing_user_consent=True. A partner proves it controls itself (a+ verified client secret) or nothing at all (a public client_id), and neither is proof that+ it controls this email, so the user has to approve the link in a browser. This holds+ regardless of whether the user has reviewed their credentials: an unreviewed account is+ still a pre-existing account, and the email may belong to a direct signup that never+ touched provisioning, so silently linking it is the takeover.++ Consent also picks the project (see agentic_authorize), so nothing the partner sends can+ select a team for an account it did not create.+ """+ if partner.provisioning_skip_existing_user_consent:capture_provisioning_event("account_request","silent_blocked_existing_user",partner=partner,)- if partner and (not partner.provisioning_skip_existing_user_consent or silent_blocked):- if not code_challenge:- raise ProvisioningError(- "invalid_request", "code_challenge is required for public clients", request_id=request_id- )- if not scopes_within_ceiling(scopes, partner.ceiling_scopes):- raise ProvisioningError(- "invalid_scope",- "One or more requested scopes exceed the application's allowed scopes",- request_id=request_id,- )- return require_user_consent(- request_id,- user,- scopes,- region,- partner,- code_challenge,- code_challenge_method,+ if not code_challenge:+ raise ProvisioningError(+ "invalid_request", "code_challenge is required for public clients", request_id=request_id)-- team = resolve_team_for_existing_user(user, team_id)- if team is None:- capture_provisioning_event("account_request", "error", error_code="team_resolution_failed")+ if not scopes_within_ceiling(scopes, partner.ceiling_scopes):raise ProvisioningError(- "team_resolution_failed", "Could not resolve a project for this user", request_id=request_id+ "invalid_scope",+ "One or more requested scopes exceed the application's allowed scopes",+ request_id=request_id,)-- code = mint_auth_code(- user_id=user.id,- org_id=str(team.organization_id),- team_id=team.id,- partner_id=str(partner.id) if partner else "",- scopes=scopes,- region=region,- code_challenge=code_challenge,- code_challenge_method=code_challenge_method,+ return require_user_consent(+ request_id,+ user,+ scopes,+ region,+ partner,+ code_challenge,+ code_challenge_method,)- capture_provisioning_event("account_request", "existing_user", partner=partner, region=region, team_id=team.id)-- return {"id": request_id, "type": "oauth", "oauth": {"code": code}}-def require_user_consent(request_id: str,@@ -260,10 +214,9 @@ def handle_new_user(scopes: list[str],*,region: str,- partner: OAuthApplication | None,+ partner: OAuthApplication,code_challenge: str,code_challenge_method: str,- authenticated_user: User | None,) -> dict[str, Any]:name = data.get("name", "")first_name = name.split(" ")[0] if name else ""@@ -292,11 +245,9 @@ def handle_new_user(existing,scopes,region=region,- team_id=None,partner=partner,code_challenge=code_challenge,code_challenge_method=code_challenge_method,- authenticated_user=authenticated_user,)capture_provisioning_event("account_request", "creation_failed", region=region)raise ProvisioningError(@@ -319,7 +270,7 @@ def handle_new_user(is_instance_first_user=False,is_organization_first_user=True,backend_processor="AgenticProvisioning",- social_provider=partner.name if partner else "",+ social_provider=partner.name,user_analytics_metadata=user.get_analytics_metadata(),org_analytics_metadata=organization.get_analytics_metadata(),)@@ -333,7 +284,7 @@ def handle_new_user(wizard_config = configuration.get("wizard")wizard_payload: dict[str, Any] | None = Nonewizard_repository: str | None = None- if isinstance(wizard_config, dict) and partner is not 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"))@@ -354,7 +305,7 @@ def handle_new_user(user_id=user.id,org_id=str(organization.id),team_id=team.id,- partner_id=str(partner.id) if partner else "",+ partner_id=str(partner.id),scopes=scopes,region=region,code_challenge=code_challenge,diff --git a/ee/api/agentic_provisioning/analytics.py b/ee/api/agentic_provisioning/analytics.pyindex fea3095b276e..7a886f099acf 100644--- a/ee/api/agentic_provisioning/analytics.py+++ b/ee/api/agentic_provisioning/analytics.py@@ -46,7 +46,7 @@ def capture_auth_event(app: OAuthApplication, outcome: str, **extra: object) ->properties={"outcome": outcome,"partner_type": app.provisioning_partner_type,- "auth_method": app.provisioning_auth_method,+ "client_type": app.client_type,"app_id": str(app.id),**extra,},diff --git a/ee/api/agentic_provisioning/authentication.py b/ee/api/agentic_provisioning/authentication.pyindex cc860b4856de..dd3d920a08bb 100644--- a/ee/api/agentic_provisioning/authentication.py+++ b/ee/api/agentic_provisioning/authentication.py@@ -1,9 +1,8 @@from __future__ import annotations-import hashlib+from typing import NoReturnfrom django.contrib.auth.models import AnonymousUser-from django.core.cache import cachefrom django.utils import timezoneimport structlog@@ -12,15 +11,13 @@ from rest_framework.exceptions import AuthenticationFailedfrom rest_framework.request import Requestfrom posthog.api.oauth.cimd import (- apply_provisioning_defaults,enqueue_cimd_refresh_if_stale,get_application_by_client_id,is_cimd_client_id,- is_cimd_registration_in_progress,is_cimd_url_blocked,- register_cimd_provisioning_application_task,)-from posthog.exceptions_capture import capture_exception+from posthog.api.oauth.client_assertion import ClientAssertionError, extract_client_assertion, verify_client_assertion+from posthog.api.oauth.client_auth import extract_client_credentials, verify_client_secretfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, find_oauth_access_tokenfrom posthog.models.user import User@@ -31,6 +28,13 @@ logger = structlog.get_logger(__name__)BEARER_PREFIX = "Bearer "+CLIENT_REGISTRATION_PATH = "/api/agentic/provisioning/client_registration"+# Every endpoint here requires an already-registered client, so the one actionable thing to+# tell a caller we don't recognize is where to register and get its setup diagnosed.+CLIENT_NOT_REGISTERED_MESSAGE = (+ f"No provisioning client is registered for this client_id. Register it at POST {CLIENT_REGISTRATION_PATH}"+)+class BearerTokenError(Exception):"""The bearer header is missing, unknown, or expired; the message is the@@ -65,137 +69,133 @@ def resolve_bearer_access_token(request: Request) -> OAuthAccessToken:class ProvisioningAuthentication(BaseAuthentication):"""Authenticates provisioning requests from any registered partner.- Partners are OAuthApplications with provisioning fields set (provisioning_auth_method- is non-empty). The OAuthApplication handles standard OAuth (tokens, scopes, consent)- and also stores provisioning config: auth method, feature flags- (provisioning_can_create_accounts, provisioning_can_provision_resources), and rate limits.-- Partners are identified from request signals (Bearer token or client_id param)- and dispatched to the matching auth strategy. Returns None if no partner is- identified.+ Partners are OAuthApplications with ``is_provisioning_partner`` set. The OAuthApplication+ handles standard OAuth (tokens, scopes, consent) and also stores provisioning config:+ feature flags (provisioning_can_create_accounts, provisioning_can_provision_resources)+ and rate limits.++ How a partner proves itself follows from its registered ``token_endpoint_auth_method``+ (RFC 7591), not from what a given request happens to carry: ``private_key_jwt`` partners+ sign an assertion, ``client_secret_*`` partners present their secret, and ``none``+ partners are identified by a bare client_id and rely on PKCE. These endpoints act for the+ partner rather than for an end user, so no user is ever returned. Returns None if no+ partner is identified."""- cimd_registration_pending: bool = False-- def authenticate(self, request: Request):+ def authenticate(self, request: Request) -> tuple[None, OAuthApplication] | None:app = self._identify_partner(request)if app is None:return None- try:- if app.provisioning_auth_method == "bearer":- user = self._verify_bearer(request, app)- capture_auth_event(app, "success", endpoint=request.path)- return (user, app)- elif app.provisioning_auth_method == "pkce":- capture_auth_event(app, "success", endpoint=request.path)- return self._verify_pkce(request, app)- except AuthenticationFailed:- capture_auth_event(app, "verification_failed", endpoint=request.path)- raise-- return None+ capture_auth_event(app, "success", endpoint=request.path)+ return (None, app)def _identify_partner(self, request: Request) -> OAuthApplication | None:- app = None-- # 1. Check for Bearer token -> look up OAuthApplication- if request.headers.get("authorization", "").startswith(BEARER_PREFIX):- app = self._identify_bearer_partner(request)+ # 1. A signed assertion identifies and proves a private_key_jwt partner at once.+ assertion = extract_client_assertion(request)+ if assertion is not None:+ return self._identify_assertion_partner(request, *assertion)++ # 2. So do client credentials, for a partner registered with a secret.+ credentials = extract_client_credentials(request)+ if credentials is not None:+ return self._identify_client_secret_partner(request, *credentials)++ # 3. A bare client_id identifies a public client, which relies on PKCE.+ client_id = request.data.get("client_id") or request.query_params.get("client_id")+ if not client_id:+ return None- # 2. Check for client_id in request body (PKCE public clients)+ app = self._identify_pkce_partner(client_id)if app is None:- client_id = request.data.get("client_id") or request.query_params.get("client_id")- if client_id:- app = self._identify_pkce_partner(client_id)+ # The caller named a client, so tell it the client is unknown rather than+ # returning a bare "unauthorized" it cannot act on.+ raise AuthenticationFailed(CLIENT_NOT_REGISTERED_MESSAGE)- if app is not None and not app.provisioning_active:- return None+ # A confidential partner that presented no proof must not fall through to the public+ # path. Its client_id is published like any other, so honoring it here would let+ # anyone act as that partner simply by sending nothing else.+ if app.requires_client_authentication:+ self._reject(request, app, "This client must authenticate")return app- def _identify_bearer_partner(self, request: Request) -> OAuthApplication | None:+ def _reject(self, request: Request, app: OAuthApplication, reason: str) -> NoReturn:+ """Fail a partner that was identified but did not prove itself."""+ capture_auth_event(app, "verification_failed", endpoint=request.path)+ raise AuthenticationFailed(reason)++ def _identify_assertion_partner(self, request: Request, assertion: str, client_id: str) -> OAuthApplication | None:+ app = self._resolve_partner(client_id)+ if app is None:+ raise AuthenticationFailed(CLIENT_NOT_REGISTERED_MESSAGE)+ if not app.uses_private_key_jwt_auth:+ self._reject(request, app, "This client does not authenticate with a client assertion")+try:- access_token = resolve_bearer_access_token(request)- except BearerTokenError:- return None+ verify_client_assertion(app, assertion)+ except ClientAssertionError as exc:+ self._reject(request, app, str(exc))- app = access_token.application- if app is None or not app.is_provisioning_partner:+ return app++ def _identify_client_secret_partner(+ self, request: Request, client_id: str, client_secret: str+ ) -> OAuthApplication | None:+ app = self._resolve_partner(client_id)+ if app is None:return None+ if not app.uses_client_secret_auth:+ self._reject(request, app, "This client does not authenticate with a client secret")- return app if app.provisioning_active else None+ if not verify_client_secret(client_secret, app.client_secret or ""):+ self._reject(request, app, "Invalid client credentials")- def _identify_pkce_partner(self, client_id: str) -> OAuthApplication | None:- if is_cimd_client_id(client_id):- if is_cimd_url_blocked(client_id):- return None-- app = OAuthApplication.objects.filter(cimd_metadata_url=client_id).first()- if app is not None:- # The raw lookup above bypasses get_or_create_cimd_application, so the- # CIMD document's TTL-based refresh never fires on this path. Enqueue it- # here so edits to live metadata (scope ceiling, redirect_uris, config)- # propagate instead of freezing at first registration. Refresh stays- # async; this request still serves the existing app.- try:- enqueue_cimd_refresh_if_stale(client_id)- except Exception as e:- logger.warning(- "provisioning_cimd_refresh_enqueue_error",- client_id=client_id,- error=str(e),- error_type=type(e).__name__,- )-- try:- if not app.is_provisioning_partner:- apply_provisioning_defaults(app)- except Exception as e:- logger.warning(- "provisioning_cimd_backfill_error",- client_id=client_id,- error=str(e),- error_type=type(e).__name__,- )- capture_exception(e)- try:- app.refresh_from_db()- except Exception:- return None- return app if app.provisioning_active else None-- # New CIMD URL: kick off background registration, don't block the worker.- # cache.add is atomic - coalesces concurrent first-time requests so only- # one gets to enqueue until the worker's own fetch lock takes over.- if not is_cimd_registration_in_progress(client_id):- enqueue_key = f"cimd:enqueued:{hashlib.sha256(client_id.encode()).hexdigest()}"- if cache.add(enqueue_key, True, timeout=30):- register_cimd_provisioning_application_task.delay(client_id)- self.cimd_registration_pending = True- return None+ return app++ def _resolve_partner(self, client_id: str) -> OAuthApplication | None:+ """Look up an active provisioning partner by client_id.+ Unlike the PKCE path this never *registers* an unknown CIMD client: a caller that+ brought its own proof has to already exist for that proof to mean anything.+ """try:app = get_application_by_client_id(client_id)- if not app.is_provisioning_partner or not app.provisioning_active:- return None- return appexcept OAuthApplication.DoesNotExist:return None- def _verify_bearer(self, request: Request, app: OAuthApplication):- try:- access_token = resolve_bearer_access_token(request)- except BearerTokenError as exc:- raise AuthenticationFailed(str(exc))+ if not app.is_provisioning_partner or not app.provisioning_active:+ return None- if access_token.application_id != app.id:- raise AuthenticationFailed("Token not issued for this partner")+ if app.is_cimd_client:+ # A confidential CIMD partner reaches every provisioning endpoint through this+ # path, so without a refresh here its metadata document would never be re-read+ # again: scope ceiling and jwks_uri edits would freeze at whatever the app was+ # promoted with. Async, so this request still serves the app we already have.+ try:+ enqueue_cimd_refresh_if_stale(app.cimd_metadata_url or client_id)+ except Exception as e:+ logger.warning(+ "provisioning_cimd_refresh_enqueue_error",+ client_id=client_id,+ error=str(e),+ error_type=type(e).__name__,+ )- return access_token.user+ return app- def _verify_pkce(self, request: Request, app: OAuthApplication):- return (None, app)+ def _identify_pkce_partner(self, client_id: str) -> OAuthApplication | None:+ """Resolve a public client from its client_id alone.++ Registering an unknown client is not this path's job. It used to be, by enqueueing a+ background CIMD fetch and answering "retry shortly", which meant a partner's first+ call always failed for a reason indistinguishable from a typo. Registration is now an+ explicit call to client_registration, so an unknown client_id simply does not resolve+ and the caller is pointed there.+ """+ if is_cimd_client_id(client_id) and is_cimd_url_blocked(client_id):+ return None+ return self._resolve_partner(client_id)class ProvisioningBearerAuthentication(BaseAuthentication):@@ -212,17 +212,13 @@ class ProvisioningBearerAuthentication(BaseAuthentication):except BearerTokenError as exc:raise ProvisioningError("unauthorized", str(exc), status=401)- # The token must belong to an active provisioning partner's app.+ # The token must belong to an active provisioning partner's app. An app that was never+ # a partner, or has been un-flagged as one, must fail closed here rather than having+ # its outstanding access tokens still reach the resource and deep-link endpoints.app = access_token.applicationif app is None or not app.is_provisioning_partner:raise ProvisioningError("unauthorized", "Authentication failed", status=401)- # Only bearer/pkce partners are supported. An app configured with any other- # auth method (e.g. a leftover hmac partner row) must fail closed here, or its- # outstanding bearer tokens could still reach the resource and deep-link- # endpoints without the second factor that method implied.- if app.provisioning_auth_method not in ("bearer", "pkce"):- raise ProvisioningError("unauthorized", "Authentication failed", status=401)if not app.provisioning_active:raise ProvisioningError("unauthorized", "Partner is deactivated", status=401)if not app.provisioning_can_provision_resources:@@ -235,25 +231,41 @@ class ProvisioningBearerAuthentication(BaseAuthentication):def authenticate_confidential_partner(request: Request) -> OAuthApplication:- """Identify a provisioning partner, requiring proof-bearing auth.+ """Identify a provisioning partner, requiring proof-bearing auth and an admin-registered+ partner identity.++ 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.- Only Bearer partners carry proof that the caller controls the partner.- PKCE partners are identified solely by a public ``client_id`` anyone can send, so- they never qualify for these endpoints — they exchange GitHub OAuth codes and read- back GitHub account metadata, which must sit behind a real partner trust boundary.+ 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.++ CIMD auto-registration is the only path that sets ``is_provisioning_partner`` without an+ admin, so it is the only one that needs a second signal, and the signal is an admin-set+ ``provisioning_partner_type``. Deliberately not required of non-CIMD partners: those exist+ only because someone created them in the admin, and demanding a partner type of them would+ lock out an already-configured partner whose type field was simply left blank.Raises :class:`ProvisioningError` when no qualifying partner is identified."""auth = ProvisioningAuthentication()try:result = auth.authenticate(request)- except AuthenticationFailed:- result = None+ 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 Noneif partner is None:- raise ProvisioningError("unauthorized", "Authentication required", status=401)- if partner.provisioning_auth_method != "bearer":+ 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 partner.is_cimd_client and not partner.provisioning_partner_type:+ raise ProvisioningError("forbidden", "This endpoint requires a registered provisioning partner", status=403)return partner@@ -267,4 +279,4 @@ class ConfidentialPartnerAuthentication(BaseAuthentication):return AnonymousUser(), authenticate_confidential_partner(request)def authenticate_header(self, request: Request) -> str:- return "Bearer"+ return "Basic"diff --git a/ee/api/agentic_provisioning/constants.py b/ee/api/agentic_provisioning/constants.pyindex 2cf008ddfc6b..b078904360f9 100644--- a/ee/api/agentic_provisioning/constants.py+++ b/ee/api/agentic_provisioning/constants.py@@ -21,6 +21,18 @@ CIMD_DOMAIN_RATE_LIMIT_PREFIX = "cimd_registration_domain_rate:"CIMD_DOMAIN_RATE_LIMIT_MAX = 5CIMD_DOMAIN_RATE_LIMIT_WINDOW_SECONDS = 3600+# The client registration endpoint dereferences a caller-supplied URL synchronously, so it is+# capped per client_id on top of the per-IP and per-domain CIMD limits. Generous enough for a+# partner iterating on a broken metadata document, low enough that it is not an amplifier.+CLIENT_REGISTRATION_RATE_LIMIT_PREFIX = "provisioning_client_registration:"+CLIENT_REGISTRATION_RATE_LIMIT_MAX = 30+CLIENT_REGISTRATION_RATE_LIMIT_WINDOW_SECONDS = 3600+# Ceiling across every client_id one address checks, so registering a pile of clients does not+# multiply the per-client budget into an unbounded number of synchronous outbound fetches.+# Well above the per-client limit, since one address legitimately operating several partners+# should still be able to spend a full budget on each.+CLIENT_REGISTRATION_IP_RATE_LIMIT_MAX = 120+PARTNER_RATE_LIMIT_PREFIX = "provisioning_partner_rate:"PARTNER_RATE_LIMIT_WINDOW_SECONDS = 3600PARTNER_RATE_LIMIT_DEFAULTS: dict[str, int] = {diff --git a/ee/api/agentic_provisioning/exceptions.py b/ee/api/agentic_provisioning/exceptions.pyindex 6da360fb80c3..4ab4a83b158e 100644--- a/ee/api/agentic_provisioning/exceptions.py+++ b/ee/api/agentic_provisioning/exceptions.py@@ -48,6 +48,7 @@ class ProvisioningError(Exception):resource_id: str = "",envelope: Envelope | None = None,retry_after: int | None = None,+ extra: dict[str, Any] | None = None,) -> None:super().__init__(message)self.code = code@@ -57,6 +58,9 @@ class ProvisioningError(Exception):self.resource_id = resource_idself.envelope = envelopeself.retry_after = retry_after+ # Structured detail merged alongside the error in the typed envelope, for failures+ # whose whole value is the detail (client_registration reports per-check results).+ self.extra = extradef provisioning_error_body(error: ProvisioningError, default_envelope: Envelope) -> dict[str, Any]:@@ -66,6 +70,8 @@ def provisioning_error_body(error: ProvisioningError, default_envelope: Envelopebody: dict[str, Any]if envelope == "typed":body = {"type": "error", "error": {"code": error.code, "message": error.message}}+ if error.extra:+ body.update(error.extra)# "id" appears only when a request_id was threaded through; some call# sites carry "" (rendered as "id": "") and others no id at all.if error.request_id is not None:diff --git a/ee/api/agentic_provisioning/serializers.py b/ee/api/agentic_provisioning/serializers.pyindex 5ccfa8d1f054..73efb456c8fb 100644--- a/ee/api/agentic_provisioning/serializers.py+++ b/ee/api/agentic_provisioning/serializers.py@@ -15,6 +15,8 @@ from django.utils.dateparse import parse_datetimefrom rest_framework import serializers+from posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARER+from ee.api.agentic_provisioning.analytics import capture_provisioning_eventfrom ee.api.agentic_provisioning.credentials import validate_label_prefixfrom ee.api.agentic_provisioning.exceptions import ProvisioningError@@ -72,7 +74,7 @@ class AccountRequestSerializer(serializers.Serializer):required=False,allow_null=True,default=dict,- help_text="Partner configuration: region (US/EU), organization_name, team_id, wizard block.",+ help_text="Partner configuration: region (US/EU), organization_name, wizard block.",)code_challenge = serializers.CharField(required=False,@@ -278,3 +280,42 @@ class DeepLinkSerializer(serializers.Serializer):def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:attrs["purpose"] = attrs.get("purpose") or "dashboard"return attrs+++class ClientRegistrationSerializer(serializers.Serializer):+ """POST /provisioning/client_registration body."""++ client_id = serializers.CharField(+ help_text=(+ "The client_id to register and diagnose. For a CIMD client this is the https URL of "+ "its own metadata document, which is what gets fetched."+ ),+ )+ client_assertion = serializers.CharField(+ required=False,+ allow_blank=True,+ allow_null=True,+ default="",+ help_text=(+ "Optional private_key_jwt assertion to verify end to end, so a partner can confirm "+ "its signing setup before relying on it. Verifying consumes the assertion's jti, so "+ "send one minted for this check rather than reusing it afterwards."+ ),+ )+ client_assertion_type = serializers.CharField(+ required=False,+ allow_blank=True,+ allow_null=True,+ default="",+ help_text=("Must be urn:ietf:params:oauth:client-assertion-type:jwt-bearer when client_assertion is sent."),+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ attrs["client_assertion"] = attrs.get("client_assertion") or ""+ attrs["client_assertion_type"] = attrs.get("client_assertion_type") or ""+ if attrs["client_assertion"] and attrs["client_assertion_type"] != CLIENT_ASSERTION_TYPE_JWT_BEARER:+ raise ProvisioningError(+ "invalid_request",+ f"client_assertion_type must be {CLIENT_ASSERTION_TYPE_JWT_BEARER}",+ )+ return attrsdiff --git a/ee/api/agentic_provisioning/teams.py b/ee/api/agentic_provisioning/teams.pyindex 22aaa7f100d1..19373884e2a8 100644--- a/ee/api/agentic_provisioning/teams.py+++ b/ee/api/agentic_provisioning/teams.py@@ -20,46 +20,6 @@ class ProjectIdCollisionError(Exception):self.project_id = project_id-def resolve_team_for_existing_user(user: User, requested_team_id: int | None = None) -> Team | None:- """Pick a team for an existing user during email-based account linking.-- If requested_team_id is provided and the user has access, use it.- Otherwise auto-select: single non-demo team → use it, only demo teams →- create a new project, multiple teams → create a new project in the first org.- """- memberships = list(user.organization_memberships.select_related("organization").all())- if not memberships:- return None-- org_ids = [m.organization_id for m in memberships]-- if requested_team_id is not None:- try:- team = Team.objects.get(id=requested_team_id, is_demo=False)- except Team.DoesNotExist:- return None- if team.organization_id not in org_ids:- return None- # Org membership alone is not access: a partner can name any team id in- # the user's orgs, so a team the user is excluded from must not become- # the scope of the minted code.- if not user_can_access_team(user, team):- return None- return team-- non_demo_teams = [- team- for team in Team.objects.filter(organization_id__in=org_ids, is_demo=False)- if user_can_access_team(user, team)- ]-- if len(non_demo_teams) == 1:- return non_demo_teams[0]-- organization = memberships[0].organization- return Team.objects.create_with_data(initiating_user=user, organization=organization)--def resolve_or_create_project_team(project_id: str,scoped_teams: list[int],diff --git a/ee/api/agentic_provisioning/test/base.py b/ee/api/agentic_provisioning/test/base.pyindex 0e00e292fcbf..3e4c98c905f5 100644--- a/ee/api/agentic_provisioning/test/base.py+++ b/ee/api/agentic_provisioning/test/base.py@@ -2,6 +2,7 @@ import jsonimport base64import hashlibimport secrets+from urllib.parse import quote_plusfrom posthog.test.base import APIBaseTest@@ -18,6 +19,9 @@ from ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIXfrom ee.models.rbac.access_control import AccessControlTEST_PARTNER_CLIENT_ID = "test_partner_client_id"+# Stored hashed by ClientSecretField.pre_save, so the plaintext has to live here for+# requests to present it.+TEST_PARTNER_CLIENT_SECRET = "test_partner_client_secret"# Broad ceiling so token exchanges in tests aren't rejected by the per-app scope cap.TEST_PARTNER_SCOPES = [@@ -44,13 +48,13 @@ class ProvisioningTestBase(APIBaseTest):client_id=TEST_PARTNER_CLIENT_ID,defaults={"name": "Test Provisioning Partner",- "client_secret": "",+ "client_secret": TEST_PARTNER_CLIENT_SECRET,"client_type": OAuthApplication.CLIENT_CONFIDENTIAL,"authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,"redirect_uris": "https://partner.example.com/callback","algorithm": "RS256","scopes": TEST_PARTNER_SCOPES,- "provisioning_auth_method": "bearer",+ "is_provisioning_partner": True,"provisioning_partner_type": "test_partner","provisioning_active": True,"provisioning_can_create_accounts": True,@@ -86,6 +90,23 @@ class ProvisioningTestBase(APIBaseTest):def _post_with_bearer(self, url: str, data: dict | None = None, token: str = "", **kwargs):return self._post_api(url, data, HTTP_AUTHORIZATION=f"Bearer {token}", **kwargs)+ def _client_credentials(self, partner=None, secret: str | None = None) -> dict[str, str]:+ """The client_secret_post form: credentials merged into the request body."""+ partner = partner or self.partner+ return {+ "client_id": partner.client_id,+ "client_secret": TEST_PARTNER_CLIENT_SECRET if secret is None else secret,+ }++ def _basic_auth_header(self, partner=None, secret: str | None = None) -> str:+ """The client_secret_basic form, which is the only one a GET can carry."""+ partner = partner or self.partner+ raw = f"{quote_plus(partner.client_id)}:{quote_plus(TEST_PARTNER_CLIENT_SECRET if secret is None else secret)}"+ return f"Basic {base64.b64encode(raw.encode()).decode()}"++ def _post_with_client_secret(self, url: str, data: dict | None = None, partner=None, **kwargs):+ return self._post_api(url, {**(data or {}), **self._client_credentials(partner)}, **kwargs)+def _pkce_pair(self) -> tuple[str, str]:verifier = secrets.token_urlsafe(48)challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()).rstrip(b"=").decode()@@ -113,12 +134,15 @@ class ProvisioningTestBase(APIBaseTest):)return code, verifier- def _request_bearer_token(self, scopes: list[str] | None = None, partner=None):+ def _request_bearer_token(self, scopes: list[str] | None = None, partner=None, secret: str | None = None):+ partner = partner or self.partnercode, verifier = self._mint_auth_code(scopes=scopes, partner=partner)- return self.client.post(- "/api/agentic/oauth/token",- data={"grant_type": "authorization_code", "code": code, "code_verifier": verifier},- )+ data = {"grant_type": "authorization_code", "code": code, "code_verifier": verifier}+ # A confidential partner has to authenticate at the token endpoint; a public one+ # exchanges on the code_verifier alone.+ if partner.uses_client_secret_auth:+ data.update(self._client_credentials(partner, secret=secret))+ return self.client.post("/api/agentic/oauth/token", data=data)def _get_bearer_token(self) -> str:return self._request_bearer_token().json()["access_token"]diff --git a/ee/api/agentic_provisioning/test/test_account_requests.py b/ee/api/agentic_provisioning/test/test_account_requests.pyindex 3b12ca889db5..453462302451 100644--- a/ee/api/agentic_provisioning/test/test_account_requests.py+++ b/ee/api/agentic_provisioning/test/test_account_requests.py@@ -11,9 +11,7 @@ from django.utils import timezonefrom parameterized import parameterized-from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken-from posthog.models.organization import Organization-from posthog.models.team.team import Team+from posthog.models.oauth import OAuthApplicationfrom posthog.models.user import Userfrom ee.api.agentic_provisioning.analytics import capture_provisioning_event@@ -35,22 +33,8 @@ class TestAccountRequests(ProvisioningTestBase):payload.update(overrides)return payload- def _post_account_request(self, payload, token: str | None = None):- return self._post_with_bearer(ACCOUNT_REQUESTS_URL, payload, token=token or self._get_bearer_token())-- def _silent_partner_token_for(self, user: User) -> str:- # A skip-consent partner may only mint silently for an existing user when the- # bearer token belongs to that same user (see _caller_proved_existing_trust).- self.partner.provisioning_skip_existing_user_consent = True- self.partner.save(update_fields=["provisioning_skip_existing_user_consent"])- token = OAuthAccessToken.objects.create(- user=user,- application=self.partner,- token=f"tok_{user.id}",- expires=timezone.now() + timedelta(hours=1),- scope="query:read",- )- return token.token+ def _post_account_request(self, payload):+ return self._post_with_client_secret(ACCOUNT_REQUESTS_URL, payload)def test_no_identified_partner_returns_401(self):res = self._post_api(ACCOUNT_REQUESTS_URL, self._account_request_payload())@@ -92,77 +76,17 @@ class TestAccountRequests(ProvisioningTestBase):assert "issued_at" in code_datadatetime.fromisoformat(code_data["issued_at"])- def test_existing_user_auth_code_cached_with_team(self):- token = self._silent_partner_token_for(self.user)- res = self._post_account_request(self._account_request_payload(email=self.user.email), token=token)- assert res.status_code == 200- assert res.json()["type"] == "oauth"- code = res.json()["oauth"]["code"]- code_data = cache.get(f"{AUTH_CODE_CACHE_PREFIX}{code}")- assert code_data is not None- assert code_data["team_id"] == self.team.id- assert code_data["region"] == "US"- assert code_data["partner_id"] == str(self.partner.id)-- def test_existing_user_with_requested_team_id(self):- token = self._silent_partner_token_for(self.user)- second_team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)- payload = self._account_request_payload(email=self.user.email, configuration={"team_id": second_team.id})- res = self._post_account_request(payload, token=token)- assert res.status_code == 200- code = res.json()["oauth"]["code"]- code_data = cache.get(f"{AUTH_CODE_CACHE_PREFIX}{code}")- assert code_data["team_id"] == second_team.id-- @parameterized.expand(- [- ("nonexistent", 999999, "team_resolution_failed"),- ("non_numeric", "abc", "invalid_request"),- ]- )- def test_existing_user_with_bad_team_id_returns_400(self, _name, team_id, expected_code):- token = self._silent_partner_token_for(self.user)- payload = self._account_request_payload(email=self.user.email, configuration={"team_id": team_id})- res = self._post_account_request(payload, token=token)- assert res.status_code == 400- assert res.json()["error"]["code"] == expected_code-- @parameterized.expand(["other_org", "restricted_in_own_org"])- def test_existing_user_with_inaccessible_team_id_returns_400(self, case):- token = self._silent_partner_token_for(self.user)- if case == "other_org":- other_org = Organization.objects.create(name="Other Org")- target = Team.objects.create(organization=other_org, name="Other Team")- else:- target = Team.objects.create_with_data(- initiating_user=self.user, organization=self.organization, name="Restricted project"- )- self._restrict_team_access(target)-- payload = self._account_request_payload(email=self.user.email, configuration={"team_id": target.id})- res = self._post_account_request(payload, token=token)- assert res.status_code == 400- assert res.json()["error"]["code"] == "team_resolution_failed"-- def test_existing_user_auto_select_skips_restricted_team(self):- token = self._silent_partner_token_for(self.user)- self._restrict_team_access(self.team)+ def test_existing_user_requires_consent_even_for_skip_consent_partner(self):+ # No partner may silently link a pre-existing account. A verified client secret proves+ # the partner controls itself, never that it controls this email.+ self.partner.provisioning_skip_existing_user_consent = True+ self.partner.save(update_fields=["provisioning_skip_existing_user_consent"])- res = self._post_account_request(self._account_request_payload(email=self.user.email), token=token)+ payload = self._account_request_payload(email=self.user.email, code_challenge=VALID_CODE_CHALLENGE)+ res = self._post_account_request(payload)assert res.status_code == 200- code_data = cache.get(f"{AUTH_CODE_CACHE_PREFIX}{res.json()['oauth']['code']}")- assert code_data["team_id"] != self.team.id-- def test_existing_user_multi_team_creates_new_project(self):- token = self._silent_partner_token_for(self.user)- Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)- team_count_before = Team.objects.filter(organization=self.organization, is_demo=False).count()- res = self._post_account_request(self._account_request_payload(email=self.user.email), token=token)- assert res.status_code == 200- assert res.json()["type"] == "oauth"- team_count_after = Team.objects.filter(organization=self.organization, is_demo=False).count()- assert team_count_after == team_count_before + 1+ assert res.json()["type"] == "requires_auth"def test_expired_request_returns_400(self):payload = self._account_request_payload(expires_at=(timezone.now() - timedelta(minutes=1)).isoformat())@@ -266,7 +190,7 @@ class TestPKCEPartnerExistingUserConsent(ProvisioningTestBase):redirect_uris="https://partner.example.com/callback",algorithm="RS256",is_first_party=True,- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_partner_type="test_partner",provisioning_active=True,provisioning_can_create_accounts=True,@@ -414,199 +338,6 @@ class TestPKCEPartnerExistingUserConsent(ProvisioningTestBase):assert "code_challenge" in res.json()["error"]["message"]-class TestSilentRemintRequiresTrustProof(ProvisioningTestBase):- """A partner with skip_existing_user_consent=True can only mint silently for an- existing user when the caller proved a prior trust relationship with that user- (a bearer token belonging to that user). Otherwise the consent screen is- required. This holds whether or not the user has reviewed their credentials:- an unreviewed account is still a pre-existing account that a caller must not- be able to silently link."""-- def setUp(self):- super().setUp()- self.partner = OAuthApplication.objects.create(- client_id="silent-partner",- name="Silent Partner",- client_secret="",- client_type=OAuthApplication.CLIENT_PUBLIC,- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,- redirect_uris="https://partner.example.com/callback",- algorithm="RS256",- is_first_party=True,- provisioning_auth_method="pkce",- provisioning_partner_type="test_partner",- provisioning_active=True,- provisioning_can_create_accounts=True,- provisioning_can_provision_resources=True,- provisioning_skip_existing_user_consent=True,- )- self.other_partner = OAuthApplication.objects.create(- client_id="other-partner",- name="Other Partner",- client_secret="",- client_type=OAuthApplication.CLIENT_PUBLIC,- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,- redirect_uris="https://other.example.com/callback",- algorithm="RS256",- is_first_party=True,- provisioning_auth_method="pkce",- provisioning_partner_type="test_partner",- provisioning_active=True,- provisioning_can_create_accounts=True,- provisioning_can_provision_resources=True,- provisioning_skip_existing_user_consent=True,- )- self.bearer_partner = OAuthApplication.objects.create(- client_id="bearer-partner",- name="Bearer Partner",- client_secret="",- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,- redirect_uris="https://bearer.example.com/callback",- algorithm="RS256",- is_first_party=True,- provisioning_auth_method="bearer",- provisioning_partner_type="test_partner",- provisioning_active=True,- provisioning_can_create_accounts=True,- provisioning_can_provision_resources=True,- provisioning_skip_existing_user_consent=True,- )-- def _post_as_partner(self, data: dict, client_id: str = "silent-partner"):- return self._post_api(ACCOUNT_REQUESTS_URL, {**data, "client_id": client_id})-- def _post_as_bearer_partner(self, data: dict, token: str):- return self._post_with_bearer(ACCOUNT_REQUESTS_URL, data, token=token)-- def _account_request_payload(self, **overrides):- payload = {- "id": "acctreq_silent_test",- "email": "[email protected]",- "scopes": ["query:read"],- "code_challenge": VALID_CODE_CHALLENGE,- "code_challenge_method": "S256",- "expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),- }- payload.update(overrides)- return payload-- def _make_user(self, *, credentials_reviewed: bool) -> User:- user = User.objects.create_and_join(- organization=self.organization,- email="[email protected]",- password="testpass",- first_name="Existing",- )- user.credentials_reviewed_at = timezone.now() if credentials_reviewed else None- user.save(update_fields=["credentials_reviewed_at"])- return user-- def _make_live_access_token(self, user: User, partner: OAuthApplication) -> OAuthAccessToken:- return OAuthAccessToken.objects.create(- user=user,- application=partner,- token=f"tok_{user.id}_{partner.id}",- expires=timezone.now() + timedelta(hours=1),- scope="query:read",- )-- def _make_revoked_refresh_token(self, user: User, partner: OAuthApplication) -> OAuthRefreshToken:- return OAuthRefreshToken.objects.create(- user=user,- application=partner,- token=f"rtok_{user.id}_{partner.id}",- revoked=timezone.now(),- )-- def test_unreviewed_existing_user_pkce_requires_consent(self):- # A public PKCE caller never proves control of the partner, so it must not mint- # silently for an existing account — even an unreviewed one, whose email may belong- # to a direct signup the caller has no relationship with.- self._make_user(credentials_reviewed=False)- res = self._post_as_partner(self._account_request_payload())- assert res.status_code == 200- data = res.json()- assert data["type"] == "requires_auth"- assert "oauth" not in data-- @parameterized.expand([("reviewed", True), ("unreviewed", False)])- def test_pkce_caller_with_live_credential_requires_consent(self, _name, reviewed):- # A public PKCE caller is unauthenticated, so an existing live credential for the- # claimed client_id is not proof the caller controls the partner. It must not unlock- # the silent path for an existing user, in either review state.- user = self._make_user(credentials_reviewed=reviewed)- self._make_live_access_token(user, self.partner)- res = self._post_as_partner(self._account_request_payload())- assert res.status_code == 200- data = res.json()- assert data["type"] == "requires_auth"- assert "oauth" not in data-- @parameterized.expand(- [- ("no_credentials", lambda self, user: None),- (- "different_partner_credential",- lambda self, user: self._make_live_access_token(user, self.other_partner),- ),- ("only_revoked_token", lambda self, user: self._make_revoked_refresh_token(user, self.partner)),- ]- )- def test_reviewed_user_without_live_caller_credential_falls_through_to_consent(self, _name, setup_credential):- user = self._make_user(credentials_reviewed=True)- setup_credential(self, user)- res = self._post_as_partner(self._account_request_payload())- assert res.status_code == 200- data = res.json()- assert data["type"] == "requires_auth"- assert "url" in data["requires_auth"]- assert "/api/agentic/authorize" in data["requires_auth"]["url"]- assert "oauth" not in data-- url = data["requires_auth"]["url"]- state = parse_qs(urlparse(url).query)["state"][0]- pending = cache.get(f"{PENDING_AUTH_CACHE_PREFIX}{state}")- assert pending is not None- assert pending["partner_id"] == str(self.partner.id)-- @parameterized.expand([("reviewed", True), ("unreviewed", False)])- def test_bearer_caller_cannot_remint_for_other_user(self, _name, reviewed):- # A bearer token only proves the caller holds *some* user's token under the partner's- # client, not that they control the partner. An attacker holding their own token must- # not ride a victim's account to mint a code for it, whether or not the victim has- # reviewed credentials — an unreviewed account is still a pre-existing account.- victim = self._make_user(credentials_reviewed=reviewed)- self._make_live_access_token(victim, self.bearer_partner)-- attacker = User.objects.create_and_join(- organization=self.organization,- email="[email protected]",- password="testpass",- first_name="Attacker",- )- attacker_token = self._make_live_access_token(attacker, self.bearer_partner).token-- res = self._post_as_bearer_partner(self._account_request_payload(), token=attacker_token)- assert res.status_code == 200- data = res.json()- assert data["type"] == "requires_auth"- assert "oauth" not in data-- @parameterized.expand([("reviewed", True), ("unreviewed", False)])- def test_bearer_caller_can_remint_for_own_user(self, _name, reviewed):- # The legitimate bearer re-link path: the caller presents the user's own token, which- # is genuine proof of an existing trust relationship, so it stays silent in either state.- user = self._make_user(credentials_reviewed=reviewed)- token = self._make_live_access_token(user, self.bearer_partner).token-- res = self._post_as_bearer_partner(self._account_request_payload(), token=token)- assert res.status_code == 200- data = res.json()- assert data["type"] == "oauth"- assert "code" in data["oauth"]--class TestCaptureProvisioningEvent(ProvisioningTestBase):def _make_partner(self, partner_type: str = "test_partner") -> OAuthApplication:return OAuthApplication.objects.create(diff --git a/ee/api/agentic_provisioning/test/test_account_requests_wizard.py b/ee/api/agentic_provisioning/test/test_account_requests_wizard.pyindex f679ea79b321..30cbfd30aa97 100644--- a/ee/api/agentic_provisioning/test/test_account_requests_wizard.py+++ b/ee/api/agentic_provisioning/test/test_account_requests_wizard.py@@ -54,7 +54,7 @@ class TestAccountRequestsWizardBlock(ProvisioningTestBase):return github_grants.create_grant(self.partner, AUTHORIZATION, email)def _post(self, payload: dict):- return self._post_with_bearer(ACCOUNT_REQUESTS_URL, payload, token=self._get_bearer_token())+ 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:diff --git a/ee/api/agentic_provisioning/test/test_authorize.py b/ee/api/agentic_provisioning/test/test_authorize.pyindex 4d440ddbb5cb..ea0f52ee716f 100644--- a/ee/api/agentic_provisioning/test/test_authorize.py+++ b/ee/api/agentic_provisioning/test/test_authorize.py@@ -11,7 +11,7 @@ from posthog.models.oauth import OAuthApplicationfrom posthog.models.user import Userfrom ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIX-from ee.api.agentic_provisioning.test.base import TEST_PARTNER_SCOPES, ProvisioningTestBase+from ee.api.agentic_provisioning.test.base import TEST_PARTNER_CLIENT_SECRET, TEST_PARTNER_SCOPES, ProvisioningTestBasePARTNER_CALLBACK = "https://partner.example.com/callback"@@ -37,14 +37,14 @@ class AuthorizeTestBase(ProvisioningTestBase):return OAuthApplication.objects.create(client_id="authorize-skip-consent-partner",name="Skip Consent Partner",- client_secret="",+ client_secret=TEST_PARTNER_CLIENT_SECRET,client_type=OAuthApplication.CLIENT_CONFIDENTIAL,authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,redirect_uris=PARTNER_CALLBACK,algorithm="RS256",is_first_party=True,scopes=TEST_PARTNER_SCOPES,- provisioning_auth_method="bearer",+ is_provisioning_partner=True,provisioning_partner_type="test_partner",provisioning_active=True,provisioning_skip_existing_user_consent=True,@@ -165,7 +165,12 @@ class TestAgenticAuthorize(AuthorizeTestBase):token_res = self._post_api("/api/agentic/oauth/token",- {"grant_type": "authorization_code", "code": code, "code_verifier": verifier},+ {+ "grant_type": "authorization_code",+ "code": code,+ "code_verifier": verifier,+ **self._client_credentials(partner),+ },)assert token_res.status_code == 200data = token_res.json()@@ -229,7 +234,7 @@ class TestAgenticAuthorizeConfirm(AgenticAuthorizeMultiOrgBase):authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,redirect_uris=PARTNER_CALLBACK,algorithm="RS256",- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_partner_type="test_partner",provisioning_active=True,)diff --git a/ee/api/agentic_provisioning/test/test_client_registration.py b/ee/api/agentic_provisioning/test/test_client_registration.pynew file mode 100644index 000000000000..a83f98f4c87f--- /dev/null+++ b/ee/api/agentic_provisioning/test/test_client_registration.py@@ -0,0 +1,259 @@+import json+import time+from ipaddress import ip_address++from unittest.mock import patch++from django.core.cache import cache+from django.test import override_settings++import jwt+from cryptography.hazmat.primitives.asymmetric import rsa+from parameterized import parameterized++from posthog.api.oauth.cimd import CIMDFetchError+from posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARER, ClientAssertionError+from posthog.models.oauth import OAuthApplication++from ee.api.agentic_provisioning.test.base import TEST_PARTNER_SCOPES, ProvisioningTestBase++REGISTRATION_URL = "/api/agentic/provisioning/client_registration"+ACCOUNT_REQUESTS_URL = "/api/agentic/provisioning/account_requests"+CIMD_URL = "https://newpartner.example.com/.well-known/oauth-client-metadata.json"+JWKS_URI = "https://newpartner.example.com/.well-known/jwks.json"+KID = "reg-key"++KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)+++def _jwks() -> dict:+ jwk = json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(KEY.public_key()))+ jwk.update({"kid": KID, "use": "sig", "alg": "RS256"})+ return {"keys": [jwk]}+++class _CacheHeaderlessResponse:+ """Stands in for the requests.Response the CIMD fetch returns, which is read only for+ cache headers."""++ headers: dict[str, str] = {}+++@override_settings(SITE_URL="https://us.posthog.com")+class TestClientRegistration(ProvisioningTestBase):+ def setUp(self):+ super().setUp()+ cache.clear()++ def _register(self, body: dict, *, jwks: dict | None = None, metadata_error: Exception | None = None):+ """Drive the endpoint with both outbound fetches stubbed. They are separate patches+ because the metadata document and the JWKS are fetched by different modules."""+ metadata = {+ "client_id": CIMD_URL,+ "client_name": "New Partner",+ "redirect_uris": ["https://newpartner.example.com/callback"],+ "grant_types": ["authorization_code"],+ "response_types": ["code"],+ "token_endpoint_auth_method": "private_key_jwt",+ "jwks_uri": JWKS_URI,+ }+ metadata_patch = (+ patch(+ "posthog.api.oauth.cimd.fetch_client_json_document",+ side_effect=metadata_error,+ )+ if metadata_error+ else patch(+ "posthog.api.oauth.cimd.fetch_client_json_document",+ return_value=(metadata, _CacheHeaderlessResponse()),+ )+ )+ with (+ # example.com does not resolve, and the SSRF guard runs before the fetch, so+ # without this the metadata check would fail for a reason unrelated to the test.+ patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")}),+ metadata_patch,+ patch(+ "posthog.api.oauth.client_assertion.fetch_client_json_document",+ return_value=(jwks if jwks is not None else _jwks(), None),+ ),+ ):+ return self._post_api(REGISTRATION_URL, body)++ def _make_partner(self, **overrides) -> OAuthApplication:+ defaults = {+ "name": "Registered Partner",+ "client_id": "opaque-registered-client-id",+ "is_cimd_client": True,+ "cimd_metadata_url": CIMD_URL,+ "client_secret": "",+ "client_type": OAuthApplication.CLIENT_CONFIDENTIAL,+ "jwks_uri": JWKS_URI,+ "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,+ "redirect_uris": "https://newpartner.example.com/callback",+ "algorithm": "RS256",+ "scopes": TEST_PARTNER_SCOPES,+ "is_provisioning_partner": True,+ "provisioning_active": True,+ "provisioning_can_create_accounts": True,+ }+ return OAuthApplication.objects.create(**{**defaults, **overrides})++ def _assertion(self, **overrides) -> str:+ now = int(time.time())+ claims = {+ "iss": CIMD_URL,+ "sub": CIMD_URL,+ "aud": "https://us.posthog.com/api/agentic/oauth/token",+ "jti": f"reg-jti-{now}",+ "iat": now,+ "exp": now + 60,+ }+ claims.update(overrides)+ return jwt.encode(claims, KEY, algorithm="RS256", headers={"kid": KID})++ def test_unregistered_client_id_is_reported_as_not_registered(self):+ res = self._register({"client_id": "totally-unknown-client-id"})++ assert res.status_code == 400+ body = res.json()+ assert body["registered"] is False+ assert body["error"]["code"] == "registration_failed"+ # The per-check detail is the point: a bare error code would not tell the partner+ # whether the document was unreachable, malformed, or simply never registered.+ assert [check["name"] for check in body["checks"]] == ["client_exists"]+ assert body["checks"][0]["ok"] is False++ def test_reports_diagnostics_for_a_private_key_jwt_partner(self):+ self._make_partner()++ res = self._register({"client_id": CIMD_URL})++ assert res.status_code == 200, res.json()+ body = res.json()+ assert body["registered"] is True+ assert body["client_id"] == CIMD_URL+ assert 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+ checks = {check["name"]: check for check in body["checks"]}+ assert checks["jwks"]["ok"] is True+ assert KID in checks["jwks"]["detail"]++ def test_partner_registered_by_an_admin_can_use_github_grants(self):+ self._make_partner(provisioning_partner_type="wizard")++ 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+ # endpoint's job, and without it such a client could never reach any endpoint here.+ self._make_partner(is_provisioning_partner=False, provisioning_active=False)++ res = self._register({"client_id": CIMD_URL})++ assert res.status_code == 200, res.json()+ app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_URL)+ assert app.is_provisioning_partner+ assert app.provisioning_active++ def test_deactivated_partner_is_not_reactivated_by_re_registering(self):+ # Only a client that is not yet a partner gets the defaults applied. Registering again+ # must not undo an admin turning a partner off, which would make the endpoint a way for+ # a partner to reinstate itself.+ self._make_partner(provisioning_active=False)++ res = self._register({"client_id": CIMD_URL})++ assert res.status_code == 400, res.json()+ assert res.json()["error"]["code"] == "registration_failed"+ app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_URL)+ assert app.provisioning_active is False++ def test_unreachable_jwks_is_reported_as_a_failed_check(self):+ self._make_partner()++ with patch(+ "posthog.api.oauth.client_assertion._fetch_jwks_document",+ side_effect=ClientAssertionError("Client keys could not be retrieved"),+ ):+ res = self._register({"client_id": CIMD_URL})++ # Registration itself is fine, the keys are not: reporting both separately is what+ # lets a partner tell "PostHog doesn't know me" from "my key server is down".+ assert res.status_code == 200, res.json()+ checks = {check["name"]: check for check in res.json()["checks"]}+ assert checks["metadata_document"]["ok"] is True+ assert checks["provisioning_enabled"]["ok"] is True+ assert checks["jwks"]["ok"] is False++ @parameterized.expand(+ [+ ("valid", {}, True),+ ("wrong_audience", {"aud": "https://elsewhere.example.com/token"}, False),+ ("wrong_subject", {"sub": "https://attacker.example.com/doc.json"}, False),+ ]+ )+ def test_verifies_a_supplied_assertion(self, _name, overrides, expected_ok):+ self._make_partner()++ res = self._register(+ {+ "client_id": CIMD_URL,+ "client_assertion": self._assertion(**overrides),+ "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER,+ }+ )++ assert res.status_code == 200, res.json()+ checks = {check["name"]: check for check in res.json()["checks"]}+ assert checks["client_assertion"]["ok"] is expected_ok++ def test_rejects_an_assertion_with_the_wrong_type(self):+ self._make_partner()++ res = self._register(+ {"client_id": CIMD_URL, "client_assertion": "x.y.z", "client_assertion_type": "urn:something:else"}+ )++ assert res.status_code == 400+ assert res.json()["error"]["code"] == "invalid_request"+++class TestUnregisteredClientsFailClosed(ProvisioningTestBase):+ """Every endpoint requires an already-registered client and points at the registration+ endpoint, instead of the old behavior where an unknown CIMD client_id silently kicked off+ a 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})++ assert res.status_code == 401+ message = res.json()["error"]["message"]+ assert "No provisioning client is registered" in message+ assert "client_registration" in messagediff --git a/ee/api/agentic_provisioning/test/test_deep_links.py b/ee/api/agentic_provisioning/test/test_deep_links.pyindex 6a9251132339..4e55638ed6d4 100644--- a/ee/api/agentic_provisioning/test/test_deep_links.py+++ b/ee/api/agentic_provisioning/test/test_deep_links.py@@ -67,10 +67,10 @@ class TestDeepLinks(ProvisioningTestBase):assert res.status_code == 403assert res.json()["error"]["code"] == "deep_links_not_enabled"- def test_outstanding_token_of_hmac_configured_partner_rejected(self):+ def test_outstanding_token_of_unflagged_partner_rejected(self):token = self._get_bearer_token()- self.partner.provisioning_auth_method = "hmac"- self.partner.save(update_fields=["provisioning_auth_method"])+ self.partner.is_provisioning_partner = False+ self.partner.save(update_fields=["is_provisioning_partner"])res = self._post_with_bearer("/api/agentic/provisioning/deep_links",data={"purpose": "dashboard"},diff --git a/ee/api/agentic_provisioning/test/test_e2e_flow.py b/ee/api/agentic_provisioning/test/test_e2e_flow.pyindex ec6c6f4cd01d..000d4d7a6784 100644--- a/ee/api/agentic_provisioning/test/test_e2e_flow.py+++ b/ee/api/agentic_provisioning/test/test_e2e_flow.py@@ -15,9 +15,7 @@ class TestE2EProvisioningFlow(ProvisioningTestBase):"""Walk through the full partner provisioning flow end-to-end."""def test_full_provisioning_flow(self):- partner_token = self._get_bearer_token()-- # 1. Account request (new user) from the bearer-authenticated partner+ # 1. Account request (new user) from the confidential partnerverifier, challenge = self._pkce_pair()account_request = {"id": "acctreq_e2e_test",@@ -27,16 +25,20 @@ class TestE2EProvisioningFlow(ProvisioningTestBase):"code_challenge_method": "S256","expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),}- res = self._post_with_bearer(- "/api/agentic/provisioning/account_requests", data=account_request, token=partner_token- )+ res = self._post_with_client_secret("/api/agentic/provisioning/account_requests", data=account_request)assert res.status_code == 200assert res.json()["type"] == "oauth"auth_code = res.json()["oauth"]["code"]- # 2. Exchange authorization code for tokens (PKCE)+ # 2. Exchange authorization code for tokens (PKCE plus client authentication)res = self._post_api(- TOKEN_URL, {"grant_type": "authorization_code", "code": auth_code, "code_verifier": verifier}+ TOKEN_URL,+ {+ "grant_type": "authorization_code",+ "code": auth_code,+ "code_verifier": verifier,+ **self._client_credentials(),+ },)assert res.status_code == 200token_data = res.json()@@ -100,7 +102,10 @@ class TestE2EProvisioningFlow(ProvisioningTestBase):assert "expired_or_invalid_token" in reuse_res["Location"]# 7. Refresh the token- res = self._post_api(TOKEN_URL, {"grant_type": "refresh_token", "refresh_token": refresh_token})+ res = self._post_api(+ TOKEN_URL,+ {"grant_type": "refresh_token", "refresh_token": refresh_token, **self._client_credentials()},+ )assert res.status_code == 200new_access_token = res.json()["access_token"]assert new_access_token != access_token@@ -126,7 +131,7 @@ class TestE2EProvisioningFlow(ProvisioningTestBase):algorithm="RS256",is_first_party=True,scopes=["query:read"],- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_partner_type="test_partner",provisioning_active=True,provisioning_can_create_accounts=True,diff --git a/ee/api/agentic_provisioning/test/test_github_grants.py b/ee/api/agentic_provisioning/test/test_github_grants.pyindex 6fb14c2e2196..ab4b26edbdbd 100644--- a/ee/api/agentic_provisioning/test/test_github_grants.py+++ b/ee/api/agentic_provisioning/test/test_github_grants.py@@ -10,7 +10,7 @@ from posthog.models.oauth import OAuthApplicationfrom ee.api.agentic_provisioning import github_grantsfrom ee.api.agentic_provisioning.constants import GITHUB_GRANT_CACHE_PREFIX-from ee.api.agentic_provisioning.test.base import ProvisioningTestBase+from ee.api.agentic_provisioning.test.base import TEST_PARTNER_CLIENT_SECRET, ProvisioningTestBaseACCESS_TOKEN = "gho_secret_user_token"@@ -60,15 +60,12 @@ REPOSITORIES_RESPONSE = _github_response(class TestGitHubGrants(ProvisioningTestBase):- def setUp(self):- super().setUp()- self.bearer = self._get_bearer_token()-def _post_grants(self, body: dict):- return self._post_with_bearer("/api/agentic/provisioning/github/grants", body, token=self.bearer)+ return self._post_with_client_secret("/api/agentic/provisioning/github/grants", body)def _get_grants(self, url: str):- return self._get_with_bearer(url, self.bearer)+ # 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 (@@ -151,7 +148,7 @@ class TestGitHubGrants(ProvisioningTestBase):authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,redirect_uris="https://pkce.example.com",algorithm="RS256",- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_active=True,provisioning_can_create_accounts=True,)@@ -261,16 +258,20 @@ class TestGitHubGrants(ProvisioningTestBase):assert response.status_code == 404assert response.json()["error"]["code"] == "grant_not_found"- def _create_other_partner(self) -> OAuthApplication:+ def _create_other_partner(+ self, *, partner_type: str = "other_test_partner", 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="",+ 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",- provisioning_auth_method="bearer",+ is_provisioning_partner=True,+ provisioning_partner_type=partner_type,provisioning_active=True,provisioning_can_create_accounts=True,)@@ -305,7 +306,6 @@ class TestGitHubGrants(ProvisioningTestBase):grant = github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")url = f"/api/agentic/provisioning/github/grants/{grant.grant_id}/repositories"other_partner = self._create_other_partner()- other_bearer = self._request_bearer_token(partner=other_partner).json()["access_token"]def fake_github_request(method, request_url, **kwargs):if request_url.endswith("/user/installations"):@@ -316,12 +316,47 @@ class TestGitHubGrants(ProvisioningTestBase):patch("ee.api.agentic_provisioning.throttling.GITHUB_GRANT_POLL_RATE_LIMIT_MAX", 1),patch("ee.api.agentic_provisioning.github_grants.github_request", side_effect=fake_github_request),):- foreign = self._get_with_bearer(url, other_bearer)+ foreign = self._get_api(url, HTTP_AUTHORIZATION=self._basic_auth_header(other_partner))owner = self._get_grants(url)assert foreign.status_code == 404assert owner.status_code == 200+ def test_repositories_rejects_a_self_registered_cimd_partner(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. An+ # admin-set provisioning_partner_type is what separates one PostHog vouched for.+ grant = github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")+ unvouched = self._create_other_partner(partner_type="", 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_non_cimd_partner_with_no_partner_type(self):+ # Only CIMD auto-registration can make a partner without an admin, so a non-CIMD app is+ # vouched for by the fact that it exists. Requiring a partner type of it too would lock+ # out an already-configured partner whose type field was left blank.+ grant = github_grants.create_grant(self.partner, AUTHORIZATION, "[email protected]")+ admin_registered = self._create_other_partner(partner_type="")++ 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(diff --git a/ee/api/agentic_provisioning/test/test_oauth_token.py b/ee/api/agentic_provisioning/test/test_oauth_token.pyindex 591417a09b0f..b94203ac3ad3 100644--- a/ee/api/agentic_provisioning/test/test_oauth_token.py+++ b/ee/api/agentic_provisioning/test/test_oauth_token.py@@ -35,10 +35,21 @@ class TestOAuthTokenExchange(ProvisioningTestBase):return code, verifierdef _exchange_code(self, code: str, verifier: str):- return self._post_api(TOKEN_URL, {"grant_type": "authorization_code", "code": code, "code_verifier": verifier})+ return self._post_api(+ TOKEN_URL,+ {+ "grant_type": "authorization_code",+ "code": code,+ "code_verifier": verifier,+ **self._client_credentials(),+ },+ )def _refresh(self, refresh_token: str):- return self._post_api(TOKEN_URL, {"grant_type": "refresh_token", "refresh_token": refresh_token})+ return self._post_api(+ TOKEN_URL,+ {"grant_type": "refresh_token", "refresh_token": refresh_token, **self._client_credentials()},+ )def _stamp_session_revoke(self, when=None) -> None:OAuthApplication.objects.filter(id=self.partner.id).update(sessions_revoked_at=when or timezone.now())@@ -120,6 +131,66 @@ class TestOAuthTokenExchange(ProvisioningTestBase):assert res.status_code == 401assert res.json()["error_description"] == "code_verifier is required for PKCE"+ @parameterized.expand(+ [+ ("missing_credentials", None),+ ("wrong_secret", "not-the-real-secret"),+ ]+ )+ def test_confidential_partner_without_valid_secret_cannot_exchange_code(self, _name, secret):+ code, verifier = self._mint_auth_code()+ body = {"grant_type": "authorization_code", "code": code, "code_verifier": verifier}+ if secret is not None:+ body.update(self._client_credentials(secret=secret))++ res = self._post_api(TOKEN_URL, body)++ assert res.status_code == 401+ assert res.json()["error"] == "invalid_client"+ # Client authentication runs before the code is consumed, so a rejected attempt must+ # leave the caller able to retry with the right secret.+ assert self._exchange_code(code, verifier).status_code == 200++ def test_confidential_partner_without_valid_secret_cannot_refresh(self):+ refresh_token = self._request_bearer_token().json()["refresh_token"]++ res = self._post_api(+ TOKEN_URL,+ {+ "grant_type": "refresh_token",+ "refresh_token": refresh_token,+ **self._client_credentials(secret="not-the-real-secret"),+ },+ )++ assert res.status_code == 401+ assert res.json()["error"] == "invalid_client"+ # The rejected refresh must not have revoked the caller's only token.+ assert self._refresh(refresh_token).status_code == 200++ def test_pkce_partner_exchanges_code_without_a_secret(self):+ # PKCE partners are public clients: code_verifier is their only client authentication,+ # so requiring a secret from confidential partners must not reach them.+ pkce_partner = OAuthApplication.objects.create(+ client_id="pkce-token-partner",+ name="PKCE Token Partner",+ client_secret="",+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://partner.example.com/callback",+ algorithm="RS256",+ scopes=TEST_PARTNER_SCOPES,+ is_provisioning_partner=True,+ provisioning_partner_type="test_partner",+ provisioning_active=True,+ )+ code, verifier = self._mint_auth_code(partner=pkce_partner)++ res = self._post_api(TOKEN_URL, {"grant_type": "authorization_code", "code": code, "code_verifier": verifier})++ assert res.status_code == 200+ assert res.json()["access_token"].startswith("pha_")+def test_pkce_mismatch_returns_400_without_consuming_code(self):code, verifier = self._mint_auth_code()res = self._exchange_code(code, "wrong_verifier_" + "a" * 32)@@ -145,9 +216,8 @@ class TestOAuthTokenExchange(ProvisioningTestBase):assert res.json()["error"] == "invalid_scope"def test_omitted_request_scopes_resolve_to_app_ceiling(self):- partner_token = self._get_bearer_token()verifier, challenge = self._pkce_pair()- res = self._post_with_bearer(+ res = self._post_with_client_secret("/api/agentic/provisioning/account_requests",data={"id": "req_scopeless",@@ -155,7 +225,6 @@ class TestOAuthTokenExchange(ProvisioningTestBase):"code_challenge": challenge,"code_challenge_method": "S256",},- token=partner_token,)assert res.status_code == 200code = res.json()["oauth"]["code"]diff --git a/ee/api/agentic_provisioning/test/test_partner_rate_limits.py b/ee/api/agentic_provisioning/test/test_partner_rate_limits.pyindex 92ee573b1384..9dd6e3e5fd4a 100644--- a/ee/api/agentic_provisioning/test/test_partner_rate_limits.py+++ b/ee/api/agentic_provisioning/test/test_partner_rate_limits.py@@ -11,7 +11,7 @@ from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefresfrom ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIX, PARTNER_RATE_LIMIT_DEFAULTSfrom ee.api.agentic_provisioning.exceptions import ProvisioningError-from ee.api.agentic_provisioning.test.base import ProvisioningTestBase+from ee.api.agentic_provisioning.test.base import TEST_PARTNER_CLIENT_SECRET, ProvisioningTestBasefrom ee.api.agentic_provisioning.throttling import enforce_partner_rate_limitPARTNER_CLIENT_ID = "partner_rate_limit_test"@@ -27,13 +27,13 @@ class TestPartnerRateLimits(ProvisioningTestBase):self.partner_app = OAuthApplication.objects.create(client_id=PARTNER_CLIENT_ID,name="Rate Limit Test Partner",- client_secret="partner_secret",+ client_secret=TEST_PARTNER_CLIENT_SECRET,client_type=OAuthApplication.CLIENT_CONFIDENTIAL,authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,redirect_uris="https://partner.example.com/callback",algorithm="RS256",is_first_party=True,- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_partner_type="test_partner",provisioning_active=True,provisioning_can_create_accounts=True,@@ -112,7 +112,7 @@ class TestPartnerRateLimits(ProvisioningTestBase):authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,redirect_uris="https://other.example.com/callback",algorithm="RS256",- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_partner_type="other",provisioning_active=True,provisioning_rate_limit_account_requests=2,@@ -144,6 +144,7 @@ class TestPartnerRateLimits(ProvisioningTestBase):"grant_type": "authorization_code","code": code,"code_verifier": code_verifier,+ **self._client_credentials(self.partner_app),}).encode()res = self.client.post(@@ -183,6 +184,7 @@ class TestPartnerRateLimits(ProvisioningTestBase):{"grant_type": "refresh_token","refresh_token": "test_refresh_token_1",+ **self._client_credentials(self.partner_app),}).encode()res = self.client.post(@@ -213,6 +215,7 @@ class TestPartnerRateLimits(ProvisioningTestBase):{"grant_type": "refresh_token","refresh_token": "test_refresh_token_2",+ **self._client_credentials(self.partner_app),}).encode()res = self.client.post(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.pynew file mode 100644index 000000000000..eb02341410d2--- /dev/null+++ b/ee/api/agentic_provisioning/test/test_private_key_jwt_partner.py@@ -0,0 +1,245 @@+import json+import time++from unittest.mock import patch++from django.core.cache import cache+from django.test import override_settings++import jwt+from cryptography.hazmat.primitives.asymmetric import rsa++from posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARER+from posthog.models.oauth import OAuthAccessToken, OAuthApplication++from ee.api.agentic_provisioning.test.base import TEST_PARTNER_SCOPES, ProvisioningTestBase++ACCOUNT_REQUESTS_URL = "/api/agentic/provisioning/account_requests"+TOKEN_URL = "/api/agentic/oauth/token"+PARTNER_CLIENT_ID = "https://jwtpartner.example.com/.well-known/oauth-client-metadata.json"+PARTNER_JWKS_URI = "https://jwtpartner.example.com/.well-known/jwks.json"+KID = "jwt-partner-key"++# Generated once for the module: RSA-2048 keygen is ~100ms and no test mutates the key.+PARTNER_KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)+FOREIGN_KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)+++@override_settings(SITE_URL="https://us.posthog.com")+class TestPrivateKeyJwtPartner(ProvisioningTestBase):+ """A private_key_jwt partner authenticating end to end, the way a CIMD client that+ published a jwks_uri would."""++ def setUp(self):+ super().setUp()+ cache.clear()+ self.private_key = PARTNER_KEY+ public_jwk = json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(self.private_key.public_key()))+ public_jwk.update({"kid": KID, "use": "sig", "alg": "RS256"})+ self.jwks = {"keys": [public_jwk]}++ # Mirrors a real CIMD registration: the client knows itself by its metadata URL, while+ # the client_id column holds the opaque value generated at registration.+ self.jwt_partner = OAuthApplication.objects.create(+ name="JWT Partner",+ client_id="opaque-jwt-partner-client-id",+ is_cimd_client=True,+ cimd_metadata_url=PARTNER_CLIENT_ID,+ client_secret="",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ jwks_uri=PARTNER_JWKS_URI,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://jwtpartner.example.com/callback",+ algorithm="RS256",+ scopes=TEST_PARTNER_SCOPES,+ is_provisioning_partner=True,+ provisioning_partner_type="test_partner",+ provisioning_active=True,+ provisioning_can_create_accounts=True,+ provisioning_can_provision_resources=True,+ )++ def _assertion(self, **overrides) -> str:+ now = int(time.time())+ claims = {+ "iss": PARTNER_CLIENT_ID,+ "sub": PARTNER_CLIENT_ID,+ "aud": "https://us.posthog.com/api/agentic/oauth/token",+ "jti": f"jti-{now}-{overrides.pop('jti_suffix', 'default')}",+ "iat": now,+ "exp": now + 60,+ }+ claims.update(overrides)+ return jwt.encode(claims, self.private_key, algorithm="RS256", headers={"kid": KID})++ def _assertion_body(self, **overrides) -> dict:+ return {+ "client_assertion": self._assertion(**overrides),+ "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER,+ }++ def _post(self, url: str, data: dict):+ with patch("posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=(self.jwks, None)):+ return self._post_api(url, data)++ def test_account_request_authenticates_with_an_assertion(self):+ res = self._post(+ ACCOUNT_REQUESTS_URL,+ {"id": "req_jwt", "email": "[email protected]", **self._assertion_body()},+ )+ assert res.status_code == 200, res.json()+ assert res.json()["type"] == "oauth"++ def test_account_request_rejected_without_an_assertion(self):+ # The client_id is public, so presenting it alone must not authenticate a confidential+ # partner.+ res = self._post_api(+ ACCOUNT_REQUESTS_URL,+ {+ "id": "req_jwt_bare",+ "email": "[email protected]",+ "client_id": PARTNER_CLIENT_ID,+ "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",+ "code_challenge_method": "S256",+ },+ )+ assert res.status_code == 401+ assert res.json()["error"]["code"] == "unauthorized"++ def test_account_request_rejected_when_signed_by_another_key(self):+ now = int(time.time())+ forged = jwt.encode(+ {+ "iss": PARTNER_CLIENT_ID,+ "sub": PARTNER_CLIENT_ID,+ "aud": "https://us.posthog.com/api/agentic/oauth/token",+ "jti": "forged",+ "iat": now,+ "exp": now + 60,+ },+ FOREIGN_KEY,+ algorithm="RS256",+ headers={"kid": KID},+ )+ res = self._post(+ ACCOUNT_REQUESTS_URL,+ {+ "id": "req_forged",+ "email": "[email protected]",+ "client_assertion": forged,+ "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER,+ },+ )+ assert res.status_code == 401++ def test_token_exchange_requires_an_assertion(self):+ code, verifier = self._mint_auth_code(partner=self.jwt_partner)++ res = self._post_api(TOKEN_URL, {"grant_type": "authorization_code", "code": code, "code_verifier": verifier})++ assert res.status_code == 401+ assert res.json()["error"] == "invalid_client"+ # Client authentication runs before the code is consumed, so the caller can retry.+ retry = self._post(+ TOKEN_URL,+ {+ "grant_type": "authorization_code",+ "code": code,+ "code_verifier": verifier,+ **self._assertion_body(jti_suffix="retry"),+ },+ )+ assert retry.status_code == 200, retry.json()++ def test_full_flow_from_account_request_to_resource(self):+ verifier, challenge = self._pkce_pair()+ res = self._post(+ ACCOUNT_REQUESTS_URL,+ {+ "id": "req_jwt_flow",+ "email": "[email protected]",+ "scopes": ["query:read", "project:read"],+ "code_challenge": challenge,+ "code_challenge_method": "S256",+ **self._assertion_body(jti_suffix="acct"),+ },+ )+ assert res.status_code == 200, res.json()+ code = res.json()["oauth"]["code"]++ tokens = self._post(+ TOKEN_URL,+ {+ "grant_type": "authorization_code",+ "code": code,+ "code_verifier": verifier,+ **self._assertion_body(jti_suffix="token"),+ },+ )+ assert tokens.status_code == 200, tokens.json()+ access_token = tokens.json()["access_token"]++ # The access token is an ordinary OAuth credential regardless of how the partner+ # authenticated, so the resource endpoints are unchanged.+ resource = self._post_with_bearer("/api/agentic/provisioning/resources", {}, token=access_token)+ assert resource.status_code == 200, resource.json()+ assert resource.json()["status"] == "complete"++ refreshed = self._post(+ TOKEN_URL,+ {+ "grant_type": "refresh_token",+ "refresh_token": tokens.json()["refresh_token"],+ **self._assertion_body(jti_suffix="refresh"),+ },+ )+ assert refreshed.status_code == 200, refreshed.json()+ assert OAuthAccessToken.objects.filter(token=refreshed.json()["access_token"]).exists()++ def test_assertion_cannot_be_replayed_across_requests(self):+ body = {"id": "req_replay", "email": "[email protected]", **self._assertion_body()}+ assert self._post(ACCOUNT_REQUESTS_URL, body).status_code == 200++ replayed = self._post(ACCOUNT_REQUESTS_URL, {**body, "id": "req_replay_2", "email": "[email protected]"})+ assert replayed.status_code == 401++ @patch("ee.api.agentic_provisioning.authentication.enqueue_cimd_refresh_if_stale")+ def test_authenticating_refreshes_stale_cimd_metadata(self, mock_refresh):+ # This is the only path a confidential CIMD partner takes, so if it did not refresh,+ # the client's metadata document would freeze at whatever it was promoted with and+ # later scope or jwks_uri edits would never be picked up.+ res = self._post(+ ACCOUNT_REQUESTS_URL,+ {"id": "req_refresh", "email": "[email protected]", **self._assertion_body()},+ )+ 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_provisioning_auth.py b/ee/api/agentic_provisioning/test/test_provisioning_auth.pyindex dc541d822f7e..7196d2131a25 100644--- a/ee/api/agentic_provisioning/test/test_provisioning_auth.py+++ b/ee/api/agentic_provisioning/test/test_provisioning_auth.py@@ -1,4 +1,5 @@import json+from ipaddress import ip_addressfrom unittest.mock import MagicMock, patch@@ -6,13 +7,18 @@ from django.core.cache import cache as real_cachefrom parameterized import parameterized-from posthog.api.oauth.cimd import _blocked_key, _cache_key+from posthog.api.oauth.cimd import (+ _blocked_key,+ _cache_key,+ apply_provisioning_defaults,+ fetch_and_upsert_cimd_application,+)from posthog.models.oauth import OAuthApplicationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.user import Userfrom ee.api.agentic_provisioning.authentication import ProvisioningAuthentication-from ee.api.agentic_provisioning.test.base import ProvisioningTestBase+from ee.api.agentic_provisioning.test.base import TEST_PARTNER_CLIENT_SECRET, ProvisioningTestBaseWIZARD_CLIENT_ID = "test-wizard-client"@@ -25,13 +31,13 @@ class TestProvisioningAuthentication(ProvisioningTestBase):self.wizard_app = OAuthApplication.objects.create(client_id=WIZARD_CLIENT_ID,name="PostHog Wizard",- client_secret="",+ client_secret=TEST_PARTNER_CLIENT_SECRET,client_type=OAuthApplication.CLIENT_CONFIDENTIAL,authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,redirect_uris="http://localhost:8239/callback",algorithm="RS256",is_first_party=True,- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_partner_type="wizard",provisioning_active=True,provisioning_can_create_accounts=True,@@ -44,55 +50,117 @@ class TestProvisioningAuthentication(ProvisioningTestBase):{"id": request_id,"email": email,- "client_id": WIZARD_CLIENT_ID,"code_challenge": challenge,"code_challenge_method": "S256",+ **self._client_credentials(self.wizard_app),},)- def _exchange_code(self, code: str, verifier: str):+ def _exchange_code(self, code: str, verifier: str, partner=None):return self.client.post("/api/agentic/oauth/token",- data={"grant_type": "authorization_code", "code": code, "code_verifier": verifier},+ data={+ "grant_type": "authorization_code",+ "code": code,+ "code_verifier": verifier,+ **self._client_credentials(partner or self.wizard_app),+ },)- # --- Bearer identification ---+ # --- client_secret identification ---- def test_bearer_partner_identified_by_token(self):- token = self._get_bearer_token()+ @parameterized.expand(["body", "basic_header"])+ def test_client_secret_partner_identified(self, transport):+ payload = {"id": f"req_secret_{transport}", "email": f"{transport}[email protected]"}+ if transport == "body":+ res = self._post_with_client_secret("/api/agentic/provisioning/account_requests", payload)+ else:+ res = self._post_api(+ "/api/agentic/provisioning/account_requests",+ {**payload, "client_id": self.partner.client_id},+ HTTP_AUTHORIZATION=self._basic_auth_header(),+ )++ assert res.status_code == 200+ assert res.json()["type"] == "oauth"++ @parameterized.expand(+ [+ ("wrong_secret", "not-the-real-secret"),+ ("blank_secret", ""),+ ]+ )+ def test_client_secret_partner_rejected_without_the_right_secret(self, _name, secret):+ res = self._post_api(+ "/api/agentic/provisioning/account_requests",+ {+ "id": "req_bad_secret",+ "email": "[email protected]",+ "client_id": self.partner.client_id,+ "client_secret": secret,+ },+ )+ assert res.status_code == 401+ assert res.json()["error"]["code"] == "unauthorized"++ def test_client_secret_partner_cannot_downgrade_to_public_client_id(self):+ # A confidential partner's client_id is public. Accepting it on its own would let+ # anyone act as the partner just by leaving the secret out.+ res = self._post_api(+ "/api/agentic/provisioning/account_requests",+ {+ "id": "req_no_secret",+ "email": "[email protected]",+ "client_id": self.partner.client_id,+ "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",+ "code_challenge_method": "S256",+ },+ )+ assert res.status_code == 401+ assert res.json()["error"]["code"] == "unauthorized"++ def test_access_token_no_longer_identifies_a_partner(self):+ # Partners used to prove themselves by presenting an access token they had been+ # issued. Only client credentials do that now; a token identifies a user, not a client.res = self._post_with_bearer("/api/agentic/provisioning/account_requests",- {"id": "req_bearer", "email": "[email protected]"},- token=token,+ {"id": "req_token_only", "email": "[email protected]"},+ token=self._get_bearer_token(),)- assert res.status_code == 200- assert res.json()["type"] == "oauth"+ assert res.status_code == 401+ assert res.json()["error"]["code"] == "unauthorized"- def test_inactive_bearer_partner_rejected(self):- token = self._get_bearer_token()+ def test_inactive_client_secret_partner_rejected(self):self.partner.provisioning_active = Falseself.partner.save(update_fields=["provisioning_active"])- res = self._post_with_bearer(+ res = self._post_with_client_secret("/api/agentic/provisioning/account_requests",- {"id": "req_inactive_bearer", "email": "[email protected]"},- token=token,+ {"id": "req_inactive_secret", "email": "[email protected]"},)assert res.status_code == 401assert res.json()["error"]["code"] == "unauthorized"- # --- HMAC partners are fail-closed ---+ # --- apps that aren't flagged as partners are fail-closed ---- def test_hmac_partner_can_no_longer_authenticate(self):+ @parameterized.expand(+ [+ ("confidential", OAuthApplication.CLIENT_CONFIDENTIAL),+ ("public", OAuthApplication.CLIENT_PUBLIC),+ ]+ )+ def test_app_not_flagged_as_partner_cannot_authenticate(self, name, client_type):+ # The legacy HMAC partners land here after the backfill: an app can carry every other+ # provisioning flag and still be refused, of either client type.OAuthApplication.objects.create(- client_id="legacy-hmac-partner",- name="Legacy HMAC Partner",+ client_id=f"legacy-partner-{name}",+ name=f"Legacy Partner {name}",client_secret="",- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ client_type=client_type,authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,redirect_uris="https://legacy.example.com/callback",algorithm="RS256",- provisioning_auth_method="hmac",+ is_provisioning_partner=False,provisioning_partner_type="stripe",provisioning_active=True,provisioning_can_create_accounts=True,@@ -101,8 +169,7 @@ class TestProvisioningAuthentication(ProvisioningTestBase):res = self._post_api("/api/agentic/provisioning/account_requests",- {"id": "req_hmac", "email": "[email protected]", "client_id": "legacy-hmac-partner"},- HTTP_STRIPE_SIGNATURE="t=1234567890,v1=deadbeef",+ {"id": "req_legacy", "email": f"legacy-{name}@example.com", "client_id": f"legacy-partner-{name}"},)assert res.status_code == 401assert res.json()["error"]["code"] == "unauthorized"@@ -153,12 +220,12 @@ class TestProvisioningAuthentication(ProvisioningTestBase):OAuthApplication.objects.create(name="Disabled Partner",client_id="disabled-partner",- client_secret="",+ client_secret=TEST_PARTNER_CLIENT_SECRET,client_type=OAuthApplication.CLIENT_CONFIDENTIAL,authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,redirect_uris="https://localhost",algorithm="RS256",- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_partner_type="disabled",provisioning_active=True,provisioning_can_create_accounts=False,@@ -166,7 +233,12 @@ class TestProvisioningAuthentication(ProvisioningTestBase):res = self._post_api("/api/agentic/provisioning/account_requests",- {"id": "req_disabled", "email": "[email protected]", "client_id": "disabled-partner"},+ {+ "id": "req_disabled",+ "email": "[email protected]",+ "client_id": "disabled-partner",+ "client_secret": TEST_PARTNER_CLIENT_SECRET,+ },)assert res.status_code == 403assert res.json()["error"]["code"] == "forbidden"@@ -237,7 +309,7 @@ class TestProvisioningAuthentication(ProvisioningTestBase):algorithm="RS256",is_cimd_client=True,cimd_metadata_url=cimd_url,- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_partner_type="wizard",provisioning_active=True,provisioning_can_create_accounts=True,@@ -270,7 +342,7 @@ class TestProvisioningAuthentication(ProvisioningTestBase):algorithm="RS256",is_cimd_client=True,cimd_metadata_url=cimd_url,- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_partner_type="wizard",provisioning_active=False,provisioning_can_create_accounts=True,@@ -309,7 +381,7 @@ class TestProvisioningAuthentication(ProvisioningTestBase):algorithm="RS256",is_cimd_client=True,cimd_metadata_url=cimd_url,- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_partner_type="wizard",provisioning_active=True,provisioning_can_create_accounts=True,@@ -339,9 +411,9 @@ class TestProvisioningAuthentication(ProvisioningTestBase):{"id": "req_plain","email": "[email protected]",- "client_id": WIZARD_CLIENT_ID,"code_challenge": "some_challenge","code_challenge_method": "plain",+ **self._client_credentials(self.wizard_app),},)assert res.status_code == 400@@ -376,44 +448,26 @@ def _cimd_mock_response(metadata: dict | None, status_code: int = 200):return resp-@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))-class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):+@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+class TestCimdProvisioningRegistration(ProvisioningTestBase):def setUp(self):super().setUp()OAuthApplication.objects.filter(cimd_metadata_url=CIMD_PROV_URL).delete()real_cache.clear()- @patch("ee.api.agentic_provisioning.authentication.register_cimd_provisioning_application_task")- def test_new_cimd_partner_returns_202_and_kicks_off_registration(self, mock_task, _url_mock):- _, challenge = self._pkce_pair()- res = self.client.post(- "/api/agentic/provisioning/account_requests",- data={- "id": "req_cimd_auto",- "email": "[email protected]",- "client_id": CIMD_PROV_URL,- "code_challenge": challenge,- "code_challenge_method": "S256",- },- content_type="application/json",- )-- assert res.status_code == 202- assert res.json()["type"] == "registering"- assert res.json()["retry_after"] == 5- mock_task.delay.assert_called_once_with(CIMD_PROV_URL)+ def _register(self) -> OAuthApplication:+ """Register the partner the way client_registration does."""+ app = fetch_and_upsert_cimd_application(CIMD_PROV_URL)+ assert app is not None+ return apply_provisioning_defaults(app)- @patch("posthog.api.oauth.cimd.requests.get")- def test_new_cimd_partner_succeeds_after_background_registration(self, mock_get, _url_mock):+ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_registered_cimd_partner_can_create_accounts(self, mock_get, _url_mock):mock_get.return_value = _cimd_mock_response(_make_cimd_metadata())- from posthog.api.oauth.cimd import register_cimd_provisioning_application_task-- register_cimd_provisioning_application_task(CIMD_PROV_URL)-- app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_PROV_URL)+ app = self._register()assert app.is_cimd_client- assert app.provisioning_auth_method == "pkce"+ assert app.is_provisioning_partnerassert app.provisioning_activeassert app.provisioning_can_create_accountsassert app.provisioning_can_provision_resources@@ -433,14 +487,12 @@ class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):assert res.status_code == 200assert res.json()["type"] == "oauth"- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_cimd_scope_ceiling_refreshes_on_agentic_auth_after_metadata_edit(self, mock_get, _url_mock):- from posthog.api.oauth.cimd import _cache_key, register_cimd_provisioning_application_task-initial = _make_cimd_metadata()initial["com.posthog"] = {"scopes": ["insight:read"]}mock_get.return_value = _cimd_mock_response(initial)- register_cimd_provisioning_application_task(CIMD_PROV_URL)+ self._register()app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_PROV_URL)assert app.scopes == ["insight:read"]@@ -470,84 +522,6 @@ class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):app.refresh_from_db()assert app.scopes == ["insight:read", "dashboard:read"]- @patch("posthog.api.oauth.cimd.refresh_cimd_metadata_task")- def test_existing_cimd_app_gets_provisioning_backfilled(self, mock_refresh, _url_mock):- OAuthApplication.objects.create(- name="Pre-existing CIMD",- client_secret="",- client_type=OAuthApplication.CLIENT_PUBLIC,- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,- redirect_uris="http://127.0.0.1:3000/callback",- algorithm="RS256",- is_cimd_client=True,- cimd_metadata_url=CIMD_PROV_URL,- )-- _, challenge = self._pkce_pair()- res = self.client.post(- "/api/agentic/provisioning/account_requests",- data={- "id": "req_cimd_backfill",- "email": "[email protected]",- "client_id": CIMD_PROV_URL,- "code_challenge": challenge,- "code_challenge_method": "S256",- },- content_type="application/json",- )- assert res.status_code == 200-- app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_PROV_URL)- assert app.provisioning_auth_method == "pkce"- assert app.provisioning_active-- def test_cimd_backfill_db_error_degrades_to_unauthorized(self, _url_mock):- OAuthApplication.objects.create(- name="CIMD DB Error App",- client_secret="",- client_type=OAuthApplication.CLIENT_PUBLIC,- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,- redirect_uris="http://127.0.0.1:3000/callback",- algorithm="RS256",- is_cimd_client=True,- cimd_metadata_url=CIMD_PROV_URL,- )- with patch(- "ee.api.agentic_provisioning.authentication.apply_provisioning_defaults",- side_effect=RuntimeError("simulated DB error"),- ):- _, challenge = self._pkce_pair()- res = self.client.post(- "/api/agentic/provisioning/account_requests",- data={- "id": "req_cimd_db_err",- "email": "[email protected]",- "client_id": CIMD_PROV_URL,- "code_challenge": challenge,- "code_challenge_method": "S256",- },- content_type="application/json",- )- assert res.status_code == 401-- @patch("ee.api.agentic_provisioning.authentication.register_cimd_provisioning_application_task")- def test_new_cimd_url_returns_202_not_401(self, mock_task, _url_mock):- _, challenge = self._pkce_pair()- res = self.client.post(- "/api/agentic/provisioning/account_requests",- data={- "id": "req_cimd_fail",- "email": "[email protected]",- "client_id": CIMD_PROV_URL,- "code_challenge": challenge,- "code_challenge_method": "S256",- },- content_type="application/json",- )- assert res.status_code == 202- assert res.json()["type"] == "registering"- mock_task.delay.assert_called_once()-@patch("posthog.api.oauth.cimd.refresh_cimd_metadata_task")def test_partner_rate_limit_enforced_after_threshold(self, mock_refresh, _url_mock):OAuthApplication.objects.create(@@ -559,7 +533,7 @@ class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):algorithm="RS256",is_cimd_client=True,cimd_metadata_url=CIMD_PROV_URL,- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_active=True,provisioning_can_create_accounts=True,provisioning_can_provision_resources=True,@@ -593,8 +567,7 @@ class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):assert res.json()["error"]["code"] == "rate_limited"@patch("posthog.api.oauth.cimd.CIMD_THROTTLE_CLASSES", new=[])- @patch("ee.api.agentic_provisioning.authentication.register_cimd_provisioning_application_task")- def test_cimd_domain_rate_limit_blocks_excessive_registrations(self, mock_task, _url_mock):+ def test_cimd_domain_rate_limit_blocks_excessive_registrations(self, _url_mock):from ee.api.agentic_provisioning.constants import CIMD_DOMAIN_RATE_LIMIT_MAXbase_domain = "evil.example.com"@@ -613,7 +586,7 @@ class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):},content_type="application/json",)- assert res.status_code == 202, f"Request {i} failed: {res.json()}"+ assert res.status_code == 401, f"Request {i} failed: {res.json()}"url = f"https://{base_domain}/path-blocked/metadata.json"res = self.client.post(@@ -631,8 +604,7 @@ class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):assert res.json()["error"]["code"] == "rate_limited"@patch("posthog.api.oauth.cimd.CIMD_THROTTLE_CLASSES", new=[])- @patch("ee.api.agentic_provisioning.authentication.register_cimd_provisioning_application_task")- def test_cimd_domain_rate_limit_does_not_block_different_domains(self, mock_task, _url_mock):+ def test_cimd_domain_rate_limit_does_not_block_different_domains(self, _url_mock):from ee.api.agentic_provisioning.constants import CIMD_DOMAIN_RATE_LIMIT_MAX_, challenge = self._pkce_pair()@@ -650,7 +622,7 @@ class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):},content_type="application/json",)- assert res.status_code == 202, f"Request {i} for domain-{i} failed: {res.json()}"+ assert res.status_code == 401, f"Request {i} for domain-{i} failed: {res.json()}"@patch("posthog.api.oauth.cimd.CIMD_THROTTLE_CLASSES", new=[])@patch("posthog.api.oauth.cimd.refresh_cimd_metadata_task")@@ -671,7 +643,7 @@ class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):algorithm="RS256",is_cimd_client=True,cimd_metadata_url=url,- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_active=True,provisioning_can_create_accounts=True,provisioning_can_provision_resources=True,@@ -702,7 +674,7 @@ class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):algorithm="RS256",is_cimd_client=True,cimd_metadata_url=CIMD_PROV_URL,- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_active=True,provisioning_can_create_accounts=True,provisioning_can_provision_resources=True,@@ -758,7 +730,7 @@ class TestCimdProvisioningAutoRegistration(ProvisioningTestBase):algorithm="RS256",is_cimd_client=True,cimd_metadata_url=CIMD_PROV_URL,- provisioning_auth_method="pkce",+ is_provisioning_partner=True,provisioning_active=True,provisioning_can_create_accounts=True,provisioning_can_provision_resources=True,diff --git a/ee/api/agentic_provisioning/test/test_region_proxy.py b/ee/api/agentic_provisioning/test/test_region_proxy.pyindex 6573fc917fd8..97de6f35b206 100644--- a/ee/api/agentic_provisioning/test/test_region_proxy.py+++ b/ee/api/agentic_provisioning/test/test_region_proxy.py@@ -222,9 +222,7 @@ class TestDecoratorIntegration(ProvisioningTestBase):"configuration": {"region": "EU"},"scopes": ["query:read"],}- res = self._post_with_bearer(- "/api/agentic/provisioning/account_requests", data=payload, token=self._get_bearer_token()- )+ res = self._post_with_client_secret("/api/agentic/provisioning/account_requests", data=payload)assert res.status_code == 200assert res.json()["type"] == "oauth"@@ -235,9 +233,7 @@ class TestDecoratorIntegration(ProvisioningTestBase):"configuration": {"region": "US"},"scopes": ["query:read"],}- res = self._post_with_bearer(- "/api/agentic/provisioning/account_requests", data=payload, token=self._get_bearer_token()- )+ res = self._post_with_client_secret("/api/agentic/provisioning/account_requests", data=payload)assert res.status_code == 200assert res.json()["type"] == "oauth"@@ -433,9 +429,7 @@ class TestCrossRegionLoopback(ProvisioningTestBase):"scopes": ["query:read"],}- res = self._post_with_bearer(- "/api/agentic/provisioning/account_requests", data=payload, token=self._get_bearer_token()- )+ res = self._post_with_client_secret("/api/agentic/provisioning/account_requests", data=payload)assert mock_request.called, "US instance should have proxied to EU"assert captured["host"] == "eu.posthog.com"@@ -517,9 +511,7 @@ class TestCrossRegionLoopback(ProvisioningTestBase):"configuration": {"region": "EU"},"scopes": ["query:read"],}- self._post_with_bearer(- "/api/agentic/provisioning/account_requests", data=payload, token=self._get_bearer_token()- )+ self._post_with_client_secret("/api/agentic/provisioning/account_requests", data=payload)assert call_count["n"] == 1, (f"proxy should fire exactly once (US→EU); got {call_count['n']} — loop header not respected"diff --git a/ee/api/agentic_provisioning/test/test_scope_hydration.py b/ee/api/agentic_provisioning/test/test_scope_hydration.pyindex 217a59960da1..7c72282b9fba 100644--- a/ee/api/agentic_provisioning/test/test_scope_hydration.py+++ b/ee/api/agentic_provisioning/test/test_scope_hydration.py@@ -47,7 +47,10 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):self.organization_membership.save()def _refresh(self, refresh_token: str):- return self._post_api(TOKEN_URL, {"grant_type": "refresh_token", "refresh_token": refresh_token})+ return self._post_api(+ TOKEN_URL,+ {"grant_type": "refresh_token", "refresh_token": refresh_token, **self._client_credentials()},+ )def test_issuance_hydrates_with_previously_provisioned_teams(self):previously_provisioned = self._provision_team(self.partner, "Previously provisioned", "proj_existing")diff --git a/ee/api/agentic_provisioning/throttling.py b/ee/api/agentic_provisioning/throttling.pyindex 22ebcaba9b18..d89a73266f80 100644--- a/ee/api/agentic_provisioning/throttling.py+++ b/ee/api/agentic_provisioning/throttling.py@@ -26,6 +26,7 @@ A caller can burst up to 2x a limit across a window boundary (``limit`` atfrom __future__ import annotationsimport time+from hashlib import sha256from typing import ClassVar, castfrom urllib.parse import urlparse@@ -46,6 +47,10 @@ from ee.api.agentic_provisioning.constants import (CIMD_DOMAIN_RATE_LIMIT_MAX,CIMD_DOMAIN_RATE_LIMIT_PREFIX,CIMD_DOMAIN_RATE_LIMIT_WINDOW_SECONDS,+ CLIENT_REGISTRATION_IP_RATE_LIMIT_MAX,+ CLIENT_REGISTRATION_RATE_LIMIT_MAX,+ CLIENT_REGISTRATION_RATE_LIMIT_PREFIX,+ CLIENT_REGISTRATION_RATE_LIMIT_WINDOW_SECONDS,GITHUB_GRANT_POLL_RATE_LIMIT_MAX,GITHUB_GRANT_POLL_RATE_LIMIT_PREFIX,GITHUB_GRANT_POLL_RATE_LIMIT_WINDOW_SECONDS,@@ -247,6 +252,48 @@ def enforce_wizard_run_user_rate_limit(user_id: int, resource_id: str = "") -> N)+class ClientRegistrationThrottle(BaseThrottle):+ """Cap client_registration calls per client_id.++ That endpoint performs a synchronous outbound fetch of a caller-supplied URL, so unlike+ :class:`CIMDRegistrationThrottle` this applies whether or not the client already exists:+ an already-registered partner re-running diagnostics is exactly the case that would+ otherwise fetch without limit.++ Counted per client_id and per address. CIMDRegistrationThrottle only screens by IP and+ domain while a client is new, so without the second counter a caller could register a+ stack of client_ids and then spend a full per-client budget on each of them from one+ address, turning the per-client cap into an arbitrarily large total.+ """++ # Not a ClassVar: the per-address refusal narrows the message on the instance, the same way+ # CIMDRegistrationThrottle distinguishes its domain limit.+ error_message: str = "Too many registration checks for this client. Try again later."++ def allow_request(self, request: Request, view: APIView) -> bool:+ client_id = request.data.get("client_id") or ""+ if not client_id:+ return True+ window_index = int(time.time()) // CLIENT_REGISTRATION_RATE_LIMIT_WINDOW_SECONDS+ key = f"{CLIENT_REGISTRATION_RATE_LIMIT_PREFIX}{sha256(client_id.encode()).hexdigest()}:{window_index}"+ if _fixed_window_count(key, CLIENT_REGISTRATION_RATE_LIMIT_WINDOW_SECONDS) > CLIENT_REGISTRATION_RATE_LIMIT_MAX:+ return False++ ident = self.get_ident(request)+ if not ident:+ return True+ ip_key = f"{CLIENT_REGISTRATION_RATE_LIMIT_PREFIX}ip:{sha256(ident.encode()).hexdigest()}:{window_index}"+ if _fixed_window_count(ip_key, CLIENT_REGISTRATION_RATE_LIMIT_WINDOW_SECONDS) > (+ CLIENT_REGISTRATION_IP_RATE_LIMIT_MAX+ ):+ self.error_message = "Too many registration checks from this address. Try again later."+ return False+ return True++ def wait(self) -> int:+ return _window_retry_after(CLIENT_REGISTRATION_RATE_LIMIT_WINDOW_SECONDS)++class CIMDRegistrationThrottle(BaseThrottle):"""Rate-limit first-time CIMD app registration by IP and domain to match /authorize protections.diff --git a/ee/api/agentic_provisioning/urls.py b/ee/api/agentic_provisioning/urls.pyindex 6cc34670e66e..59fa276e8b21 100644--- a/ee/api/agentic_provisioning/urls.py+++ b/ee/api/agentic_provisioning/urls.py@@ -1,8 +1,9 @@"""Routes for the agentic provisioning namespace, included from ``ee/urls.py``.Partner endpoints live under ``/api/agentic/`` and are ``csrf_exempt`` (they-authenticate with a bearer token or PKCE, never a session cookie). The consent-and login routes are browser-facing and keep CSRF protection.+authenticate with a signed client assertion, client credentials, PKCE, or an OAuth+access token, never a session cookie). The consent and login routes are+browser-facing and keep CSRF protection."""from django.urls import path@@ -11,6 +12,11 @@ from django.views.decorators.csrf import csrf_exemptfrom ee.api.agentic_provisioning import viewsurlpatterns = [+ path(+ "api/agentic/provisioning/client_registration",+ csrf_exempt(views.ClientRegistrationView.as_view()),+ name="agentic_provisioning_client_registration",+ ),path("api/agentic/provisioning/account_requests",csrf_exempt(views.AccountRequestsView.as_view()),diff --git a/ee/api/agentic_provisioning/views/__init__.py b/ee/api/agentic_provisioning/views/__init__.pyindex 08b50f415c8c..6cf92089168d 100644--- a/ee/api/agentic_provisioning/views/__init__.py+++ b/ee/api/agentic_provisioning/views/__init__.py@@ -1,5 +1,6 @@from ee.api.agentic_provisioning.views.account_requests import AccountRequestsViewfrom ee.api.agentic_provisioning.views.authorize import AuthorizeConfirmView, AuthorizePendingView, agentic_authorize+from ee.api.agentic_provisioning.views.client_registration import ClientRegistrationViewfrom ee.api.agentic_provisioning.views.deep_links import DeepLinksView, agentic_loginfrom ee.api.agentic_provisioning.views.github_grants import GitHubGrantRepositoriesView, GitHubGrantsCreateViewfrom ee.api.agentic_provisioning.views.oauth_token import OAuthTokenView@@ -16,6 +17,7 @@ __all__ = ["AccountRequestsView","AuthorizeConfirmView","AuthorizePendingView",+ "ClientRegistrationView","DeepLinksView","GitHubGrantRepositoriesView","GitHubGrantsCreateView",diff --git a/ee/api/agentic_provisioning/views/account_requests.py b/ee/api/agentic_provisioning/views/account_requests.pyindex 049f358e9956..e2eeea056c25 100644--- a/ee/api/agentic_provisioning/views/account_requests.py+++ b/ee/api/agentic_provisioning/views/account_requests.py@@ -19,7 +19,7 @@ from posthog.scopes import effective_ceilingfrom ee.api.agentic_provisioning.accounts import handle_existing_user, handle_new_userfrom ee.api.agentic_provisioning.analytics import capture_provisioning_event-from ee.api.agentic_provisioning.authentication import ProvisioningAuthentication+from ee.api.agentic_provisioning.authentication import CLIENT_NOT_REGISTERED_MESSAGE, ProvisioningAuthenticationfrom ee.api.agentic_provisioning.constants import CODE_CHALLENGE_REfrom ee.api.agentic_provisioning.exceptions import ProvisioningErrorfrom ee.api.agentic_provisioning.serializers import AccountRequestSerializer@@ -30,27 +30,25 @@ from ee.api.agentic_provisioning.views.base import ProvisioningAPIViewclass AccountRequestsView(ProvisioningAPIView):region_proxy_strategy = "body_region"partner_throttle_classes = [CIMDRegistrationThrottle]+ # Identifies the partner inline rather than through an authentication class because the+ # region proxy and the request-id echo both need the parsed body alongside the partner.+ authenticates_in_handler = Truedef post(self, request: Request) -> Response:# --- Identify partner ---auth = ProvisioningAuthentication()partner = None- authenticated_user = Nonetry:result = auth.authenticate(request)if result:- authenticated_user, partner = result- except AuthenticationFailed:- raise ProvisioningError("unauthorized", "Authentication failed", status=401)-- if partner is None and auth.cimd_registration_pending:- return Response(- {"type": "registering", "retry_after": 5},- status=202,- )+ _, partner = result+ except AuthenticationFailed as exc:+ # Surface the reason: an unregistered client needs to be told to register, which+ # a flat "authentication failed" does not convey.+ raise ProvisioningError("unauthorized", str(exc.detail), status=401)if partner is None:- raise ProvisioningError("unauthorized", "Authentication required", status=401)+ raise ProvisioningError("unauthorized", CLIENT_NOT_REGISTERED_MESSAGE, status=401)# --- Parse request ---data = self.validated_body(AccountRequestSerializer, request)@@ -86,15 +84,6 @@ class AccountRequestsView(ProvisioningAPIView):region = (configuration.get("region") or "US").upper()- requested_team_id = configuration.get("team_id")- if requested_team_id is not None:- try:- requested_team_id = int(requested_team_id)- except (ValueError, TypeError):- raise ProvisioningError(- "invalid_request", "configuration.team_id must be an integer", request_id=request_id- )-existing_user = User.objects.filter(email=email).first()if existing_user:@@ -104,11 +93,9 @@ class AccountRequestsView(ProvisioningAPIView):existing_user,scopes,region=region,- team_id=requested_team_id,partner=partner,code_challenge=code_challenge,code_challenge_method=code_challenge_method,- authenticated_user=authenticated_user,))@@ -122,6 +109,5 @@ class AccountRequestsView(ProvisioningAPIView):partner=partner,code_challenge=code_challenge,code_challenge_method=code_challenge_method,- authenticated_user=authenticated_user,))diff --git a/ee/api/agentic_provisioning/views/base.py b/ee/api/agentic_provisioning/views/base.pyindex ca526e5e51c5..4026c416cd30 100644--- a/ee/api/agentic_provisioning/views/base.py+++ b/ee/api/agentic_provisioning/views/base.py@@ -33,14 +33,42 @@ from ee.api.agentic_provisioning.serializers import first_error_messageclass ProvisioningAPIView(RegionProxyMixin, APIView):"""Base for every endpoint in this namespace.- Unauthenticated by default (each endpoint declares its own partner auth);- errors raised as :class:`ProvisioningError` render in the view's envelope.+ Errors raised as :class:`ProvisioningError` render in the view's envelope.++ A subclass must either declare ``authentication_classes`` or set+ ``authenticates_in_handler = True``, so an endpoint added later cannot end up+ unauthenticated by inheriting a permissive default. See :meth:`__init_subclass__`."""authentication_classes: list[type[BaseAuthentication]] = []permission_classes: list = []error_envelope: ClassVar[Envelope] = "typed"+ # Set by the few endpoints that must authenticate mid-handler rather than through a DRF+ # authentication class: the token endpoint resolves its partner from the grant it is+ # redeeming, and account_requests needs the CIMD registration-pending signal that+ # ProvisioningAuthentication exposes as instance state.+ authenticates_in_handler: ClassVar[bool] = False++ def __init_subclass__(cls, **kwargs: Any) -> None:+ """Refuse to define an endpoint that authenticates nobody.++ These endpoints are partner-facing and several act on a partner's behalf without an+ end user, so an accidentally open one would not fail any ordinary test. Making the+ omission a definition-time error means it cannot reach review.+ """+ super().__init_subclass__(**kwargs)+ # Intermediate bases exist to be subclassed and carry no routes of their own.+ if cls.__name__.endswith("APIView"):+ return+ if not cls.authentication_classes and not cls.authenticates_in_handler:+ raise TypeError(+ f"{cls.__name__} declares no authentication_classes. Provisioning endpoints are "+ "partner-facing, so set authentication_classes (for example to "+ "ConfidentialPartnerAuthentication) or, if it must authenticate inside the "+ "handler, set authenticates_in_handler = True."+ )+# Provisioning throttles keyed on something DRF has by the time it calls# check_throttles (the partner on request.auth, a URL kwarg). Additive to# DEFAULT_THROTTLE_CLASSES, which still guards these endpoints per IP.@@ -92,8 +120,12 @@ class ProvisioningAPIView(RegionProxyMixin, APIView):class ConfidentialPartnerAPIView(ProvisioningAPIView):- """Base for confidential-partner endpoints (GitHub grants): the bearer-authed- partner rides ``request.auth``; typed envelope."""+ """Base for confidential-partner endpoints (GitHub grants).++ 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.+ """authentication_classes = [ConfidentialPartnerAuthentication]diff --git a/ee/api/agentic_provisioning/views/client_registration.py b/ee/api/agentic_provisioning/views/client_registration.pynew file mode 100644index 000000000000..32e79a690401--- /dev/null+++ b/ee/api/agentic_provisioning/views/client_registration.py@@ -0,0 +1,187 @@+"""POST /provisioning/client_registration — register a partner client and report why it+does or does not work.++This is the one door into the namespace: every other endpoint requires an already-registered+client and points here when it doesn't find one. Registration is synchronous so a partner+knows the outcome from the response rather than polling, and each check is reported+individually so a broken setup names its own cause instead of surfacing as a bare 401.++Deliberately unauthenticated: a partner that has not registered yet has no credential to+present, so requiring one would make the endpoint useless for the case it exists to serve.+What that exposes is bounded — the only URL a caller can make us dereference is the one it is+claiming as its own client_id, which goes through the same SSRF validation, DNS check and+blocklist as any other CIMD fetch — and it is rate limited per client_id, per IP and per+domain because the fetch is synchronous.+"""++from __future__ import annotations++from typing import Any++from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.oauth.cimd import (+ CIMDFetchError,+ CIMDValidationError,+ apply_provisioning_defaults,+ fetch_and_upsert_cimd_application,+ get_application_by_client_id,+ is_cimd_client_id,+ is_cimd_url_blocked,+)+from posthog.api.oauth.client_assertion import ClientAssertionError, describe_jwks, verify_client_assertion+from posthog.models.oauth import OAuthApplication++from ee.api.agentic_provisioning.analytics import capture_provisioning_event+from ee.api.agentic_provisioning.exceptions import ProvisioningError+from ee.api.agentic_provisioning.serializers import ClientRegistrationSerializer+from ee.api.agentic_provisioning.throttling import CIMDRegistrationThrottle, ClientRegistrationThrottle+from ee.api.agentic_provisioning.views.base import ProvisioningAPIView+++class ClientRegistrationView(ProvisioningAPIView):+ # Unauthenticated by design, see the module docstring.+ authenticates_in_handler = True+ partner_throttle_classes = [ClientRegistrationThrottle, CIMDRegistrationThrottle]++ def post(self, request: Request) -> Response:+ data = self.validated_body(ClientRegistrationSerializer, request)+ client_id = data["client_id"]+ checks: list[dict[str, Any]] = []++ app = self._register_or_resolve(client_id, checks)+ if app is None:+ # Nothing else can be said about a client we could not resolve, and the caller+ # needs a failure status rather than a 200 that looks like success.+ raise ProvisioningError(+ "registration_failed",+ _first_failure(checks) or "Could not register this client",+ extra={"client_id": client_id, "registered": False, "checks": checks},+ )++ self._check_jwks(app, checks)+ if data["client_assertion"]:+ self._check_assertion(app, data["client_assertion"], checks)++ capture_provisioning_event(+ "client_registration",+ "checked",+ partner=app,+ passed=all(check["ok"] for check in checks),+ )+ return Response(+ {+ "client_id": app.effective_client_id,+ "registered": True,+ "client_type": app.client_type,+ "token_endpoint_auth_method": app.token_endpoint_auth_method.value,+ "jwks_uri": app.jwks_uri,+ "scopes": app.ceiling_scopes,+ "provisioning": {+ "active": app.provisioning_active,+ "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 that PostHog+ # registered as a partner) 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 not (app.is_cimd_client and not app.provisioning_partner_type)+ and app.provisioning_can_create_accounts+ ),+ },+ "checks": checks,+ }+ )++ def _register_or_resolve(self, client_id: str, checks: list[dict[str, Any]]) -> OAuthApplication | None:+ """Register a CIMD client from its metadata document, or look up a manually+ registered one. Returns None with the reason recorded in ``checks``."""+ if not is_cimd_client_id(client_id):+ # A non-CIMD client_id has no document to fetch, so it can only have been+ # registered by a PostHog admin.+ try:+ admin_registered = get_application_by_client_id(client_id)+ except OAuthApplication.DoesNotExist:+ _record(checks, "client_exists", False, "No client is registered with this client_id")+ return None+ _record(checks, "client_exists", True, "Registered by a PostHog admin")+ return self._require_partner(admin_registered, checks)++ if is_cimd_url_blocked(client_id):+ _record(checks, "metadata_document", False, "This client_id has been blocked")+ return None++ # An already-registered client keeps working when its document is momentarily+ # unreachable, so a failed re-fetch is reported as one failed check rather than+ # suppressing every other diagnostic the caller came for.+ existing = OAuthApplication.objects.filter(cimd_metadata_url=client_id).first()+ app: OAuthApplication | None+ try:+ app = fetch_and_upsert_cimd_application(client_id)+ if app is None:+ raise CIMDFetchError("Registration is already in progress, retry shortly")+ except (CIMDFetchError, CIMDValidationError) as exc:+ _record(checks, "metadata_document", False, str(exc))+ if existing is None:+ return None+ app = existing+ else:+ _record(checks, "metadata_document", True, "Fetched and validated")++ # A CIMD client that has never been used for provisioning carries no provisioning+ # config yet, so registering here is what makes the rest of the namespace reachable.+ if not app.is_provisioning_partner:+ apply_provisioning_defaults(app)+ app.refresh_from_db()+ return self._require_partner(app, checks)++ def _require_partner(self, app: OAuthApplication, checks: list[dict[str, Any]]) -> OAuthApplication | None:+ if not app.is_provisioning_partner:+ _record(checks, "provisioning_enabled", False, "This client is not enabled for agentic provisioning")+ return None+ if not app.provisioning_active:+ _record(checks, "provisioning_enabled", False, "Provisioning is deactivated for this client")+ return None+ _record(checks, "provisioning_enabled", True, "Active")+ return app++ def _check_jwks(self, app: OAuthApplication, checks: list[dict[str, Any]]) -> None:+ if not app.jwks_uri:+ # Not a failure: a public client legitimately publishes no keys. Reported so the+ # response says which of the two situations the caller is in.+ _record(+ checks,+ "jwks",+ True,+ "No jwks_uri, so this client authenticates with PKCE only and cannot use the GitHub grant endpoints",+ )+ return++ try:+ key_ids = describe_jwks(app.jwks_uri)+ except ClientAssertionError as exc:+ _record(checks, "jwks", False, str(exc))+ return+ _record(checks, "jwks", True, f"{len(key_ids)} key(s) served: {', '.join(key_ids)}")++ def _check_assertion(self, app: OAuthApplication, assertion: str, checks: list[dict[str, Any]]) -> None:+ try:+ verify_client_assertion(app, assertion)+ except ClientAssertionError as exc:+ _record(checks, "client_assertion", False, str(exc))+ return+ _record(checks, "client_assertion", True, "Verified, and its jti is now consumed")+++def _record(checks: list[dict[str, Any]], name: str, ok: bool, detail: str) -> None:+ checks.append({"name": name, "ok": ok, "detail": detail})+++def _first_failure(checks: list[dict[str, Any]]) -> str:+ return next((check["detail"] for check in checks if not check["ok"]), "")diff --git a/ee/api/agentic_provisioning/views/oauth_token.py b/ee/api/agentic_provisioning/views/oauth_token.pyindex 521ea20b5946..11d531d58d95 100644--- a/ee/api/agentic_provisioning/views/oauth_token.py+++ b/ee/api/agentic_provisioning/views/oauth_token.py@@ -15,11 +15,14 @@ from django.core.cache import cachefrom django.core.exceptions import ValidationErrorfrom django.db import transactionfrom django.utils import timezone+from django.utils.crypto import constant_time_compareimport structlogfrom rest_framework.request import Requestfrom rest_framework.response import Response+from posthog.api.oauth.client_assertion import ClientAssertionError, extract_client_assertion, verify_client_assertion+from posthog.api.oauth.client_auth import extract_client_credentials, verify_client_secretfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshTokenfrom posthog.models.user import Userfrom posthog.models.utils import generate_random_oauth_access_token, generate_random_oauth_refresh_token@@ -43,9 +46,70 @@ from ee.api.agentic_provisioning.views.base import ProvisioningAPIViewlogger = structlog.get_logger(__name__)+def _require_client_authentication(request: Request, oauth_app: OAuthApplication, grant_type: str) -> None:+ """Make confidential partners prove themselves before their grant is spent.++ Public partners keep ``code_verifier`` as their only client authentication, which is what+ RFC 7636 prescribes and RFC 6749 section 3.2.1 expects. The app is resolved from the grant+ rather than from a caller-supplied client_id, so a confidential partner cannot reach the+ public path by presenting nothing.+ """+ if not oauth_app.requires_client_authentication:+ return++ if oauth_app.uses_private_key_jwt_auth:+ _verify_assertion_or_fail(request, oauth_app, grant_type)+ return++ credentials = extract_client_credentials(request)+ if credentials is None:+ capture_provisioning_event(+ "token_exchange", "missing_client_credentials", partner=oauth_app, grant_type=grant_type+ )+ raise ProvisioningError("invalid_client", "client_id and client_secret are required", status=401)++ client_id, client_secret = credentials+ if not constant_time_compare(client_id, oauth_app.effective_client_id) or not verify_client_secret(+ client_secret, oauth_app.client_secret or ""+ ):+ capture_provisioning_event(+ "token_exchange", "invalid_client_credentials", partner=oauth_app, grant_type=grant_type+ )+ raise ProvisioningError("invalid_client", "Invalid client credentials", status=401)+++def _verify_assertion_or_fail(request: Request, oauth_app: OAuthApplication, grant_type: str) -> None:+ assertion = extract_client_assertion(request)+ if assertion is None:+ capture_provisioning_event(+ "token_exchange", "missing_client_assertion", partner=oauth_app, grant_type=grant_type+ )+ raise ProvisioningError("invalid_client", "A client_assertion is required", status=401)++ assertion_value, asserted_client_id = assertion+ # The assertion is verified against the app the grant names, so an assertion validly+ # signed by a different client cannot be used to redeem this one's grant.+ if not constant_time_compare(asserted_client_id, oauth_app.effective_client_id):+ capture_provisioning_event(+ "token_exchange", "client_assertion_mismatch", partner=oauth_app, grant_type=grant_type+ )+ raise ProvisioningError("invalid_client", "Client assertion does not match this grant", status=401)++ try:+ verify_client_assertion(oauth_app, assertion_value)+ except ClientAssertionError as exc:+ capture_provisioning_event(+ "token_exchange", "invalid_client_assertion", partner=oauth_app, grant_type=grant_type+ )+ raise ProvisioningError("invalid_client", str(exc), status=401)++class OAuthTokenView(ProvisioningAPIView):error_envelope = "oauth"region_proxy_strategy = "token_lookup"+ # The partner is resolved from the grant being redeemed, not from the request, so+ # authentication happens in _require_client_authentication once the grant is known.+ authenticates_in_handler = Truedef post(self, request: Request) -> Response:grant_type = request.data.get("grant_type", "")@@ -90,12 +154,10 @@ class OAuthTokenView(ProvisioningAPIView):capture_provisioning_event("token_exchange", "pkce_mismatch", grant_type="authorization_code")raise ProvisioningError("invalid_grant", "PKCE code_verifier does not match")- # Consume the code before rate limiting so a leaked auth code can't be replayed- # to burn the partner's bucket. Auth codes are single-use by spec, so the- # tradeoff (rate-limited client loses the code) is acceptable — clients can- # re-initiate the OAuth flow if rate-limited.- cache.delete(cache_key)-+ # Resolved before the code is consumed because a confidential partner's client+ # authentication is checked against this app, and that check has to be able to fail+ # without spending the code. An unknown partner_id therefore leaves the code in the+ # cache to expire on its own; it is unusable either way.oauth_app: OAuthApplication | None = Nonepartner_id = code_data.get("partner_id", "")if partner_id:@@ -107,6 +169,14 @@ class OAuthTokenView(ProvisioningAPIView):capture_provisioning_event("token_exchange", "oauth_app_missing", grant_type="authorization_code")raise ProvisioningError("invalid_grant", "Unknown application for this authorization code")+ _require_client_authentication(request, oauth_app, "authorization_code")++ # Consume the code before rate limiting so a leaked auth code can't be replayed+ # to burn the partner's bucket. Auth codes are single-use by spec, so the+ # tradeoff (rate-limited client loses the code) is acceptable — clients can+ # re-initiate the OAuth flow if rate-limited.+ cache.delete(cache_key)+enforce_partner_rate_limit(oauth_app, "token_exchanges")user_id = code_data["user_id"]@@ -220,6 +290,21 @@ class OAuthTokenView(ProvisioningAPIView):capture_provisioning_event("token_exchange", "missing_refresh_token", grant_type="refresh_token")raise ProvisioningError("invalid_request", "refresh_token is required")+ # Authenticate the client before opening the transaction. Verification is expensive+ # (a password-hash comparison, or a JWKS fetch on a cache miss), so doing it here+ # keeps that work out of the row lock taken below, where it would serialize every+ # concurrent refresh for the partner. Resolving the app unlocked is safe because only+ # its registration state is read, which the lock does not protect anyway.+ application_id = (+ OAuthRefreshToken.objects.filter(token=refresh_token_value, revoked__isnull=True)+ .values_list("application_id", flat=True)+ .first()+ )+ if application_id:+ unlocked_app = OAuthApplication.objects.filter(id=application_id).first()+ if unlocked_app is not None:+ _require_client_authentication(request, unlocked_app, "refresh_token")+# Lock the app row first (revoke_application_sessions locks it before sweeping tokens),# then re-read the refresh token under that lock, so the rotate-and-mint serializes with# the revoke: either we hold the lock and our new tokens land before its sweep, or it@@ -227,11 +312,6 @@ class OAuthTokenView(ProvisioningAPIView):# the app up by id first (without locking the token row) keeps the lock order app→token,# matching the revoke, so the two can't deadlock.with transaction.atomic():- application_id = (- OAuthRefreshToken.objects.filter(token=refresh_token_value, revoked__isnull=True)- .values_list("application_id", flat=True)- .first()- )locked_app = lock_application(application_id) if application_id else Noneold_refresh = (OAuthRefreshToken.objects.select_related("user", "access_token")@@ -292,7 +372,7 @@ class OAuthTokenView(ProvisioningAPIView):# provisioning_partner_type is a stable marker set at partner registration;# checking it instead of is_provisioning_partner prevents a bypass when an admin- # clears provisioning_auth_method to disable a partner without revoking tokens.+ # clears that flag to disable a partner without revoking its tokens.if oauth_app and oauth_app.provisioning_partner_type:enforce_partner_rate_limit(oauth_app, "token_exchanges")diff --git a/posthog/admin/admins/oauth_admin.py b/posthog/admin/admins/oauth_admin.pyindex 6d65f7a2a850..8b5d8ea8b060 100644--- a/posthog/admin/admins/oauth_admin.py+++ b/posthog/admin/admins/oauth_admin.py@@ -5,7 +5,7 @@ import hashlibfrom urllib.parse import urlencodefrom django import forms-from django.contrib import admin+from django.contrib import admin, messagesfrom django.contrib.admin import helpersfrom django.template.response import TemplateResponsefrom django.utils.html import format_html@@ -36,11 +36,6 @@ class OAuthApplicationForm(forms.ModelForm):self.fields["authorization_grant_type"].disabled = Trueself.fields["authorization_grant_type"].help_text = "Only authorization code grant type is supported"- if "provisioning_signing_secret" in self.fields:- self.fields[- "provisioning_signing_secret"- ].help_text = "Only used for HMAC provisioning partners. Leave blank for PKCE or bearer clients."-# For new applications, set defaultsif not self.instance.pk:# Pre-generate client_id and client_secret@@ -81,13 +76,42 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne"is_first_party","auth_brand","provisioning_active",- "provisioning_auth_method",+ "is_provisioning_partner","provisioning_partner_type",)search_fields = ("name", "client_id", "cimd_metadata_url", "user__email", "organization__name")autocomplete_fields = ("user", "organization")ordering = ("name",)- actions = ("revoke_all_sessions",)+ actions = ("revoke_all_sessions", "regenerate_client_secret")++ @admin.action(description="Generate a new client secret")+ def regenerate_client_secret(self, request, queryset):+ # client_secret is only editable on the add form (it is hashed on save and can never be+ # read back), so this is the only way to give an existing app a secret or rotate one.+ for application in queryset:+ # Gated on the auth method rather than the client type: a private_key_jwt client is+ # confidential too, but authenticates by signed assertion, so a secret minted for it+ # would never be checked and would look like working credentials to an operator.+ if not application.uses_client_secret_auth:+ self.message_user(+ request,+ f"{application.name}: skipped, its token_endpoint_auth_method is "+ f"'{application.token_endpoint_auth_method.value}', which uses no client secret.",+ level=messages.ERROR,+ )+ continue++ plaintext_secret = generate_client_secret()+ application.client_secret = plaintext_secret+ # ClientSecretField.pre_save hashes it, so plaintext_secret is the only copy that+ # will ever exist.+ application.save(update_fields=["client_secret"])+ self.message_user(+ request,+ f"{application.name} ({application.client_id}) new client secret, save it now, "+ f"it cannot be shown again: {plaintext_secret}",+ level=messages.WARNING,+ )@admin.action(description="Revoke all sessions (force re-auth under current scopes)")def revoke_all_sessions(self, request, queryset):@@ -138,6 +162,8 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne# Model validation also rejects optional_scopes on CIMD apps: a split would# let the partner grow the locked required set via metadata refresh.readonly.append("optional_scopes")+ # Also re-derived from the metadata document on each refresh.+ readonly.append("jwks_uri")return tuple(readonly)else:return ("id", "is_dcr_client", "is_cimd_client")@@ -145,7 +171,7 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-nedef get_fieldsets(self, request, obj=None):if obj:provisioning_fields = [- "provisioning_auth_method",+ "is_provisioning_partner","provisioning_partner_type","provisioning_active","provisioning_skip_existing_user_consent",@@ -157,21 +183,35 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne"provisioning_rate_limit_token_exchanges","provisioning_rate_limit_resource_creates",]- if obj.provisioning_auth_method == "hmac":- provisioning_fields.append("provisioning_signing_secret")return ((None, {"fields": ("id", "name", "client_id", "client_type", "auth_brand", "logo_uri")}),("Authorization",- {"fields": ("authorization_grant_type", "redirect_uris", "algorithm", "scopes", "optional_scopes")},+ {+ "fields": (+ "authorization_grant_type",+ "jwks_uri",+ "redirect_uris",+ "algorithm",+ "scopes",+ "optional_scopes",+ )+ },),("Ownership", {"fields": ("user", "organization")}),("Status", {"fields": ("is_verified", "is_first_party", "is_dcr_client", "is_cimd_client")}),("Provisioning",{- "description": "Provisioning settings for agentic partners. HMAC signing secret is only used for HMAC clients.",+ "description": (+ "Provisioning settings for agentic partners. How a partner 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. Only "+ "confidential partners may use the GitHub grant endpoints. Use the 'Generate a new "+ "client secret' action to issue a secret."+ ),"fields": tuple(provisioning_fields),},),@@ -188,7 +228,16 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne(None, {"fields": ("name", "client_id", "client_secret", "client_type", "auth_brand", "logo_uri")}),("Authorization",- {"fields": ("authorization_grant_type", "redirect_uris", "algorithm", "scopes", "optional_scopes")},+ {+ "fields": (+ "authorization_grant_type",+ "jwks_uri",+ "redirect_uris",+ "algorithm",+ "scopes",+ "optional_scopes",+ )+ },),("Ownership", {"fields": ("user", "organization")}),("Status", {"fields": ("is_verified", "is_first_party")}),diff --git a/posthog/admin/test_oauth_admin.py b/posthog/admin/test_oauth_admin.pyindex 76af26fe21b4..28d44d6c3021 100644--- a/posthog/admin/test_oauth_admin.py+++ b/posthog/admin/test_oauth_admin.py@@ -5,12 +5,13 @@ from posthog.test.base import BaseTestfrom unittest.mock import patchfrom django.contrib.admin import AdminSite+from django.contrib.auth.hashers import check_passwordfrom django.test import RequestFactoryfrom django.utils import timezonefrom parameterized import parameterized-from posthog.admin.admins.oauth_admin import OAuthApplicationAdmin, OAuthApplicationForm+from posthog.admin.admins.oauth_admin import OAuthApplicationAdminfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken@@ -21,28 +22,54 @@ class TestOAuthApplicationAdmin(BaseTest):def test_list_filter_includes_provisioning_fields(self):assert "provisioning_active" in self.admin.list_filter- assert "provisioning_auth_method" in self.admin.list_filter+ assert "is_provisioning_partner" in self.admin.list_filterassert "provisioning_partner_type" in self.admin.list_filter@parameterized.expand([- ("pkce", False),- ("hmac", True),+ ("client_secret", OAuthApplication.CLIENT_CONFIDENTIAL, None, True),+ ("public", OAuthApplication.CLIENT_PUBLIC, None, False),+ # Confidential, but a jwks_uri means it authenticates by signed assertion, so a+ # secret would be inert while looking like working credentials to an operator.+ (+ "private_key_jwt",+ OAuthApplication.CLIENT_CONFIDENTIAL,+ "https://example.com/.well-known/jwks.json",+ False,+ ),])- def test_signing_secret_visibility(self, auth_method, expected_visible):- app = OAuthApplication(provisioning_auth_method=auth_method)- fieldsets = self.admin.get_fieldsets(request=None, obj=app)- provisioning = next(fieldset for fieldset in fieldsets if fieldset[0] == "Provisioning")- if expected_visible:- assert "provisioning_signing_secret" in provisioning[1]["fields"]- else:- assert "provisioning_signing_secret" not in provisioning[1]["fields"]-- def test_form_marks_signing_secret_as_hmac_only(self):- form = OAuthApplicationForm()-- assert "Only used for HMAC provisioning partners" in form.fields["provisioning_signing_secret"].help_text+ def test_regenerate_client_secret_action(self, name, client_type, jwks_uri, expects_secret):+ app = OAuthApplication.objects.create(+ name=f"Secret Action App {name}",+ client_id=f"secret_action_client_id_{name}",+ client_secret="",+ client_type=client_type,+ jwks_uri=jwks_uri,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ organization=self.organization,+ algorithm="RS256",+ )++ secret_before = app.client_secret++ request = RequestFactory().post("/")+ with patch.object(self.admin, "message_user") as message_user:+ self.admin.regenerate_client_secret(request=request, queryset=OAuthApplication.objects.filter(id=app.id))++ app.refresh_from_db()+ message = message_user.call_args.args[1]+ if not expects_secret:+ assert app.client_secret == secret_before+ assert "skipped" in message+ return++ # The plaintext is surfaced once in the admin message and only ever stored hashed, so+ # an operator who can't read it out of that message could never hand it to a partner.+ assert app.client_secret != secret_before+ plaintext = message.rsplit(": ", 1)[1]+ assert check_password(plaintext, app.client_secret)@freeze_time("2026-01-01 00:00:00")def test_revoke_all_sessions_action_force_invalidates_tokens(self):diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.pyindex 7e1b87ee0438..4bc1730d5a04 100644--- a/posthog/api/oauth/cimd.py+++ b/posthog/api/oauth/cimd.py@@ -11,7 +11,7 @@ import reimport jsonimport timeimport hashlib-from typing import TypedDict+from typing import TypedDict, castfrom urllib.parse import urlparsefrom django.core.cache import cache@@ -31,12 +31,14 @@ from posthog.models.oauth import (CIMDBlocklistEntry,CIMDVerificationToken,OAuthApplication,+ TokenEndpointAuthMethod,find_cimd_verification_token,)from posthog.ph_client import ph_scoped_capturefrom posthog.rate_limit import IPThrottlefrom posthog.scopes import filter_to_unprivileged_scopes-from posthog.security.url_validation import is_url_allowed+from posthog.security.pinned_requests import PinnedIPAdapter, select_pinned_ip+from posthog.security.url_validation import is_url_allowed, validate_url_and_pin_ipsfrom .client_name import sanitize_client_name, validate_client_name@@ -51,8 +53,13 @@ CIMD_CACHE_DEFAULT_TTL = 3600 # 1 hourCIMD_CACHE_MIN_TTL = 300 # 5 minutesCIMD_CACHE_MAX_TTL = 86400 # 24 hours-# Forbidden token_endpoint_auth_method values for CIMD clients (they have no client_secret)-CIMD_FORBIDDEN_AUTH_METHODS = frozenset({"client_secret_post", "client_secret_basic", "client_secret_jwt"})+# What a CIMD client may register as: public, or confidential via an asymmetric key it+# publishes. Every secret-based method is excluded by omission, because CIMD has no+# registration ceremony in which a shared secret could be delivered. An allowlist rather than+# a denylist so a method added to RFC 7591 later is refused until it is deliberately reviewed.+CIMD_SUPPORTED_AUTH_METHODS = frozenset(+ {TokenEndpointAuthMethod.NONE.value, TokenEndpointAuthMethod.PRIVATE_KEY_JWT.value}+)class CIMDFetchError(Exception):@@ -110,6 +117,7 @@ CIMDMetadataDocument = TypedDict("grant_types": list[str],"response_types": list[str],"token_endpoint_auth_method": str,+ "jwks_uri": str,# Legacy top-level token — still read for backwards compatibility."posthog_verification_token": str,# Preferred namespace — takes precedence over the legacy top-level key.@@ -119,30 +127,32 @@ CIMDMetadataDocument = TypedDict()-def validate_cimd_url(url: str | None, *, perform_dns_check: bool = False) -> tuple[bool, str | None]:- """- Validate a CIMD URL for format and optionally SSRF safety.+def validate_fetchable_https_url(+ url: str | None, *, perform_dns_check: bool = False, what: str = "URL"+) -> tuple[bool, str | None]:+ """Validate that a client-controlled URL is safe for us to dereference.- Returns (True, None) if valid, or (False, error_message).+ Returns (True, None) if valid, or (False, error_message). ``what`` names the URL in those+ messages, since they reach the client that published it.Without perform_dns_check this is a cheap string-only check.With perform_dns_check=True it also resolves DNS and blocks private IPs.++ These are safety rules only, so they apply to any partner-published document. The+ stricter shape rules that make a URL usable as a CIMD ``client_id`` live in+ :func:`validate_cimd_url`."""if not url or not url.startswith("https://"):- return False, "CIMD client_id must use HTTPS"+ return False, f"{what} must use HTTPS"try:parsed = urlparse(url)except Exception:return False, "Invalid URL"- if not parsed.path or parsed.path == "/":- return False, "CIMD client_id must include a path component"if parsed.fragment:- return False, "CIMD client_id must not contain a fragment"- if parsed.query:- return False, "CIMD client_id must not contain query parameters"+ return False, f"{what} must not contain a fragment"if parsed.username or parsed.password:- return False, "CIMD client_id must not contain userinfo"+ return False, f"{what} must not contain userinfo"if perform_dns_check:allowed, reason = is_url_allowed(url)@@ -152,6 +162,27 @@ def validate_cimd_url(url: str | None, *, perform_dns_check: bool = False) -> tureturn True, None+def validate_cimd_url(url: str | None, *, perform_dns_check: bool = False) -> tuple[bool, str | None]:+ """+ Validate a CIMD URL for format and optionally SSRF safety.++ Adds the identity requirements a CIMD ``client_id`` carries on top of the safety checks:+ the URL is the client's stable identifier, so it must name a document (a path) and must+ not vary by query string.+ """+ safe, error = validate_fetchable_https_url(url, perform_dns_check=perform_dns_check, what="CIMD client_id")+ if not safe:+ return False, error++ parsed = urlparse(url or "")+ if not parsed.path or parsed.path == "/":+ return False, "CIMD client_id must include a path component"+ if parsed.query:+ return False, "CIMD client_id must not contain query parameters"++ return True, None++def is_cimd_client_id(client_id: str | None) -> bool:"""Cheap format check: is this a valid CIMD URL shape?"""valid, _ = validate_cimd_url(client_id)@@ -217,45 +248,85 @@ def _parse_cache_ttl(response: requests.Response) -> int:return CIMD_CACHE_DEFAULT_TTL-def fetch_cimd_metadata(url: str) -> tuple[CIMDMetadataDocument, int]:+def fetch_client_json_document(+ url: str,+ *,+ what: str,+ max_size: int = CIMD_MAX_DOCUMENT_SIZE,+ user_agent: str = "PostHog-CIMD/1.0",+ require_identity_url_shape: bool = True,+) -> tuple[dict, requests.Response]:+ """Fetch a client-controlled JSON document over HTTPS with the full hardening set.++ Shared by the CIMD metadata document and the JWKS a private_key_jwt client publishes,+ so both partner-controlled URLs we dereference get identical protections: SSRF+ validation including a DNS check, no redirects, a byte cap enforced both from+ Content-Length and incrementally, and a total transfer deadline so a slow-drip server+ can't hold a worker open.++ ``require_identity_url_shape`` applies the extra CIMD ``client_id`` shape rules. A+ ``jwks_uri`` is an ordinary document reference rather than an identifier, so it passes+ False and stays free to carry a query string.++ Returns the parsed JSON object and the response, the latter so callers can read cache+ headers. Raises CIMDValidationError for an unsafe URL or oversized/invalid body,+ CIMDFetchError for network and HTTP failures."""- Fetch and validate a CIMD metadata document.-- Returns (metadata, cache_ttl_seconds).- Raises CIMDFetchError on network/HTTP errors, CIMDValidationError on invalid content.- """- valid, error = validate_cimd_url(url, perform_dns_check=True)+ if require_identity_url_shape:+ valid, error = validate_cimd_url(url)+ else:+ valid, error = validate_fetchable_https_url(url, what=what)if not valid:raise CIMDValidationError(error)+ # The SSRF check resolves the host, and requests would resolve it a second time when+ # it opens the connection. The client controls this URL and its DNS, so it can answer+ # the first lookup with a public address and the second with an internal one. Pinning+ # the connection to the addresses we actually validated closes that rebinding window;+ # PinnedIPAdapter keeps the original hostname for SNI and certificate verification.+ allowed, reason, pinned_ips = validate_url_and_pin_ips(url)+ if not allowed:+ raise CIMDValidationError(f"URL blocked: {reason}")++ adapter = PinnedIPAdapter()+ hostname = (urlparse(url).hostname or "").lower()+ chosen_ip = select_pinned_ip(pinned_ips)+ if chosen_ip is not None:+ adapter.pin(hostname, chosen_ip)++ # Validation above rejects any non-HTTPS URL, so only the https adapter is mounted.+ session = requests.Session()+ session.mount("https://", adapter)+try:- response = requests.get(+ response = session.get(url,timeout=CIMD_FETCH_TIMEOUT_SECONDS,headers={"Accept": "application/json",- "User-Agent": "PostHog-CIMD/1.0",+ "User-Agent": user_agent,},stream=True,allow_redirects=False,)except requests.RequestException as e:- raise CIMDFetchError(f"Failed to fetch metadata: {e}") from e+ session.close()+ raise CIMDFetchError(f"Failed to fetch {what}: {e}") from etry:if response.is_redirect or response.is_permanent_redirect:raise CIMDFetchError(- f"Metadata endpoint returned redirect (HTTP {response.status_code}), redirects are not allowed"+ f"{what} endpoint returned redirect (HTTP {response.status_code}), redirects are not allowed")if response.status_code != 200:- raise CIMDFetchError(f"Metadata endpoint returned HTTP {response.status_code}")+ raise CIMDFetchError(f"{what} endpoint returned HTTP {response.status_code}")# Early reject if Content-Length exceeds limitcontent_length = response.headers.get("Content-Length")if content_length:try:- if int(content_length) > CIMD_MAX_DOCUMENT_SIZE:- raise CIMDValidationError(f"Metadata document exceeds {CIMD_MAX_DOCUMENT_SIZE} byte limit")+ if int(content_length) > max_size:+ raise CIMDValidationError(f"{what} exceeds {max_size} byte limit")except ValueError:pass # Non-numeric Content-Length; fall through to incremental size check@@ -268,22 +339,37 @@ def fetch_cimd_metadata(url: str) -> tuple[CIMDMetadataDocument, int]:bytes_read = 0for chunk in response.iter_content(chunk_size=4096):bytes_read += len(chunk)- if bytes_read > CIMD_MAX_DOCUMENT_SIZE:- raise CIMDValidationError(f"Metadata document exceeds {CIMD_MAX_DOCUMENT_SIZE} byte limit")+ if bytes_read > max_size:+ raise CIMDValidationError(f"{what} exceeds {max_size} byte limit")chunks.append(chunk)if time.monotonic() > deadline:- raise CIMDFetchError("Metadata fetch exceeded total time limit")+ raise CIMDFetchError(f"{what} fetch exceeded total time limit")body = b"".join(chunks)finally:response.close()+ session.close()try:- metadata: CIMDMetadataDocument = json.loads(body)+ parsed = json.loads(body)except Exception as e:- raise CIMDValidationError(f"Invalid JSON in metadata document: {e}") from e+ raise CIMDValidationError(f"Invalid JSON in {what}: {e}") from e- if not isinstance(metadata, dict):- raise CIMDValidationError("Metadata document must be a JSON object")+ if not isinstance(parsed, dict):+ raise CIMDValidationError(f"{what} must be a JSON object")+ return parsed, response+++def fetch_cimd_metadata(url: str) -> tuple[CIMDMetadataDocument, int]:+ """+ Fetch and validate a CIMD metadata document.++ Returns (metadata, cache_ttl_seconds).+ Raises CIMDFetchError on network/HTTP errors, CIMDValidationError on invalid content.+ """+ parsed, response = fetch_client_json_document(url, what="Metadata document")+ # The fetcher guarantees a JSON object; whether its keys match the TypedDict is what the+ # validation below establishes.+ metadata = cast(CIMDMetadataDocument, parsed)# client_id MUST match the URL (simple string comparison per spec)if metadata.get("client_id") != url:@@ -303,11 +389,31 @@ def fetch_cimd_metadata(url: str) -> tuple[CIMDMetadataDocument, int]:if re.search(r"\s", uri):raise CIMDValidationError("redirect_uri must not contain whitespace")- # CIMD clients cannot use secret-based auth methods+ # private_key_jwt is the only way for a CIMD client to be confidential: the key is+ # asymmetric, and its public half travels in a document served from the client_id URL+ # itself, so nothing secret has to be delivered out of band.auth_method = metadata.get("token_endpoint_auth_method", "none")- if auth_method in CIMD_FORBIDDEN_AUTH_METHODS:+ if auth_method not in CIMD_SUPPORTED_AUTH_METHODS:raise CIMDValidationError(f"CIMD clients cannot use token_endpoint_auth_method '{auth_method}'")+ jwks_uri = metadata.get("jwks_uri")+ if auth_method == TokenEndpointAuthMethod.PRIVATE_KEY_JWT.value:+ # Without a key source the client could never be authenticated, so accepting the+ # registration would produce a confidential client that fails every request.+ if not jwks_uri or not isinstance(jwks_uri, str):+ raise CIMDValidationError("token_endpoint_auth_method 'private_key_jwt' requires a jwks_uri")+ if not jwks_uri.startswith("https://"):+ raise CIMDValidationError("jwks_uri must be an https URL")+ # A second client-controlled URL we will dereference, so it gets the same SSRF+ # screening as the metadata document itself.+ jwks_allowed, jwks_error = validate_cimd_url(jwks_uri, perform_dns_check=True)+ if not jwks_allowed:+ raise CIMDValidationError(f"jwks_uri is not allowed: {jwks_error}")+ elif jwks_uri is not None:+ # Ignore a key source the client isn't going to authenticate with, rather than+ # storing a URL we would never fetch.+ metadata.pop("jwks_uri", None)+# Validate logo_uri if present: must be HTTPS and pass SSRF checkslogo_uri = metadata.get("logo_uri")if logo_uri:@@ -388,6 +494,22 @@ def _resolve_optional_scopes(metadata: CIMDMetadataDocument) -> list[str] | Nonereturn filter_to_unprivileged_scopes(raw_optional)+def _resolve_client_authentication(metadata: CIMDMetadataDocument) -> tuple[str, str | None]:+ """Map a validated CIMD document's declared auth method onto ``(client_type, jwks_uri)``.++ A client advertising private_key_jwt is confidential in the RFC 6749 sense even though it+ holds no secret, because it can authenticate; everything else is public and relies on PKCE.+ Those two stored fields are what OAuthApplication.token_endpoint_auth_method reads back.++ This is what lets a client upgrade in place: it edits its own metadata document, and the+ next refresh promotes it without the client_id changing or an operator being involved.+ """+ auth_method = metadata.get("token_endpoint_auth_method", TokenEndpointAuthMethod.NONE.value)+ if auth_method == TokenEndpointAuthMethod.PRIVATE_KEY_JWT.value:+ return AbstractApplication.CLIENT_CONFIDENTIAL, metadata.get("jwks_uri")+ return AbstractApplication.CLIENT_PUBLIC, None++def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthApplication:"""Create a new OAuthApplication from CIMD metadata."""client_name = metadata.get("client_name", "CIMD Client")@@ -404,10 +526,13 @@ def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthAresolved_scopes = _resolve_scopes(metadata)resolved_optional_scopes = _resolve_optional_scopes(metadata)+ client_type, jwks_uri = _resolve_client_authentication(metadata)+app = OAuthApplication(name=client_name,redirect_uris=redirect_uris,- client_type=AbstractApplication.CLIENT_PUBLIC,+ client_type=client_type,+ jwks_uri=jwks_uri,client_secret="",authorization_grant_type=AbstractApplication.GRANT_AUTHORIZATION_CODE,algorithm="RS256",@@ -459,11 +584,23 @@ def _update_cimd_application(app: OAuthApplication, metadata: CIMDMetadataDocumeapp.logo_uri = new_uri if (new_uri := metadata.get("logo_uri")) is not None else app.logo_uriapp.cimd_metadata_last_fetched = timezone.now()+ # Re-derived on every refresh, in both directions: a client that starts publishing a+ # jwks_uri is promoted to confidential here, and one that stops is demoted back to public+ # rather than being left as a confidential client whose key source has gone away.+ app.client_type, app.jwks_uri = _resolve_client_authentication(metadata)+# Re-evaluate verification on every refresh so a rotated/removed token# unlinks the app on the next fetch.verification = _resolve_verification_token(metadata)new_org = verification.organization if verification else None- update_fields = ["name", "redirect_uris", "logo_uri", "cimd_metadata_last_fetched"]+ update_fields = [+ "name",+ "redirect_uris",+ "logo_uri",+ "cimd_metadata_last_fetched",+ "client_type",+ "jwks_uri",+ ]resolved_scopes = _resolve_scopes(metadata)if resolved_scopes is not None:@@ -620,41 +757,6 @@ def refresh_cimd_metadata_task(url: str) -> None:capture_exception(e)-@shared_task(ignore_result=True, time_limit=30)-def register_cimd_provisioning_application_task(url: str) -> None:- """Celery task: fetch CIMD metadata, create the app, and backfill provisioning defaults."""- try:- with ph_scoped_capture() as capture_ph_event:- app = fetch_and_upsert_cimd_application(url, capture_ph_event=capture_ph_event)- if app is None:- return- if not app.is_provisioning_partner:- apply_provisioning_defaults(app)- capture_ph_event(- distinct_id=url,- event="cimd_provisioning_partner_registered",- properties={- "cimd_url": url,- "client_name": app.name,- "app_id": str(app.pk),- "account_requests_rate_limit": app.provisioning_rate_limit_account_requests,- "is_verified": app.organization_id is not None,- "organization_id": str(app.organization_id) if app.organization_id else None,- },- )- except CIMDValidationError as e:- # Expected rejection of a non-compliant partner document — log for observability, don't surface as an error.- logger.warning("cimd_background_registration_failed", url=url, error=str(e))- except CIMDFetchError as e:- logger.warning("cimd_background_registration_failed", url=url, error=str(e))- capture_exception(e)---def is_cimd_registration_in_progress(url: str) -> bool:- """Check if a fetch/registration is currently in progress for this CIMD URL."""- return bool(cache.get(_fetch_lock_key(url)))--def get_or_create_cimd_application(url: str) -> OAuthApplication:"""Resolve a CIMD URL to an OAuthApplication.@@ -706,18 +808,20 @@ def get_application_by_client_id(client_id: str) -> OAuthApplication:return OAuthApplication.objects.get(client_id=client_id)-# Defaults applied when a CIMD app is first used for provisioning. A self-serve-# partner can hit /account_requests immediately without manual admin setup; the-# app is opted into provisioning at the same trust level as other PKCE partners.-# The account-request rate limit is set to a conservative floor so a single-# self-serve partner cannot burn through bulk user-onboarding calls — admin can-# raise it per-partner once a partner demonstrates legitimate volume. Verified-# partners (those who presented a valid `posthog_verification_token`) get a-# higher default since abuse is traceable to a real PostHog organization.+# Defaults applied when a CIMD app is opted into provisioning at client_registration. A+# self-serve partner gets there without manual admin setup, at the same trust level as other+# PKCE partners. The account-request rate limit is set to a conservative floor so a single+# self-serve partner cannot burn through bulk user-onboarding calls - admin can raise it+# per-partner once a partner demonstrates legitimate volume. Verified partners (those who+# presented a valid `posthog_verification_token`) get a higher default since abuse is+# traceable to a real PostHog organization.CIMD_PROVISIONING_ACCOUNT_REQUESTS_DEFAULT_RATE_LIMIT = 10 # per hour, anonymous CIMDCIMD_PROVISIONING_ACCOUNT_REQUESTS_VERIFIED_RATE_LIMIT = 100 # per hour, verified CIMD-CIMD_PROVISIONING_DEFAULTS = {- "provisioning_auth_method": "pkce",+CIMD_PROVISIONING_DEFAULTS: dict[str, bool | int | str] = {+ # Nothing here touches client authentication: that is derived from the client's own+ # metadata document by _resolve_client_authentication, so a CIMD partner is public or+ # private_key_jwt according to what it publishes.+ "is_provisioning_partner": True,"provisioning_active": True,"provisioning_can_create_accounts": True,"provisioning_can_provision_resources": True,@@ -747,36 +851,21 @@ def apply_provisioning_defaults(app: OAuthApplication) -> OAuthApplication:rather than re-enabling a partner an admin has explicitly disabled."""if app.provisioning_disabled:return app+ became_partner = not app.is_provisioning_partnerdefaults = _cimd_provisioning_defaults_for(app)for field, value in defaults.items():setattr(app, field, value)app.save(update_fields=list(defaults.keys()))- return app---def get_or_create_cimd_provisioning_application(url: str) -> OAuthApplication | None:- """- Resolve a CIMD URL to an OAuthApplication configured as a provisioning partner.-- Creates the CIMD app via the normal fetch+upsert path if it doesn't exist,- then backfills provisioning defaults if they haven't been set. Existing apps- that already have provisioning fields configured (e.g. via admin) are left alone.-- Returns None if the URL is blocklisted.- Raises CIMDFetchError / CIMDValidationError on fetch failures.- """- if is_cimd_url_blocked(url):- logger.warning("cimd_blocked_url", url=url)- return None- app = get_or_create_cimd_application(url)- if not app.is_provisioning_partner:- apply_provisioning_defaults(app)+ # A partner appearing without an admin creating it is the event worth watching for abuse,+ # so it fires on the transition only - re-running the defaults over an existing partner is+ # not a new partner.+ if became_partner:posthoganalytics.capture(- distinct_id=url,+ distinct_id=app.cimd_metadata_url or str(app.pk),event="cimd_provisioning_partner_registered",properties={- "cimd_url": url,+ "cimd_url": app.cimd_metadata_url,"client_name": app.name,"app_id": str(app.pk),"account_requests_rate_limit": app.provisioning_rate_limit_account_requests,diff --git a/posthog/api/oauth/client_assertion.py b/posthog/api/oauth/client_assertion.pynew file mode 100644index 000000000000..80ce18249882--- /dev/null+++ b/posthog/api/oauth/client_assertion.py@@ -0,0 +1,264 @@+"""``private_key_jwt`` client authentication (RFC 7521 / RFC 7523 section 2.2).++A client authenticates by signing a short-lived JWT with its private key instead of+presenting a shared secret. We verify the signature against the public keys the client+publishes at its ``jwks_uri``, so no credential ever has to be transmitted to us or stored+by us, and the client can rotate keys on its own by publishing a new set.++This pairs particularly well with CIMD clients, whose ``client_id`` is itself an HTTPS URL:+control of that URL is what establishes the client's identity, so a key served from it is+authentic without any registration ceremony.+"""++from __future__ import annotations++import time+from typing import Any++from django.conf import settings+from django.core.cache import cache++import jwt+import structlog+from jwt import PyJWK, PyJWKSet++from posthog.api.oauth.cimd import CIMDFetchError, CIMDValidationError, fetch_client_json_document+from posthog.models.oauth import OAuthApplication++logger = structlog.get_logger(__name__)++CLIENT_ASSERTION_TYPE_JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"++# Asymmetric signatures only. Allowing an HMAC family here would be a key-confusion hole:+# the "public" key we fetch is attacker-publishable, so an HS256 assertion signed with that+# same value as the shared secret would verify. "none" is excluded for the same reason.+ALLOWED_ASSERTION_ALGORITHMS = ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512"]++# An assertion is a single-use credential presented immediately, so it needs no real+# lifetime. Capping it bounds how long a captured assertion is replayable if the jti cache+# is ever lost, and bounds how far ahead a client may pre-mint.+MAX_ASSERTION_LIFETIME_SECONDS = 300+ASSERTION_CLOCK_SKEW_SECONDS = 30++JWKS_CACHE_PREFIX = "oauth_client_jwks:"+JWKS_CACHE_TTL_SECONDS = 3600+# Short negative TTL so a client that has just fixed a broken JWKS isn't locked out for an+# hour, while a persistently broken one still can't trigger a fetch per request.+JWKS_NEGATIVE_CACHE_TTL_SECONDS = 60+JWKS_MAX_DOCUMENT_SIZE = 16 * 1024+JWKS_MAX_KEYS = 10++JTI_CACHE_PREFIX = "oauth_client_assertion_jti:"+++class ClientAssertionError(Exception):+ """The assertion is missing, malformed, or does not verify. The message is wire-safe."""+++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.+ """+ 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 ""+++def extract_client_assertion(request: Any) -> tuple[str, str] | None:+ """Return the ``(client_assertion, client_id)`` a request presents, or None.++ ``client_id`` is optional on the wire for this method (RFC 7521 section 4.2 allows the+ assertion to carry the identity), so it falls back to the assertion's own ``sub``.+ """+ assertion = _request_field(request, "client_assertion")+ assertion_type = _request_field(request, "client_assertion_type")+ if not assertion or assertion_type != CLIENT_ASSERTION_TYPE_JWT_BEARER:+ return None++ client_id = _request_field(request, "client_id") or _unverified_subject(assertion)+ if not client_id:+ return None++ return assertion, client_id+++def _unverified_subject(assertion: str) -> str:+ """Read ``sub`` without verifying, only to locate which client to verify against.++ Never trusted for authentication: the claim is re-checked against the resolved+ application's client_id after the signature verifies.+ """+ try:+ # nosemgrep: python.jwt.security.unverified-jwt-decode.unverified-jwt-decode+ claims = jwt.decode(assertion, options={"verify_signature": False})+ except jwt.PyJWTError:+ return ""+ subject = claims.get("sub") or ""+ return subject if isinstance(subject, str) else ""+++def expected_assertion_audiences(*token_endpoint_paths: str) -> list[str]:+ """Audiences we accept, kept to an explicit set so an assertion minted for another+ service can't be replayed against us.++ RFC 7523 section 3 lets a client address either the issuer or the endpoint it is calling,+ so both are accepted. Callers pass the paths their own endpoint answers on.+ """+ site_url = settings.SITE_URL.rstrip("/")+ return [site_url, *(f"{site_url}{path}" for path in token_endpoint_paths)]+++AGENTIC_TOKEN_ENDPOINT_PATH = "/api/agentic/oauth/token"+++def describe_jwks(jwks_uri: str) -> list[str]:+ """Fetch and validate a key set, returning its key ids, for diagnostics.++ Always goes to the network so the answer reflects what the client is serving right now+ rather than what it served up to an hour ago. Raises ClientAssertionError with the reason+ the document was rejected, which is the whole point of calling this.+ """+ key_set = load_jwks(jwks_uri, force_refresh=True)+ return [key.key_id or "(no kid)" for key in key_set.keys]+++def load_jwks(jwks_uri: str, *, force_refresh: bool = False) -> PyJWKSet:+ """Return the client's key set, cached, so a token exchange doesn't fetch on every call.++ Failures are cached too (briefly), so a client with a broken or hostile jwks_uri can't+ turn each of its requests into an outbound fetch.+ """+ cache_key = f"{JWKS_CACHE_PREFIX}{jwks_uri}"+ cached = None if force_refresh else cache.get(cache_key)+ if cached is not None:+ if cached == "error":+ raise ClientAssertionError("Client keys could not be retrieved")+ return PyJWKSet.from_dict(cached)++ try:+ parsed = _fetch_jwks_document(jwks_uri)+ except ClientAssertionError:+ cache.set(cache_key, "error", timeout=JWKS_NEGATIVE_CACHE_TTL_SECONDS)+ raise++ cache.set(cache_key, parsed, timeout=JWKS_CACHE_TTL_SECONDS)+ return PyJWKSet.from_dict(parsed)+++def _fetch_jwks_document(jwks_uri: str) -> dict:+ """Fetch and validate the JWKS, raising ClientAssertionError on any rejection so the+ caller has a single place to record the negative cache entry."""+ try:+ parsed, _ = fetch_client_json_document(+ jwks_uri,+ what="JWKS",+ max_size=JWKS_MAX_DOCUMENT_SIZE,+ user_agent="PostHog-OAuth-JWKS/1.0",+ require_identity_url_shape=False,+ )+ except (CIMDFetchError, CIMDValidationError) as e:+ logger.warning("client_assertion_jwks_fetch_failed", jwks_uri=jwks_uri, error=str(e))+ raise ClientAssertionError("Client keys could not be retrieved") from e++ # Capping the key count keeps a hostile JWKS from making each verification walk a huge+ # set. Everything else about the document's shape is PyJWKSet's own validation.+ keys = parsed.get("keys")+ if isinstance(keys, list) and len(keys) > JWKS_MAX_KEYS:+ raise ClientAssertionError(f"JWKS must not contain more than {JWKS_MAX_KEYS} keys")++ try:+ PyJWKSet.from_dict(parsed)+ except Exception as e:+ raise ClientAssertionError(f"JWKS could not be parsed: {e}") from e++ return parsed+++def _select_key(key_set: PyJWKSet, assertion: str) -> PyJWK:+ """Pick the key the assertion's header names, or the only key when it names none.++ Requiring a `kid` once the client publishes more than one key keeps verification from+ degrading into "try every key", which would let a rotated-out key keep working.+ """+ try:+ header = jwt.get_unverified_header(assertion)+ except jwt.PyJWTError as e:+ raise ClientAssertionError("Client assertion header is malformed") from e++ kid = header.get("kid")+ if kid:+ try:+ return key_set[kid]+ except KeyError as e:+ raise ClientAssertionError("Client assertion is signed by an unknown key") from e++ if len(key_set.keys) == 1:+ return key_set.keys[0]+ raise ClientAssertionError("Client assertion must carry a kid when the JWKS holds several keys")+++def _consume_jti(client_id: str, jti: str, expires_at: int) -> None:+ """Reject a replayed assertion. Scoped per client so one client cannot burn another's+ identifiers. Held until the assertion would have expired anyway, so the cache never has+ to outlive the window in which a replay would be accepted.+ """+ ttl = max(int(expires_at - time.time()) + ASSERTION_CLOCK_SKEW_SECONDS, 1)+ if not cache.add(f"{JTI_CACHE_PREFIX}{client_id}:{jti}", True, timeout=ttl):+ raise ClientAssertionError("Client assertion has already been used")+++def verify_client_assertion(app: OAuthApplication, assertion: str, *, audiences: list[str] | None = None) -> None:+ """Verify a ``private_key_jwt`` assertion presented by ``app``, or raise.++ Checks, in order: the app is registered for this method and has a key source; the+ signature verifies against that key under an asymmetric algorithm; the audience is us;+ ``iss`` and ``sub`` both identify this client (RFC 7523 section 3); the lifetime is+ bounded; and the ``jti`` has not been seen before.+ """+ if not app.uses_private_key_jwt_auth or not app.jwks_uri:+ raise ClientAssertionError("This client is not registered for private_key_jwt authentication")++ key = _select_key(load_jwks(app.jwks_uri), assertion)+ # A CIMD client names itself by its metadata URL, not by the opaque client_id column, so+ # that is the identity its assertion carries.+ client_identifier = app.effective_client_id++ try:+ claims = jwt.decode(+ assertion,+ key=key,+ algorithms=ALLOWED_ASSERTION_ALGORITHMS,+ audience=audiences if audiences is not None else expected_assertion_audiences(AGENTIC_TOKEN_ENDPOINT_PATH),+ issuer=client_identifier,+ leeway=ASSERTION_CLOCK_SKEW_SECONDS,+ options={+ # iat is required so the lifetime cap below always has a lower bound to+ # measure against. Without it a client could set exp arbitrarily far out.+ "require": ["exp", "iat", "iss", "sub", "aud", "jti"],+ "verify_aud": True,+ "verify_exp": True,+ },+ )+ except jwt.PyJWTError as e:+ # The reason is logged rather than returned: which check failed is useful to us and+ # not something an unauthenticated caller needs.+ logger.warning("client_assertion_rejected", app_id=str(app.id), error=str(e), error_type=type(e).__name__)+ raise ClientAssertionError("Client assertion is invalid") from e++ # RFC 7523 section 3: for client authentication both iss and sub are the client_id.+ # `issuer` above covers iss; sub is checked here so an assertion minted to act as one+ # client cannot authenticate another.+ if claims.get("sub") != client_identifier:+ raise ClientAssertionError("Client assertion subject does not match the client")++ expires_at = claims["exp"]+ if expires_at - claims["iat"] > MAX_ASSERTION_LIFETIME_SECONDS:+ raise ClientAssertionError(f"Client assertion lifetime exceeds {MAX_ASSERTION_LIFETIME_SECONDS} seconds")++ _consume_jti(client_identifier, str(claims["jti"]), int(expires_at))diff --git a/posthog/api/oauth/client_auth.py b/posthog/api/oauth/client_auth.pynew file mode 100644index 000000000000..ac27a39127ff--- /dev/null+++ b/posthog/api/oauth/client_auth.py@@ -0,0 +1,80 @@+"""Client authentication primitives shared by every OAuth token consumer.++Both the oauthlib-backed ``/oauth/token`` endpoint and the hand-rolled agentic token+endpoint have to answer the same question -- has this client proven it is who it claims to+be -- so the comparison itself lives here rather than being written once per endpoint.+"""++from __future__ import annotations++import base64+import binascii+from typing import Any+from urllib.parse import unquote_plus++from django.contrib.auth.hashers import check_password, identify_hasher+from django.utils.crypto import constant_time_compare++BASIC_PREFIX = "Basic "+++def verify_client_secret(provided_secret: str, stored_secret: str) -> bool:+ """Check a presented client secret against the stored one.++ Mirrors oauth2_provider's ``OAuth2Validator._check_secret`` so hashed and legacy+ unhashed secrets both verify, but fails closed when either side is blank.++ The blank guard is what the library is missing, and it is load-bearing. An application+ created with ``client_secret=""`` does not store an empty string: ``ClientSecretField``+ runs ``make_password("")`` on save, so the column holds a valid hash *of* the empty+ string. ``check_password("", <hash of "">)`` is ``True``, so without this guard a client+ that presents no secret at all authenticates as any such application. Applications+ registered for ``private_key_jwt`` are exactly that shape, since their proof is a signed+ assertion and they never receive a secret.+ """+ if not provided_secret or not stored_secret:+ return False++ try:+ identify_hasher(stored_secret)+ except ValueError:+ # Raised when the stored secret was never hashed.+ return constant_time_compare(provided_secret, stored_secret)+ return check_password(provided_secret, stored_secret)+++def client_credentials_from_basic_auth(request: Any) -> tuple[str, str] | None:+ auth_header = request.headers.get("authorization", "")+ if not auth_header.startswith(BASIC_PREFIX):+ return None++ try:+ decoded = base64.b64decode(auth_header[len(BASIC_PREFIX) :].strip()).decode("utf-8")+ except (binascii.Error, ValueError, UnicodeDecodeError):+ return None++ client_id, separator, client_secret = decoded.partition(":")+ if not separator or not client_id or not client_secret:+ return None++ # RFC 6749 section 2.3.1 requires both halves to be form-urlencoded before they are+ # base64'd, so a secret containing ":" survives the split above.+ return unquote_plus(client_id), unquote_plus(client_secret)+++def extract_client_credentials(request: Any) -> tuple[str, str] | None:+ """Return the ``(client_id, client_secret)`` pair the request presents, or None.++ Both RFC 6749 transports are accepted. Basic auth is read first because the GitHub+ grant listing endpoint is a GET, which has no body to carry the pair.+ """+ from_basic = client_credentials_from_basic_auth(request)+ if from_basic is not None:+ return from_basic++ client_id = request.data.get("client_id") or ""+ client_secret = request.data.get("client_secret") or ""+ if client_id and client_secret:+ return client_id, client_secret++ return Nonediff --git a/posthog/api/oauth/dcr.py b/posthog/api/oauth/dcr.pyindex ef5ba502515d..a4ac03dd3917 100644--- a/posthog/api/oauth/dcr.py+++ b/posthog/api/oauth/dcr.py@@ -26,7 +26,7 @@ from rest_framework.response import Responsefrom rest_framework.views import APIViewfrom posthog.exceptions_capture import capture_exception-from posthog.models.oauth import OAuthApplication+from posthog.models.oauth import OAuthApplication, TokenEndpointAuthMethodfrom posthog.rate_limit import IPThrottlefrom posthog.scopes import filter_to_unprivileged_scopes@@ -90,9 +90,9 @@ class DCRRequestSerializer(serializers.Serializer):help_text="OAuth response types the client will use",)token_endpoint_auth_method = serializers.ChoiceField(- choices=["none", "client_secret_post"],+ choices=[TokenEndpointAuthMethod.NONE.value, TokenEndpointAuthMethod.CLIENT_SECRET_POST.value],required=False,- default="none",+ default=TokenEndpointAuthMethod.NONE.value,help_text="How the client authenticates at the token endpoint: 'none' for public clients, 'client_secret_post' for confidential clients",)scope = serializers.CharField(@@ -130,7 +130,7 @@ class DynamicClientRegistrationView(APIView):now = timezone.now()client_name = sanitize_client_name(data["client_name"]) if data.get("client_name") else "MCP Client"- is_confidential = data.get("token_endpoint_auth_method") == "client_secret_post"+ is_confidential = data.get("token_endpoint_auth_method") == TokenEndpointAuthMethod.CLIENT_SECRET_POST.valueclient_type = AbstractApplication.CLIENT_CONFIDENTIAL if is_confidential else AbstractApplication.CLIENT_PUBLIC# Generate the secret before create() so we can return the plaintext@@ -217,7 +217,8 @@ class DynamicClientRegistrationView(APIView):},)- auth_method = data.get("token_endpoint_auth_method", "none")+ # Read back off the created app so the response can't disagree with what was stored.+ auth_method = app.token_endpoint_auth_method.value# Build response per RFC 7591 Section 3.2response_data: dict[str, Any] = {diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.pyindex 9211b51ff9b2..007d0529523a 100644--- a/posthog/api/oauth/test_cimd.py+++ b/posthog/api/oauth/test_cimd.py@@ -1,6 +1,7 @@import jsonimport base64import hashlib+from ipaddress import ip_addressfrom typing import castfrom urllib.parse import urlencode@@ -24,18 +25,18 @@ from posthog.api.oauth.cimd import (CIMDValidationError,_fetch_lock_key,_resolve_scopes,+ apply_provisioning_defaults,fetch_and_upsert_cimd_application,fetch_cimd_metadata,get_application_by_client_id,get_or_create_cimd_application,- get_or_create_cimd_provisioning_application,is_cimd_client_id,refresh_cimd_metadata_task,- register_cimd_provisioning_application_task,validate_cimd_url,+ validate_fetchable_https_url,)from posthog.api.oauth.client_name import sanitize_client_name-from posthog.models.oauth import OAuthApplication, create_cimd_verification_token+from posthog.models.oauth import OAuthApplication, TokenEndpointAuthMethod, create_cimd_verification_tokenfrom posthog.scopes import OAUTH_SCOPES_HIDDEN, PRIVILEGED_SCOPESVALID_CIMD_URL = "https://app.example.com/.well-known/oauth-client-metadata.json"@@ -56,6 +57,37 @@ def _make_metadata(url: str = VALID_CIMD_URL, com_posthog: dict | None = None, *return metadata+CIMD_JWKS_URI = "https://app.example.com/.well-known/jwks.json"+++def _metadata_for_auth(with_jwks: bool) -> dict:+ if not with_jwks:+ return _make_metadata()+ return _make_metadata(token_endpoint_auth_method="private_key_jwt", jwks_uri=CIMD_JWKS_URI)+++def _captured_events(mock_capture) -> list:+ return [call.kwargs.get("event") for call in mock_capture.call_args_list]+++def _register_provisioning_partner(url: str = VALID_CIMD_URL) -> OAuthApplication:+ """Register a CIMD app and opt it into provisioning, the way client_registration does."""+ app = fetch_and_upsert_cimd_application(url)+ assert app is not None+ return apply_provisioning_defaults(app)+++def _document_fetches(mock_get, url: str = VALID_CIMD_URL) -> list:+ """Calls the mocked session made for ``url``.++ The fetch runs on a session with a pinned-IP adapter mounted, so the patch target is+ ``requests.Session.get``, which is process-wide. Unrelated traffic during a request+ (the ClickHouse health ping) lands on the same mock, so counting raw calls would not+ measure the document fetch under test.+ """+ return [call for call in mock_get.call_args_list if call.args and call.args[0] == url]++def _mock_response(metadata: dict | None = None, status_code: int = 200, headers: dict | None = None):"""Create a mock requests.Response."""@@ -139,9 +171,9 @@ def test_validate_cimd_url_ssrf_blocked(mock_return, url, expected_error):assert error == expected_error-@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))+@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})class TestFetchCimdMetadata(APIBaseTest):- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_success(self, mock_get, _url_mock):metadata = _make_metadata()mock_get.return_value = _mock_response(metadata, headers={"Cache-Control": "max-age=3600"})@@ -151,7 +183,7 @@ class TestFetchCimdMetadata(APIBaseTest):self.assertEqual(result["client_name"], "Test MCP Client")self.assertEqual(ttl, 3600)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_client_id_mismatch(self, mock_get, _url_mock):metadata = _make_metadata(client_id="https://wrong.example.com/other.json")mock_get.return_value = _mock_response(metadata)@@ -159,7 +191,7 @@ class TestFetchCimdMetadata(APIBaseTest):fetch_cimd_metadata(VALID_CIMD_URL)self.assertIn("does not match", str(ctx.exception))- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_too_large(self, mock_get, _url_mock):resp = _mock_response(_make_metadata())resp.iter_content = MagicMock(return_value=iter([b"x" * 6000]))@@ -169,7 +201,7 @@ class TestFetchCimdMetadata(APIBaseTest):fetch_cimd_metadata(VALID_CIMD_URL)self.assertIn("limit", str(ctx.exception))- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_invalid_json(self, mock_get, _url_mock):resp = _mock_response()resp.status_code = 200@@ -179,7 +211,7 @@ class TestFetchCimdMetadata(APIBaseTest):with self.assertRaises(CIMDValidationError):fetch_cimd_metadata(VALID_CIMD_URL)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_missing_redirect_uris(self, mock_get, _url_mock):metadata = _make_metadata()del metadata["redirect_uris"]@@ -188,7 +220,7 @@ class TestFetchCimdMetadata(APIBaseTest):fetch_cimd_metadata(VALID_CIMD_URL)self.assertIn("redirect_uris", str(ctx.exception))- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_redirect_uri_with_whitespace_rejected(self, mock_get, _url_mock):metadata = _make_metadata(redirect_uris=["https://legit.com/callback https://attacker.com/steal"])mock_get.return_value = _mock_response(metadata)@@ -196,42 +228,73 @@ class TestFetchCimdMetadata(APIBaseTest):fetch_cimd_metadata(VALID_CIMD_URL)self.assertEqual(str(ctx.exception), "redirect_uri must not contain whitespace")- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_non_200_response(self, mock_get, _url_mock):mock_get.return_value = _mock_response(status_code=404)with self.assertRaises(CIMDFetchError) as ctx:fetch_cimd_metadata(VALID_CIMD_URL)self.assertIn("404", str(ctx.exception))- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_timeout(self, mock_get, _url_mock):mock_get.side_effect = requests.Timeout("Connection timed out")with self.assertRaises(CIMDFetchError):fetch_cimd_metadata(VALID_CIMD_URL)- @patch("posthog.api.oauth.cimd.requests.get")- def test_forbidden_auth_method(self, mock_get, _url_mock):- metadata = _make_metadata(token_endpoint_auth_method="client_secret_post")- mock_get.return_value = _mock_response(metadata)+ @parameterized.expand([("client_secret_post",), ("client_secret_basic",), ("client_secret_jwt",), ("tls_auth",)])+ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_unsupported_auth_method(self, auth_method, mock_get, _url_mock):+ # Only "none" and "private_key_jwt" are supported: CIMD has no ceremony in which a+ # shared secret could be delivered, and anything unrecognized fails closed.+ mock_get.return_value = _mock_response(_make_metadata(token_endpoint_auth_method=auth_method))with self.assertRaises(CIMDValidationError) as ctx:fetch_cimd_metadata(VALID_CIMD_URL)- self.assertIn("client_secret_post", str(ctx.exception))+ self.assertIn(auth_method, str(ctx.exception))++ @parameterized.expand([("missing_jwks_uri", None), ("non_https_jwks_uri", "http://app.example.com/jwks.json")])+ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_private_key_jwt_requires_a_usable_jwks_uri(self, _name, jwks_uri, mock_get, _url_mock):+ metadata = _make_metadata(token_endpoint_auth_method="private_key_jwt")+ if jwks_uri is not None:+ metadata["jwks_uri"] = jwks_uri+ mock_get.return_value = _mock_response(metadata)+ with self.assertRaises(CIMDValidationError):+ fetch_cimd_metadata(VALID_CIMD_URL)- @patch("posthog.api.oauth.cimd.requests.get")+ @parameterized.expand(+ [+ # A jwks_uri names a document rather than identifying the client, so the CIMD+ # client_id shape rules must not apply to it. A versioned key set is legitimate.+ ("query_string", "https://app.example.com/jwks.json?v=2", True),+ ("bare_host", "https://app.example.com", True),+ ("plaintext_http", "http://app.example.com/jwks.json", False),+ ("fragment", "https://app.example.com/jwks.json#k", False),+ ]+ )+ def test_jwks_uri_is_not_held_to_cimd_client_id_shape_rules(self, _url_mock, _name, url, expected_valid):+ valid, _error = validate_fetchable_https_url(url)+ assert valid is expected_valid+ if not expected_valid:+ return+ # The same URL as a client_id is a different question: that one must be a stable+ # identifier, so a query string or a bare host is rejected there.+ assert validate_cimd_url(url)[0] is False++ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_cache_ttl_clamped_to_minimum(self, mock_get, _url_mock):metadata = _make_metadata()mock_get.return_value = _mock_response(metadata, headers={"Cache-Control": "max-age=10"})_, ttl = fetch_cimd_metadata(VALID_CIMD_URL)self.assertEqual(ttl, 300) # Clamped to 5 min minimum- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_cache_ttl_clamped_to_maximum(self, mock_get, _url_mock):metadata = _make_metadata()mock_get.return_value = _mock_response(metadata, headers={"Cache-Control": "max-age=999999"})_, ttl = fetch_cimd_metadata(VALID_CIMD_URL)self.assertEqual(ttl, 86400) # Clamped to 24h maximum- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_default_cache_ttl(self, mock_get, _url_mock):metadata = _make_metadata()mock_get.return_value = _mock_response(metadata, headers={})@@ -239,11 +302,11 @@ class TestFetchCimdMetadata(APIBaseTest):self.assertEqual(ttl, 3600) # Default 1 hour-@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))+@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})class TestFetchAndUpsertCimdApplication(APIBaseTest):"""Tests for fetch_and_upsert_cimd_application — the core fetch+create/update function."""- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_creates_new_application(self, mock_get, _url_mock):metadata = _make_metadata(logo_uri="https://example.com/logo.png")mock_get.return_value = _mock_response(metadata, headers={})@@ -262,7 +325,41 @@ class TestFetchAndUpsertCimdApplication(APIBaseTest):self.assertIsNone(app.organization)self.assertIsNone(app.user)- @patch("posthog.api.oauth.cimd.requests.get")+ @parameterized.expand(+ [+ # Publishing a key set is the upgrade path with no re-onboarding: the client edits+ # its own metadata document and the next refresh promotes it in place.+ ("promoted_when_a_jwks_uri_appears", False, True, TokenEndpointAuthMethod.PRIVATE_KEY_JWT),+ # A confidential client whose key source disappeared could never authenticate again,+ # so it must fall back to public rather than becoming permanently unusable.+ ("demoted_when_the_jwks_uri_disappears", True, False, TokenEndpointAuthMethod.NONE),+ ]+ )+ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_client_authentication_is_re_derived_on_every_refresh(+ self, _name, starts_with_jwks, ends_with_jwks, expected_method, mock_get, _url_mock+ ):+ mock_get.return_value = _mock_response(_metadata_for_auth(starts_with_jwks), headers={})+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)+ assert app is not None++ mock_get.return_value = _mock_response(_metadata_for_auth(ends_with_jwks), headers={})+ refreshed = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert refreshed is not None+ # Same row and same client_id: the transition needs no operator and no re-registration.+ self.assertEqual(refreshed.pk, app.pk)+ self.assertEqual(refreshed.client_id, app.client_id)+ self.assertIs(refreshed.token_endpoint_auth_method, expected_method)+ if ends_with_jwks:+ self.assertEqual(refreshed.jwks_uri, CIMD_JWKS_URI)+ # It holds no secret, but it can authenticate, so it is confidential per RFC 6749.+ self.assertEqual(refreshed.client_type, OAuthApplication.CLIENT_CONFIDENTIAL)+ else:+ self.assertIsNone(refreshed.jwks_uri)+ self.assertEqual(refreshed.client_type, OAuthApplication.CLIENT_PUBLIC)++ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_updates_existing_application(self, mock_get, _url_mock):metadata1 = _make_metadata(client_name="Original Name")mock_get.return_value = _mock_response(metadata1, headers={})@@ -278,18 +375,18 @@ class TestFetchAndUpsertCimdApplication(APIBaseTest):self.assertEqual(updated.name, "Updated Name")self.assertEqual(updated.logo_uri, "https://example.com/new-logo.png")- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_returns_none_when_lock_held(self, mock_get, _url_mock):# Simulate another caller holding the lockreal_cache.set(_fetch_lock_key(VALID_CIMD_URL), True, timeout=30)result = fetch_and_upsert_cimd_application(VALID_CIMD_URL)self.assertIsNone(result)- mock_get.assert_not_called()+ self.assertEqual(_document_fetches(mock_get), [])real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_blocked_name_uses_default(self, mock_get, _url_mock):metadata = _make_metadata(client_name="PostHog Official Client")mock_get.return_value = _mock_response(metadata, headers={})@@ -298,13 +395,24 @@ class TestFetchAndUpsertCimdApplication(APIBaseTest):assert app is not Noneself.assertEqual(app.name, "CIMD Client")- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_fetch_failure_propagates(self, mock_get, _url_mock):mock_get.side_effect = requests.ConnectionError("DNS resolution failed")with self.assertRaises(CIMDFetchError):fetch_and_upsert_cimd_application(VALID_CIMD_URL)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_blocked_url_prevents_fetch(self, mock_get, _url_mock):+ from posthog.api.oauth.cimd import block_cimd_url, unblock_cimd_url++ block_cimd_url(VALID_CIMD_URL)+ result = fetch_and_upsert_cimd_application(VALID_CIMD_URL)+ self.assertIsNone(result)+ self.assertEqual(_document_fetches(mock_get), [])++ unblock_cimd_url(VALID_CIMD_URL)++ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_releases_lock_on_failure(self, mock_get, _url_mock):mock_get.side_effect = requests.ConnectionError("DNS failed")with self.assertRaises(CIMDFetchError):@@ -314,11 +422,11 @@ class TestFetchAndUpsertCimdApplication(APIBaseTest):self.assertIsNone(real_cache.get(_fetch_lock_key(VALID_CIMD_URL)))-@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))+@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})class TestGetOrCreateCimdApplication(APIBaseTest):"""Tests for get_or_create_cimd_application — the orchestration layer."""- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_returns_existing_when_cache_fresh(self, mock_get, _url_mock):metadata = _make_metadata()mock_get.return_value = _mock_response(metadata, headers={})@@ -327,10 +435,10 @@ class TestGetOrCreateCimdApplication(APIBaseTest):app2 = get_or_create_cimd_application(VALID_CIMD_URL)self.assertEqual(app1.pk, app2.pk)- self.assertEqual(mock_get.call_count, 1)+ self.assertEqual(len(_document_fetches(mock_get)), 1)@patch("posthog.api.oauth.cimd.cache")- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_stale_cache_returns_immediately_and_queues_refresh(self, mock_get, mock_cache, _url_mock):mock_cache.get.return_value = Nonemock_cache.add.return_value = True@@ -344,13 +452,13 @@ class TestGetOrCreateCimdApplication(APIBaseTest):self.assertEqual(result.name, "Original Name")mock_task.delay.assert_called_once_with(VALID_CIMD_URL)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_new_client_fetch_failure_raises(self, mock_get, _url_mock):mock_get.side_effect = requests.ConnectionError("DNS resolution failed")with self.assertRaises(CIMDFetchError):get_or_create_cimd_application(VALID_CIMD_URL)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_refresh_task_updates_metadata(self, mock_get, _url_mock):metadata1 = _make_metadata(client_name="Original Name")mock_get.return_value = _mock_response(metadata1, headers={})@@ -372,7 +480,7 @@ class TestGetOrCreateCimdApplication(APIBaseTest):("over_length_after_escape", "<" * 300),])- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_client_name_from_metadata_is_html_escaped(self, _name, payload, mock_get, _url_mock):mock_get.return_value = _mock_response(_make_metadata(client_name=payload), headers={})@@ -384,7 +492,7 @@ class TestGetOrCreateCimdApplication(APIBaseTest):self.assertNotIn("<", app.name)self.assertNotIn(">", app.name)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_refresh_escapes_client_name_idempotently(self, mock_get, _url_mock):payload = "<script>alert(1)</script>"mock_get.return_value = _mock_response(_make_metadata(client_name="Safe Name"), headers={})@@ -401,7 +509,7 @@ class TestGetOrCreateCimdApplication(APIBaseTest):self.assertEqual(app.name, escape(payload))self.assertNotIn("<", app.name)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_refresh_task_handles_fetch_failure_gracefully(self, mock_get, _url_mock):metadata = _make_metadata(client_name="Original Name")mock_get.return_value = _mock_response(metadata, headers={})@@ -413,34 +521,20 @@ class TestGetOrCreateCimdApplication(APIBaseTest):app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)self.assertEqual(app.name, "Original Name")- @parameterized.expand(- [- ("refresh", refresh_cimd_metadata_task),- ("registration", register_cimd_provisioning_application_task),- ]- )@patch("posthog.api.oauth.cimd.capture_exception")@patch("posthog.api.oauth.cimd.fetch_and_upsert_cimd_application")- def test_background_task_does_not_capture_expected_validation_error(- self, _name, task_fn, mock_fetch, mock_capture, _url_mock- ):+ def test_refresh_task_does_not_capture_expected_validation_error(self, mock_fetch, mock_capture, _url_mock):# Rejecting a non-compliant partner document is expected, so it must not surface as an error-tracking issue.mock_fetch.side_effect = CIMDValidationError("document exceeds the 5120 byte limit")- task_fn(VALID_CIMD_URL)+ refresh_cimd_metadata_task(VALID_CIMD_URL)mock_capture.assert_not_called()- @parameterized.expand(- [- ("refresh", refresh_cimd_metadata_task),- ("registration", register_cimd_provisioning_application_task),- ]- )@patch("posthog.api.oauth.cimd.capture_exception")@patch("posthog.api.oauth.cimd.fetch_and_upsert_cimd_application")- def test_background_task_captures_unexpected_fetch_error(self, _name, task_fn, mock_fetch, mock_capture, _url_mock):+ def test_refresh_task_captures_unexpected_fetch_error(self, mock_fetch, mock_capture, _url_mock):error = CIMDFetchError("connection reset")mock_fetch.side_effect = error- task_fn(VALID_CIMD_URL)+ refresh_cimd_metadata_task(VALID_CIMD_URL)mock_capture.assert_called_once_with(error)@@ -484,18 +578,18 @@ class TestGetApplicationByClientId(APIBaseTest):get_application_by_client_id("https://unknown.example.com/.well-known/oauth-client-metadata.json")-@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))-class TestGetOrCreateCimdProvisioningApplication(APIBaseTest):- @patch("posthog.api.oauth.cimd.requests.get")- def test_creates_new_app_with_provisioning_defaults(self, mock_get, _url_mock):+@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+class TestApplyProvisioningDefaults(APIBaseTest):+ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_opting_a_cimd_app_in_grants_the_full_default_profile(self, mock_get, _url_mock):mock_get.return_value = _mock_response(_make_metadata(), headers={})+ existing = fetch_and_upsert_cimd_application(VALID_CIMD_URL)+ assert existing is not None+ self.assertFalse(existing.is_provisioning_partner)- app = get_or_create_cimd_provisioning_application(VALID_CIMD_URL)- assert app is not None+ app = apply_provisioning_defaults(existing)- self.assertTrue(app.is_cimd_client)- self.assertEqual(app.cimd_metadata_url, VALID_CIMD_URL)- self.assertEqual(app.provisioning_auth_method, "pkce")+ self.assertTrue(app.is_provisioning_partner)self.assertTrue(app.provisioning_active)self.assertTrue(app.provisioning_can_create_accounts)self.assertTrue(app.provisioning_can_provision_resources)@@ -505,92 +599,40 @@ class TestGetOrCreateCimdProvisioningApplication(APIBaseTest):)@patch("posthog.api.oauth.cimd.posthoganalytics.capture")- @patch("posthog.api.oauth.cimd.requests.get")- def test_emits_registration_event_on_provisioning_upgrade(self, mock_get, mock_capture, _url_mock):- mock_get.return_value = _mock_response(_make_metadata(), headers={})-- get_or_create_cimd_provisioning_application(VALID_CIMD_URL)-- events = [call.kwargs.get("event") for call in mock_capture.call_args_list]- self.assertIn("cimd_provisioning_partner_registered", events)-- @patch("posthog.api.oauth.cimd.posthoganalytics.capture")- @patch("posthog.api.oauth.cimd.requests.get")- def test_no_event_when_provisioning_already_configured(self, mock_get, mock_capture, _url_mock):- mock_get.return_value = _mock_response(_make_metadata(), headers={})- get_or_create_cimd_provisioning_application(VALID_CIMD_URL)- mock_capture.reset_mock()-- get_or_create_cimd_provisioning_application(VALID_CIMD_URL)-- events = [call.kwargs.get("event") for call in mock_capture.call_args_list]- self.assertNotIn("cimd_provisioning_partner_registered", events)-- @patch("posthog.api.oauth.cimd.requests.get")- def test_backfills_provisioning_defaults_on_existing_cimd_app(self, mock_get, _url_mock):+ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_registration_event_fires_once_on_the_transition(self, mock_get, mock_capture, _url_mock):mock_get.return_value = _mock_response(_make_metadata(), headers={})existing = fetch_and_upsert_cimd_application(VALID_CIMD_URL)assert existing is not None- self.assertFalse(existing.is_provisioning_partner)- app = get_or_create_cimd_provisioning_application(VALID_CIMD_URL)- assert app is not None+ apply_provisioning_defaults(existing)+ self.assertIn("cimd_provisioning_partner_registered", _captured_events(mock_capture))- self.assertEqual(app.pk, existing.pk)- self.assertEqual(app.provisioning_auth_method, "pkce")- self.assertTrue(app.provisioning_active)- self.assertTrue(app.provisioning_can_create_accounts)- self.assertTrue(app.provisioning_can_provision_resources)+ mock_capture.reset_mock()+ apply_provisioning_defaults(existing)+ self.assertNotIn("cimd_provisioning_partner_registered", _captured_events(mock_capture))- @patch("posthog.api.oauth.cimd.requests.get")- def test_preserves_existing_provisioning_config(self, mock_get, _url_mock):+ @patch("posthog.api.oauth.cimd.posthoganalytics.capture")+ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_disabled_partner_is_not_re_enabled(self, mock_get, mock_capture, _url_mock):mock_get.return_value = _mock_response(_make_metadata(), headers={})existing = fetch_and_upsert_cimd_application(VALID_CIMD_URL)assert existing is not None- existing.provisioning_auth_method = "hmac"- existing.provisioning_active = False- existing.provisioning_can_create_accounts = False- existing.save(- update_fields=["provisioning_auth_method", "provisioning_active", "provisioning_can_create_accounts"]- )-- app = get_or_create_cimd_provisioning_application(VALID_CIMD_URL)- assert app is not None-- self.assertEqual(app.provisioning_auth_method, "hmac")- self.assertFalse(app.provisioning_active)- self.assertFalse(app.provisioning_can_create_accounts)-- @patch("posthog.api.oauth.cimd.requests.get")- def test_fetch_failure_raises(self, mock_get, _url_mock):- mock_get.side_effect = requests.ConnectionError("DNS resolution failed")- with self.assertRaises(CIMDFetchError):- get_or_create_cimd_provisioning_application(VALID_CIMD_URL)-- def test_blocked_url_returns_none(self, _url_mock):- from posthog.api.oauth.cimd import block_cimd_url, unblock_cimd_url-- block_cimd_url(VALID_CIMD_URL)- result = get_or_create_cimd_provisioning_application(VALID_CIMD_URL)- self.assertIsNone(result)-- unblock_cimd_url(VALID_CIMD_URL)+ existing.provisioning_disabled = True+ existing.save(update_fields=["provisioning_disabled"])+ mock_capture.reset_mock()- @patch("posthog.api.oauth.cimd.requests.get")- def test_blocked_url_prevents_fetch(self, mock_get, _url_mock):- from posthog.api.oauth.cimd import block_cimd_url, unblock_cimd_url+ app = apply_provisioning_defaults(existing)- block_cimd_url(VALID_CIMD_URL)- result = fetch_and_upsert_cimd_application(VALID_CIMD_URL)- self.assertIsNone(result)- mock_get.assert_not_called()+ self.assertFalse(app.is_provisioning_partner)+ app.refresh_from_db()+ self.assertFalse(app.is_provisioning_partner)+ self.assertNotIn("cimd_provisioning_partner_registered", _captured_events(mock_capture))- unblock_cimd_url(VALID_CIMD_URL)--@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))+@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})class TestCIMDVerificationToken(APIBaseTest):- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_valid_verification_token_links_app_to_organization(self, mock_get, _url_mock):token, plaintext = create_cimd_verification_token(organization=self.organization, label="Test partner", created_by=self.user@@ -605,7 +647,7 @@ class TestCIMDVerificationToken(APIBaseTest):token.refresh_from_db()self.assertIsNotNone(token.last_used_at)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_invalid_verification_token_leaves_app_unlinked(self, mock_get, _url_mock):metadata = _make_metadata(posthog_verification_token="phvt_totally_made_up")mock_get.return_value = _mock_response(metadata, headers={})@@ -615,7 +657,7 @@ class TestCIMDVerificationToken(APIBaseTest):assert app is not Noneself.assertIsNone(app.organization_id)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_missing_verification_token_leaves_app_unlinked(self, mock_get, _url_mock):mock_get.return_value = _mock_response(_make_metadata(), headers={})@@ -624,7 +666,7 @@ class TestCIMDVerificationToken(APIBaseTest):assert app is not Noneself.assertIsNone(app.organization_id)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_verified_partner_gets_higher_rate_limit(self, mock_get, _url_mock):_, plaintext = create_cimd_verification_token(organization=self.organization, label="Verified partner", created_by=self.user@@ -632,7 +674,7 @@ class TestCIMDVerificationToken(APIBaseTest):metadata = _make_metadata(posthog_verification_token=plaintext)mock_get.return_value = _mock_response(metadata, headers={})- app = get_or_create_cimd_provisioning_application(VALID_CIMD_URL)+ app = _register_provisioning_partner()assert app is not Noneself.assertEqual(app.organization_id, self.organization.id)@@ -641,11 +683,11 @@ class TestCIMDVerificationToken(APIBaseTest):CIMD_PROVISIONING_ACCOUNT_REQUESTS_VERIFIED_RATE_LIMIT,)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_unverified_partner_gets_default_rate_limit(self, mock_get, _url_mock):mock_get.return_value = _mock_response(_make_metadata(), headers={})- app = get_or_create_cimd_provisioning_application(VALID_CIMD_URL)+ app = _register_provisioning_partner()assert app is not Noneself.assertIsNone(app.organization_id)@@ -654,7 +696,7 @@ class TestCIMDVerificationToken(APIBaseTest):CIMD_PROVISIONING_ACCOUNT_REQUESTS_DEFAULT_RATE_LIMIT,)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_refresh_unlinks_app_when_token_removed(self, mock_get, _url_mock):_, plaintext = create_cimd_verification_token(organization=self.organization, label="Rotating partner", created_by=self.user@@ -672,7 +714,7 @@ class TestCIMDVerificationToken(APIBaseTest):assert refreshed is not Noneself.assertIsNone(refreshed.organization_id)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_refresh_links_app_when_token_added(self, mock_get, _url_mock):# First fetch: no token → unlinkedmock_get.return_value = _mock_response(_make_metadata(), headers={})@@ -690,7 +732,7 @@ class TestCIMDVerificationToken(APIBaseTest):assert refreshed is not Noneself.assertEqual(refreshed.organization_id, self.organization.id)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_non_string_verification_token_is_ignored(self, mock_get, _url_mock):metadata = _make_metadata()metadata["posthog_verification_token"] = {"not": "a string"}@@ -701,10 +743,10 @@ class TestCIMDVerificationToken(APIBaseTest):assert app is not Noneself.assertIsNone(app.organization_id)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_refresh_bumps_rate_limit_when_token_added_post_registration(self, mock_get, _url_mock):mock_get.return_value = _mock_response(_make_metadata(), headers={})- get_or_create_cimd_provisioning_application(VALID_CIMD_URL)+ _register_provisioning_partner()app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)self.assertIsNone(app.organization_id)self.assertEqual(@@ -726,13 +768,13 @@ class TestCIMDVerificationToken(APIBaseTest):CIMD_PROVISIONING_ACCOUNT_REQUESTS_VERIFIED_RATE_LIMIT,)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_refresh_drops_rate_limit_when_token_removed(self, mock_get, _url_mock):_, plaintext = create_cimd_verification_token(organization=self.organization, label="Rotating partner", created_by=self.user)mock_get.return_value = _mock_response(_make_metadata(posthog_verification_token=plaintext), headers={})- get_or_create_cimd_provisioning_application(VALID_CIMD_URL)+ _register_provisioning_partner()app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)self.assertEqual(app.organization_id, self.organization.id)self.assertEqual(@@ -751,10 +793,10 @@ class TestCIMDVerificationToken(APIBaseTest):CIMD_PROVISIONING_ACCOUNT_REQUESTS_DEFAULT_RATE_LIMIT,)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_refresh_preserves_admin_custom_rate_limit(self, mock_get, _url_mock):mock_get.return_value = _mock_response(_make_metadata(), headers={})- get_or_create_cimd_provisioning_application(VALID_CIMD_URL)+ _register_provisioning_partner()app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)app.provisioning_rate_limit_account_requests = 250app.provisioning_rate_limit_account_requests_source = "admin"@@ -787,7 +829,7 @@ class TestAuthorizationServerMetadata(APIBaseTest):self.assertTrue(data.get("client_id_metadata_document_supported"))-@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))+@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})class TestCIMDAuthorizeIntegration(APIBaseTest):"""Integration tests for the CIMD flow through /oauth/authorize/."""@@ -813,7 +855,7 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):)return f"/oauth/authorize/?{params}"- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_cimd_url_creates_app_and_returns_consent_screen(self, mock_get, _url_mock):metadata = _make_metadata()mock_get.return_value = _mock_response(metadata)@@ -825,9 +867,9 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):app = OAuthApplication.objects.get(cimd_metadata_url=VALID_CIMD_URL)self.assertTrue(app.is_cimd_client)self.assertEqual(app.name, "Test MCP Client")- mock_get.assert_called_once()+ self.assertEqual(len(_document_fetches(mock_get)), 1)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_cimd_existing_app_skips_fetch(self, mock_get, _url_mock):# Pre-create a CIMD appmetadata = _make_metadata()@@ -840,10 +882,10 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):response = self.client.get(url)self.assertEqual(response.status_code, 200)- mock_get.assert_not_called()+ self.assertEqual(_document_fetches(mock_get), [])self.assertEqual(OAuthApplication.objects.filter(cimd_metadata_url=VALID_CIMD_URL).count(), 1)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_cimd_fetch_failure_rejects_new_client(self, mock_get, _url_mock):mock_get.side_effect = requests.ConnectionError("DNS failed")url = self._authorize_url(VALID_CIMD_URL)@@ -853,7 +895,7 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):self.assertEqual(response.status_code, 400)self.assertIn("invalid", response.json().get("error", "").lower())- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_cimd_mismatched_redirect_uri_rejected(self, mock_get, _url_mock):metadata = _make_metadata()mock_get.return_value = _mock_response(metadata)@@ -864,7 +906,7 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):self.assertEqual(response.status_code, 400)- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_cimd_rate_limit_rejects_new_client(self, mock_get, _url_mock):metadata = _make_metadata()mock_get.return_value = _mock_response(metadata)@@ -879,7 +921,9 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):response = self.client.get(url)self.assertEqual(response.status_code, 400)- mock_get.assert_not_called()+ self.assertEqual(+ _document_fetches(mock_get, "https://new-client.example.com/.well-known/oauth-client-metadata.json"), []+ )def test_cimd_requires_authentication(self, _url_mock):self.client.logout()@@ -891,7 +935,7 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):self.assertIn("/login", response["Location"])-@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))+@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})class TestCIMDComPostHogNamespace(APIBaseTest):"""Tests for the com.posthog namespace: scopes and nested verification_token."""@@ -903,7 +947,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):("top_level",),])- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_verification_token_dual_read(self, token_placement, mock_get, _url_mock):token, plaintext = create_cimd_verification_token(organization=self.organization, label="Dual-read partner", created_by=self.user@@ -920,7 +964,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):self.assertEqual(app.organization_id, self.organization.id)# (d) continued: an unrecognized nested token falls back to a valid top-level one.- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_verification_token_falls_back_when_nested_unrecognized(self, mock_get, _url_mock):_, plaintext = create_cimd_verification_token(organization=self.organization, label="Fallback partner", created_by=self.user@@ -936,7 +980,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):self.assertEqual(app.organization_id, self.organization.id)# (d) continued: nested token takes precedence over top-level when both present.- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_nested_token_takes_precedence_over_top_level(self, mock_get, _url_mock):_, plaintext_nested = create_cimd_verification_token(organization=self.organization, label="Nested partner", created_by=self.user@@ -958,7 +1002,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):("empty", [], []),])- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_scopes_written_to_app_on_creation(self, _name, input_scopes, expected_scopes, mock_get, _url_mock):metadata = _make_metadata(com_posthog={"scopes": input_scopes})mock_get.return_value = _mock_response(metadata, headers={})@@ -969,7 +1013,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):self.assertEqual(sorted(app.scopes), sorted(expected_scopes))# (c) Only UNPRIVILEGED_SCOPES pass — privileged, hidden, and unknown strings are all dropped.- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_non_grantable_scopes_stripped(self, mock_get, _url_mock):hidden_scope = next(iter(OAUTH_SCOPES_HIDDEN)) if OAUTH_SCOPES_HIDDEN else Noneinput_scopes = [@@ -994,7 +1038,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):self.assertIn("insight:read", app.scopes)# Duplicate scopes in the metadata array collapse to one entry, order preserved.- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_duplicate_scopes_deduped(self, mock_get, _url_mock):metadata = _make_metadata(com_posthog={"scopes": ["insight:read", "dashboard:write", "insight:read"]})mock_get.return_value = _mock_response(metadata, headers={})@@ -1005,7 +1049,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):self.assertEqual(app.scopes, ["insight:read", "dashboard:write"])# (b) absent com.posthog.scopes on refresh leaves existing scopes untouched.- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_absent_scopes_on_refresh_leaves_existing_untouched(self, mock_get, _url_mock):metadata_create = _make_metadata(com_posthog={"scopes": ["insight:read"]})mock_get.return_value = _mock_response(metadata_create, headers={})@@ -1020,7 +1064,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):self.assertIn("insight:read", refreshed.scopes)# (a) present scopes on refresh override the existing application.scopes.- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_present_scopes_on_refresh_override_existing(self, mock_get, _url_mock):metadata_create = _make_metadata(com_posthog={"scopes": ["insight:read", "dashboard:write"]})mock_get.return_value = _mock_response(metadata_create, headers={})@@ -1036,7 +1080,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):# com.posthog.optional_scopes carries the required/optional split: required `scopes` and the# declinable `optional_scopes` are written together on creation, capped to grantable scopes.- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_optional_scopes_written_to_app_on_creation(self, mock_get, _url_mock):metadata = _make_metadata(com_posthog={"scopes": ["insight:read"], "optional_scopes": ["dashboard:read", "llm_gateway:read"]}@@ -1053,7 +1097,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):# Both fields refresh together so the split never drifts: a metadata refresh rewrites# `optional_scopes` alongside `scopes`.- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_optional_scopes_refresh_together_with_scopes(self, mock_get, _url_mock):mock_get.return_value = _mock_response(_make_metadata(com_posthog={"scopes": ["insight:read"], "optional_scopes": ["dashboard:read"]}), headers={}@@ -1074,7 +1118,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):# metadata document, but republishing it on refresh can never escalate the ceiling past# the unprivileged allow-list — privileged, hidden, and unknown scopes are stripped on# the refresh path exactly as on creation.- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_refresh_cannot_grant_non_grantable_scopes(self, mock_get, _url_mock):mock_get.return_value = _mock_response(_make_metadata(com_posthog={"scopes": ["insight:read"]}), headers={})fetch_and_upsert_cimd_application(VALID_CIMD_URL)@@ -1096,7 +1140,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):self.assertEqual(refreshed.scopes, ["insight:read"])# absent com.posthog.scopes on initial creation → empty scopes list.- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_absent_scopes_on_creation_yields_empty_list(self, mock_get, _url_mock):mock_get.return_value = _mock_response(_make_metadata(), headers={})app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)@@ -1107,7 +1151,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):# A present, non-empty com.posthog.scopes that strips to nothing is rejected, not# stored as [] (which would widen the app to the broad UNPRIVILEGED default via the# empty-ceiling fallback). Mirrors DCR's all-stripped rejection; no app is created.- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_all_non_grantable_scopes_on_creation_rejected(self, mock_get, _url_mock):only_non_grantable = [*sorted(PRIVILEGED_SCOPES), "not_a_real_scope:write"]mock_get.return_value = _mock_response(_make_metadata(com_posthog={"scopes": only_non_grantable}), headers={})@@ -1119,7 +1163,7 @@ class TestCIMDComPostHogNamespace(APIBaseTest):# On refresh, a doc whose scopes all strip out is rejected and the existing ceiling is# left untouched (fail-closed) rather than widened to the default.- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_all_non_grantable_scopes_on_refresh_leaves_existing_untouched(self, mock_get, _url_mock):mock_get.return_value = _mock_response(_make_metadata(com_posthog={"scopes": ["insight:read"]}), headers={})created = fetch_and_upsert_cimd_application(VALID_CIMD_URL)diff --git a/posthog/api/oauth/test_client_assertion.py b/posthog/api/oauth/test_client_assertion.pynew file mode 100644index 000000000000..c28a3f031663--- /dev/null+++ b/posthog/api/oauth/test_client_assertion.py@@ -0,0 +1,211 @@+import json+import time+from typing import cast++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.cache import cache+from django.test import override_settings++import jwt+from cryptography.hazmat.primitives.asymmetric import rsa+from parameterized import parameterized+from rest_framework.parsers import JSONParser+from rest_framework.request import Request+from rest_framework.test import APIRequestFactory++from posthog.api.oauth.cimd import CIMDFetchError+from posthog.api.oauth.client_assertion import (+ CLIENT_ASSERTION_TYPE_JWT_BEARER,+ MAX_ASSERTION_LIFETIME_SECONDS,+ ClientAssertionError,+ extract_client_assertion,+ load_jwks,+ verify_client_assertion,+)+from posthog.models.oauth import OAuthApplication, TokenEndpointAuthMethod++CLIENT_ID = "https://partner.example.com/.well-known/oauth-client-metadata.json"+JWKS_URI = "https://partner.example.com/.well-known/jwks.json"+AUDIENCE = "https://us.posthog.com/api/agentic/oauth/token"+KID = "partner-key-1"+++def _rsa_key():+ return rsa.generate_private_key(public_exponent=65537, key_size=2048)+++# Generated once for the module: RSA-2048 keygen is ~100ms, and no test mutates a key, so+# building one per test method would add seconds to the suite for nothing.+KEY = _rsa_key()+OTHER_KEY = _rsa_key()+++def _drf_request(data: dict) -> Request:+ raw = APIRequestFactory().post("/", data, format="json")+ return cast(Request, Request(raw, parsers=[JSONParser()]))+++def _jwks_for(private_key, kid: str = KID) -> dict:+ jwk = json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(private_key.public_key()))+ jwk.update({"kid": kid, "use": "sig", "alg": "RS256"})+ return {"keys": [jwk]}+++@override_settings(SITE_URL="https://us.posthog.com")+class TestClientAssertion(BaseTest):+ def setUp(self):+ super().setUp()+ cache.clear()+ self.private_key = KEY+ self.jwks = _jwks_for(self.private_key)+ self.app = OAuthApplication.objects.create(+ name="Assertion Partner",+ client_id=CLIENT_ID,+ client_secret="",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ jwks_uri=JWKS_URI,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://partner.example.com/callback",+ algorithm="RS256",+ is_provisioning_partner=True,+ provisioning_active=True,+ )++ def _claims(self, **overrides) -> dict:+ now = int(time.time())+ claims = {+ "iss": CLIENT_ID,+ "sub": CLIENT_ID,+ "aud": AUDIENCE,+ "jti": f"jti-{now}-{overrides.pop('jti_suffix', 'default')}",+ "iat": now,+ "exp": now + 60,+ }+ claims.update(overrides)+ return {k: v for k, v in claims.items() if v is not None}++ def _assertion(self, *, key=None, kid: str | None = KID, algorithm: str = "RS256", **overrides) -> str:+ headers = {"kid": kid} if kid else {}+ return jwt.encode(self._claims(**overrides), key or self.private_key, algorithm=algorithm, headers=headers)++ def _verify(self, assertion: str) -> None:+ with patch("posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=(self.jwks, None)):+ verify_client_assertion(self.app, assertion)++ def test_valid_assertion_verifies(self):+ self._verify(self._assertion())++ def test_assertion_is_single_use(self):+ assertion = self._assertion()+ self._verify(assertion)++ # Replaying the same jti must fail even though the signature is still perfectly valid.+ with self.assertRaises(ClientAssertionError):+ self._verify(assertion)++ @parameterized.expand(+ [+ ("wrong_issuer", {"iss": "https://attacker.example.com/metadata.json"}),+ ("wrong_subject", {"sub": "https://attacker.example.com/metadata.json"}),+ ("wrong_audience", {"aud": "https://elsewhere.example.com/token"}),+ ("expired", {"exp": int(time.time()) - 120, "iat": int(time.time()) - 180}),+ ("missing_jti", {"jti": None}),+ ("missing_exp", {"exp": None}),+ # Without iat there is no lower bound to measure the lifetime cap against, so an+ # assertion could name an exp arbitrarily far in the future.+ ("missing_iat", {"iat": None}),+ ]+ )+ def test_rejected_claims(self, _name, overrides):+ with self.assertRaises(ClientAssertionError):+ self._verify(self._assertion(**overrides))++ def test_assertion_signed_by_another_key_is_rejected(self):+ # The whole point of the scheme: only the holder of the published key can authenticate.+ with self.assertRaises(ClientAssertionError):+ self._verify(self._assertion(key=OTHER_KEY))++ def test_hmac_algorithm_is_rejected(self):+ # Key confusion: the public key is published, so if an HMAC family were accepted an+ # attacker could sign with the public key material as the shared secret.+ forged_secret = str(self.private_key.public_key().public_numbers().n)+ assertion = jwt.encode(self._claims(), forged_secret, algorithm="HS256", headers={"kid": KID})+ with self.assertRaises(ClientAssertionError):+ self._verify(assertion)++ def test_unsigned_assertion_is_rejected(self):+ # nosemgrep: python.jwt.security.jwt-none-alg.jwt-python-none-alg (forging an alg=none token is the point: this asserts verify_client_assertion refuses it)+ assertion = jwt.encode(self._claims(), key="", algorithm="none")+ with self.assertRaises(ClientAssertionError):+ self._verify(assertion)++ def test_overlong_lifetime_is_rejected(self):+ now = int(time.time())+ with self.assertRaises(ClientAssertionError):+ self._verify(self._assertion(iat=now, exp=now + MAX_ASSERTION_LIFETIME_SECONDS + 60))++ def test_unknown_kid_is_rejected(self):+ with self.assertRaises(ClientAssertionError):+ self._verify(self._assertion(kid="rotated-out-key"))++ def test_kid_required_when_jwks_holds_several_keys(self):+ self.jwks = {"keys": [*self.jwks["keys"], *_jwks_for(OTHER_KEY, kid="partner-key-2")["keys"]]}+ with self.assertRaises(ClientAssertionError):+ self._verify(self._assertion(kid=None))++ def test_client_not_registered_for_the_method_is_rejected(self):+ # Dropping the key source moves it back to client_secret authentication.+ self.app.jwks_uri = None+ self.app.save(update_fields=["jwks_uri"])+ assert self.app.token_endpoint_auth_method is TokenEndpointAuthMethod.CLIENT_SECRET_POST+ with self.assertRaises(ClientAssertionError):+ self._verify(self._assertion())++ def test_jwks_is_cached_across_verifications(self):+ with patch(+ "posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=(self.jwks, None)+ ) as fetch:+ verify_client_assertion(self.app, self._assertion(jti_suffix="a"))+ verify_client_assertion(self.app, self._assertion(jti_suffix="b"))+ # A second exchange must not mean a second outbound fetch.+ fetch.assert_called_once()++ def test_jwks_fetch_failure_is_negatively_cached(self):+ with patch(+ "posthog.api.oauth.client_assertion.fetch_client_json_document",+ side_effect=CIMDFetchError("unreachable"),+ ) as fetch:+ for _ in range(3):+ with self.assertRaises(ClientAssertionError):+ load_jwks(JWKS_URI)+ # A client with a broken jwks_uri must not turn each request into an outbound fetch.+ fetch.assert_called_once()++ def test_jwks_with_too_many_keys_is_rejected(self):+ # The cap is on key count, so the same key material under distinct kids exercises it.+ many = {"keys": [_jwks_for(KEY, kid=f"k{i}")["keys"][0] for i in range(11)]}+ with patch("posthog.api.oauth.client_assertion.fetch_client_json_document", return_value=(many, None)):+ with self.assertRaises(ClientAssertionError):+ load_jwks(JWKS_URI)++ @parameterized.expand(+ [+ ("wrong_type", {"client_assertion": "x.y.z", "client_assertion_type": "urn:something:else"}),+ ("missing_type", {"client_assertion": "x.y.z"}),+ ("missing_assertion", {"client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER}),+ ("empty", {}),+ ]+ )+ def test_no_assertion_extracted(self, _name, data):+ assert extract_client_assertion(_drf_request(data)) is None++ def test_assertion_client_id_falls_back_to_subject(self):+ # RFC 7521 section 4.2 lets the assertion carry the identity, so a caller may omit+ # client_id entirely.+ assertion = self._assertion()+ request = _drf_request(+ {"client_assertion": assertion, "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER}+ )+ assert extract_client_assertion(request) == (assertion, CLIENT_ID)diff --git a/posthog/api/oauth/test_client_auth.py b/posthog/api/oauth/test_client_auth.pynew file mode 100644index 000000000000..81ec4717bf4a--- /dev/null+++ b/posthog/api/oauth/test_client_auth.py@@ -0,0 +1,33 @@+from django.contrib.auth.hashers import make_password+from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.api.oauth.client_auth import verify_client_secret+from posthog.api.oauth.views import OAuthValidator+++class TestVerifyClientSecret(SimpleTestCase):+ @parameterized.expand(+ [+ ("correct_hashed", "s3cret", make_password("s3cret"), True),+ ("wrong_hashed", "wrong", make_password("s3cret"), False),+ ("correct_unhashed_legacy", "s3cret", "s3cret", True),+ ("wrong_unhashed_legacy", "wrong", "s3cret", False),+ # An app created with client_secret="" stores make_password(""), a valid hash of+ # the empty string, so a bare check_password would authenticate any caller that+ # presents no secret. Applications registered for private_key_jwt are exactly that+ # shape, since their proof is a signed assertion and they hold no secret.+ ("blank_provided_against_hash_of_blank", "", make_password(""), False),+ ("blank_provided_against_real_secret", "", make_password("s3cret"), False),+ ("blank_stored", "s3cret", "", False),+ ]+ )+ def test_verify_client_secret(self, _name, provided, stored, expected):+ assert verify_client_secret(provided, stored) is expected++ def test_validator_rejects_a_blank_secret(self):+ # The library's own _check_secret accepts this, so the override is what stands between+ # a credential-less request and every confidential app that holds no secret.+ assert OAuthValidator()._check_secret("", make_password("")) is False+ assert OAuthValidator()._check_secret("s3cret", make_password("s3cret")) is Truediff --git a/posthog/api/oauth/test_raycast_metadata.py b/posthog/api/oauth/test_raycast_metadata.pyindex 72ff2ff49e9f..7ad7b83ae7be 100644--- a/posthog/api/oauth/test_raycast_metadata.py+++ b/posthog/api/oauth/test_raycast_metadata.py@@ -1,4 +1,5 @@import json+from ipaddress import ip_addressfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch@@ -67,8 +68,8 @@ class TestRaycastClientMetadataView(SimpleTestCase):@override_settings(SITE_URL="https://us.posthog.com")class TestRaycastClientMetadataRegistration(APIBaseTest):- @patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))- @patch("posthog.api.oauth.cimd.requests.get")+ @patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})+ @patch("posthog.api.oauth.cimd.requests.Session.get")def test_document_registers_through_cimd(self, mock_get, _url_mock):# Serve the live document back through the CIMD fetch path (the HTTP fetch# is patched since CIMD client_ids must be HTTPS), then assert it registersdiff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 354a10cb4bc1..214c47725b15 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -47,11 +47,18 @@ from posthog.api.oauth.cimd import (get_or_create_cimd_application,is_cimd_client_id,)+from posthog.api.oauth.client_auth import verify_client_secretfrom posthog.api.oauth.mcp_resource_scopes import build_oauth_mcp_consent_contextfrom posthog.helpers.impersonation import get_original_user_from_session, is_impersonated_sessionfrom posthog.middleware import is_read_only_impersonationfrom posthog.models import OAuthAccessToken, OAuthApplication, Organization, Team, User-from posthog.models.oauth import OAuthApplicationAccessLevel, OAuthGrant, OAuthRefreshToken, revoke_oauth_session+from posthog.models.oauth import (+ OAuthApplicationAccessLevel,+ OAuthGrant,+ OAuthRefreshToken,+ TokenEndpointAuthMethod,+ revoke_oauth_session,+)from posthog.scopes import (ALWAYS_ALLOWED_SCOPES,downgrade_scopes_to_read_only,@@ -286,6 +293,16 @@ class OAuthAuthorizationSerializer(serializers.Serializer):class OAuthValidator(OAuth2Validator):+ def _check_secret(self, provided_secret, stored_secret):+ """Reject a blank secret, which the library's own implementation accepts.++ An application registered for ``private_key_jwt`` is confidential but holds no+ secret, so its column stores ``make_password("")``. The library compares with a bare+ ``check_password``, which returns True for an empty input against that hash, so such+ a client would authenticate here having presented no credential at all.+ """+ return verify_client_secret(provided_secret, stored_secret)+def _is_dynamic_client(self, request) -> bool:"""Check if the client was registered dynamically (DCR or CIMD)."""if hasattr(request, "client") and request.client:@@ -1628,7 +1645,12 @@ class OAuthAuthorizationServerMetadataView(_PublicMetadataView):id_jag.JWT_BEARER_GRANT_TYPE,],"authorization_grant_profiles_supported": [id_jag.ID_JAG_GRANT_PROFILE],- "token_endpoint_auth_methods_supported": ["none", "client_secret_post"],+ # private_key_jwt is deliberately absent: it is implemented on the agentic token+ # endpoint, not on the endpoint this document describes.+ "token_endpoint_auth_methods_supported": [+ TokenEndpointAuthMethod.NONE.value,+ TokenEndpointAuthMethod.CLIENT_SECRET_POST.value,+ ],"code_challenge_methods_supported": ["S256"],# Service documentation"service_documentation": "https://posthog.com/docs/api",diff --git a/posthog/migrations/1267_oauth_client_authentication.py b/posthog/migrations/1267_oauth_client_authentication.pynew file mode 100644index 000000000000..68cc34eaca9f--- /dev/null+++ b/posthog/migrations/1267_oauth_client_authentication.py@@ -0,0 +1,43 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ """Add the columns that replace provisioning_auth_method: is_provisioning_partner, and+ jwks_uri for private_key_jwt clients.++ Schema only. The backfill lands in 1267 and the retirement of the old columns in 1268,+ because a data migration in the same file as schema changes holds its locks for the whole+ file. Both new columns are additive and nullable-or-defaulted, so this half is safe to run+ on its own and leaves the previous release working untouched.+ """++ dependencies = [("posthog", "1266_comment_convo_content_trgm")]++ operations = [+ migrations.AddField(+ model_name="oauthapplication",+ name="is_provisioning_partner",+ field=models.BooleanField(+ db_default=False,+ default=False,+ help_text=(+ "Whether this app may act as an agentic provisioning partner. How it authenticates "+ "follows from client_type, so there is no separate provisioning auth method."+ ),+ ),+ ),+ migrations.AddField(+ model_name="oauthapplication",+ name="jwks_uri",+ field=models.URLField(+ blank=True,+ help_text=(+ "HTTPS URL serving the client's public keys as a JWK Set. Setting this on a "+ "confidential client switches it to private_key_jwt authentication (RFC 7523): it "+ "signs an assertion we verify against these keys instead of holding a shared secret."+ ),+ max_length=2048,+ null=True,+ ),+ ),+ ]diff --git a/posthog/migrations/1268_backfill_is_provisioning_partner.py b/posthog/migrations/1268_backfill_is_provisioning_partner.pynew file mode 100644index 000000000000..f9fc2e0f3f8b--- /dev/null+++ b/posthog/migrations/1268_backfill_is_provisioning_partner.py@@ -0,0 +1,44 @@+from django.db import migrations++import structlog++logger = structlog.get_logger(__name__)++# Methods whose apps become provisioning partners under the new boolean. Chosen to preserve+# today's behavior exactly: these are the two values the resource endpoints currently accept+# outstanding access tokens for. "hmac" is excluded because those apps already fail closed+# everywhere, and "" was never a partner.+PARTNER_AUTH_METHODS = ["pkce", "bearer"]+++def backfill_is_provisioning_partner(apps, schema_editor):+ OAuthApplication = apps.get_model("posthog", "OAuthApplication")+ partners = OAuthApplication.objects.filter(provisioning_auth_method__in=PARTNER_AUTH_METHODS)+ partners.update(is_provisioning_partner=True)++ # A "bearer" partner proved itself with an OAuth access token, so nothing ever required+ # its application to carry a usable client_secret. Afterwards a confidential app is+ # expected to authenticate as an OAuth client, and one with a blank secret resolves to+ # client_secret_post with nothing to verify against, so it can no longer reach any+ # provisioning endpoint. 1266 only just added jwks_uri, so every row still has it null and+ # none can be on private_key_jwt instead. Log the affected ids rather than let them fail+ # silently after deploy; each needs a secret set or a jwks_uri published before those+ # columns are dropped for real in a later release.+ stranded = list(partners.filter(client_type="confidential", client_secret="").values_list("id", flat=True))+ if stranded:+ logger.warning("provisioning_partners_without_client_credentials", application_ids=stranded)+++class Migration(migrations.Migration):+ """Backfill is_provisioning_partner from provisioning_auth_method.++ Alone in its own migration: a RunPython sharing a file with schema changes holds locks for+ the whole file. It has to run while provisioning_auth_method is still in the model state,+ which is why it sits before 1269 rather than after.+ """++ dependencies = [("posthog", "1267_oauth_client_authentication")]++ operations = [+ migrations.RunPython(backfill_is_provisioning_partner, migrations.RunPython.noop, elidable=True),+ ]diff --git a/posthog/migrations/1269_retire_provisioning_auth_method.py b/posthog/migrations/1269_retire_provisioning_auth_method.pynew file mode 100644index 000000000000..3eddc3096013--- /dev/null+++ b/posthog/migrations/1269_retire_provisioning_auth_method.py@@ -0,0 +1,25 @@+from django.db import migrations+++class Migration(migrations.Migration):+ """Give Postgres a default for provisioning_auth_method, ahead of 1270 dropping it from the+ model state.++ provisioning_auth_method is NOT NULL and its Django ``default=""`` was only ever applied in+ Python, so once the model stops listing the column every INSERT would violate the+ constraint. '' rather than dropping NOT NULL, so rows written by new code still read back+ exactly as the previous release expects while both are live. provisioning_signing_secret is+ already nullable and needs nothing here.++ Alone in its own migration: a RunSQL sharing a file with other operations holds its lock for+ the whole file.+ """++ dependencies = [("posthog", "1268_backfill_is_provisioning_partner")]++ operations = [+ migrations.RunSQL(+ sql="""ALTER TABLE "posthog_oauthapplication" ALTER COLUMN "provisioning_auth_method" SET DEFAULT '';""",+ reverse_sql="""ALTER TABLE "posthog_oauthapplication" ALTER COLUMN "provisioning_auth_method" DROP DEFAULT;""",+ ),+ ]diff --git a/posthog/migrations/1270_untrack_provisioning_auth_columns.py b/posthog/migrations/1270_untrack_provisioning_auth_columns.pynew file mode 100644index 000000000000..d6028d700553--- /dev/null+++ b/posthog/migrations/1270_untrack_provisioning_auth_columns.py@@ -0,0 +1,35 @@+from django.db import migrations+++class Migration(migrations.Migration):+ """Stop tracking provisioning_auth_method and provisioning_signing_secret in Django state.++ Runs after 1269 so Postgres already has a default for provisioning_auth_method by the time+ the model stops listing it, and after 1268 so the backfill still had the column in state to+ read from.+ """++ dependencies = [("posthog", "1269_retire_provisioning_auth_method")]++ operations = [+ # State-only: Django stops tracking these two columns, but they stay in Postgres so a+ # rollback to the previous release still finds them, and so no read of a dropped column+ # can 500 during the deploy window. provisioning_auth_method is superseded by+ # is_provisioning_partner plus client_type; provisioning_signing_secret held the per-app+ # HMAC secret, which has no readers left (the Stripe partner surface signs against+ # settings.STRIPE_SIGNING_SECRET instead). Drop the columns themselves in a later+ # release, once no deployed code references them.+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.RemoveField(+ model_name="oauthapplication",+ name="provisioning_auth_method",+ ),+ migrations.RemoveField(+ model_name="oauthapplication",+ name="provisioning_signing_secret",+ ),+ ],+ database_operations=[],+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 8c8e4e3d6223..7c9d997701b2 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1266_comment_convo_content_trgm+1270_untrack_provisioning_auth_columnsdiff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 32c3231ccf61..a9ecb1a90151 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -755,7 +755,6 @@ field_exclusions: dict[AuditableScope, list[str]] = {# Secrets — never diff these, even masked."client_secret","hash_client_secret",- "provisioning_signing_secret",# Reverse token relations can hold tens of thousands of rows; reading# through them in `changes_between` would scan the token tables."oauthaccesstoken",diff --git a/posthog/models/oauth.py b/posthog/models/oauth.pyindex 458ce4d15413..a8527da682c1 100644--- a/posthog/models/oauth.py+++ b/posthog/models/oauth.py@@ -23,7 +23,6 @@ from oauth2_provider.models import (from oauth2_provider.settings import oauth2_settingsfrom oauth2_provider.validators import AllowedURIValidator-from posthog.helpers.encrypted_fields import EncryptedCharFieldfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.utils import UUIDT, generate_random_token, hash_key_value, mask_key_value@@ -42,6 +41,22 @@ class OAuthApplicationAuthBrand(enum.Enum):TWIG = "twig"+class TokenEndpointAuthMethod(enum.Enum):+ """How a client authenticates at the token endpoint, per RFC 7591 section 2.++ ``NONE`` is a public client: it holds no credential and relies on PKCE (RFC 7636).+ ``CLIENT_SECRET_POST`` holds a shared secret; RFC 6749 section 2.3.1 also defines a+ ``client_secret_basic`` variant, which is not registered separately here because both+ transports are accepted from any secret-holding client. ``PRIVATE_KEY_JWT`` is+ asymmetric: the client signs an assertion (RFC 7523) that is verified against a public+ key it publishes at its ``jwks_uri``, so no shared secret ever has to be transmitted.+ """++ NONE = "none"+ CLIENT_SECRET_POST = "client_secret_post"+ PRIVATE_KEY_JWT = "private_key_jwt"++def is_loopback_host(hostname: str | None) -> bool:"""Check if hostname is a loopback address (localhost, 127.0.0.0/8, or ::1)."""if not hostname:@@ -173,20 +188,27 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignorenull=True, blank=True, help_text="When the CIMD metadata was last successfully fetched")- # Provisioning fields - only relevant for partners that provision accounts/resources- # via the agentic provisioning API. Null/blank for regular OAuth clients.- provisioning_auth_method: models.CharField = models.CharField(- max_length=20,+ # Client authentication - RFC 7591 section 2 client metadata+ jwks_uri: models.URLField = models.URLField(+ max_length=2048,+ null=True,blank=True,- default="",- help_text="Auth method for provisioning requests: hmac, bearer, or pkce. Empty for non-provisioning apps.",+ help_text=(+ "HTTPS URL serving the client's public keys as a JWK Set. Setting this on a "+ "confidential client switches it to private_key_jwt authentication (RFC 7523): it "+ "signs an assertion we verify against these keys instead of holding a shared secret."+ ),)- provisioning_signing_secret = EncryptedCharField(- max_length=500,- blank=True,- null=True,- default="",- help_text="HMAC shared secret for provisioning request verification (encrypted at rest)",++ # Provisioning fields - only relevant for partners that provision accounts/resources+ # via the agentic provisioning API. Null/blank for regular OAuth clients.+ is_provisioning_partner: models.BooleanField = models.BooleanField(+ default=False,+ db_default=False,+ help_text=(+ "Whether this app may act as an agentic provisioning partner. How it authenticates "+ "follows from client_type, so there is no separate provisioning auth method."+ ),)provisioning_partner_type: models.CharField = models.CharField(max_length=50,@@ -256,9 +278,51 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignorehelp_text="Allow this app to issue deep links that mint full web sessions. Only enable for fully trusted partners.",)+ # Client authentication is registration state on purpose. A client_id is public, so+ # inferring the method from what a request happens to present would let anyone act as a+ # confidential client by presenting nothing at all.++ @property+ def effective_client_id(self) -> str:+ """The identifier this client uses for itself on the wire.++ For a CIMD client that is its metadata URL, which is what the client sends and what it+ names itself by in a signed assertion; the ``client_id`` column holds an opaque value+ generated at registration. For every other client the two are the same.++ Gated on ``is_cimd_client`` so a stray ``cimd_metadata_url`` on a non-CIMD app cannot+ change which identifier an assertion's ``iss``/``sub`` are checked against.+ """+ if self.is_cimd_client and self.cimd_metadata_url:+ return self.cimd_metadata_url+ return self.client_id+@property- def is_provisioning_partner(self) -> bool:- return bool(self.provisioning_auth_method)+ def requires_client_authentication(self) -> bool:+ """Whether this client must prove itself, i.e. is confidential (RFC 6749 section 3.2.1)."""+ return self.client_type == AbstractApplication.CLIENT_CONFIDENTIAL++ @property+ def token_endpoint_auth_method(self) -> TokenEndpointAuthMethod:+ """Which RFC 7591 method this client authenticates with.++ Derived rather than stored: the client type says whether it authenticates at all, and a+ jwks_uri says it does so with an asymmetric key. Both are registration state, so this is+ never influenced by what a request presents.+ """+ if not self.requires_client_authentication:+ return TokenEndpointAuthMethod.NONE+ if self.jwks_uri:+ return TokenEndpointAuthMethod.PRIVATE_KEY_JWT+ return TokenEndpointAuthMethod.CLIENT_SECRET_POST++ @property+ def uses_client_secret_auth(self) -> bool:+ return self.token_endpoint_auth_method is TokenEndpointAuthMethod.CLIENT_SECRET_POST++ @property+ def uses_private_key_jwt_auth(self) -> bool:+ return self.token_endpoint_auth_method is TokenEndpointAuthMethod.PRIVATE_KEY_JWTclass Meta(AbstractApplication.Meta):verbose_name = "OAuth Application"@@ -299,8 +363,18 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignore# calling super().clean(), which would re-run the redirect validation and reject those native schemes.self._validate_redirect_uris()self._validate_optional_scopes()+ self._validate_client_authentication()self._validate_application_config()+ def _validate_client_authentication(self):+ if self.jwks_uri and not self.jwks_uri.startswith("https://"):+ raise ValidationError("jwks_uri must be an https URL")++ # A public client cannot authenticate, so a key set would never be consulted+ # Rejecting the combination keeps token_endpoint_auth_method unambiguous.+ if self.jwks_uri and not self.requires_client_authentication:+ raise ValidationError("jwks_uri is only meaningful for a confidential client")+def _validate_redirect_uris(self):validator = AllowedURIValidator({scheme.lower() for scheme in self.get_allowed_schemes()},diff --git a/posthog/security/pinned_requests.py b/posthog/security/pinned_requests.pyindex 12e1cbef81b1..5ba7fd9138b0 100644--- a/posthog/security/pinned_requests.py+++ b/posthog/security/pinned_requests.py@@ -26,6 +26,28 @@ class SSRFBlockedError(Exception):"""URL failed SSRF validation. The message is the block reason."""+def select_pinned_ip(+ pinned_ips: set[ipaddress.IPv4Address | ipaddress.IPv6Address],+) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:+ """Choose which validated address to pin, preferring IPv4.++ Pinning replaces the resolver's own address selection, so picking an arbitrary member of the+ set can hand back an AAAA record on a host with no IPv6 route. That fails outright with+ "Network is unreachable" instead of falling back to the A record the way getaddrinfo ordering+ would, which is what happens on IPv4-only CI runners and in IPv4-only clusters. Within a family+ the lowest address wins, so a host with several records pins the same one every time and a+ failure reproduces instead of arriving intermittently as set iteration order shifts.++ Returns None for an empty set, meaning the caller should pin nothing.+ """+ ipv4 = [ip for ip in pinned_ips if ip.version == 4]+ if ipv4:+ return min(ipv4, key=lambda ip: int(ip))+ if pinned_ips:+ return min(pinned_ips, key=lambda ip: int(ip))+ return None++def _canonical_host(hostname: str) -> str:"""Return the host in the same ASCII form ``requests`` connects to.@@ -144,8 +166,9 @@ def pinned_request(adapter = PinnedIPAdapter()hostname = (urlparse.urlparse(url).hostname or "").lower()- if pinned_ips:- adapter.pin(hostname, next(iter(pinned_ips)))+ chosen_ip = select_pinned_ip(pinned_ips)+ if chosen_ip is not None:+ adapter.pin(hostname, chosen_ip)session = requests.Session()session.mount("http://", adapter) # nosemgrep: request-session-with-httpdiff --git a/posthog/security/test/test_pinned_requests.py b/posthog/security/test/test_pinned_requests.pyindex b716fdcebee7..cd23b5eec557 100644--- a/posthog/security/test/test_pinned_requests.py+++ b/posthog/security/test/test_pinned_requests.py@@ -20,6 +20,28 @@ class TestPinnedRequest:session_cls.assert_not_called()+class TestSelectPinnedIP:+ # Pinning replaces the resolver's address selection, so picking an AAAA record when an A+ # record exists strands the request on any IPv4-only host ("Network is unreachable") instead+ # of falling back. That is what IPv4-only CI runners do, and it fails the whole request.+ @pytest.mark.parametrize(+ "ips,expected",+ [+ ({"2600:1f18::1", "93.184.216.34"}, "93.184.216.34"),+ ({"93.184.216.34"}, "93.184.216.34"),+ ({"2600:1f18::1"}, "2600:1f18::1"),+ # Deterministic within a family, so a broken pin reproduces instead of flapping.+ ({"93.184.216.34", "10.1.1.1", "203.0.113.9"}, "10.1.1.1"),+ ],+ )+ def test_prefers_ipv4_and_is_deterministic(self, ips, expected):+ chosen = pr.select_pinned_ip({ipaddress.ip_address(ip) for ip in ips})+ assert chosen == ipaddress.ip_address(expected)++ def test_empty_set_pins_nothing(self):+ assert pr.select_pinned_ip(set()) is None++class TestPinnedIPAdapter:@pytest.mark.parametrize("ip,expected_netloc",diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex 5558261420c7..2dcb2194b4f3 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -2,7 +2,6 @@# name: TestAllTasksRegistered.test_all_posthog_tasks_registered_snapshotlist(['posthog.api.oauth.cimd.refresh_cimd_metadata_task',- 'posthog.api.oauth.cimd.register_cimd_provisioning_application_task','posthog.approvals.tasks.expire_old_change_requests','posthog.approvals.tasks.validate_pending_change_requests','posthog.caching.warming.schedule_warming_for_teams_task',