: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): CIMD com.posthog namespace for verification_token + scopes (#61759)
Matt Brookerfc7fd49462cd
diff --git a/posthog/admin/admins/oauth_admin.py b/posthog/admin/admins/oauth_admin.pyindex 29795fb9996d..b124a697811c 100644--- a/posthog/admin/admins/oauth_admin.py+++ b/posthog/admin/admins/oauth_admin.py@@ -111,7 +111,14 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-nedef get_readonly_fields(self, request, obj=None):if obj:- return ("id", "client_id", "is_dcr_client", "is_cimd_client", "cimd_metadata_url")+ readonly = ["id", "client_id", "is_dcr_client", "is_cimd_client", "cimd_metadata_url"]+ if obj.is_cimd_client:+ # A CIMD client's scope ceiling is derived from its own metadata document and+ # re-applied on every refresh, so a manual edit here would be silently reverted.+ # The unprivileged/hidden allow-list is the only ceiling that applies to CIMD+ # apps; to cut off an abusive one, block its metadata URL rather than editing scopes.+ readonly.append("scopes")+ return tuple(readonly)else:return ("id", "is_dcr_client", "is_cimd_client")diff --git a/posthog/admin/test_oauth_admin.py b/posthog/admin/test_oauth_admin.pyindex a9b8b3140c1b..18a910fab10a 100644--- a/posthog/admin/test_oauth_admin.py+++ b/posthog/admin/test_oauth_admin.py@@ -37,3 +37,14 @@ class TestOAuthApplicationAdmin(BaseTest):form = OAuthApplicationForm()assert "Only used for HMAC provisioning partners" in form.fields["provisioning_signing_secret"].help_text++ @parameterized.expand(+ [+ ("cimd_app", True, True),+ ("regular_app", False, False),+ ]+ )+ def test_scopes_readonly_only_for_cimd_apps(self, _name, is_cimd, expected_readonly):+ app = OAuthApplication(is_cimd_client=is_cimd)+ readonly = self.admin.get_readonly_fields(request=None, obj=app)+ assert ("scopes" in readonly) is expected_readonlydiff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.pyindex b30a2849b1e7..5aac1ae7fd6d 100644--- a/posthog/api/oauth/cimd.py+++ b/posthog/api/oauth/cimd.py@@ -35,6 +35,7 @@ from posthog.models.oauth import ()from posthog.ph_client import ph_scoped_capturefrom posthog.rate_limit import IPThrottle+from posthog.scopes import UNPRIVILEGED_SCOPESfrom posthog.security.url_validation import is_url_allowedfrom .dcr import validate_client_name@@ -93,18 +94,29 @@ class CIMDGlobalThrottle(SimpleRateThrottle):CIMD_THROTTLE_CLASSES: list[type[SimpleRateThrottle]] = [CIMDBurstThrottle, CIMDSustainedThrottle, CIMDGlobalThrottle]-class CIMDMetadataDocument(TypedDict, total=False):- client_id: str- client_name: str- redirect_uris: list[str]- logo_uri: str- grant_types: list[str]- response_types: list[str]- token_endpoint_auth_method: str- # Optional PostHog extension: if present, PostHog will look up the token- # and link this CIMD app to the owning organization. Verified partners get- # a higher default rate limit and an identity trail for abuse response.- posthog_verification_token: str+class ComPostHogNamespace(TypedDict, total=False):+ verification_token: str+ scopes: list[str]+++# Functional form required: "com.posthog" is not a valid Python identifier.+CIMDMetadataDocument = TypedDict(+ "CIMDMetadataDocument",+ {+ "client_id": str,+ "client_name": str,+ "redirect_uris": list[str],+ "logo_uri": str,+ "grant_types": list[str],+ "response_types": list[str],+ "token_endpoint_auth_method": str,+ # Legacy top-level token — still read for backwards compatibility.+ "posthog_verification_token": str,+ # Preferred namespace — takes precedence over the legacy top-level key.+ "com.posthog": ComPostHogNamespace,+ },+ total=False,+)def validate_cimd_url(url: str | None, *, perform_dns_check: bool = False) -> tuple[bool, str | None]:@@ -311,14 +323,47 @@ def fetch_cimd_metadata(url: str) -> tuple[CIMDMetadataDocument, int]:def _resolve_verification_token(metadata: CIMDMetadataDocument) -> CIMDVerificationToken | None:- """Look up a CIMD metadata `posthog_verification_token`. Returns the token- record (with its organization) on match, or None if missing or invalid."""+ """Look up a verification token from CIMD metadata, preferring the nested+ `com.posthog.verification_token` and falling back to the legacy top-level+ `posthog_verification_token`. Falls back to the top-level token when the nested+ one is absent OR present-but-unrecognized, so a typo'd nested token doesn't drop+ a partner whose legacy token still resolves. Returns the token record, or None."""+ com_posthog = metadata.get("com.posthog")+ if isinstance(com_posthog, dict):+ nested_raw = com_posthog.get("verification_token")+ if nested_raw and isinstance(nested_raw, str):+ token = find_cimd_verification_token(nested_raw)+ if token is not None:+ return token+raw = metadata.get("posthog_verification_token")if not raw or not isinstance(raw, str):return Nonereturn find_cimd_verification_token(raw)+def _resolve_scopes(metadata: CIMDMetadataDocument) -> list[str] | None:+ """Read com.posthog.scopes if present, keeping only legitimately user-grantable scopes.++ Uses an allow-list (UNPRIVILEGED_SCOPES) rather than a deny-list so that+ privileged, hidden, internal, and unknown/garbage scope strings are all+ dropped in one check. Mirrors the DCR scope filter on #61225 — consolidate+ with filter_dcr_scopes once that PR merges to master.++ Returns None when the field is absent — callers treat that as a no-op+ (leave existing scopes untouched). Returns a (possibly empty) list when+ the field is present, even after non-grantable entries are filtered out.+ """+ com_posthog = metadata.get("com.posthog")+ if not isinstance(com_posthog, dict):+ return None+ # Untrusted partner JSON: the TypedDict says list[str], but guard the real type.+ raw_scopes: object = com_posthog.get("scopes")+ if not isinstance(raw_scopes, list):+ return None+ return [s for s in raw_scopes if isinstance(s, str) and s in UNPRIVILEGED_SCOPES]++def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthApplication:"""Create a new OAuthApplication from CIMD metadata."""client_name = metadata.get("client_name", "CIMD Client")@@ -330,6 +375,7 @@ def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthAredirect_uris = " ".join(metadata.get("redirect_uris", []))logo_uri = metadata.get("logo_uri") or Noneverification = _resolve_verification_token(metadata)+ resolved_scopes = _resolve_scopes(metadata)app = OAuthApplication(name=client_name,@@ -344,6 +390,7 @@ def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthAcimd_metadata_last_fetched=timezone.now(),logo_uri=logo_uri,organization=verification.organization if verification else None,+ scopes=resolved_scopes if resolved_scopes is not None else [],user=None,)app.full_clean()@@ -389,6 +436,11 @@ def _update_cimd_application(app: OAuthApplication, metadata: CIMDMetadataDocumeverification = _resolve_verification_token(metadata)new_org = verification.organization if verification else Noneupdate_fields = ["name", "redirect_uris", "logo_uri", "cimd_metadata_last_fetched"]++ resolved_scopes = _resolve_scopes(metadata)+ if resolved_scopes is not None:+ app.scopes = resolved_scopes+ update_fields.append("scopes")old_org_id = app.organization_idnew_org_id = new_org.id if new_org else Noneif old_org_id != new_org_id:@@ -503,7 +555,10 @@ def fetch_and_upsert_cimd_application(url: str, capture_ph_event=posthoganalytic"cache_ttl": cache_ttl,"is_verified": new_app.organization_id is not None,"organization_id": str(new_app.organization_id) if new_app.organization_id else None,- "had_verification_token_attempt": bool(metadata.get("posthog_verification_token")),+ "had_verification_token_attempt": bool(+ metadata.get("posthog_verification_token")+ or (isinstance(ns := metadata.get("com.posthog"), dict) and ns.get("verification_token"))+ ),},)return new_appdiff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.pyindex a9f9e57ac1be..e623bea61d71 100644--- a/posthog/api/oauth/test_cimd.py+++ b/posthog/api/oauth/test_cimd.py@@ -14,6 +14,7 @@ from django.test import override_settingsimport requestsfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsa+from parameterized import parameterizedfrom rest_framework.test import APIClientfrom posthog.api.oauth.cimd import (@@ -32,6 +33,7 @@ from posthog.api.oauth.cimd import (validate_cimd_url,)from posthog.models.oauth import OAuthApplication, create_cimd_verification_token+from posthog.scopes import OAUTH_HIDDEN_SCOPES, PRIVILEGED_SCOPESdef generate_rsa_key() -> str:@@ -47,8 +49,8 @@ def generate_rsa_key() -> str:VALID_CIMD_URL = "https://app.example.com/.well-known/oauth-client-metadata.json"-def _make_metadata(url: str = VALID_CIMD_URL, **overrides) -> dict:- metadata = {+def _make_metadata(url: str = VALID_CIMD_URL, com_posthog: dict | None = None, **overrides: object) -> dict:+ metadata: dict[str, object] = {"client_id": url,"client_name": "Test MCP Client","redirect_uris": ["http://127.0.0.1:3000/callback"],@@ -56,6 +58,8 @@ def _make_metadata(url: str = VALID_CIMD_URL, **overrides) -> dict:"response_types": ["code"],"token_endpoint_auth_method": "none",}+ if com_posthog is not None:+ metadata["com.posthog"] = com_posthogmetadata.update(overrides)return metadata@@ -868,3 +872,176 @@ class TestCIMDAuthorizeIntegration(APIBaseTest):self.assertEqual(response.status_code, 302)self.assertIn("/login", response["Location"])+++@patch("posthog.api.oauth.cimd.is_url_allowed", return_value=(True, None))+@override_settings(+ OAUTH2_PROVIDER={+ **settings.OAUTH2_PROVIDER,+ "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),+ }+)+class TestCIMDComPostHogNamespace(APIBaseTest):+ """Tests for the com.posthog namespace: scopes and nested verification_token."""++ # (d) dual-read: both com.posthog.verification_token and the legacy+ # posthog_verification_token must link the app to the organization.+ @parameterized.expand(+ [+ ("nested",),+ ("top_level",),+ ]+ )+ @patch("posthog.api.oauth.cimd.requests.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+ )+ if token_placement == "nested":+ metadata = _make_metadata(com_posthog={"verification_token": plaintext})+ else:+ metadata = _make_metadata(posthog_verification_token=plaintext)++ mock_get.return_value = _mock_response(metadata, headers={})+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert app is not None+ 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")+ 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+ )+ metadata = _make_metadata(+ posthog_verification_token=plaintext,+ com_posthog={"verification_token": "phvt_does_not_exist"},+ )+ mock_get.return_value = _mock_response(metadata, headers={})+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert app is not None+ 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")+ 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+ )+ metadata = _make_metadata(+ posthog_verification_token="phvt_fake_top_level",+ com_posthog={"verification_token": plaintext_nested},+ )+ mock_get.return_value = _mock_response(metadata, headers={})+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert app is not None+ self.assertEqual(app.organization_id, self.organization.id)++ # (a) + (e) present scopes are written to application.scopes on creation.+ @parameterized.expand(+ [+ ("with_scopes", ["insight:read", "dashboard:write"], ["insight:read", "dashboard:write"]),+ ("empty", [], []),+ ]+ )+ @patch("posthog.api.oauth.cimd.requests.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={})++ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert app is not None+ 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")+ def test_non_grantable_scopes_stripped(self, mock_get, _url_mock):+ hidden_scope = next(iter(OAUTH_HIDDEN_SCOPES)) if OAUTH_HIDDEN_SCOPES else None+ input_scopes = [+ *sorted(PRIVILEGED_SCOPES),+ "not_a_real_scope:write", # unknown / garbage string+ "insight:read", # legitimate — must survive+ ]+ if hidden_scope:+ input_scopes.append(hidden_scope)++ metadata = _make_metadata(com_posthog={"scopes": input_scopes})+ mock_get.return_value = _mock_response(metadata, headers={})++ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert app is not None+ for privileged_scope in PRIVILEGED_SCOPES:+ self.assertNotIn(privileged_scope, app.scopes)+ self.assertNotIn("not_a_real_scope:write", app.scopes)+ if hidden_scope:+ self.assertNotIn(hidden_scope, app.scopes)+ self.assertIn("insight:read", app.scopes)++ # (b) absent com.posthog.scopes on refresh leaves existing scopes untouched.+ @patch("posthog.api.oauth.cimd.requests.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={})+ fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))+ # Refresh with metadata that has no com.posthog.scopes.+ mock_get.return_value = _mock_response(_make_metadata(), headers={})+ refreshed = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert refreshed is not None+ self.assertIn("insight:read", refreshed.scopes)++ # (a) present scopes on refresh override the existing application.scopes.+ @patch("posthog.api.oauth.cimd.requests.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={})+ fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))+ metadata_refresh = _make_metadata(com_posthog={"scopes": ["survey:read"]})+ mock_get.return_value = _mock_response(metadata_refresh, headers={})+ refreshed = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert refreshed is not None+ self.assertEqual(refreshed.scopes, ["survey:read"])++ # Guard for the "scope ceiling bypass" review finding: a CIMD client controls its own+ # 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")+ 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)++ real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))+ hidden_scope = next(iter(OAUTH_HIDDEN_SCOPES)) if OAUTH_HIDDEN_SCOPES else None+ escalated = [*sorted(PRIVILEGED_SCOPES), "not_a_real_scope:write", "insight:read"]+ if hidden_scope:+ escalated.append(hidden_scope)+ mock_get.return_value = _mock_response(_make_metadata(com_posthog={"scopes": escalated}), headers={})+ refreshed = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert refreshed is not None+ for privileged_scope in PRIVILEGED_SCOPES:+ self.assertNotIn(privileged_scope, refreshed.scopes)+ self.assertNotIn("not_a_real_scope:write", refreshed.scopes)+ if hidden_scope:+ self.assertNotIn(hidden_scope, refreshed.scopes)+ self.assertEqual(refreshed.scopes, ["insight:read"])++ # absent com.posthog.scopes on initial creation → empty scopes list.+ @patch("posthog.api.oauth.cimd.requests.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)++ assert app is not None+ self.assertEqual(app.scopes, [])