: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(oauth): store the metadata URL as client_id for CIMD apps (#86100)
Rafael Audibertd58fa914269c
diff --git a/ee/api/agentic_provisioning/throttling.py b/ee/api/agentic_provisioning/throttling.pyindex d08e5aa7bdbc..0d4ca169103b 100644--- a/ee/api/agentic_provisioning/throttling.py+++ b/ee/api/agentic_provisioning/throttling.py@@ -33,7 +33,6 @@ from rest_framework.throttling import BaseThrottlefrom rest_framework.views import APIViewfrom posthog.api.oauth import cimd-from posthog.models.oauth import OAuthApplicationfrom posthog.rate_limit import IPThrottlefrom ee.api.agentic_provisioning.analytics import capture_provisioning_event@@ -182,9 +181,9 @@ class CIMDRegistrationThrottle(BaseThrottle):def allow_request(self, request: Request, view: APIView) -> bool:client_id = request.data.get("client_id") or request.query_params.get("client_id")- if not cimd.is_cimd_client_id(client_id):+ if not client_id or not cimd.is_cimd_client_id(client_id):return True- if OAuthApplication.objects.filter(cimd_metadata_url=client_id).exists():+ if cimd.find_cimd_application(client_id) is not None:return True# Attribute access (not a from-import) so tests patchingdiff --git a/ee/api/agentic_provisioning/views/client_registration.py b/ee/api/agentic_provisioning/views/client_registration.pyindex 522276665fe3..07d0ab691310 100644--- a/ee/api/agentic_provisioning/views/client_registration.py+++ b/ee/api/agentic_provisioning/views/client_registration.py@@ -29,6 +29,7 @@ from posthog.api.oauth.cimd import (CIMDFetchError,CIMDValidationError,fetch_and_upsert_cimd_application,+ find_cimd_application,get_application_by_client_id,is_cimd_client_id,is_cimd_url_blocked,@@ -124,7 +125,7 @@ class ClientRegistrationView(ProvisioningAPIView):# 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()+ existing = find_cimd_application(client_id)try:# 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 namespacediff --git a/posthog/admin/admins/oauth_admin.py b/posthog/admin/admins/oauth_admin.pyindex dd3936cf2eba..b63517792053 100644--- a/posthog/admin/admins/oauth_admin.py+++ b/posthog/admin/admins/oauth_admin.py@@ -13,6 +13,7 @@ from django.utils.html import format_htmlfrom oauth2_provider.generators import generate_client_id, generate_client_secretfrom oauth2_provider.models import AbstractApplication+from posthog.api.oauth.cimd import is_cimd_client_idfrom posthog.models.oauth import OAuthApplication, revoke_application_sessionsfrom posthog.models.oauth_provisioning import UNLIMITED_OVERRIDE, ProvisioningConfig@@ -115,8 +116,26 @@ class OAuthApplicationForm(forms.ModelForm):endpoint = field_name.removeprefix(PROVISIONING_RATE_LIMIT_PREFIX)self.fields[field_name].initial = config.rate_limits.get(endpoint)+ def _reject_cimd_shaped_client_id(self, cleaned: dict) -> None:+ """Keep a URL-form client_id to the CIMD clients that register themselves.++ A CIMD client is identified by its metadata URL, and a metadata refresh writes that+ document's redirect URIs and auth settings onto whichever row carries the URL. An app+ given that shape by hand would take those writes from a document nobody here controls.+ """+ client_id = cleaned.get("client_id")+ if not client_id or self.instance.is_cimd_client:+ return+ if is_cimd_client_id(client_id):+ self.add_error(+ "client_id",+ "A client ID that looks like a URL is reserved for CIMD clients, which register "+ "themselves. Use the generated value, or an ID that is not a URL.",+ )+def clean(self):cleaned = super().clean() or {}+ self._reject_cimd_shaped_client_id(cleaned)for field_name in self._rate_limit_field_names():# 0 is rejected rather than meaning "unlimited": that footgun is why the# unlimited sentinel is -1 (UNLIMITED_OVERRIDE).diff --git a/posthog/admin/test_oauth_admin.py b/posthog/admin/test_oauth_admin.pyindex e7049f701952..1ea7493eedd2 100644--- a/posthog/admin/test_oauth_admin.py+++ b/posthog/admin/test_oauth_admin.py@@ -202,3 +202,42 @@ class TestOAuthApplicationAdmin(BaseTest):app = OAuthApplication(is_cimd_client=is_cimd)readonly = self.admin.get_readonly_fields(request=None, obj=app)assert ("scopes" in readonly) is expected_readonly++ @parameterized.expand(+ [+ ("cimd_url", "https://partner.example.com/.well-known/oauth-client-metadata", True),+ ("opaque", "IqK3fT9vBs2LwQ8xNc4Zr7Hd", False),+ ]+ )+ def test_new_app_cannot_take_a_cimd_shaped_client_id(self, _name, client_id, expects_error):+ # A metadata refresh writes the document's redirect URIs and auth settings onto the row+ # holding that URL. An operator who could type one here would point a partner's document+ # at an app registered by hand.+ request = RequestFactory().get("/")+ request.user = self.user+ form_class = self.admin.get_form(request, None, change=False)+ form = form_class(data={"name": "Manually registered app", "client_id": client_id})+ form.is_valid()+ assert ("client_id" in form.errors) is expects_error++ @parameterized.expand(+ [+ ("add_form", False),+ ("change_form", True),+ ]+ )+ def test_cimd_identity_fields_are_not_editable(self, _name, change):+ # An operator who could turn on is_cimd_client, or set a metadata URL, would hand the+ # next metadata refresh an app that no partner registered.+ app = OAuthApplication(is_cimd_client=False) if change else None+ request = RequestFactory().get("/")+ # A user without change permission gets an empty change form, which would pass this+ # assertion without proving anything.+ self.user.is_staff = True+ request.user = self.user+ form_class = self.admin.get_form(request, app, change=change)+ assert "name" in form_class.base_fields+ editable = [+ name for name in ("is_cimd_client", "is_dcr_client", "cimd_metadata_url") if name in form_class.base_fields+ ]+ assert editable == []diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.pyindex 7d74819dffee..929320c3efb6 100644--- a/posthog/api/oauth/cimd.py+++ b/posthog/api/oauth/cimd.py@@ -672,6 +672,7 @@ def _create_cimd_application(client_type, jwks_uri = _resolve_client_authentication(metadata, allow_confidential=allow_confidential)app = OAuthApplication(+ client_id=url,name=client_name,redirect_uris=redirect_uris,client_type=client_type,@@ -897,7 +898,7 @@ def fetch_and_upsert_cimd_application(metadata, cache_ttl = fetch_cimd_metadata(url)cache.set(_cache_key(url), True, timeout=cache_ttl)- app = OAuthApplication.objects.filter(cimd_metadata_url=url).first()+ app = find_cimd_application(url)if app:updated = _update_cimd_application(app,@@ -948,7 +949,7 @@ def fetch_and_upsert_cimd_application()return new_appexcept (IntegrityError, ValidationError):- app = OAuthApplication.objects.filter(cimd_metadata_url=url).first()+ app = find_cimd_application(url)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@@ -983,7 +984,7 @@ def get_or_create_cimd_application(url: str) -> OAuthApplication:- No app: fetch synchronously (must have the app before proceeding)"""# Existing client: check cache freshness and if not fresh, fire refresh in the background, returning existing app immediately- if app := OAuthApplication.objects.filter(cimd_metadata_url=url).first():+ if app := find_cimd_application(url):enqueue_cimd_refresh_if_stale(url)return app@@ -995,7 +996,7 @@ def get_or_create_cimd_application(url: str) -> OAuthApplication:# Poll the DB until it appears or we give up.for _ in range(CIMD_FETCH_TIMEOUT_SECONDS + 1):time.sleep(1)- app = OAuthApplication.objects.filter(cimd_metadata_url=url).first()+ app = find_cimd_application(url)if app:return app@@ -1020,6 +1021,19 @@ def enqueue_cimd_refresh_if_stale(url: str) -> None:refresh_cimd_metadata_task.delay(url)+def find_cimd_application(url: str) -> OAuthApplication | None:+ """Resolve a CIMD URL-form client_id to its application, or None.++ Reads ``client_id``, which is where a CIMD client's URL now lands on registration,+ and falls back to ``cimd_metadata_url`` for the rows registered before that. Both+ columns are written on create, so the fallback only ever serves older rows, until+ the backfill moves them over."""+ return (+ OAuthApplication.objects.filter(client_id=url).first()+ or OAuthApplication.objects.filter(cimd_metadata_url=url).first()+ )++def get_application_by_client_id(client_id: str) -> OAuthApplication:"""Look up an OAuthApplication by client_id, supporting CIMD URL-form client_ids.@@ -1027,7 +1041,10 @@ def get_application_by_client_id(client_id: str) -> OAuthApplication:Raises OAuthApplication.DoesNotExist if not found."""if is_cimd_client_id(client_id):- return OAuthApplication.objects.get(cimd_metadata_url=client_id)+ app = find_cimd_application(client_id)+ if app is None:+ raise OAuthApplication.DoesNotExist+ return appreturn OAuthApplication.objects.get(client_id=client_id)diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.pyindex 5aacabacd535..d7aa19305116 100644--- a/posthog/api/oauth/test_cimd.py+++ b/posthog/api/oauth/test_cimd.py@@ -326,6 +326,7 @@ class TestFetchAndUpsertCimdApplication(APIBaseTest):assert app is not Noneself.assertTrue(app.is_cimd_client)self.assertFalse(app.is_dcr_client)+ self.assertEqual(app.client_id, VALID_CIMD_URL)self.assertEqual(app.cimd_metadata_url, VALID_CIMD_URL)self.assertEqual(app.name, "Test MCP Client")self.assertEqual(app.redirect_uris, "http://127.0.0.1:3000/callback")diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex b0aa84d732d2..29da33ab25be 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -47,6 +47,7 @@ from posthog.api.oauth.cimd import (CIMDFetchError,CIMDValidationError,enqueue_cimd_refresh_if_stale,+ find_cimd_application,get_application_by_client_id,get_or_create_cimd_application,is_cimd_client_id,@@ -387,7 +388,6 @@ class OAuthValidator(OAuth2Validator):"""Load the application from the database, supporting CIMD URL-form client_ids.- For URL-format client_ids, looks up by cimd_metadata_url.Does NOT fetch metadata — that only happens in validate_client_id()."""@@ -397,10 +397,9 @@ class OAuthValidator(OAuth2Validator):if request.client:return request.client- # CIMD URLs are looked up by cimd_metadata_url, not the auto-generated client_id UUIDapp: OAuthApplication | None = Noneif is_cimd_client_id(client_id):- app = OAuthApplication.objects.filter(cimd_metadata_url=client_id).first()+ app = find_cimd_application(client_id)else:app = OAuthApplication.objects.filter(client_id=client_id).first()@@ -1298,7 +1297,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):# Must happen here (not in the OAuthValidator) because the validator# only receives an oauthlib Request which lacks request.META for IP extraction.client_id = request.query_params.get("client_id")- if is_cimd_client_id(client_id) and not OAuthApplication.objects.filter(cimd_metadata_url=client_id).exists():+ if is_cimd_client_id(client_id) and find_cimd_application(client_id) is None:for throttle_cls in CIMD_THROTTLE_CLASSES:throttle = throttle_cls()if not throttle.allow_request(request, view=self):