: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): editable consent screen with explicit-locked scope rule (#62583)
Matt Brooker758d32a60cc4
diff --git a/ee/api/agentic_provisioning/test/test_resources.py b/ee/api/agentic_provisioning/test/test_resources.pyindex d8a6835ec3d3..2b230a7325f4 100644--- a/ee/api/agentic_provisioning/test/test_resources.py+++ b/ee/api/agentic_provisioning/test/test_resources.py@@ -152,10 +152,10 @@ class TestProvisioningResources(ProvisioningTestBase):assert pat is not Noneassert pat.label == self.team.name[:40]- def test_create_resource_pat_inherits_app_scope_ceiling(self):+ def test_create_resource_pat_narrowed_to_granted_token_scope(self):+ # The test bearer is granted only query:read; the PAT must not widen to the+ # full ceiling even when the app's grantable set is broader.token = self._get_bearer_token()- # Seed the grandfathered app's ceiling after minting the bearer so the PAT is- # capped at the app's scopes rather than the old hardcoded ["*"].app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)app.scopes = ["insight:read", "query:read"]app.save(update_fields=["scopes"])@@ -166,10 +166,25 @@ class TestProvisioningResources(ProvisioningTestBase):)pat = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()assert pat is not None- assert pat.scopes == ["insight:read", "query:read"]+ assert pat.scopes == ["query:read"]assert pat.scoped_teams == [self.team.id]assert pat.scoped_organizations == [str(self.team.organization_id)]+ def test_create_resource_pat_excludes_optional_scopes_outside_grant(self):+ token = self._get_bearer_token()+ app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)+ app.scopes = ["query:read"]+ app.optional_scopes = ["insight:read"]+ app.save(update_fields=["scopes", "optional_scopes"])+ self._post_signed_with_bearer(+ "/api/agentic/provisioning/resources",+ data={"service_id": "analytics"},+ token=token,+ )+ pat = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()+ assert pat is not None+ assert pat.scopes == ["query:read"]+def test_create_resource_omits_pat_when_app_gate_off(self):token = self._get_bearer_token()app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)@@ -198,7 +213,7 @@ class TestProvisioningResources(ProvisioningTestBase):scopes=["insight:read"],provisioning_issues_personal_api_key=gate_on,)- result = _maybe_create_provisioned_pat(self.user, self.team, app)+ result = _maybe_create_provisioned_pat(self.user, self.team, app, "insight:read")if gate_on:assert result is not Nonepat = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()@@ -740,7 +755,9 @@ class TestCreateProvisionedPat(ProvisioningTestBase):])def test_label_prefix_resolution(self, _name, label_prefix, expected_label_template):- api_key = _maybe_create_provisioned_pat(self.user, self.team, self._minting_app(), label_prefix=label_prefix)+ api_key = _maybe_create_provisioned_pat(+ self.user, self.team, self._minting_app(), "query:read", label_prefix=label_prefix+ )assert api_key is not Nonepat = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()assert pat is not None@@ -749,7 +766,9 @@ class TestCreateProvisionedPat(ProvisioningTestBase):def test_label_is_truncated_to_40_chars(self):self.team.name = "A" * 60self.team.save()- _maybe_create_provisioned_pat(self.user, self.team, self._minting_app(), label_prefix="LongPartnerName")+ _maybe_create_provisioned_pat(+ self.user, self.team, self._minting_app(), "query:read", label_prefix="LongPartnerName"+ )pat = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()assert pat is not Noneassert len(pat.label) == 40@@ -761,5 +780,5 @@ class TestCreateProvisionedPat(ProvisioningTestBase):app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)assert app.scopes == []initial_count = PersonalAPIKey.objects.filter(user=self.user).count()- assert _maybe_create_provisioned_pat(self.user, self.team, app) is None+ assert _maybe_create_provisioned_pat(self.user, self.team, app, "query:read") is Noneassert PersonalAPIKey.objects.filter(user=self.user).count() == initial_countdiff --git a/ee/api/agentic_provisioning/views.py b/ee/api/agentic_provisioning/views.pyindex 6fbe403e2e03..77ebbde65592 100644--- a/ee/api/agentic_provisioning/views.py+++ b/ee/api/agentic_provisioning/views.py@@ -539,7 +539,7 @@ def _handle_existing_user(},status=400,)- if not scopes_within_ceiling(scopes, partner.scopes):+ if not scopes_within_ceiling(scopes, partner.ceiling_scopes):return Response({"id": request_id,@@ -1133,7 +1133,7 @@ def _exchange_authorization_code(request: Request) -> Response:# Direct-mint bypasses /authorize's OAuthValidator, so the per-app scope# ceiling has to be enforced here before the token is created by hand.requested_scopes = scopes if scopes else StripeIntegration.SCOPES.split()- app_scopes = locked_app.scopes if locked_app else []+ app_scopes = locked_app.ceiling_scopes if locked_app else []if not scopes_within_ceiling(requested_scopes, app_scopes):_capture_provisioning_event("token_exchange", "scope_ceiling_exceeded", grant_type="authorization_code")return Response(@@ -1284,7 +1284,7 @@ def _exchange_refresh_token(request: Request) -> Response:# token rows — a since-tightened ceiling must drop the removed scopes, and a# token now fully outside the ceiling has to re-authorize rather than refresh.# Done up front so a rejected refresh never revokes the caller's only token.- app_scopes = oauth_app.scopes if oauth_app else []+ app_scopes = oauth_app.ceiling_scopes if oauth_app else []narrowed_scopes = narrow_scopes_to_ceiling(old_scope.split(), app_scopes)if narrowed_scopes is None:_capture_provisioning_event("token_exchange", "scope_ceiling_exceeded", grant_type="refresh_token")@@ -1481,7 +1481,7 @@ def _extract_label_prefix(request: Request) -> str | None:def _maybe_create_provisioned_pat(- user: User, team: Team, app: OAuthApplication | None, label_prefix: str | None = None+ user: User, team: Team, app: OAuthApplication | None, granted_scope: str | None, label_prefix: str | None = None) -> str | None:"""Create a Personal API Key for a provisioned user and return the raw key value.@@ -1490,11 +1490,13 @@ def _maybe_create_provisioned_pat(Returns ``None`` when the gate is off, and the caller omits ``personal_api_key``from the response entirely.- When enabled (the grandfathered legacy Stripe app), the key is scoped to the- app's ``scopes`` ceiling rather than ``["*"]`` so a provisioned PAT can never- exceed what the issuing app is itself allowed. A flag-on app with an unseeded- ceiling mints nothing: an empty-scope PAT fails every scope check, and widening- to a wildcard would bypass the ceiling.+ When enabled (the grandfathered legacy Stripe app), the key carries the granted+ OAuth token's scopes (``granted_scope``) narrowed to the app's current ceiling,+ so a provisioned PAT can exceed neither what the user granted nor what the app+ may hold. Minting from the ceiling alone would hand out optional scopes the+ grant never included. A flag-on app with an unseeded ceiling mints nothing: an+ empty-scope PAT fails every scope check, and widening to a wildcard would+ bypass the ceiling.scoped_teams is set to [team.id] so the PAT only grants access to the teambeing provisioned, matching the scoping of the OAuth token issued in the@@ -1506,9 +1508,18 @@ def _maybe_create_provisioned_pat("""if not app or not app.provisioning_issues_personal_api_key:return None- if not app.scopes:+ if not app.ceiling_scopes:_capture_provisioning_event("pat_mint", "skipped_unseeded_ceiling", partner=app, team_id=team.id)return None+ granted = (granted_scope or "").split()+ if "*" in granted:+ # A legacy wildcard token covers everything, so the ceiling is the cap.+ pat_scopes = app.ceiling_scopes+ else:+ pat_scopes = narrow_scopes_to_ceiling([s for s in granted if ":" in s], app.ceiling_scopes) or []+ if not pat_scopes:+ _capture_provisioning_event("pat_mint", "skipped_no_granted_scopes", partner=app, team_id=team.id)+ return Nonetry:api_key_value = generate_random_token_personal()label_base = f"{label_prefix} - {team.name}" if label_prefix else team.name@@ -1521,7 +1532,7 @@ def _maybe_create_provisioned_pat(label=label,secure_value=hash_key_value(api_key_value),mask_value=mask_key_value(api_key_value),- scopes=list(app.scopes),+ scopes=pat_scopes,scoped_teams=[team.id],scoped_organizations=[str(team.organization_id)],)@@ -1856,7 +1867,7 @@ def provisioning_resources_create(request: Request) -> Response:"host": host,}if personal_api_key := _maybe_create_provisioned_pat(- user, team, access_token.application, label_prefix=label_prefix+ user, team, access_token.application, access_token.scope, label_prefix=label_prefix):access_configuration["personal_api_key"] = personal_api_key@@ -1947,7 +1958,7 @@ def provisioning_rotate_credentials(request: Request, resource_id: str) -> Respo"host": host,}if personal_api_key := _maybe_create_provisioned_pat(- user, team, access_token.application, label_prefix=label_prefix+ user, team, access_token.application, access_token.scope, label_prefix=label_prefix):access_configuration["personal_api_key"] = personal_api_keydiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex afdec4f00fcd..2dad1613c5e6 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6016,14 +6016,22 @@ snapshots:hash: v1.k794b7964.4f5921778249386197b5ee6d432e297588c5a66f6e06dde3aac76a1d1d36ae97.2MB3XoQGeD1xMU4gc02WBy23P1XxjP11zwUpTtmbg80scenes-app-notebooks-nodes-support-tickets--with-tickets--light:hash: v1.k794b7964.236f9dfeedc3837cccd845dbf92ab39c67356756cb9f443903629435d5f33ac9.-VF3NOolmK2FaKcxFz8_SXEffVywLXsTkudBuqXxtig+ scenes-app-oauth-authorize--broad-free-pick--dark:+ hash: v1.k794b7964.478bfe16c75a48c2681d56e42fa9e5ac9cc1bc1575ddd6f6796a38efcfca55e8.e0w0ej4UODBCKLMi5IXKoupYWlx_JZCnu23qvAZz0Vw+ scenes-app-oauth-authorize--broad-free-pick--light:+ hash: v1.k794b7964.50e0640a01230478bfdafb656f943df772cfe8b667111524d7f5e47fd6e304a6.zzXAlE8Mtyp8YzD-4oE8sf5xwLumG6eOq1UyRmP_Y9gscenes-app-oauth-authorize--default-scopes--dark:- hash: v1.k794b7964.75a3dfa5dac33a4d5be5cb052703d6e336186e3aeec0483a844726e411168e1e.rIcOdkuJMGk2nU258kyAag_gs1n3BMadZGkhTc0txFc+ hash: v1.k794b7964.1f8d840aa1faa4a135f30132aeeead4fa35ef7612c9ecd2ba3afe9bada990801.5Su4rsQkK_Bio7pjpt19sN3e_eArf2AVSnfiYT9YHPkscenes-app-oauth-authorize--default-scopes--light:- hash: v1.k794b7964.ea92d09ab4ee986d5c05b472cf5de6e96be74dca5eb5d69aa2d25bf2f3a8f251.2LMMz7KixFidRzVgu3qG74B039qyiO6Kx-kevQoqyxE+ hash: v1.k794b7964.e5266cf2b549dda66b0a55f37daf10b22babbe32c032bccdb4eb6b2d18f6bba8.I7o54-FsDyrUctC9_sQqRsuiDuzFaVrTZ4p62A3JoBQ+ scenes-app-oauth-authorize--with-required-scopes--dark:+ hash: v1.k794b7964.2038825399aa94009a5f98096848ee08aa398857c1c8cf86c44375e9563265bb.mflovnzoua6llqFpDICk40ym3_OrfiFLIUnAikT2Qas+ scenes-app-oauth-authorize--with-required-scopes--light:+ hash: v1.k794b7964.364dc19ecd36a8a0847fce6d3955c72337b688070b08fab091a5a7c6716a0a7c.JCyjT8cMqj7jZN59idypP3lPkn_Bh3z7a6CaC95p-PMscenes-app-oauth-authorize--with-scopes--dark:- hash: v1.k794b7964.13ebea10c9925f79b3e37dd299aa2a615fcdea75e75977d663dd91e8668761d2.54tlTS2WI5hemj6Iqdc7GBv8EiEMyopfbiMUfD4cQMw+ hash: v1.k794b7964.f6f2cf0e077afc9c205781f227cd6bdc48ec9e38a16d52b4e4fab60b65d9ca5b.8L4usyBUS4Bc1II4wLiEzzXDjKQp9LF52ZBbm0GwkC8scenes-app-oauth-authorize--with-scopes--light:- hash: v1.k794b7964.be8b02daf03e8e960ec9ee04a8c1061465e5e92ac00c920519d0070bfe67360b.9Rb3NeH0fO8TUjFCtNglINOnp1nGf7CD1xylFcQU7-U+ hash: v1.k794b7964.ac46f9759407da7746f7016465807c26ed7cb2eb348841a43839f7d2a510f41e.wXFWrh0hHZfhAwy2ighYU5w_aj1RY8_oUsQmxZLqmPwscenes-app-people-cohorts--cohort-edit-dynamic--dark:hash: v1.k794b7964.b2c0b065af8c58ca547c691cc880221f64d0ac70a103bf0e47efada7300527f5.xrfnDLtIQxSP-8Ga0knhjf6CHtW0ZfBXqgI2god2ZlEscenes-app-people-cohorts--cohort-edit-dynamic--light:diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsxindex cf5bfe8f82f2..b64a7288ada4 100644--- a/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx+++ b/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx@@ -1,5 +1,6 @@-import { Meta, StoryObj } from '@storybook/react'+import { Decorator, Meta, StoryObj } from '@storybook/react'import { router } from 'kea-router'+import { useEffect, useRef } from 'react'import { useDelayedOnMountEffect } from 'lib/hooks/useOnMountEffect'import { App } from 'scenes/App'@@ -7,6 +8,37 @@ import { urls } from 'scenes/urls'import { mswDecorator } from '~/mocks/browser'+// Override the server-injected oauth_application context for a story. Set synchronously before+// the story (and its consent logic) mounts, and restored on unmount so story order can't leak.+function withOAuthApplication(overrides: Record<string, unknown>): Decorator {+ return function OAuthApplicationDecorator(Story): JSX.Element {+ const appContext = (window as any).POSTHOG_APP_CONTEXT+ const original = useRef<{ value: unknown }>()+ if (!original.current) {+ original.current = { value: appContext.oauth_application }+ appContext.oauth_application = { ...appContext.oauth_application, ...overrides }+ }+ useEffect(+ () => () => {+ appContext.oauth_application = original.current?.value+ },+ [appContext]+ )+ return <Story />+ }+}++const pushAuthorize = (scope?: string): void => {+ const params = new URLSearchParams({+ client_id: 'test-client-id',+ redirect_uri: 'https://app.example.com/oauth/callback',+ response_type: 'code',+ state: 'test-state',+ ...(scope ? { scope } : {}),+ })+ router.actions.push(`${urls.oauthAuthorize()}?${params.toString()}`)+}+const meta: Meta = {title: 'Scenes-App/OAuth/Authorize',parameters: {@@ -58,33 +90,42 @@ type Story = StoryObj<{}>export const DefaultScopes: Story = {render: () => {- useDelayedOnMountEffect(() => {- const params = new URLSearchParams({- client_id: 'test-client-id',- redirect_uri: 'https://example.com/callback',- response_type: 'code',- state: 'test-state',- })- router.actions.push(`${urls.oauthAuthorize()}?${params.toString()}`)- })-+ useDelayedOnMountEffect(() => pushAuthorize())return <App />},}+// Explicit request where every requested scope is required: rows render as a plain locked list+// (no checkboxes) and the read-only toggle is hidden, since there is nothing to toggle.export const WithScopes: Story = {+ decorators: [+ withOAuthApplication({+ required_scopes: ['experiment:read', 'experiment:write', 'query:read', 'feature_flag:write'],+ }),+ ],render: () => {- useDelayedOnMountEffect(() => {- const params = new URLSearchParams({- client_id: 'test-client-id',- redirect_uri: 'https://app.example.com/oauth/callback',- response_type: 'code',- state: 'test-state',- scope: 'experiment:read experiment:write query:read feature_flag:write',- })- router.actions.push(`${urls.oauthAuthorize()}?${params.toString()}`)- })+ useDelayedOnMountEffect(() => pushAuthorize('experiment:read experiment:write query:read feature_flag:write'))+ return <App />+ },+}+// Broad/deferred request (empty ceiling): nothing is required, so every row is deselectable and+// the read-only toggle is offered. This is the MCP case.+export const BroadFreePick: Story = {+ decorators: [withOAuthApplication({ required_scopes: [] })],+ render: () => {+ useDelayedOnMountEffect(() => pushAuthorize('experiment:read experiment:write query:read feature_flag:write'))+ return <App />+ },+}++// Mixed: feature_flag:write is required but only read was requested (renders locked at write),+// and experiment:read is required but unrequested (appears as an extra locked row). Because some+// requested scopes stay declinable, the checkboxes remain.+export const WithRequiredScopes: Story = {+ decorators: [withOAuthApplication({ required_scopes: ['experiment:read', 'feature_flag:write'] })],+ render: () => {+ useDelayedOnMountEffect(() => pushAuthorize('feature_flag:read query:read dashboard:write'))return <App />},}diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.tsxindex 7d5ff59b2a56..16c4794e9b9f 100644--- a/frontend/src/scenes/oauth/OAuthAuthorize.tsx+++ b/frontend/src/scenes/oauth/OAuthAuthorize.tsx@@ -7,8 +7,10 @@ import { IconCheck, IconCheckCircle, IconPlus, IconWarning } from '@posthog/iconimport { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'import { LemonInput } from 'lib/lemon-ui/LemonInput'import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'+import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'import { LemonSelect } from 'lib/lemon-ui/LemonSelect'import { Link } from 'lib/lemon-ui/Link'import { Spinner } from 'lib/lemon-ui/Spinner'@@ -123,7 +125,11 @@ const InlineCreateForm = ({export const OAuthAuthorize = (): JSX.Element => {const {- scopeDescriptions,+ scopeRows,+ allScopesRequired,+ identityScopeDescriptions,+ showReadOnlyToggle,+ readOnlyMode,oauthApplication,oauthApplicationLoading,allOrganizations,@@ -151,6 +157,8 @@ export const OAuthAuthorize = (): JSX.Element => {setShowCreateProject,setSelectedOrganization,setOauthAuthorizationValue,+ setReadOnlyMode,+ toggleDeniedScope,} = useActions(oauthAuthorizeLogic)const { isReadOnly: isImpersonationReadOnly, isImpersonated } = useValues(impersonationNoticeLogic)@@ -363,22 +371,68 @@ export const OAuthAuthorize = (): JSX.Element => {/>)}- <div>- <div className="text-sm font-semibold uppercase text-muted mb-2">Requested permissions</div>+ <div className="flex flex-col gap-3">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <div className="text-sm font-semibold uppercase text-muted">Permissions</div>+ {showReadOnlyToggle && (+ <LemonSegmentedButton+ size="small"+ value={readOnlyMode ? 'read' : 'full'}+ onChange={(value) => setReadOnlyMode(value === 'read')}+ options={[+ { value: 'full', label: 'All requested' },+ { value: 'read', label: 'Read-only' },+ ]}+ />+ )}+ </div>{resourceScopesLoading ? (<div className="flex items-center gap-2 py-2"><Spinner className="text-muted" /><span className="text-muted">Loading permissions...</span></div>) : (- <ul className="space-y-2">- {scopeDescriptions.map((scopeDescription, idx) => (- <li key={idx} className="flex items-center space-x-2 text-large">- <IconCheck color="var(--success)" />- <span className="font-medium">{scopeDescription}</span>- </li>- ))}- </ul>+ <>+ {identityScopeDescriptions.length > 0 && (+ <ul className="space-y-2">+ {identityScopeDescriptions.map((description, idx) => (+ <li key={idx} className="flex items-center space-x-2">+ <IconCheck color="var(--success)" />+ <span className="font-medium">{description}</span>+ </li>+ ))}+ </ul>+ )}+ {scopeRows.length > 0 &&+ (allScopesRequired ? (+ <ul className="space-y-2">+ {scopeRows.map((row) => (+ <li key={row.key} className="flex items-center space-x-2">+ <IconCheck color="var(--success)" />+ <span className="font-medium">{row.description}</span>+ </li>+ ))}+ </ul>+ ) : (+ <div className="flex flex-col gap-2">+ {scopeRows.map((row) => (+ <LemonCheckbox+ key={row.key}+ checked={row.granted}+ onChange={() =>+ row.toggleKey && toggleDeniedScope(row.toggleKey)+ }+ label={row.description}+ disabledReason={+ row.required+ ? `Required by ${oauthApplication.name}`+ : undefined+ }+ />+ ))}+ </div>+ ))}+ </>)}</div>diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.tsnew file mode 100644index 000000000000..caf6571a7d72--- /dev/null+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts@@ -0,0 +1,197 @@+import { MOCK_DEFAULT_USER } from 'lib/api.mock'++import { userLogic } from 'scenes/userLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { oauthAuthorizeLogic } from './oauthAuthorizeLogic'++describe('oauthAuthorizeLogic', () => {+ let logic: ReturnType<typeof oauthAuthorizeLogic.build>++ beforeEach(() => {+ useMocks({+ get: {+ '/api/users/@me/': MOCK_DEFAULT_USER,+ },+ })+ initKeaTests()+ userLogic.mount()+ logic = oauthAuthorizeLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ const effectiveScopesCases: { name: string; scopes: string[]; apply?: () => void; expected: string[] }[] = [+ {+ name: 'grants the full requested set, collapsed to the highest action',+ scopes: ['openid', 'feature_flag:read', 'feature_flag:write', 'insight:read'],+ expected: ['openid', 'feature_flag:write', 'insight:read'],+ },+ {+ name: 'downgrades every write scope to read in read-only mode',+ scopes: ['openid', 'feature_flag:write', 'dashboard:write', 'query:read'],+ apply: () => logic.actions.setReadOnlyMode(true),+ expected: ['openid', 'feature_flag:read', 'dashboard:read', 'query:read'],+ },+ {+ name: 'drops a denied object and keeps identity scopes',+ scopes: ['openid', 'email', 'feature_flag:write'],+ apply: () => logic.actions.toggleDeniedScope('feature_flag'),+ expected: ['openid', 'email'],+ },+ {+ name: 'grants the wildcard unchanged when read-only is off',+ scopes: ['openid', '*'],+ expected: ['openid', '*'],+ },+ ]++ it.each(effectiveScopesCases)('effectiveScopes $name', ({ scopes, apply, expected }) => {+ logic.actions.setScopes(scopes)+ apply?.()+ expect(logic.values.effectiveScopes).toEqual(expected)+ })++ it('offers the read-only toggle for wildcard requests', () => {+ logic.actions.setScopes(['*'])+ expect(logic.values.showReadOnlyToggle).toBe(true)+ })++ it('expands the wildcard to read scopes in read-only mode', () => {+ logic.actions.setScopes(['openid', '*'])+ logic.actions.setReadOnlyMode(true)+ const scopes = logic.values.effectiveScopes+ expect(scopes).toContain('openid')+ expect(scopes).toContain('feature_flag:read')+ expect(scopes).not.toContain('*')+ expect(scopes.some((scope) => scope.endsWith(':write'))).toBe(false)+ // Privileged/hidden objects are never grantable via /authorize; including them+ // would make the server reject the whole submit.+ expect(scopes).not.toContain('llm_gateway:read')+ expect(scopes).not.toContain('metrics:read')+ })++ it('uses the server-computed read set when expanding the wildcard', () => {+ logic.actions.setScopes(['openid', '*'])+ logic.actions.loadOAuthApplicationSuccess({+ name: 'Test App',+ client_id: 'test-client',+ is_verified: true,+ logo_uri: null,+ wildcard_read_scopes: ['insight:read', 'batch_import:read'],+ })+ logic.actions.setReadOnlyMode(true)+ expect(logic.values.effectiveScopes).toEqual(['openid', 'insight:read', 'batch_import:read'])+ })++ it('drops a scope when its object is denied and re-adds it when toggled back', () => {+ logic.actions.setScopes(['openid', 'feature_flag:write', 'insight:read'])+ logic.actions.toggleDeniedScope('feature_flag')+ expect(logic.values.effectiveScopes).toEqual(['openid', 'insight:read'])+ logic.actions.toggleDeniedScope('feature_flag')+ expect(logic.values.effectiveScopes).toEqual(['openid', 'feature_flag:write', 'insight:read'])+ })++ const withRequiredScopes = (required_scopes: string[]): void => {+ logic.actions.loadOAuthApplicationSuccess({+ name: 'Test App',+ client_id: 'test-client',+ is_verified: true,+ logo_uri: null,+ required_scopes,+ })+ }++ it('ignores denial of a required object and marks its row required', () => {+ logic.actions.setScopes(['openid', 'feature_flag:write', 'insight:read'])+ withRequiredScopes(['feature_flag:write'])+ logic.actions.toggleDeniedScope('feature_flag')+ expect(logic.values.effectiveScopes).toEqual(['openid', 'feature_flag:write', 'insight:read'])+ const row = logic.values.scopeRows.find((r) => r.key === 'feature_flag')+ expect(row).toMatchObject({ required: true, granted: true })+ })++ it('keeps a required write scope at write level in read-only mode', () => {+ logic.actions.setScopes(['openid', 'feature_flag:write', 'dashboard:write'])+ withRequiredScopes(['feature_flag:write'])+ logic.actions.setReadOnlyMode(true)+ expect(logic.values.effectiveScopes).toEqual(['openid', 'feature_flag:write', 'dashboard:read'])+ })++ it('downgrades to read in read-only mode when only the read level is required', () => {+ logic.actions.setScopes(['openid', 'feature_flag:write'])+ withRequiredScopes(['feature_flag:read'])+ logic.actions.setReadOnlyMode(true)+ expect(logic.values.effectiveScopes).toEqual(['openid', 'feature_flag:read'])+ const row = logic.values.scopeRows.find((r) => r.key === 'feature_flag')+ expect(row).toMatchObject({ required: true, granted: true })+ })++ it('marks all scopes required when every requested scope is required', () => {+ logic.actions.setScopes(['experiment:read', 'dashboard:write'])+ withRequiredScopes(['experiment:read', 'dashboard:write'])+ expect(logic.values.allScopesRequired).toBe(true)+ expect(logic.values.showReadOnlyToggle).toBe(false)+ })++ it('does not mark all required when a requested scope is declinable', () => {+ logic.actions.setScopes(['experiment:read', 'dashboard:write'])+ withRequiredScopes(['experiment:read'])+ expect(logic.values.allScopesRequired).toBe(false)+ })++ it('renders a locked row for required scopes the client did not request and grants them', () => {+ logic.actions.setScopes(['openid', 'insight:read'])+ withRequiredScopes(['feature_flag:read'])+ const row = logic.values.scopeRows.find((r) => r.key === 'feature_flag')+ expect(row).toMatchObject({ required: true, granted: true })+ expect(logic.values.effectiveScopes).toEqual(+ expect.arrayContaining(['openid', 'insight:read', 'feature_flag:read'])+ )+ expect(logic.values.effectiveScopes).toHaveLength(3)+ })++ it('lets the user decline an optional write above a required read floor', () => {+ logic.actions.setScopes(['openid', 'feature_flag:write'])+ withRequiredScopes(['feature_flag:read'])+ const floor = logic.values.scopeRows.find((r) => r.key === 'feature_flag')+ const upgrade = logic.values.scopeRows.find((r) => r.key === 'feature_flag:optional-write')+ expect(floor).toMatchObject({ required: true, granted: true, toggleKey: null })+ expect(upgrade).toMatchObject({ required: false, granted: true, toggleKey: 'feature_flag' })+ expect(logic.values.effectiveScopes).toContain('feature_flag:write')++ logic.actions.toggleDeniedScope('feature_flag')+ expect(logic.values.effectiveScopes).toEqual(['openid', 'feature_flag:read'])+ expect(logic.values.scopeRows.find((r) => r.key === 'feature_flag:optional-write')).toMatchObject({+ granted: false,+ })++ logic.actions.toggleDeniedScope('feature_flag')+ expect(logic.values.effectiveScopes).toContain('feature_flag:write')+ })++ it('renders the write level when a required write upgrades a requested read', () => {+ logic.actions.setScopes(['openid', 'feature_flag:read'])+ withRequiredScopes(['feature_flag:write'])+ const row = logic.values.scopeRows.find((r) => r.key === 'feature_flag')+ expect(row).toMatchObject({ required: true, granted: true })+ expect(row?.description).toContain('Write')+ expect(logic.values.effectiveScopes).toContain('feature_flag:write')+ expect(logic.values.effectiveScopes).not.toContain('feature_flag:read')+ })++ it('resets read-only mode and denied scopes when scopes are reloaded', () => {+ logic.actions.setScopes(['openid', 'feature_flag:write'])+ logic.actions.setReadOnlyMode(true)+ logic.actions.toggleDeniedScope('feature_flag')+ logic.actions.setScopes(['openid', 'insight:write'])+ expect(logic.values.readOnlyMode).toBe(false)+ expect(logic.values.deniedScopeObjects).toEqual([])+ expect(logic.values.effectiveScopes).toEqual(['openid', 'insight:write'])+ })+})diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.tsindex 2dd01bd93bdd..8f9a1be1ba0c 100644--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts@@ -6,6 +6,7 @@ import { router, urlToAction } from 'kea-router'import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import {+ API_SCOPES,DEFAULT_OAUTH_SCOPES,MCP_SERVER_OAUTH_SCOPES,getMinimumEquivalentScopes,@@ -24,6 +25,47 @@ export type OAuthAuthorizationFormValues = {access_type: 'all' | 'organizations' | 'teams'}+const IDENTITY_SCOPES = ['openid', 'profile', 'email', 'introspection']++const scopeObjectKey = (scope: string): string => (scope === '*' ? '*' : scope.split(':')[0])++const toReadOnlyScope = (scope: string): string => (scope.endsWith(':write') ? `${scope.split(':')[0]}:read` : scope)++const WILDCARD_READ_DESCRIPTION = 'Read access to all PostHog data'++// Required scopes are tracked per object at the action level that's required, so a+// required `obj:read` still lets the read-only toggle downgrade an optional `obj:write`.+export type RequiredLevel = 'read' | 'write'++const requiredLevelsFromScopes = (requiredScopes: string[]): Map<string, RequiredLevel> => {+ const levels = new Map<string, RequiredLevel>()+ for (const scope of requiredScopes) {+ if (!scope.includes(':') && scope !== '*') {+ continue+ }+ const key = scopeObjectKey(scope)+ const level: RequiredLevel = scope === '*' || scope.endsWith(':write') ? 'write' : 'read'+ if (level === 'write' || !levels.has(key)) {+ levels.set(key, level)+ }+ }+ return levels+}++// Mirrors PRIVILEGED_SCOPES + OAUTH_HIDDEN_SCOPE_OBJECTS in posthog/scopes.py: objects+// /authorize can never grant, so the wildcard expansion must skip them or the server+// would reject the whole submit with invalid_scope.+const OAUTH_UNGRANTABLE_OBJECTS: ReadonlySet<string> = new Set(['llm_gateway', 'metrics', 'wizard_session'])++// `*` grants read+write to everything; its read-only form is every grantable object's read+// scope. The server-computed list is authoritative — the local API_SCOPES list both lags+// behind new backend scopes (under-granting) and contains ungrantable ones (over-granting,+// which the server rejects). The local fallback only covers a missing app context.+const wildcardReadScopes = (oauthApplication: OAuthApplicationPublicMetadata | null): string[] =>+ oauthApplication?.wildcard_read_scopes?.length+ ? oauthApplication.wildcard_read_scopes+ : API_SCOPES.filter(({ key }) => !OAUTH_UNGRANTABLE_OBJECTS.has(key)).map(({ key }) => `${key}:read`)+const isNativeProtocol = (url: string): boolean => {try {const parsed = new URL(url)@@ -77,6 +119,8 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([})),actions({setScopes: (scopes: string[]) => ({ scopes }),+ setReadOnlyMode: (readOnly: boolean) => ({ readOnly }),+ toggleDeniedScope: (scopeObject: string) => ({ scopeObject }),setRequiredAccessLevel: (requiredAccessLevel: 'organization' | 'team' | null) => ({ requiredAccessLevel }),setScopesWereDefaulted: (scopesWereDefaulted: boolean) => ({ scopesWereDefaulted }),setIsMcpResource: (isMcpResource: boolean) => ({ isMcpResource }),@@ -200,6 +244,21 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([setScopes: (_, { scopes }) => scopes,},],+ readOnlyMode: [+ false,+ {+ setReadOnlyMode: (_, { readOnly }) => readOnly,+ setScopes: () => false,+ },+ ],+ deniedScopeObjects: [+ [] as string[],+ {+ toggleDeniedScope: (state, { scopeObject }) =>+ state.includes(scopeObject) ? state.filter((s) => s !== scopeObject) : [...state, scopeObject],+ setScopes: () => [],+ },+ ],requiredAccessLevel: [null as 'organization' | 'team' | null,{@@ -326,7 +385,7 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([: undefined,}),submit: async (values: OAuthAuthorizationFormValues) => {- const scopes = oauthAuthorizeLogic.values.scopes+ const scopes = oauthAuthorizeLogic.values.effectiveScopesconst result = await oauthAuthorize({...values,allow: true,@@ -394,12 +453,177 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([return teams.filter((t) => t.organization === selectedOrg)},],- scopeDescriptions: [+ identityScopeDescriptions: [(s) => [s.scopes],- (scopes: string[]): string[] => {- const minimumEquivalentScopes = getMinimumEquivalentScopes(scopes)-- return minimumEquivalentScopes.map(getScopeDescription).filter(Boolean) as string[]+ (scopes: string[]): string[] =>+ scopes+ .filter((scope) => IDENTITY_SCOPES.includes(scope))+ .map(getScopeDescription)+ .filter(Boolean) as string[],+ ],+ requiredScopeLevels: [+ (s) => [s.oauthApplication],+ (oauthApplication: OAuthApplicationPublicMetadata | null): Map<string, RequiredLevel> =>+ requiredLevelsFromScopes(oauthApplication?.required_scopes ?? []),+ ],+ // Only surface the read-only toggle when at least one write scope is declinable+ // (not required at write level). When every write scope is required, switching to+ // read-only would change nothing, so the toggle is a confusing no-op.+ showReadOnlyToggle: [+ (s) => [s.consentResourceScopes, s.requiredScopeLevels],+ (consentResourceScopes: string[], requiredScopeLevels: Map<string, RequiredLevel>): boolean =>+ consentResourceScopes.some((scope) => {+ if (!scope.endsWith(':write') && scope !== '*') {+ return false+ }+ return requiredScopeLevels.get(scopeObjectKey(scope)) !== 'write'+ }),+ ],+ // Requested plus required resource scopes, collapsed to the highest action per+ // object. Both the rows and the grant derive from this one set, so the consent+ // screen always displays exactly what authorizing will grant — required scopes+ // the client didn't request get a visible (locked) row, never a silent grant.+ consentResourceScopes: [+ (s) => [s.scopes, s.oauthApplication],+ (scopes: string[], oauthApplication: OAuthApplicationPublicMetadata | null): string[] => {+ const required = (oauthApplication?.required_scopes ?? []).filter(+ (scope) => scope.includes(':') || scope === '*'+ )+ return getMinimumEquivalentScopes([...scopes, ...required]).filter(+ (scope) => scope.includes(':') || scope === '*'+ )+ },+ ],+ scopeRows: [+ (s) => [s.consentResourceScopes, s.deniedScopeObjects, s.readOnlyMode, s.requiredScopeLevels],+ (+ consentResourceScopes: string[],+ deniedScopeObjects: string[],+ readOnlyMode: boolean,+ requiredScopeLevels: Map<string, RequiredLevel>+ ): {+ key: string+ toggleKey: string | null+ description: string+ granted: boolean+ required: boolean+ }[] => {+ const denied = new Set(deniedScopeObjects)+ return consentResourceScopes.flatMap((scope) => {+ const key = scopeObjectKey(scope)+ const requiredLevel = requiredScopeLevels.get(key)+ if (requiredLevel === undefined) {+ const downgrade = readOnlyMode+ if (scope === '*') {+ return [+ {+ key: '*',+ toggleKey: '*',+ description: downgrade+ ? WILDCARD_READ_DESCRIPTION+ : (getScopeDescription('*') ?? '*'),+ granted: !denied.has('*'),+ required: false,+ },+ ]+ }+ const effective = downgrade ? toReadOnlyScope(scope) : scope+ return [+ {+ key,+ toggleKey: key,+ description: getScopeDescription(effective) ?? effective,+ granted: !denied.has(key),+ required: false,+ },+ ]+ }+ // The required floor renders locked. An optional write above a required+ // read gets its own deniable row, so declining the upgrade doesn't take+ // the required level with it. Read-only mode suppresses the upgrade row+ // since the toggle already pins everything to read.+ const floorScope = scope === '*' ? '*' : `${key}:${requiredLevel}`+ const rows: {+ key: string+ toggleKey: string | null+ description: string+ granted: boolean+ required: boolean+ }[] = [+ {+ key,+ toggleKey: null,+ description: getScopeDescription(floorScope) ?? floorScope,+ granted: true,+ required: true,+ },+ ]+ if (requiredLevel === 'read' && scope.endsWith(':write') && !readOnlyMode) {+ rows.push({+ key: `${key}:optional-write`,+ toggleKey: key,+ description: getScopeDescription(scope) ?? scope,+ granted: !denied.has(key),+ required: false,+ })+ }+ return rows+ })+ },+ ],+ // When every row is required the user has nothing to toggle, so the consent screen+ // renders a plain locked list instead of disabled checkboxes that imply a choice.+ allScopesRequired: [+ (s) => [s.scopeRows],+ (scopeRows: { required: boolean }[]): boolean =>+ scopeRows.length > 0 && scopeRows.every((row) => row.required),+ ],+ effectiveScopes: [+ (s) => [+ s.scopes,+ s.consentResourceScopes,+ s.deniedScopeObjects,+ s.readOnlyMode,+ s.requiredScopeLevels,+ s.oauthApplication,+ ],+ (+ scopes: string[],+ consentResourceScopes: string[],+ deniedScopeObjects: string[],+ readOnlyMode: boolean,+ requiredScopeLevels: Map<string, RequiredLevel>,+ oauthApplication: OAuthApplicationPublicMetadata | null+ ): string[] => {+ const denied = new Set(deniedScopeObjects)+ const identity = scopes.filter((scope) => IDENTITY_SCOPES.includes(scope))+ const resources = consentResourceScopes.flatMap((scope) => {+ const key = scopeObjectKey(scope)+ const requiredLevel = requiredScopeLevels.get(key)+ if (requiredLevel === undefined) {+ if (denied.has(key)) {+ return []+ }+ if (scope === '*') {+ return readOnlyMode ? wildcardReadScopes(oauthApplication) : ['*']+ }+ return [readOnlyMode ? toReadOnlyScope(scope) : scope]+ }+ if (scope === '*') {+ return ['*']+ }+ // Denying the optional upgrade (or read-only mode) drops the grant to the+ // required floor, never below it.+ const upgradeActive =+ requiredLevel === 'read' && scope.endsWith(':write') && !readOnlyMode && !denied.has(key)+ return [upgradeActive ? scope : `${key}:${requiredLevel}`]+ })+ // Also grant the required strings verbatim: collapsing read+write pairs above+ // could otherwise drop a literal entry the server's set-difference check expects.+ const required = (oauthApplication?.required_scopes ?? []).filter(+ (scope) => scope.includes(':') || scope === '*'+ )+ return Array.from(new Set([...identity, ...resources, ...required]))},],redirectDomain: [diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 148c7f862e18..58252a5d64c6 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -7365,6 +7365,10 @@ export type OAuthApplicationPublicMetadata = {client_id: stringis_verified: booleanlogo_uri: string | null+ /** Scopes the user cannot deselect at consent. Empty unless the app declares optional scopes. */+ required_scopes?: string[]+ /** Server-computed read-only form of a `*` grant; the consent page must not derive this client-side. */+ wildcard_read_scopes?: string[]}export interface EmailSenderDomainStatus {status: 'pending' | 'success'diff --git a/posthog/admin/admins/oauth_admin.py b/posthog/admin/admins/oauth_admin.pyindex 2d377181086c..6612a59a6ddc 100644--- a/posthog/admin/admins/oauth_admin.py+++ b/posthog/admin/admins/oauth_admin.py@@ -140,6 +140,9 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne# 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")+ # Model validation also rejects optional_scopes on CIMD apps: a split would+ # let the partner grow the locked required set via metadata refresh.+ readonly.append("optional_scopes")return tuple(readonly)else:return ("id", "is_dcr_client", "is_cimd_client")@@ -166,7 +169,7 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne(None, {"fields": ("id", "name", "client_id", "client_type", "auth_brand", "logo_uri")}),("Authorization",- {"fields": ("authorization_grant_type", "redirect_uris", "algorithm", "scopes")},+ {"fields": ("authorization_grant_type", "redirect_uris", "algorithm", "scopes", "optional_scopes")},),("Ownership", {"fields": ("user", "organization")}),("Status", {"fields": ("is_verified", "is_first_party", "is_dcr_client", "is_cimd_client")}),@@ -190,7 +193,7 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne(None, {"fields": ("name", "client_id", "client_secret", "client_type", "auth_brand", "logo_uri")}),("Authorization",- {"fields": ("authorization_grant_type", "redirect_uris", "algorithm", "scopes")},+ {"fields": ("authorization_grant_type", "redirect_uris", "algorithm", "scopes", "optional_scopes")},),("Ownership", {"fields": ("user", "organization")}),("Status", {"fields": ("is_verified", "is_first_party")}),diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.pyindex 420fbba52e6f..ffafdd422b46 100644--- a/posthog/api/oauth/cimd.py+++ b/posthog/api/oauth/cimd.py@@ -370,6 +370,24 @@ def _resolve_scopes(metadata: CIMDMetadataDocument) -> list[str] | None:return filtered+def _resolve_optional_scopes(metadata: CIMDMetadataDocument) -> list[str] | None:+ """Resolve `com.posthog.optional_scopes` — the declinable subset a partner offers on top+ of its required `scopes`, so a CIMD client gets the same required/optional consent split as+ any other app. Returns None when the field is absent (leave existing scopes untouched),+ otherwise the grantable-filtered list. Unlike `scopes`, an empty result is benign (it just+ means no optional scopes, with no widen-to-default fallback), so a fully non-grantable list+ resolves to `[]` rather than rejecting the registration.+ """+ com_posthog = metadata.get("com.posthog")+ if not isinstance(com_posthog, dict):+ return None+ # Untrusted partner JSON: guard the real type rather than trust the TypedDict.+ raw_optional: object = com_posthog.get("optional_scopes")+ if not isinstance(raw_optional, list):+ return None+ return filter_to_unprivileged_scopes(raw_optional)++def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthApplication:"""Create a new OAuthApplication from CIMD metadata."""client_name = metadata.get("client_name", "CIMD Client")@@ -382,6 +400,7 @@ def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthAlogo_uri = metadata.get("logo_uri") or Noneverification = _resolve_verification_token(metadata)resolved_scopes = _resolve_scopes(metadata)+ resolved_optional_scopes = _resolve_optional_scopes(metadata)app = OAuthApplication(name=client_name,@@ -397,6 +416,7 @@ def _create_cimd_application(url: str, metadata: CIMDMetadataDocument) -> OAuthAlogo_uri=logo_uri,organization=verification.organization if verification else None,scopes=resolved_scopes if resolved_scopes is not None else [],+ optional_scopes=resolved_optional_scopes if resolved_optional_scopes is not None else [],user=None,)app.full_clean()@@ -447,6 +467,12 @@ def _update_cimd_application(app: OAuthApplication, metadata: CIMDMetadataDocumeif resolved_scopes is not None:app.scopes = resolved_scopesupdate_fields.append("scopes")+ # Refresh `optional_scopes` from the same metadata so the required/optional split never+ # drifts: both fields are rewritten together on every fetch.+ resolved_optional_scopes = _resolve_optional_scopes(metadata)+ if resolved_optional_scopes is not None:+ app.optional_scopes = resolved_optional_scopes+ update_fields.append("optional_scopes")old_org_id = app.organization_idnew_org_id = new_org.id if new_org else Noneif old_org_id != new_org_id:diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.pyindex a24be17adb2d..43d00f753ab5 100644--- a/posthog/api/oauth/test_cimd.py+++ b/posthog/api/oauth/test_cimd.py@@ -964,6 +964,42 @@ class TestCIMDComPostHogNamespace(APIBaseTest):assert refreshed is not Noneself.assertEqual(refreshed.scopes, ["survey:read"])+ # com.posthog.optional_scopes carries the required/optional split: required `scopes` and the+ # declinable `optional_scopes` are written together on creation, capped to grantable scopes.+ @patch("posthog.api.oauth.cimd.requests.get")+ def test_optional_scopes_written_to_app_on_creation(self, mock_get, _url_mock):+ metadata = _make_metadata(+ com_posthog={"scopes": ["insight:read"], "optional_scopes": ["dashboard:read", "llm_gateway: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"])+ # llm_gateway:read is privileged, stripped by the grantable filter.+ self.assertEqual(app.optional_scopes, ["dashboard:read"])+ self.assertEqual(app.required_scopes, ["insight:read"])++ # Both fields refresh together so the split never drifts: a metadata refresh rewrites+ # `optional_scopes` alongside `scopes`.+ @patch("posthog.api.oauth.cimd.requests.get")+ def test_optional_scopes_refresh_together_with_scopes(self, mock_get, _url_mock):+ mock_get.return_value = _mock_response(+ _make_metadata(com_posthog={"scopes": ["insight:read"], "optional_scopes": ["dashboard:read"]}), headers={}+ )+ fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ real_cache.delete(_fetch_lock_key(VALID_CIMD_URL))+ mock_get.return_value = _mock_response(+ _make_metadata(com_posthog={"scopes": ["survey:read"], "optional_scopes": ["experiment:read"]}), headers={}+ )+ refreshed = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert refreshed is not None+ self.assertEqual(refreshed.scopes, ["survey:read"])+ self.assertEqual(refreshed.optional_scopes, ["experiment: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 ondiff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex 9ca2a432cf6b..7db1832ca782 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -14,6 +14,7 @@ from unittest.mock import patchfrom django.conf import settingsfrom django.db import OperationalError+from django.http import HttpResponsefrom django.test import SimpleTestCase, override_settingsfrom django.utils import timezone@@ -2606,9 +2607,11 @@ class TestOAuthAPI(APIBaseTest):assert locationself.assertIn("error=invalid_scope", location)- def test_authorize_accepts_scope_within_app_ceiling(self):+ def test_authorize_accepts_full_grant_of_app_ceiling(self):+ # Without optional_scopes every ceiling scope is required, so a grant that+ # includes the whole ceiling succeeds.self._set_ceiling("experiment:read", "dashboard:read")- response = self._authorize_post("experiment:read")+ response = self._authorize_post("experiment:read dashboard:read")self.assertEqual(response.status_code, status.HTTP_200_OK)redirect_to = response.json()["redirect_to"]self.assertNotIn("error=invalid_scope", redirect_to)@@ -2641,6 +2644,18 @@ class TestOAuthAPI(APIBaseTest):assert locationself.assertIn("error=invalid_scope", location)+ def test_authorize_get_passes_wildcard_read_scopes_to_consent_page(self):+ with patch("posthog.api.oauth.views.render_template", return_value=HttpResponse("")) as mock_render:+ response = self.client.get(f"{self.base_authorization_url}&scope=*")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ wildcard_reads = mock_render.call_args.kwargs["context"]["oauth_application"]["wildcard_read_scopes"]+ self.assertIn("insight:read", wildcard_reads)+ self.assertIn("batch_import:read", wildcard_reads)+ self.assertNotIn("llm_gateway:read", wildcard_reads)+ self.assertNotIn("wizard_session:read", wildcard_reads)+ self.assertIn("metrics:read", wildcard_reads)+ self.assertFalse(any(scope.endswith(":write") for scope in wildcard_reads))+def test_authorize_wildcard_accepted_when_app_ceiling_empty(self):# Existing clients (the PostHog Code CLI today) still send scope=*# against apps that have no explicit ceiling. Until wildcard retirement@@ -2651,6 +2666,75 @@ class TestOAuthAPI(APIBaseTest):self.assertNotIn("error=invalid_scope", redirect_to)self.assertIn("code=", redirect_to)+ # --- Required vs. optional scopes (OAuthApplication.optional_scopes) ---++ def _set_scope_split(self, required: list[str], optional: list[str]) -> None:+ self.confidential_application.scopes = required+ self.confidential_application.optional_scopes = optional+ self.confidential_application.save()++ @parameterized.expand(+ [+ ("grants_required_plus_optional", "experiment:read dashboard:read", status.HTTP_200_OK),+ ("allows_dropping_optional", "experiment:read", status.HTTP_200_OK),+ ("rejects_missing_required", "dashboard:read", status.HTTP_400_BAD_REQUEST),+ ]+ )+ def test_authorize_post_with_scope_split(self, _name, granted_scope, expected_status):+ self._set_scope_split(["experiment:read"], ["dashboard:read"])+ response = self._authorize_post(granted_scope)+ self.assertEqual(response.status_code, expected_status)+ if expected_status == status.HTTP_200_OK:+ self.assertIn("code=", response.json()["redirect_to"])+ else:+ body = response.json()+ self.assertEqual(body["error"], "invalid_scope")+ self.assertIn("experiment:read", body["error_description"])++ def test_scopes_without_optional_are_all_required(self):+ # Every explicit ceiling scope is required and locked at consent; dropping one+ # 400s. The consent UI force-includes all required scopes, so only a raw+ # partial POST that bypasses it reaches this rejection.+ self._set_ceiling("experiment:read", "dashboard:read")+ self.assertEqual(self.confidential_application.required_scopes, ["experiment:read", "dashboard:read"])+ response = self._authorize_post("dashboard:read")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ body = response.json()+ self.assertEqual(body["error"], "invalid_scope")+ self.assertIn("experiment:read", body["error_description"])++ @freeze_time("2025-01-01 00:00:00")+ def test_auto_approval_skipped_when_request_omits_required_scope(self):+ # An existing token covering the (optional-only) request must not auto-approve+ # below the required floor; the consent screen handles granting the full set.+ self._set_scope_split(["experiment:read"], ["dashboard:read"])+ OAuthAccessToken.objects.create(+ application=self.confidential_application,+ user=self.user,+ token="at_auto_approval_optional_only",+ expires=timezone.now() + timedelta(hours=1),+ scope="dashboard:read",+ scoped_teams=[self.team.id],+ scoped_organizations=None,+ )+ with patch("posthog.api.oauth.views.render_template", return_value=HttpResponse("")) as mock_render:+ response = self.client.get(f"{self.base_authorization_url}&scope=dashboard:read&approval_prompt=auto")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_render.assert_called_once()++ def test_authorize_get_passes_required_scopes_to_consent_page(self):+ self._set_scope_split(["experiment:read"], ["dashboard:read"])+ with patch("posthog.api.oauth.views.render_template", return_value=HttpResponse("")) as mock_render:+ response = self.client.get(f"{self.base_authorization_url}&scope=experiment:read%20dashboard:read")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ context = mock_render.call_args.kwargs["context"]+ self.assertEqual(context["oauth_application"]["required_scopes"], ["experiment:read"])++ def test_refresh_keeps_optional_scope_within_combined_ceiling(self):+ self._set_scope_split(["experiment:read"], ["dashboard:read"])+ refresh_token = self._create_refreshable_token_pair("experiment:read dashboard:read")+ self.assertEqual(self._refresh_and_get_scopes(refresh_token), {"experiment:read", "dashboard:read"})+@parameterized.expand([(diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex c125fffcb823..8ccef863a8ad 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -414,8 +414,10 @@ class OAuthValidator(OAuth2Validator):return Falsedef validate_scopes(self, client_id, scopes, client, request, *args, **kwargs):- """Enforce the per-application scope ceiling from `OAuthApplication.scopes`.+ """Enforce the per-application scope ceiling from the app's grantable set.+ The ceiling is `scopes` plus `optional_scopes` (`ceiling_scopes`), so an app+ using the required/optional split can request its optional scopes too.Delegates the ceiling resolution to `scopes_within_ceiling` so `/authorize`and the hand-rolled provisioning mint paths share one implementation. Theonly `/authorize`-specific bit kept here is mutating `request.scopes` when@@ -423,7 +425,7 @@ class OAuthValidator(OAuth2Validator):from `DEFAULT_SCOPES`. `*` is accepted under an empty ceiling here (legacyPostHog Code CLI) but not on the provisioning paths — see the flag."""- app_scopes = getattr(client, "scopes", None) or []+ app_scopes = getattr(client, "ceiling_scopes", None) or []requested = set(scopes or [])if not requested:request.scopes = sorted(effective_ceiling(app_scopes) | ALWAYS_ALLOWED_SCOPES)@@ -435,8 +437,8 @@ class OAuthValidator(OAuth2Validator):DOT's refresh grant copies the prior access token's scopes verbatim and neverre-runs `validate_scopes`, so a token minted before a ceiling was tightened would- keep refreshing into the old, broader set. Intersecting with `application.scopes`- means a narrowed app drops the removed scopes on the next refresh.+ keep refreshing into the old, broader set. Intersecting with the app's+ `ceiling_scopes` means a narrowed app drops the removed scopes on the next refresh.Always-allowed scopes (OIDC, introspection) pass through, mirroring`validate_scopes`. Resolution when the app has a ceiling:@@ -448,7 +450,9 @@ class OAuthValidator(OAuth2Validator):re-authorizes and gets a token within the current ceiling, rather thansilently keeping out-of-ceiling access.- An empty `application.scopes` (no ceiling) is a no-op.+ An empty `ceiling_scopes` (no ceiling) is a no-op. Refresh never enforces the+ required floor — a token consented below a later-declared required set keeps+ its narrower scopes rather than silently widening on refresh."""original = super().get_original_scopes(refresh_token, request, *args, **kwargs)# DOT's base returns the stored scope as a space-delimited string; oauthlib@@ -461,7 +465,7 @@ class OAuthValidator(OAuth2Validator):rt = OAuthRefreshToken.objects.filter(token=refresh_token).select_related("application").first()application = rt.application if rt else None- narrowed = narrow_scopes_to_ceiling(original_list, getattr(application, "scopes", None) or [])+ narrowed = narrow_scopes_to_ceiling(original_list, getattr(application, "ceiling_scopes", None) or [])if narrowed is None:# Raised inside oauthlib's validate_token_request, which create_token_response# wraps and turns into an RFC 6749 `invalid_grant` 400 — not a 500.@@ -951,8 +955,13 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):except OAuthToolkitError as error:return self.error_response(error, application, state=request.query_params.get("state"))- # Check for auto-approval- if request.query_params.get("approval_prompt", oauth2_settings.REQUEST_APPROVAL_PROMPT) == "auto":+ # Check for auto-approval. Skipped when the request omits a required scope:+ # auto-approving would mint a grant below the app's required floor, so fall+ # through to the consent screen, which displays and grants the full required set.+ required_resource_scopes = {scope for scope in application.required_scopes if ":" in scope}+ if request.query_params.get(+ "approval_prompt", oauth2_settings.REQUEST_APPROVAL_PROMPT+ ) == "auto" and required_resource_scopes <= set(scope_str.split()):try:tokens = OAuthAccessToken.objects.filter(user=request.user, application=application, expires__gt=timezone.now()@@ -985,6 +994,13 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):"client_id": application.client_id,"is_verified": application.is_verified,"logo_uri": application.logo_uri,+ "required_scopes": application.required_scopes,+ # The read-only form of a `*` grant, computed from the same ceiling+ # resolution `validate_scopes` enforces — the frontend's scope list+ # drifts from the server's (both over- and under-granting otherwise).+ "wildcard_read_scopes": sorted(+ scope for scope in effective_ceiling(application.ceiling_scopes) if scope.endswith(":read")+ ),}},)@@ -1023,6 +1039,29 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):scopes = downgrade_scopes_to_read_only(scopes)if serializer.validated_data["allow"]:+ # Required scopes can't be deselected at consent. Compare against the same+ # read-only downgrade applied to the grant, so impersonation doesn't 400.+ # Filtered to resource scopes to mirror the consent UI, which only renders+ # and force-includes `object:action` rows (identity scopes always pass).+ required = {scope for scope in application.required_scopes if ":" in scope}+ if is_read_only_impersonation(request):+ required = set(downgrade_scopes_to_read_only(" ".join(sorted(required))).split())+ missing_required = required - set(scopes.split())+ if missing_required:+ logger.warning(+ "oauth_authorize_missing_required_scopes",+ client_id=serializer.validated_data["client_id"],+ missing=sorted(missing_required),+ )+ return Response(+ {+ "error": "invalid_scope",+ "error_description": "The grant is missing scopes the application requires: "+ + ", ".join(sorted(missing_required)),+ },+ status=status.HTTP_400_BAD_REQUEST,+ )+if block := _impersonation_ai_processing_block(request,access_level=serializer.validated_data.get("access_level"),@@ -1087,7 +1126,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):requested_scope = self.request.query_params.get("scope") or ""rejected_scopes = scopes_outside_ceiling(requested_scope.split(),- application.scopes or [],+ application.ceiling_scopes,allow_wildcard_under_empty_ceiling=True,)posthoganalytics.capture(diff --git a/posthog/migrations/1234_oauthapplication_optional_scopes_and_more.py b/posthog/migrations/1234_oauthapplication_optional_scopes_and_more.pynew file mode 100644index 000000000000..4040857c5f6c--- /dev/null+++ b/posthog/migrations/1234_oauthapplication_optional_scopes_and_more.py@@ -0,0 +1,37 @@+# Generated by Django 5.2.14 on 2026-06-16 21:19++import django.contrib.postgres.fields+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1233_backfill_duckgresserverteam"),+ ]++ operations = [+ migrations.AddField(+ model_name="oauthapplication",+ name="optional_scopes",+ field=django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=100),+ blank=True,+ db_default=[],+ default=list,+ help_text="Additive declinable scopes layered on top of the required `scopes` base — the user may decline these at consent. Requires a non-empty `scopes` (an app with optional extras must have a required base).",+ size=None,+ ),+ ),+ migrations.AlterField(+ model_name="oauthapplication",+ name="scopes",+ field=django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=100),+ blank=True,+ db_default=[],+ default=list,+ help_text="Required scope ceiling — strings tokens issued for this app may carry, all required and locked on the consent screen. Empty list means a broad/deferred request (the user picks freely).",+ size=None,+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex d8b06abfe5eb..074e368e6c8e 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1233_backfill_duckgresserverteam+1234_oauthapplication_optional_scopes_and_morediff --git a/posthog/models/oauth.py b/posthog/models/oauth.pyindex c53e295856b3..d71d3e3fe8c8 100644--- a/posthog/models/oauth.py+++ b/posthog/models/oauth.py@@ -109,9 +109,39 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignoredb_default=[],blank=True,null=False,- help_text=("Scope ceiling — strings tokens issued for this app may carry. Empty list means no per-app cap."),+ help_text=(+ "Required scope ceiling — strings tokens issued for this app may carry, all required and "+ "locked on the consent screen. Empty list means a broad/deferred request (the user picks freely)."+ ),+ )++ optional_scopes: ArrayField = ArrayField(+ models.CharField(max_length=100),+ default=list,+ db_default=[],+ blank=True,+ null=False,+ help_text=(+ "Additive declinable scopes layered on top of the required `scopes` base — the user may "+ "decline these at consent. Requires a non-empty `scopes` (an app with optional extras must "+ "have a required base)."+ ),)+ @property+ def ceiling_scopes(self) -> list[str]:+ """The full grantable set: `scopes` plus `optional_scopes`, deduplicated."""+ return list(dict.fromkeys([*self.scopes, *self.optional_scopes]))++ @property+ def required_scopes(self) -> list[str]:+ # Everything in the explicit ceiling is required and locked at consent; optional_scopes+ # are additive declinable extras. An empty `scopes` is a broad/deferred request+ # (MCP / `*` / empty) so nothing is required and the user picks freely. Self-registered+ # (DCR / CIMD) ceilings are already filtered to grantable scopes and shown as locked rows+ # the user can decline by cancelling, so they carry the same required floor as any other app.+ return list(self.scopes)+# Generation marker for app-wide session revocation. A refresh presenting a token issued# before this timestamp is rejected at mint time, so a refresh racing revoke_application_sessions# can't slip new tokens past the one-shot bulk revoke.@@ -257,6 +287,24 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignoredef clean(self):super().clean()+ if self.optional_scopes:+ if not self.scopes:+ raise ValidationError(+ {"optional_scopes": "Declaring optional scopes requires a non-empty required set in `scopes`."}+ )+ for field, values in (("scopes", self.scopes), ("optional_scopes", self.optional_scopes)):+ non_resource = [scope for scope in values if ":" not in scope]+ if non_resource:+ # `*` or identity scopes in a required set either brick /authorize+ # (explicit ceilings reject `*`) or 400 every consent the client+ # didn't request them on, with no UI recourse.+ raise ValidationError(+ {+ field: f"With optional scopes declared, every entry must be a resource scope "+ f"(object:action); invalid: {', '.join(non_resource)}"+ }+ )+for uri in self.redirect_uris.split(" "):if not uri:continuediff --git a/posthog/models/test/test_oauth.py b/posthog/models/test/test_oauth.pyindex e7231117c2b7..2a20de02a9a3 100644--- a/posthog/models/test/test_oauth.py+++ b/posthog/models/test/test_oauth.py@@ -69,6 +69,52 @@ class TestOAuthModels(TestCase):app.refresh_from_db()self.assertEqual(app.scopes, ["insight:read", "llm_gateway:read"])+ @parameterized.expand(+ [+ ("empty_scopes_broad", [], [], [], []),+ ("explicit_no_optional_all_required", ["insight:read"], [], ["insight:read"], ["insight:read"]),+ ("split", ["insight:read"], ["dashboard:read"], ["insight:read", "dashboard:read"], ["insight:read"]),+ (+ "overlap_deduped",+ ["insight:read", "dashboard:write"],+ ["dashboard:write", "experiment:read"],+ ["insight:read", "dashboard:write", "experiment:read"],+ ["insight:read", "dashboard:write"],+ ),+ ]+ )+ def test_ceiling_and_required_scope_properties(self, _name, scopes, optional, expected_ceiling, expected_required):+ app = self._make_app(f"Split {_name}", f"split_{_name}_client", scopes=scopes, optional_scopes=optional)+ self.assertEqual(app.ceiling_scopes, expected_ceiling)+ self.assertEqual(app.required_scopes, expected_required)++ @parameterized.expand(+ [+ ("optional_without_required", [], ["dashboard:read"], "optional_scopes"),+ ("wildcard_in_required", ["*"], ["dashboard:read"], "scopes"),+ ("identity_scope_in_required", ["openid", "insight:read"], ["dashboard:read"], "scopes"),+ ("identity_scope_in_optional", ["insight:read"], ["openid"], "optional_scopes"),+ ]+ )+ def test_scope_split_validation_rejects_invalid_configs(self, _name, scopes, optional, error_field):+ with self.assertRaises(ValidationError) as ctx:+ self._make_app(f"Invalid {_name}", f"invalid_{_name}_client", scopes=scopes, optional_scopes=optional)+ self.assertIn(error_field, ctx.exception.message_dict)++ def test_cimd_application_can_declare_optional_scopes(self):+ # CIMD partners declare the required/optional split in their metadata; both fields are+ # refreshed together, so the split is a first-class CIMD feature, not a forbidden one.+ app = self._make_app(+ "CIMD Split",+ "cimd_split_client",+ is_cimd_client=True,+ cimd_metadata_url="https://example.com/oauth-client",+ scopes=["insight:read"],+ optional_scopes=["dashboard:read"],+ )+ self.assertEqual(app.required_scopes, ["insight:read"])+ self.assertEqual(app.ceiling_scopes, ["insight:read", "dashboard:read"])+def test_oauth_access_token_label_defaults_to_empty_string(self):app = self._make_app("Token Label Default", "token_label_default_client")token = OAuthAccessToken.objects.create(