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.

feat(oauth): capture requested and rejected scopes on rejection event (#61869)

Matt Brooker97b9a524abff
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 605fdd1ccc68..ed30bf2a8ae9 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -2459,11 +2459,27 @@ class TestOAuthAPI(APIBaseTest):
@parameterized.expand(
[
- ("ceiling_excludes_requested", ["experiment:read"], "experiment:write"),
- ("empty_ceiling_rejects_privileged", [], "llm_gateway:read"),
+ (
+ "ceiling_excludes_requested",
+ ["experiment:read"],
+ "experiment:write",
+ "experiment:write",
+ ["experiment:write"],
+ ),
+ ("empty_ceiling_rejects_privileged", [], "llm_gateway:read", "llm_gateway:read", ["llm_gateway:read"]),
+ # mixed grantable + out-of-ceiling scope: requested records the full set, rejected pins to just the offender
+ (
+ "mixed_scope_isolates_offender",
+ ["experiment:read"],
+ "experiment:read%20experiment:write",
+ "experiment:read experiment:write",
+ ["experiment:write"],
+ ),
]
)
- def test_authorize_rejection_captures_invalid_scope_event(self, _name, ceiling, requested_scope):
+ def test_authorize_rejection_captures_invalid_scope_event(
+ self, _name, ceiling, requested_scope, expected_requested_scopes, expected_rejected_scopes
+ ):
self._set_ceiling(*ceiling)
with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:
response = self.client.get(f"{self.base_authorization_url}&scope={requested_scope}")
@@ -2478,6 +2494,8 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(props["registration_type"], "manual")
self.assertEqual(props["is_verified"], self.confidential_application.is_verified)
self.assertEqual(props["is_first_party"], self.confidential_application.is_first_party)
+ self.assertEqual(props["requested_scopes"], expected_requested_scopes)
+ self.assertEqual(props["rejected_scopes"], expected_rejected_scopes)
def test_authorize_success_does_not_capture_invalid_scope_event(self):
self._set_ceiling("experiment:read")
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index abc16dc4a231..f69c874c0a7d 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -55,6 +55,7 @@ from posthog.scopes import (
effective_ceiling,
get_oauth_scopes_supported,
narrow_scopes_to_ceiling,
+ scopes_outside_ceiling,
scopes_within_ceiling,
)
from posthog.security.url_validation import has_authority_bypass_chars
@@ -910,6 +911,15 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
# Surface scope-ceiling rejections so on-call can alert on /authorize failing with invalid_scope.
if getattr(error_response["error"], "error", None) == "invalid_scope" and application is not None:
distinct_id = getattr(getattr(self.request, "user", None), "distinct_id", None) or application.client_id
+ # invalid_scope only reaches error_response from the GET authorize request, where
+ # oauthlib raises it pre-consent (the consent POST returns it as a redirect, not a
+ # raise), so the requested scope is always in the query string here.
+ requested_scope = self.request.query_params.get("scope") or ""
+ rejected_scopes = scopes_outside_ceiling(
+ requested_scope.split(),
+ application.scopes or [],
+ allow_wildcard_under_empty_ceiling=True,
+ )
posthoganalytics.capture(
distinct_id=str(distinct_id),
event="oauth_authorization_rejected",
@@ -920,6 +930,8 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
"registration_type": self._registration_type(application),
"is_verified": application.is_verified,
"is_first_party": application.is_first_party,
+ "requested_scopes": requested_scope,
+ "rejected_scopes": rejected_scopes,
},
)
diff --git a/posthog/scopes.py b/posthog/scopes.py
index f2b76d7235dd..6f6ad7b1a227 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -286,6 +286,30 @@ def scopes_within_ceiling(
return to_check.issubset(allowed)
+def scopes_outside_ceiling(
+ requested: Iterable[str],
+ app_scopes: Iterable[str],
+ *,
+ allow_wildcard_under_empty_ceiling: bool = False,
+) -> list[str]:
+ """The requested scopes that fall outside an app's ceiling — the inverse of
+ `scopes_within_ceiling`, naming *which* scopes triggered an `invalid_scope`
+ rejection rather than just whether one did. For instrumentation only; the
+ resolution rules mirror `scopes_within_ceiling` exactly so the two never drift.
+
+ Returns a sorted list, empty when every requested scope is grantable.
+ """
+ app = frozenset(app_scopes or [])
+ to_check = set(requested) - ALWAYS_ALLOWED_SCOPES
+ if not to_check:
+ return []
+ if app:
+ # `*` is never grantable under an explicit ceiling, even if listed.
+ return sorted(s for s in to_check if s == "*" or s not in app)
+ allowed = UNPRIVILEGED_SCOPES | {"*"} if allow_wildcard_under_empty_ceiling else UNPRIVILEGED_SCOPES
+ return sorted(to_check - allowed)
+
+
def narrow_scopes_to_ceiling(original: Iterable[str], app_scopes: Iterable[str]) -> list[str] | None:
"""Cap previously-granted scopes at an app's current ceiling (refresh-time).
diff --git a/posthog/test/test_scopes.py b/posthog/test/test_scopes.py
index b6590e609fb0..53b0923e701a 100644
--- a/posthog/test/test_scopes.py
+++ b/posthog/test/test_scopes.py
@@ -22,6 +22,7 @@ from posthog.scopes import (
get_oauth_scopes_supported,
get_scope_descriptions,
narrow_scopes_to_ceiling,
+ scopes_outside_ceiling,
scopes_within_ceiling,
)
@@ -271,6 +272,28 @@ class TestScopesWithinCeiling(SimpleTestCase):
assert effective_ceiling(["query:read", "insight:read"]) == frozenset({"query:read", "insight:read"})
+class TestScopesOutsideCeiling(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("subset_within_ceiling_none_rejected", ["query:read"], ["query:read", "insight:read"], []),
+ ("isolates_offender_from_grantable", ["query:read", "insight:write"], ["query:read"], ["insight:write"]),
+ ("privileged_rejected_without_ceiling", ["llm_gateway:read"], [], ["llm_gateway:read"]),
+ ("wildcard_rejected_under_explicit_ceiling", ["query:read", "*"], ["query:read"], ["*"]),
+ ("oidc_never_rejected", ["openid", "insight:write"], ["query:read"], ["insight:write"]),
+ ]
+ )
+ def test_resolution(self, _name: str, requested: list[str], app_scopes: list[str], expected: list[str]) -> None:
+ assert scopes_outside_ceiling(requested, app_scopes) == expected
+
+ def test_inverse_of_within_ceiling(self) -> None:
+ # The two helpers must never disagree: empty offender list iff within ceiling.
+ cases = [(["query:read", "insight:write"], ["query:read"]), (["query:read"], []), (["*"], [])]
+ for requested, app_scopes in cases:
+ within = scopes_within_ceiling(requested, app_scopes, allow_wildcard_under_empty_ceiling=True)
+ outside = scopes_outside_ceiling(requested, app_scopes, allow_wildcard_under_empty_ceiling=True)
+ assert within is (outside == [])
+
+
class TestNarrowScopesToCeiling(SimpleTestCase):
@parameterized.expand(
[