: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
fix(provisioning): gate partner registration on the client's own opt-in (#83980)
Rafael Audibertcba4cdbc83d4
diff --git a/ee/api/agentic_provisioning/test/test_client_registration.py b/ee/api/agentic_provisioning/test/test_client_registration.pyindex caf3909d7d0c..d98c9c5bfe58 100644--- a/ee/api/agentic_provisioning/test/test_client_registration.py+++ b/ee/api/agentic_provisioning/test/test_client_registration.py@@ -25,6 +25,8 @@ KID = "reg-key"KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)+_DECLARES_PROVISIONING = {"provisioning": True}+def _jwks() -> dict:jwk = json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(KEY.public_key()))@@ -45,10 +47,11 @@ class TestClientRegistration(ProvisioningTestBase):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 = {+ def _document(self, *, com_posthog: object = _DECLARES_PROVISIONING) -> dict:+ """The document a client wanting to register publishes. Passing com_posthog=None leaves+ the namespace out, which is the shape of a third party that never asked for any of+ this."""+ document: dict[str, object] = {"client_id": CIMD_URL,"client_name": "New Partner","redirect_uris": ["https://newpartner.example.com/callback"],@@ -57,6 +60,21 @@ class TestClientRegistration(ProvisioningTestBase):"token_endpoint_auth_method": "private_key_jwt","jwks_uri": JWKS_URI,}+ if com_posthog is not None:+ document["com.posthog"] = com_posthog+ return document++ def _register(+ self,+ body: dict,+ *,+ document: dict | None = None,+ 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 = document if document is not None else self._document()metadata_patch = (patch("posthog.api.oauth.cimd.fetch_client_json_document",@@ -234,6 +252,69 @@ class TestClientRegistration(ProvisioningTestBase):assert app.is_provisioning_partnerassert app.provisioning.active+ @parameterized.expand(+ [+ ("no_com_posthog_namespace", None),+ ("declares_false", {"provisioning": False}),+ # A truthy string is a malformed declaration, not consent: reading it as one would+ # grant a stranger the capabilities off someone else's typo.+ ("declares_a_truthy_string", {"provisioning": "true"}),+ ]+ )+ def test_a_document_that_does_not_opt_in_is_not_promoted(self, _name, com_posthog):+ # A CIMD client_id is a public URL, so anyone can name a third party's OAuth client+ # here. Promoting it would hand the caller that client's identity and account-request+ # quota, and flip the client's own token exchanges onto private_key_jwt, which its+ # runtime may never send.+ self._make_partner(+ is_provisioning_partner=False,+ client_type=OAuthApplication.CLIENT_PUBLIC,+ jwks_uri=None,+ _provisioning_config=provisioning_config(active=False, can_create_accounts=False),+ )++ res = self._register({"client_id": CIMD_URL}, document=self._document(com_posthog=com_posthog))++ assert res.status_code == 400, res.json()+ checks = {check["name"]: check for check in res.json()["checks"]}+ assert checks["provisioning_enabled"]["ok"] is False+ assert '"com.posthog": {"provisioning": true}' in checks["provisioning_enabled"]["detail"]+ app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_URL)+ assert app.is_provisioning_partner is False+ assert app.provisioning.can_create_accounts is False+ assert app.client_type == OAuthApplication.CLIENT_PUBLIC++ def test_a_document_we_could_not_store_is_not_promoted(self):+ # A rejected save leaves the row describing the previous document. Promoting off it+ # would grant provisioning, and derive client_type from a stored key set, that the+ # client's current document does not describe, while the response called the fetch fine.+ self._make_partner(+ is_provisioning_partner=False,+ client_type=OAuthApplication.CLIENT_PUBLIC,+ jwks_uri=None,+ _provisioning_config=provisioning_config(active=False, can_create_accounts=False),+ )+ document = self._document()+ # Passes CIMD document validation, which does not look at fragments, and is refused by+ # the model.+ document["redirect_uris"] = ["https://newpartner.example.com/callback#fragment"]++ res = self._register({"client_id": CIMD_URL}, document=document)++ assert res.status_code == 400, res.json()+ checks = {check["name"]: check for check in res.json()["checks"]}+ assert checks["metadata_document"]["ok"] is False+ assert "fragment not allowed" in checks["metadata_document"]["detail"]+ # The opt-in may well be in the document we refused, so the answer points at the+ # rejection rather than sending the client's owner after a key they already published.+ assert '"com.posthog"' not in checks["provisioning_enabled"]["detail"]+ assert "metadata_document" in checks["provisioning_enabled"]["detail"]+ app = OAuthApplication.objects.get(cimd_metadata_url=CIMD_URL)+ assert app.is_provisioning_partner is False+ assert app.provisioning.can_create_accounts is False+ assert app.client_type == OAuthApplication.CLIENT_PUBLIC+ assert app.redirect_uris == "https://newpartner.example.com/callback"+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 fordiff --git a/ee/api/agentic_provisioning/test/test_provisioning_auth.py b/ee/api/agentic_provisioning/test/test_provisioning_auth.pyindex 5b7d9ec72920..6d8f6431d8da 100644--- a/ee/api/agentic_provisioning/test/test_provisioning_auth.py+++ b/ee/api/agentic_provisioning/test/test_provisioning_auth.py@@ -7,12 +7,7 @@ from django.core.cache import cache as real_cachefrom parameterized import parameterized-from posthog.api.oauth.cimd import (- _blocked_key,- _cache_key,- apply_provisioning_defaults,- fetch_and_upsert_cimd_application,-)+from posthog.api.oauth.cimd import _blocked_key, _cache_key, fetch_and_upsert_cimd_applicationfrom posthog.models.oauth import OAuthApplicationfrom posthog.models.oauth_provisioning import ProvisioningRateLimitsfrom posthog.models.personal_api_key import PersonalAPIKey@@ -421,6 +416,7 @@ def _make_cimd_metadata(url: str = CIMD_PROV_URL, **overrides) -> dict:"grant_types": ["authorization_code"],"response_types": ["code"],"token_endpoint_auth_method": "none",+ "com.posthog": {"provisioning": True},}metadata.update(overrides)return metadata@@ -446,10 +442,11 @@ class TestCimdProvisioningRegistration(ProvisioningTestBase):real_cache.clear()def _register(self) -> OAuthApplication:- """Register the partner the way client_registration does."""- app = fetch_and_upsert_cimd_application(CIMD_PROV_URL)+ """Register the partner the way client_registration does, so the promotion depends on+ the mocked document declaring the opt-in."""+ app = fetch_and_upsert_cimd_application(CIMD_PROV_URL, register_provisioning=True)assert app is not None- return apply_provisioning_defaults(app)+ return app@patch("posthog.api.oauth.cimd.requests.Session.get")def test_registered_cimd_partner_can_create_accounts(self, mock_get, _url_mock):@@ -480,7 +477,7 @@ class TestCimdProvisioningRegistration(ProvisioningTestBase):@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):initial = _make_cimd_metadata()- initial["com.posthog"] = {"scopes": ["insight:read"]}+ initial["com.posthog"] = {"provisioning": True, "scopes": ["insight:read"]}mock_get.return_value = _cimd_mock_response(initial)self._register()@@ -490,7 +487,7 @@ class TestCimdProvisioningRegistration(ProvisioningTestBase):# Partner edits the live metadata to widen the ceiling; the cached doc goes stale.real_cache.delete(_cache_key(CIMD_PROV_URL))widened = _make_cimd_metadata()- widened["com.posthog"] = {"scopes": ["insight:read", "dashboard:read"]}+ widened["com.posthog"] = {"provisioning": True, "scopes": ["insight:read", "dashboard:read"]}mock_get.return_value = _cimd_mock_response(widened)# A later agentic provisioning auth request must propagate the edit — the bug was thatdiff --git a/ee/api/agentic_provisioning/views/client_registration.py b/ee/api/agentic_provisioning/views/client_registration.pyindex a539ab227b74..522276665fe3 100644--- a/ee/api/agentic_provisioning/views/client_registration.py+++ b/ee/api/agentic_provisioning/views/client_registration.py@@ -8,10 +8,14 @@ individually so a broken setup names its own cause instead of surfacing as a barDeliberately unauthenticated: a partner that has not registered yet has no credential topresent, 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.+What that exposes is bounded on two counts. 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. The capabilities that registration grants come+from the fetched document declaring the opt-in, never from the request, so the caller decides+which client_id we look at and nothing else. Without that, sending a third party's client_id+would be enough to conscript its OAuth client into a provisioning partner, since a CIMD+client_id is a public URL and a public client's only credential is that same URL."""from __future__ import annotations@@ -24,7 +28,6 @@ from rest_framework.response import Responsefrom posthog.api.oauth.cimd import (CIMDFetchError,CIMDValidationError,- apply_provisioning_defaults,fetch_and_upsert_cimd_application,get_application_by_client_id,is_cimd_client_id,@@ -122,29 +125,32 @@ class ClientRegistrationView(ProvisioningAPIView):# 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 | Nonetry:- app = fetch_and_upsert_cimd_application(client_id)+ # A CIMD client that has never been used for provisioning carries no provisioning+ # config yet, and this is the call that gives it one, so the rest of the namespace+ # becomes reachable. The upsert only opts the client in if the document it just+ # fetched declares it, which is why the promotion lives with the fetch rather than+ # here: this request cannot show that its sender owns the client_id it named.+ app = fetch_and_upsert_cimd_application(client_id, register_provisioning=True)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 document we could not read or could not store leaves the row describing an+ # older one, so a client that is not already a partner stays one short of+ # registered until a document we can act on arrives.+ return self._require_partner(existing, checks, document_read=False)+ _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:+ def _require_partner(+ self, app: OAuthApplication, checks: list[dict[str, Any]], *, document_read: bool = True+ ) -> OAuthApplication | None:if not app.is_provisioning_partner:- _record(checks, "provisioning_enabled", False, "This client is not enabled for agentic provisioning")+ _record(checks, "provisioning_enabled", False, _not_a_partner_detail(app, document_read=document_read))return Noneif not app.provisioning.active:_record(checks, "provisioning_enabled", False, "Provisioning is deactivated for this client")@@ -180,6 +186,33 @@ class ClientRegistrationView(ProvisioningAPIView):_record(checks, "client_assertion", True, "Verified, and its jti is now consumed")+def _not_a_partner_detail(app: OAuthApplication, *, document_read: bool) -> str:+ """Why this client is not a provisioning partner, in terms of what its owner can change.++ A CIMD client registers by publishing the opt-in, so the detail has to name the key. The+ caller may not be the client's owner, but nothing here is a secret: the key is documented,+ and the document it goes in is public by construction.++ ``document_read`` is False when this answer rests on a stored row rather than the document+ the client publishes now, which is a different situation to report: the key may well be+ there already, and telling its owner to add it would send them after a problem they fixed.+ """+ if app.provisioning.disabled:+ return "Provisioning is blocked for this client. Contact PostHog support if that is unexpected."+ if app.is_cimd_client and not document_read:+ return (+ "This client is not registered for agentic provisioning, and its metadata document "+ "could not be read to check for the opt-in. Fix the error in the metadata_document "+ "check, then register again."+ )+ if app.is_cimd_client:+ return (+ "This client is not enabled for agentic provisioning. Add "+ '"com.posthog": {"provisioning": true} to your client metadata document, then register again.'+ )+ return "This client is not enabled for agentic provisioning"++def _record(checks: list[dict[str, Any]], name: str, ok: bool, detail: str) -> None:checks.append({"name": name, "ok": ok, "detail": detail})diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.pyindex 4d5fb4ce0518..5adda93be2c1 100644--- a/posthog/api/oauth/cimd.py+++ b/posthog/api/oauth/cimd.py@@ -16,7 +16,7 @@ from typing import TYPE_CHECKING, TypedDict, castfrom urllib.parse import urlparsefrom django.core.cache import cache-from django.core.exceptions import ValidationError+from django.core.exceptions import NON_FIELD_ERRORS, ValidationErrorfrom django.db import IntegrityError, transactionfrom django.utils import timezone@@ -116,6 +116,7 @@ CIMD_THROTTLE_CLASSES: list[type[SimpleRateThrottle]] = [CIMDBurstThrottle, CIMDclass ComPostHogNamespace(TypedDict, total=False):verification_token: strscopes: list[str]+ provisioning: bool# Functional form required: "com.posthog" is not a valid Python identifier.@@ -593,6 +594,26 @@ def _resolve_optional_scopes(metadata: CIMDMetadataDocument) -> list[str] | Nonereturn filter_to_unprivileged_scopes(raw_optional)+def _cimd_declares_provisioning(metadata: CIMDMetadataDocument) -> bool:+ """Whether the document opts its client into being an agentic provisioning partner.++ This is the proof of control that registration turns on. A CIMD client_id is a public+ HTTPS URL that appears in /authorize query strings and in the client's own documentation,+ so a request naming one says nothing about who sent it; the document served from that URL+ is the one thing only its owner can change. Requiring the declaration here is what keeps a+ stranger from conscripting a third party's OAuth client into a provisioning partner, which+ would hand the caller that client's identity and account-request quota, and would flip the+ client's own token exchanges onto an auth method it never agreed to send.++ Strictly ``True``: a truthy string or a non-empty dict is a malformed declaration, and+ treating one as consent would grant capabilities off a typo.+ """+ com_posthog = metadata.get("com.posthog")+ if not isinstance(com_posthog, dict):+ return False+ return com_posthog.get("provisioning") is True++def _resolve_client_authentication(metadata: CIMDMetadataDocument, *, allow_confidential: bool) -> tuple[str, str | None]:@@ -719,11 +740,27 @@ def _retier_account_requests_limit(app: OAuthApplication, *, verified: bool) ->)+def _describe_validation_error(error: ValidationError) -> str:+ """Flatten a model ValidationError into one line a partner can act on.++ Field names are safe to name: every field the update writes comes from the document itself,+ which is public by construction.+ """+ error_dict = getattr(error, "message_dict", None)+ if not error_dict:+ return " ".join(error.messages)+ return "; ".join(+ " ".join(messages) if field == NON_FIELD_ERRORS else f"{field}: {' '.join(messages)}"+ for field, messages in error_dict.items()+ )++def _update_cimd_application(app: OAuthApplication,metadata: CIMDMetadataDocument,*,allow_confidential: bool = False,+ strict: bool = False,capture_ph_event: CapturePhEvent = posthoganalytics.capture,) -> OAuthApplication:"""@@ -731,6 +768,14 @@ def _update_cimd_application(On validation failure, refreshes from the database so the caller neversees a partially-mutated in-memory object.++ ``strict=True`` turns that rejection into a ``CIMDValidationError`` instead of a kept row.+ Registration asks for it, because a rejected save leaves the row describing an older+ document, and everything registration then decides - the provisioning promotion, the+ client_type it derives from the stored key set, the response it reports - would describe+ metadata the client no longer publishes, with the caller told the fetch succeeded. Every+ other caller leaves it False: a refresh that cannot store a document is a partner keeping+ the config it last published, not a reason to break it."""client_name = metadata.get("client_name")if client_name:@@ -790,6 +835,8 @@ def _update_cimd_application(capture_exception(e)# Refresh from DB so we don't return a mutated-but-unsaved objectapp.refresh_from_db()+ if strict:+ raise CIMDValidationError(f"Metadata document was rejected: {_describe_validation_error(e)}") from eelse:if verification is not None:_touch_verification_token(verification)@@ -818,11 +865,36 @@ def _update_cimd_application(return app+def _register_partner_if_declared(+ app: OAuthApplication, metadata: CIMDMetadataDocument, *, register_provisioning: bool+) -> None:+ """Opt a CIMD client into provisioning when its own document asks for it.++ Both conditions are required. ``register_provisioning`` says the caller is the registration+ endpoint, and the declaration says the client wants this, which is the part a stranger+ cannot supply. Kept next to the fetch because this is the only point where the document and+ the row it was written to are both in hand: nothing on the app records what the document+ declared, so a caller further out would have to take the request's word for it.++ Already-registered partners are left alone, so re-registering can neither reinstate a+ partner an admin deactivated nor re-apply the defaults over its current config. The check+ here only saves the lock; ``apply_provisioning_defaults`` repeats it on the locked row,+ which is what settles a registration racing an admin promoting the same client.+ """+ if not register_provisioning or app.is_provisioning_partner:+ return+ if not _cimd_declares_provisioning(metadata):+ return+ apply_provisioning_defaults(app)+ app.refresh_from_db()++def fetch_and_upsert_cimd_application(url: str,capture_ph_event: CapturePhEvent = posthoganalytics.capture,*,allow_confidential: bool = False,+ register_provisioning: bool = False,) -> OAuthApplication | None:"""Fetch CIMD metadata and create or update the application.@@ -839,6 +911,15 @@ def fetch_and_upsert_cimd_application(for the next hourly refresh to notice ``is_provisioning_partner`` has since flipped. Everyother caller leaves this False; an already-registered partner still promotes on refresh viaits persisted ``is_provisioning_partner``, independent of this flag.++ ``register_provisioning=True`` marks the call the client-registration endpoint makes, which+ is the only place a CIMD client becomes a provisioning partner. The flag alone does not+ grant anything: the freshly fetched document also has to declare the opt-in, so the+ capabilities follow the client's published intent rather than whoever sent the request. The+ ordinary /authorize and background-refresh paths leave it False, so registration stays an+ explicit act at one endpoint instead of a side effect of any fetch. It also makes a document+ that fails model validation a ``CIMDValidationError`` rather than a kept row, so nothing is+ granted off metadata we could not store; see ``_update_cimd_application``."""if is_cimd_url_blocked(url):logger.warning("cimd_blocked_url_fetch_attempt", url=url)@@ -855,9 +936,14 @@ def fetch_and_upsert_cimd_application(app = OAuthApplication.objects.filter(cimd_metadata_url=url).first()if app:updated = _update_cimd_application(- app, metadata, allow_confidential=allow_confidential, capture_ph_event=capture_ph_event+ app,+ metadata,+ allow_confidential=allow_confidential,+ strict=register_provisioning,+ capture_ph_event=capture_ph_event,)logger.debug("cimd_app_updated", url=url, app_id=str(updated.pk))+ _register_partner_if_declared(updated, metadata, register_provisioning=register_provisioning)capture_ph_event(distinct_id=url,event="cimd_application_metadata_refreshed",@@ -877,6 +963,7 @@ def fetch_and_upsert_cimd_application(url, metadata, allow_confidential=allow_confidential, capture_ph_event=capture_ph_event)logger.debug("cimd_app_created", url=url, app_id=str(new_app.pk), client_name=new_app.name)+ _register_partner_if_declared(new_app, metadata, register_provisioning=register_provisioning)capture_ph_event(distinct_id=url,event="cimd_application_created",@@ -900,6 +987,9 @@ def fetch_and_upsert_cimd_application(app = OAuthApplication.objects.filter(cimd_metadata_url=url).first()if app:logger.debug("cimd_app_race_resolved", url=url, app_id=str(app.pk))+ # The row a concurrent caller won the race with was written from this same+ # document, so the declaration in it still speaks for this client.+ _register_partner_if_declared(app, metadata, register_provisioning=register_provisioning)return appraisefinally:@@ -1031,13 +1121,15 @@ def _cimd_provisioning_defaults_for(app: OAuthApplication) -> "ProvisioningConfidef apply_provisioning_defaults(app: OAuthApplication) -> OAuthApplication:"""Opt a CIMD app into provisioning with the self-serve defaults, and persist them.- Respects the `disabled` kill switch - returns the app untouched rather than re-enabling a- partner an admin has explicitly disabled.+ Only ever promotes a client that is not a partner yet, and respects the `disabled` kill+ switch: an app that is either already registered or explicitly disabled comes back untouched,+ rather than having the defaults laid over the config it has now.- Locks and re-reads the config first. Registration runs after a network fetch of the metadata- document, so the caller's copy of the app can be seconds or minutes old, and layering the- defaults over that copy would write back a capability - or a cleared kill switch - that an- admin revoked while the fetch was in flight.+ Both of those are decided on the locked row, not the caller's. Registration runs after a+ network fetch of the metadata document, so the copy it hands in can be seconds or minutes+ old, and an admin can promote and restrict the client inside that window. Deciding from the+ stale copy would write back a capability - or a cleared kill switch - that the admin revoked+ while the fetch was in flight.Promotion to confidential happens in the same write. A partner that publishes a key set hasto present an assertion, and the bare-client_id path stays open to a public app, so an app@@ -1048,9 +1140,13 @@ def apply_provisioning_defaults(app: OAuthApplication) -> OAuthApplication:with transaction.atomic():current = OAuthApplication.objects.select_for_update().get(pk=app.pk)app._provisioning_config = current._provisioning_config+ if current.is_provisioning_partner:+ # Registered since the caller read the row, so this is no longer the promotion it+ # looked like then, and the defaults would land on top of a config an admin set.+ app.is_provisioning_partner = True+ return appif app.provisioning.disabled:return app- became_partner = not current.is_provisioning_partnerapp.is_provisioning_partner = Trueapp.provisioning = _cimd_provisioning_defaults_for(app)updated_fields = ["is_provisioning_partner", "_provisioning_config"]@@ -1060,20 +1156,18 @@ def apply_provisioning_defaults(app: OAuthApplication) -> OAuthApplication:updated_fields.append("client_type")app.save(update_fields=updated_fields)- # 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=app.cimd_metadata_url or str(app.pk),- event="cimd_provisioning_partner_registered",- properties={- "cimd_url": app.cimd_metadata_url,- "client_name": app.name,- "app_id": str(app.pk),- "account_requests_rate_limit": app.provisioning.rate_limits.account_requests,- "is_verified": app.organization_id is not None,- "organization_id": str(app.organization_id) if app.organization_id else None,- },- )+ # A partner appearing without an admin creating it is the event worth watching for abuse.+ # Only the promotion reaches here, so it fires on the transition and nowhere else.+ posthoganalytics.capture(+ distinct_id=app.cimd_metadata_url or str(app.pk),+ event="cimd_provisioning_partner_registered",+ properties={+ "cimd_url": app.cimd_metadata_url,+ "client_name": app.name,+ "app_id": str(app.pk),+ "account_requests_rate_limit": app.provisioning.rate_limits.account_requests,+ "is_verified": app.organization_id is not None,+ "organization_id": str(app.organization_id) if app.organization_id else None,+ },+ )return appdiff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.pyindex 7677550cf915..621718aacbcd 100644--- a/posthog/api/oauth/test_cimd.py+++ b/posthog/api/oauth/test_cimd.py@@ -79,7 +79,9 @@ def _captured_events(mock_capture) -> 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."""+ """Register a CIMD app and opt it into provisioning, skipping the document declaration the+ registration endpoint requires, so a test that is about a partner's config does not also+ have to publish one."""app = fetch_and_upsert_cimd_application(url)assert app is not Nonereturn apply_provisioning_defaults(app)@@ -644,6 +646,28 @@ class TestApplyProvisioningDefaults(APIBaseTest):CIMD_PROVISIONING_ACCOUNT_REQUESTS_DEFAULT_RATE_LIMIT,)+ @parameterized.expand(+ [+ ("registration_call", True, True),+ # The /authorize and background-refresh paths read the same document. Promoting+ # there would grant the capabilities outside the registration endpoint, so past its+ # per-client_id, per-IP and per-domain throttles, and on a request the client did+ # not make.+ ("ordinary_fetch", False, False),+ ]+ )+ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_only_the_registration_call_promotes_a_declaring_document(+ self, _name, register_provisioning, expected_partner, mock_get, _url_mock+ ):+ mock_get.return_value = _mock_response(_make_metadata(com_posthog={"provisioning": True}), headers={})++ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL, register_provisioning=register_provisioning)++ assert app is not None+ self.assertEqual(app.is_provisioning_partner, expected_partner)+ self.assertEqual(app.provisioning.can_create_accounts, expected_partner)+@patch("posthog.api.oauth.cimd.posthoganalytics.capture")@patch("posthog.api.oauth.cimd.requests.Session.get")def test_registration_event_fires_once_on_the_transition(self, mock_get, mock_capture, _url_mock):@@ -676,6 +700,25 @@ class TestApplyProvisioningDefaults(APIBaseTest):self.assertFalse(app.is_provisioning_partner)self.assertNotIn("cimd_provisioning_partner_registered", _captured_events(mock_capture))+ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_registration_does_not_overwrite_a_partner_created_mid_fetch(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+ # An admin registers and restricts the client through a separate row read, the way it+ # looks to a registration whose metadata fetch overlapped the edit. `existing` still+ # says non-partner, so only the locked read can tell the defaults not to land.+ admin_copy = OAuthApplication.objects.get(pk=existing.pk)+ admin_copy.is_provisioning_partner = True+ admin_copy.save(update_fields=["is_provisioning_partner"])+ admin_copy.update_provisioning(active=False, can_create_accounts=False)++ app = apply_provisioning_defaults(existing)++ app.refresh_from_db()+ self.assertFalse(app.provisioning.active)+ self.assertFalse(app.provisioning.can_create_accounts)+@patch("posthog.api.oauth.cimd.requests.Session.get")def test_registration_does_not_restore_a_capability_revoked_mid_fetch(self, mock_get, _url_mock):mock_get.return_value = _mock_response(_make_metadata(), headers={})diff --git a/posthog/api/oauth/test_wizard_metadata.py b/posthog/api/oauth/test_wizard_metadata.pyindex 3b9f7696f456..9827199fbf6c 100644--- a/posthog/api/oauth/test_wizard_metadata.py+++ b/posthog/api/oauth/test_wizard_metadata.py@@ -14,6 +14,7 @@ class TestWizardClientMetadataView(SimpleTestCase):assert data["grant_types"] == ["authorization_code"]assert data["response_types"] == ["code"]assert data["token_endpoint_auth_method"] == "none"+ assert data["com.posthog"] == {"provisioning": True}def test_client_id_matches_hosted_path(self):res = self.client.get("/api/oauth/wizard/client-metadata")diff --git a/posthog/api/oauth/wizard_metadata.py b/posthog/api/oauth/wizard_metadata.pyindex 7045dc242580..688ccc58e6b1 100644--- a/posthog/api/oauth/wizard_metadata.py+++ b/posthog/api/oauth/wizard_metadata.py@@ -25,6 +25,7 @@ class WizardClientMetadataView(View):"grant_types": ["authorization_code"],"response_types": ["code"],"token_endpoint_auth_method": "none",+ "com.posthog": {"provisioning": True},}response = JsonResponse(metadata)