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.

fix(oauth): stop the consent screen dead-ending on cancel and blank scope (#104564)

posthog[bot]59b1784804ad
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d6439b85fb19..87f8aa30ab97 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10305,9 +10305,9 @@ snapshots:
scenes-app-oauth-authorize--wildcard-scope--light:
hash: v1.k794b7964.95034a6e25daf17b6feda53516e2bb3f681e7d036c1fcfb04ddd887f32515e8f.6mGoqUajhralYp32CniS-HRo0Or5AIEpNSXOC44xX7o
scenes-app-oauth-authorize--with-application-logo--dark:
- hash: v1.k794b7964.fbbcc2ee9993cdf147788b606adf87bfff6934094aca3e5f33c2ea3e075ce206.b4b_Yi9bKZ56dDhVz6Sf3IY0r13zh4U5ovkfpCEmCrE
+ hash: v1.k794b7964.eabf9a2b40e318b15473a1d986ba3cbe54d42ed8ab1a0c970aedd4d7d2ea1d83.zlVFiI8Eb6eqIRgSq5iu4zPfabro_kSv7bJ-b0Mo5bk
scenes-app-oauth-authorize--with-application-logo--light:
- hash: v1.k794b7964.4afab937271d0d86e106e8df0b2053bc06585b969ed7a8508030ceebc25596cb.iz6G4K_W0R9ymOOcXfrSEdzRu9WxjvPSJSIlW10oAmk
+ hash: v1.k794b7964.15114853c996f90ae0db6fbc34ba37637762cc5aab29e3a3bfa255f8af55ac03.b6bKq4fsmURm6DY7E9Mqekh73pnREf9rz3B9LgxhP6Q
scenes-app-oauth-authorize--with-required-scopes--dark:
hash: v1.k794b7964.f078f02667fddd8216ec0782c45f1fb95d8bbe6cae9887643e00f284216027cd.Zm5Vw89T37jz_UtxgdvbtIYH3Xo6X-pVxNK28AxFNiE
scenes-app-oauth-authorize--with-required-scopes--light:
diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
index 1c9da9cde678..12d9402d9947 100644
--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts
@@ -161,6 +161,12 @@ describe('oauthAuthorizeLogic', () => {
mcpConsent: { is_mcp_resource: true, scopes: ['openid', 'query:read'] },
expected: ['openid', 'query:read'],
},
+ {
+ name: 'falls back to the identity scopes when the server resolved the request to nothing',
+ urlScope: 'made:up other:junk',
+ resolution: { scopes: [], was_defaulted: true },
+ expected: DEFAULT_OAUTH_SCOPES,
+ },
{
name: 'falls back to the URL when the server sent no resolution',
urlScope: 'insight:read',
diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
index d2b0439410da..7c3b2fabf2e2 100644
--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts
@@ -911,6 +911,13 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
const requestedScopes = searchParams['scope']?.split(' ')?.filter((scope: string) => scope.length) ?? []
const oauthMcpConsent = getAppContext()?.oauth_mcp_consent
const scopeResolution = getAppContext()?.oauth_scope_resolution
+ // The screen needs a set it can submit, because an empty one renders no
+ // permissions and posts a blank scope the API rejects. An empty server
+ // resolution therefore falls back to the identity-only DEFAULT_OAUTH_SCOPES,
+ // which is safe: it grants no resource access, so the person consents to
+ // nothing they did not see. The URL's own tokens are deliberately not reused,
+ // since those are what the server resolved to nothing.
+ const fallbackScopes = scopeResolution || !requestedScopes.length ? DEFAULT_OAUTH_SCOPES : requestedScopes
const scopesWereDefaulted = scopeResolution?.was_defaulted ?? requestedScopes.length === 0
@@ -936,9 +943,8 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
actions.setScopes(oauthMcpConsent.scopes ?? DEFAULT_OAUTH_SCOPES)
} else {
actions.setIsMcpResource(false)
- actions.setScopes(
- scopeResolution?.scopes ?? (requestedScopes.length ? requestedScopes : DEFAULT_OAUTH_SCOPES)
- )
+ // `??` keeps an empty array, so the length is what to test here.
+ actions.setScopes(scopeResolution?.scopes.length ? scopeResolution.scopes : fallbackScopes)
}
}
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 5811de891708..ab25d3adca2f 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -282,6 +282,13 @@ class TestOAuthAPI(APIBaseTest):
("truncated", TRUNCATED_SCOPE_REQUEST, ["canvas:read", "insight:read", "notebook:read"], True),
("complete", "insight:read canvas:read", ["canvas:read", "insight:read"], False),
("short_request_with_a_fragment_tail", "insight:read can", ["insight:read"], False),
+ (
+ "every_resource_token_unknown",
+ "...(full scope list)...",
+ ["canvas:read", "insight:read", "notebook:read"],
+ True,
+ ),
+ ("identity_scope_only", "openid", ["openid"], False),
]
)
@patch("posthog.api.oauth.views.render_template")
@@ -533,6 +540,58 @@ class TestOAuthAPI(APIBaseTest):
expected_expiration = timezone.now() + timedelta(minutes=expiration_minutes)
self.assertEqual(grant.expires, expected_expiration)
+ @parameterized.expand(
+ [
+ ("organization_without_a_selection", OAuthApplicationAccessLevel.ORGANIZATION.value),
+ ("team_without_a_selection", OAuthApplicationAccessLevel.TEAM.value),
+ ]
+ )
+ def test_authorize_post_denial_ignores_the_scoping_controls(self, _name, access_level):
+ response = self.client.post(
+ "/oauth/authorize/",
+ {
+ **self.base_authorization_post_body,
+ "allow": False,
+ "access_level": access_level,
+ "scoped_organizations": [],
+ "scoped_teams": [],
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["redirect_to"], "https://example.com/callback?error=access_denied")
+
+ def test_authorize_post_denial_accepts_a_blank_scope(self):
+ response = self.client.post(
+ "/oauth/authorize/",
+ {**self.base_authorization_post_body, "allow": False, "scope": ""},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["redirect_to"], "https://example.com/callback?error=access_denied")
+
+ def test_authorize_post_grant_still_rejects_a_blank_scope(self):
+ response = self.client.post(
+ "/oauth/authorize/",
+ {**self.base_authorization_post_body, "scope": ""},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("scope", response.json())
+
+ def test_authorize_post_grant_still_requires_a_scoped_organization(self):
+ response = self.client.post(
+ "/oauth/authorize/",
+ {
+ **self.base_authorization_post_body,
+ "access_level": OAuthApplicationAccessLevel.ORGANIZATION.value,
+ "scoped_organizations": [],
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("scoped_organizations", response.json())
+
def test_authorize_post_denied_authorization(self):
response = self.client.post(
"/oauth/authorize/",
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index cecc1ee1f1fe..e82a822ab857 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -392,7 +392,7 @@ class OAuthAuthorizationSerializer(serializers.Serializer):
code_challenge_method = serializers.CharField(required=False, allow_null=True, default=None)
nonce = serializers.CharField(required=False, allow_null=True, default=None)
claims = serializers.CharField(required=False, allow_null=True, default=None)
- scope = serializers.CharField()
+ scope = serializers.CharField(allow_blank=True)
allow = serializers.BooleanField()
prompt = serializers.CharField(required=False, allow_null=True, default=None)
approval_prompt = serializers.CharField(required=False, allow_null=True, default=None)
@@ -408,7 +408,28 @@ class OAuthAuthorizationSerializer(serializers.Serializer):
raise ValueError("OAuthAuthorizationSerializer requires 'user' in context")
super().__init__(*args, **kwargs)
+ def validate(self, attrs: dict) -> dict:
+ # A denial needs no scope, so the field accepts a blank one. A grant still does.
+ if attrs.get("allow") and not attrs.get("scope", "").strip():
+ raise serializers.ValidationError({"scope": "This field may not be blank."})
+ return attrs
+
+ def _is_denial(self) -> bool:
+ """Whether the request refuses the grant rather than making one.
+
+ A denial mints nothing, so the scoping controls it carries are irrelevant. Without
+ this the consent screen can reach a state it cannot leave: pick "Organizations",
+ select none, and both Authorize and Cancel fail the same validator, so the person
+ cannot even refuse.
+ """
+ try:
+ return not self.fields["allow"].to_internal_value(self.initial_data.get("allow"))
+ except (serializers.ValidationError, TypeError):
+ return False
+
def validate_scoped_organizations(self, scoped_organization_ids: list[str]) -> list[str]:
+ if self._is_denial():
+ return []
access_level = self.initial_data.get("access_level")
requesting_user: User = self.context["user"]
user_permissions = UserPermissions(requesting_user)
@@ -432,6 +453,8 @@ class OAuthAuthorizationSerializer(serializers.Serializer):
return []
def validate_scoped_teams(self, scoped_team_ids: list[int]) -> list[int]:
+ if self._is_denial():
+ return []
access_level = self.initial_data.get("access_level")
requesting_user: User = self.context["user"]
user_permissions = UserPermissions(requesting_user)
@@ -1520,7 +1543,19 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
requested_scope_tokens = (request.query_params.get("scope") or "").split()
scope_was_truncated = is_truncated_scope_request(requested_scope_tokens)
- scopes_were_defaulted = not requested_scope_tokens or scope_was_truncated
+
+ # `validate_scopes` clamps a request whose every resource token is unknown down to
+ # nothing. That is a valid outcome for a token, but not for a consent screen: the
+ # screen shows no permissions, and its Authorize button posts a blank scope the
+ # POST rejects. Resolve such a request the way an omitted scope resolves instead.
+ # A client sends one by accident when it builds the URL from an unsubstituted
+ # scope placeholder, so every token arrives as junk.
+ requested_resource_tokens = set(requested_scope_tokens) - ALWAYS_ALLOWED_SCOPES
+ nothing_grantable = bool(requested_resource_tokens) and not (set(scopes) - ALWAYS_ALLOWED_SCOPES)
+ if nothing_grantable:
+ scopes = sorted(effective_ceiling(application.ceiling_scopes) | ALWAYS_ALLOWED_SCOPES)
+
+ scopes_were_defaulted = not requested_scope_tokens or scope_was_truncated or nothing_grantable
# Track OAuth authorization attempts with the authenticated user
registration_type = self._registration_type(application)
@@ -1532,6 +1567,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
"requested_scope_count": len(requested_scope_tokens),
"has_resource": bool(request.query_params.get("resource")),
"scope_was_truncated": scope_was_truncated,
+ "nothing_grantable": nothing_grantable,
},
)