: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): add RFC 7591 scope field to DCR registration (#61225)
Matt Brooker5f6635f4dc1a
diff --git a/posthog/api/oauth/dcr.py b/posthog/api/oauth/dcr.pyindex 55524bcc573a..11beb9ed76d2 100644--- a/posthog/api/oauth/dcr.py+++ b/posthog/api/oauth/dcr.py@@ -28,6 +28,7 @@ from rest_framework.views import APIViewfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.oauth import OAuthApplicationfrom posthog.rate_limit import IPThrottle+from posthog.scopes import UNPRIVILEGED_SCOPESlogger = structlog.get_logger(__name__)@@ -37,6 +38,26 @@ BLOCKED_CLIENT_NAME_PREFIXES = ["posthog"] # Block names starting with theseBLOCKED_CLIENT_NAME_WORDS = ["official", "verified", "trusted"] # Block names containing these+def filter_dcr_scopes(scope: str) -> list[str]:+ """Parse an RFC 7591 space-delimited `scope` string into a deduped list,+ keeping only scopes in `UNPRIVILEGED_SCOPES`. Order is preserved so the+ response echo matches what the client kept.++ Allow-list, not deny-list: a self-serve DCR client may only register safe+ scopes. `UNPRIVILEGED_SCOPES` excludes privileged (`llm_gateway:*`), internal+ (`signal_scout_internal`, ...), hidden (`metrics`, `wizard_session`), and any+ unknown/junk string — none of which may reach the per-app ceiling, since+ `/authorize` would otherwise grant them on a user-consented token."""+ seen: set[str] = set()+ result: list[str] = []+ for token in scope.split():+ if token not in UNPRIVILEGED_SCOPES or token in seen:+ continue+ seen.add(token)+ result.append(token)+ return result++def validate_client_name(value: str) -> None:"""Validate that client name doesn't impersonate official apps."""lower_value = value.lower()@@ -102,6 +123,11 @@ class DCRRequestSerializer(serializers.Serializer):default="none",help_text="How the client authenticates at the token endpoint: 'none' for public clients, 'client_secret_post' for confidential clients",)+ scope = serializers.CharField(+ required=False,+ allow_blank=True,+ help_text="Space-delimited OAuth scopes (RFC 7591). Sets the client's scope ceiling; privileged scopes are stripped, and a set that strips to nothing is rejected. Omit to use the default scope set.",+ )class DynamicClientRegistrationView(APIView):@@ -141,6 +167,24 @@ class DynamicClientRegistrationView(APIView):# the create() call simple -- we just don't return it in the response.plaintext_secret = generate_client_secret()+ requested_scope = data.get("scope")+ app_scopes = filter_dcr_scopes(requested_scope) if requested_scope else []++ # A non-empty `scope` that filters to nothing means the client asked only for+ # scopes it can't self-register (privileged/internal/hidden/unknown). Reject+ # rather than store an empty ceiling: an empty ceiling resolves to the broad+ # default at /authorize, so silently accepting would widen the client beyond+ # what it requested. Absent / "" / null `scope` is the legitimate "use default"+ # path and falls through to an empty ceiling below.+ if requested_scope and not app_scopes:+ return Response(+ {+ "error": "invalid_client_metadata",+ "error_description": "None of the requested scopes are available to self-registered clients. Omit `scope` to register with the default scope set.",+ },+ status=status.HTTP_400_BAD_REQUEST,+ )+try:app = OAuthApplication.objects.create(name=data.get("client_name", "MCP Client"),@@ -152,6 +196,7 @@ class DynamicClientRegistrationView(APIView):skip_authorization=False,is_dcr_client=True,dcr_client_id_issued_at=now,+ scopes=app_scopes,organization=None,user=None,)@@ -218,4 +263,9 @@ class DynamicClientRegistrationView(APIView):if data.get("client_name"):response_data["client_name"] = data["client_name"]+ # RFC 7591 Section 3.2.1: when the server modifies requested scopes, it+ # returns the registered `scope` so the client sees the privileged-strip.+ if app_scopes:+ response_data["scope"] = " ".join(app_scopes)+return Response(response_data, status=status.HTTP_201_CREATED)diff --git a/posthog/api/oauth/test_dcr.py b/posthog/api/oauth/test_dcr.pyindex a0cfdf6402ef..9f7964476fd5 100644--- a/posthog/api/oauth/test_dcr.py+++ b/posthog/api/oauth/test_dcr.py@@ -1,3 +1,6 @@+import base64+import hashlib+from posthog.test.base import APIBaseTestfrom django.conf import settings@@ -5,10 +8,11 @@ from django.test import override_settingsfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsa+from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIClient-from posthog.models.oauth import OAuthApplication+from posthog.models.oauth import OAuthApplication, OAuthApplicationAccessLeveldef generate_rsa_key() -> str:@@ -380,3 +384,151 @@ class TestDynamicClientRegistration(APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_201_CREATED)self.assertEqual(response.json()["client_name"], "My Analytics Dashboard")++ @parameterized.expand(+ [+ # (name, requested scope, expected app.scopes ceiling, expected echoed `scope` in 201 — None means omitted)+ ("single_scope", "experiment:read", ["experiment:read"], "experiment:read"),+ (+ "multiple_scopes",+ "experiment:read dashboard:write",+ ["experiment:read", "dashboard:write"],+ "experiment:read dashboard:write",+ ),+ (+ "strips_privileged",+ "experiment:read llm_gateway:read llm_gateway:write",+ ["experiment:read"],+ "experiment:read",+ ),+ ("strips_internal", "experiment:read signal_scout_internal:write", ["experiment:read"], "experiment:read"),+ (+ "strips_hidden",+ "experiment:read metrics:read wizard_session:write",+ ["experiment:read"],+ "experiment:read",+ ),+ ("strips_unknown_junk", "experiment:read not_a_real:scope", ["experiment:read"], "experiment:read"),+ (+ "dedupes_preserving_order",+ "experiment:read dashboard:read experiment:read",+ ["experiment:read", "dashboard:read"],+ "experiment:read dashboard:read",+ ),+ ("blank_string_yields_empty", "", [], None),+ (+ "extra_whitespace_ignored",+ " experiment:read dashboard:read ",+ ["experiment:read", "dashboard:read"],+ "experiment:read dashboard:read",+ ),+ ]+ )+ def test_scope_registration_writes_filtered_ceiling(self, _name, scope, expected_scopes, expected_response_scope):+ response = self.client.post(+ "/oauth/register/",+ {"redirect_uris": ["https://example.com/callback"], "scope": scope},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ app = OAuthApplication.objects.get(client_id=response.json()["client_id"])+ self.assertEqual(app.scopes, expected_scopes)+ if expected_response_scope is None:+ self.assertNotIn("scope", response.json())+ else:+ self.assertEqual(response.json()["scope"], expected_response_scope)++ @parameterized.expand(+ [+ ("only_privileged", "llm_gateway:read llm_gateway:write"),+ ("only_internal_hidden_junk", "signal_scout_internal:write metrics:read not_a_real:scope"),+ ]+ )+ def test_register_with_only_ungrantable_scopes_is_rejected(self, _name, scope):+ response = self.client.post(+ "/oauth/register/",+ {"redirect_uris": ["https://example.com/callback"], "scope": scope},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["error"], "invalid_client_metadata")++ def test_register_without_scope_leaves_ceiling_empty(self):+ # Distinct from blank_string above: the `scope` key is absent entirely, exercising+ # the `data.get("scope")` None branch rather than the empty-string branch.+ response = self.client.post(+ "/oauth/register/",+ {"redirect_uris": ["https://example.com/callback"]},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ app = OAuthApplication.objects.get(client_id=response.json()["client_id"])+ self.assertEqual(app.scopes, [])+ self.assertNotIn("scope", response.json())++ CODE_VERIFIER = "dcr_scope_test_verifier"++ @property+ def code_challenge(self) -> str:+ digest = hashlib.sha256(self.CODE_VERIFIER.encode("utf-8")).digest()+ return base64.urlsafe_b64encode(digest).decode("utf-8").replace("=", "")++ def _register_dcr_client(self, **extra) -> str:+ body = {"redirect_uris": ["https://example.com/callback"], **extra}+ response = self.client.post("/oauth/register/", body, format="json")+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ return response.json()["client_id"]++ def _authorize_consent_post(self, client_id: str, scope: str):+ """POST the consent form, mirroring TestOAuthAPI. Returns a JSON+ `redirect_to` payload rather than rendering the consent template, so+ the assertion doesn't depend on a built frontend. The dict is passed+ directly (multipart) so empty scoped_* lists are omitted, not sent as+ the literal "[]"."""+ self.client.force_login(self.user)+ body = {+ "client_id": client_id,+ "redirect_uri": "https://example.com/callback",+ "response_type": "code",+ "code_challenge": self.code_challenge,+ "code_challenge_method": "S256",+ "allow": True,+ "access_level": OAuthApplicationAccessLevel.ALL.value,+ "scoped_organizations": [],+ "scoped_teams": [],+ "scope": scope,+ }+ return self.client.post("/oauth/authorize/", body)++ def test_no_scope_dcr_client_resolves_to_unprivileged_default_at_authorize(self):+ """Regression: a DCR client (Cursor, mcp-remote) that registers without+ scope= must resolve to the broad UNPRIVILEGED default at /authorize, so+ an unprivileged scope is granted (code issued, not invalid_scope)."""+ client_id = self._register_dcr_client()+ response = self._authorize_consent_post(client_id, "experiment:read")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ redirect_to = response.json()["redirect_to"]+ self.assertNotIn("error=invalid_scope", redirect_to)+ self.assertIn("code=", redirect_to)++ def test_no_scope_dcr_client_rejects_privileged_scope_at_authorize(self):+ """The broad default excludes PRIVILEGED_SCOPES, so a no-ceiling DCR+ client cannot obtain llm_gateway access at /authorize."""+ client_id = self._register_dcr_client()+ self.client.force_login(self.user)+ response = self.client.get(+ "/oauth/authorize/",+ {+ "client_id": client_id,+ "redirect_uri": "https://example.com/callback",+ "response_type": "code",+ "scope": "llm_gateway:read",+ "code_challenge": self.code_challenge,+ "code_challenge_method": "S256",+ "state": "test123",+ },+ )+ self.assertEqual(response.status_code, status.HTTP_302_FOUND)+ location = response.get("Location")+ assert location+ self.assertIn("error=invalid_scope", location)