Skip to content

: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.

refactor(oauth): consolidate DCR and CIMD scope filtering (#62180)

Matt Brooker97bbe5c241a1
diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.py
index 5aac1ae7fd6d..a6c6112e2d0a 100644
--- a/posthog/api/oauth/cimd.py
+++ b/posthog/api/oauth/cimd.py
@@ -35,7 +35,7 @@ from posthog.models.oauth import (
)
from posthog.ph_client import ph_scoped_capture
from posthog.rate_limit import IPThrottle
-from posthog.scopes import UNPRIVILEGED_SCOPES
+from posthog.scopes import filter_to_unprivileged_scopes
from posthog.security.url_validation import is_url_allowed
from .dcr import validate_client_name
@@ -343,16 +343,9 @@ def _resolve_verification_token(metadata: CIMDMetadataDocument) -> CIMDVerificat
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.
+ """Resolve the allow-listed `com.posthog.scopes` for an app, or None when the field
+ is absent so callers leave existing scopes untouched. A present field returns a
+ (possibly empty) list, capped to grantable scopes by `filter_to_unprivileged_scopes`.
"""
com_posthog = metadata.get("com.posthog")
if not isinstance(com_posthog, dict):
@@ -361,7 +354,7 @@ def _resolve_scopes(metadata: CIMDMetadataDocument) -> list[str] | None:
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]
+ return filter_to_unprivileged_scopes(raw_scopes)
def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthApplication:
diff --git a/posthog/api/oauth/dcr.py b/posthog/api/oauth/dcr.py
index 11beb9ed76d2..b284912d0bec 100644
--- a/posthog/api/oauth/dcr.py
+++ b/posthog/api/oauth/dcr.py
@@ -28,7 +28,7 @@ from rest_framework.views import APIView
from posthog.exceptions_capture import capture_exception
from posthog.models.oauth import OAuthApplication
from posthog.rate_limit import IPThrottle
-from posthog.scopes import UNPRIVILEGED_SCOPES
+from posthog.scopes import filter_to_unprivileged_scopes
logger = structlog.get_logger(__name__)
@@ -39,23 +39,9 @@ BLOCKED_CLIENT_NAME_WORDS = ["official", "verified", "trusted"] # Block names c
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
+ """Parse an RFC 7591 space-delimited `scope` string into the deduped, allow-listed
+ scopes a DCR client may register. See `filter_to_unprivileged_scopes` for the rule."""
+ return filter_to_unprivileged_scopes(scope.split())
def validate_client_name(value: str) -> None:
diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.py
index e623bea61d71..07b36542c171 100644
--- a/posthog/api/oauth/test_cimd.py
+++ b/posthog/api/oauth/test_cimd.py
@@ -982,6 +982,17 @@ class TestCIMDComPostHogNamespace(APIBaseTest):
self.assertNotIn(hidden_scope, app.scopes)
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")
+ 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={})
+
+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
+ assert app is not None
+ 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")
def test_absent_scopes_on_refresh_leaves_existing_untouched(self, mock_get, _url_mock):
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 6f6ad7b1a227..4f7880f0e790 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -246,6 +246,26 @@ OIDC_SCOPES: tuple[str, ...] = ("openid", "profile", "email")
ALWAYS_ALLOWED_SCOPES: frozenset[str] = frozenset(OIDC_SCOPES) | {"introspection"}
+def filter_to_unprivileged_scopes(scopes: Iterable[object]) -> list[str]:
+ """Keep only self-serve-grantable scopes from a declared list, deduped, order preserved.
+
+ The single allow-list for scopes a self-registering client declares, covering both DCR
+ (the RFC 7591 `scope` string, split before it gets here) and CIMD (`com.posthog.scopes`).
+ `UNPRIVILEGED_SCOPES` drops privileged (`llm_gateway:*`), internal, hidden, and unknown
+ strings: none may reach a per-app ceiling, since `/authorize` would otherwise grant them
+ on a user-consented token. Non-string entries are dropped too, so raw partner JSON is safe
+ to pass straight in.
+ """
+ seen: set[str] = set()
+ result: list[str] = []
+ for token in scopes:
+ if not isinstance(token, str) or token not in UNPRIVILEGED_SCOPES or token in seen:
+ continue
+ seen.add(token)
+ result.append(token)
+ return result
+
+
def effective_ceiling(app_scopes: Iterable[str]) -> frozenset[str]:
"""The scope set a request resolves against: the explicit `app_scopes` ceiling,
or the broad `UNPRIVILEGED_SCOPES` default when the app has none."""
diff --git a/posthog/test/test_scopes.py b/posthog/test/test_scopes.py
index 53b0923e701a..5319797a6a4e 100644
--- a/posthog/test/test_scopes.py
+++ b/posthog/test/test_scopes.py
@@ -19,6 +19,7 @@ from posthog.scopes import (
UNPRIVILEGED_SCOPES,
downgrade_scopes_to_read_only,
effective_ceiling,
+ filter_to_unprivileged_scopes,
get_oauth_scopes_supported,
get_scope_descriptions,
narrow_scopes_to_ceiling,
@@ -321,3 +322,29 @@ class TestNarrowScopesToCeiling(SimpleTestCase):
self, _name: str, requested: list[str], app_scopes: list[str], expected: list[str] | None
) -> None:
assert narrow_scopes_to_ceiling(requested, app_scopes) == expected
+
+
+class TestFilterToUnprivilegedScopes(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("keeps_unprivileged", ["insight:read", "dashboard:write"], ["insight:read", "dashboard:write"]),
+ ("drops_privileged", ["llm_gateway:read", "insight:read"], ["insight:read"]),
+ ("drops_unknown_string", ["not_a_real_scope:write", "query:read"], ["query:read"]),
+ (
+ "dedupes_preserving_order",
+ ["insight:read", "query:read", "insight:read"],
+ ["insight:read", "query:read"],
+ ),
+ ("empty_in_empty_out", [], []),
+ ("all_dropped_yields_empty", ["llm_gateway:read", "garbage"], []),
+ ]
+ )
+ def test_resolution(self, _name: str, given: list[str], expected: list[str]) -> None:
+ assert filter_to_unprivileged_scopes(given) == expected
+
+ def test_non_string_entries_dropped(self) -> None:
+ # Callers pass raw partner JSON (CIMD `com.posthog.scopes`), which may hold non-strings.
+ assert filter_to_unprivileged_scopes(["insight:read", 123, None, {"x": 1}, "query:read"]) == [
+ "insight:read",
+ "query:read",
+ ]