: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): note that access controls still apply (#102106)
Alex Liderb5ee6cbaa974
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex ee0d117ff9ec..767237de5de8 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9656,6 +9656,10 @@ snapshots:hash: v1.k794b7964.dded071925e13813948059d3a851fda7045079765dd39c35a1909a33f4818670.uLBVI91IfZ7a2kAB6tnEs6CHaEQ_xl-6gI91X4096sMscenes-app-notebooks-widget-views--workflow-views--light:hash: v1.k794b7964.cd7fa77d9236079839583863834cd6f2a7a0aea88be4bdb1fb68e4e9c0ab4dab.df8Gy7QN0LSBis_grrNFZCyPlgTJV9k90oTKS9o2ouI+ scenes-app-oauth-authorize--access-controls-apply--dark:+ hash: v1.k794b7964.2268c82adb701899471a901fb008d250988c8443985ed232003ca12295b1d921.i8DoC2hnX3sWU5b-vb4iYAhnFb8ZMMlXM4F1KBUYEhk+ scenes-app-oauth-authorize--access-controls-apply--light:+ hash: v1.k794b7964.fea1155c17aac8781f826253e9518af5be6bbcc077d1fca1661d11396b86fe49.mV_6zj24dUY_Di77iUM35r40WPSxuLKJbvFtiELPWDMscenes-app-oauth-authorize--all-scopes-optional--dark:hash: v1.k794b7964.a03d00f6626add00255abe8fa712c056cecbf929f724284de20cf6e936a96fbe.cCaJ_N0193dGvxNreYfm9ltl9zmGo4r3-9-vKCX7TwQscenes-app-oauth-authorize--all-scopes-optional--light:diff --git a/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsxindex 4f63afc66869..22e6b28250ac 100644--- a/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx+++ b/frontend/src/scenes/oauth/OAuthAuthorize.stories.tsx@@ -195,6 +195,37 @@ export const ManyOptionalScopes: Story = {},}+// Sets the server flag that says one of the user's organizations has access-control rules.+// The story below shows the notice this flag adds under the permission list. The decorator+// restores the original flag on unmount so it cannot leak into other stories.+const withAccessControls: Decorator = function AccessControlsDecorator(Story): JSX.Element {+ const appContext = (window as any).POSTHOG_APP_CONTEXT+ const original = useRef<{ value: unknown } | null>(null)+ if (!original.current) {+ original.current = { value: appContext.oauth_consent_access_controls_apply }+ appContext.oauth_consent_access_controls_apply = true+ }+ useEffect(+ () => () => {+ appContext.oauth_consent_access_controls_apply = original.current?.value+ },+ [appContext]+ )+ return <Story />+}++export const AccessControlsApply: Story = {+ decorators: [withAccessControls, withOAuthApplication({ required_scopes: [] })],+ render: () => {+ useDelayedOnMountEffect(() =>+ pushAuthorize(+ 'openid profile email project:read feature_flag:read feature_flag:write insight:write query:read'+ )+ )+ return <App />+ },+}+const everyScopeRequest = ['openid', 'profile', 'email', ...API_SCOPES.map(({ key }) => `${key}:write`)].join(' ')// The worst case for the layout: a client that asks for every scope PostHog has, which is onediff --git a/frontend/src/scenes/oauth/OAuthAuthorize.tsx b/frontend/src/scenes/oauth/OAuthAuthorize.tsxindex 43cd6ab520b4..fb43e1282719 100644--- a/frontend/src/scenes/oauth/OAuthAuthorize.tsx+++ b/frontend/src/scenes/oauth/OAuthAuthorize.tsx@@ -3,7 +3,7 @@ import { useActions, useValues } from 'kea'import { Form } from 'kea-forms'import { useMemo, useState } from 'react'-import { IconCheck, IconCheckCircle, IconPlus, IconWarning } from '@posthog/icons'+import { IconCheck, IconCheckCircle, IconLock, IconPlus, IconWarning } from '@posthog/icons'import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'import { upgradeModalLogic } from 'lib/components/UpgradeModal/upgradeModalLogic'@@ -146,6 +146,7 @@ export const OAuthAuthorize = (): JSX.Element => {redirectUrl,scopesWereDefaulted,isMcpResource,+ accessControlsApply,showCreateProject,newProjectLoading,selectedOrganization,@@ -470,6 +471,13 @@ export const OAuthAuthorize = (): JSX.Element => {))}</div>)}+ {accessControlsApply && (+ <LemonBanner type="info" icon={<IconLock className="LemonBanner__icon" />}>+ <strong className="block">Access controls still apply.</strong>+ {appName} can only do what both your access level and these permissions+ allow.+ </LemonBanner>+ )}</div></div></div>diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.tsindex fc5bb6084eaf..1442550848d3 100644--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.test.ts@@ -6,6 +6,7 @@ import { userLogic } from 'scenes/userLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { AppContext } from '~/types'import { describeOAuthError, oauthAuthorizeLogic } from './oauthAuthorizeLogic'@@ -301,6 +302,23 @@ describe('oauthAuthorizeLogic', () => {})// Opaque client-owned params must reach the API byte-for-byte, whatever they look like.+ it.each([+ { name: 'the server sets no flag', flag: undefined, expected: false },+ { name: 'the server sets the flag to false', flag: false, expected: false },+ { name: 'the server sets the flag to true', flag: true, expected: true },+ ])('reports access controls as $expected when $name', ({ flag, expected }) => {+ const original = window.POSTHOG_APP_CONTEXT+ window.POSTHOG_APP_CONTEXT = { ...original, oauth_consent_access_controls_apply: flag } as AppContext+ try {+ logic.unmount()+ logic = oauthAuthorizeLogic()+ logic.mount()+ expect(logic.values.accessControlsApply).toBe(expected)+ } finally {+ window.POSTHOG_APP_CONTEXT = original+ }+ })+describe('OAuth parameter passthrough', () => {const JSON_STATE = '{"flow_id":"5a8f3d48-c841-4375-b06d-5c828c86282d","provider":"posthog"}'diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.tsindex bd5619469934..b56b4f93b8e6 100644--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts@@ -190,6 +190,7 @@ const oauthAuthorize = async (// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface oauthAuthorizeLogicValues {user: UserType | null // userLogic+ accessControlsApply: booleanadjustableScopeRows: OAuthScopeRow[]allOrganizations: OrganizationBasicType[]allScopesRequired: boolean@@ -705,6 +706,8 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([},})),selectors(() => ({+ // The server sets this flag once for the page, so no action changes it.+ accessControlsApply: [() => [], (): boolean => getAppContext()?.oauth_consent_access_controls_apply === true],allOrganizations: [(s) => [s.user],(user: UserType): OrganizationBasicType[] => {diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex e3cf191f82df..0bee0cc8e6eb 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5236,6 +5236,8 @@ export interface AppContext {oauth_application?: OAuthApplicationPublicMetadata/** Server-resolved MCP scopes for OAuth consent when the client omits `scope`. */oauth_mcp_consent?: OAuthMcpConsentContext+ /** One of the user's organizations has the access-control feature and at least one rule, so a granted scope can reach less. */+ oauth_consent_access_controls_apply?: boolean/** The user's configured homepage for the current team, bootstrapped so navigation can honor it on first paint. */homepage?: SceneTab | null}diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex 91a0fd27d24a..81839f66e9d3 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -32,6 +32,7 @@ from posthog.api.oauth.cimd import CIMD_SUPPORTED_AUTH_METHODSfrom posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARERfrom posthog.api.oauth.metadata import authorization_server_metadata, openid_provider_metadatafrom posthog.api.oauth.views import OAuthTokenView, OAuthValidator, _token_error_code+from posthog.constants import AvailableFeaturefrom posthog.helpers.oauth_pending_connection import (PENDING_OAUTH_CONNECTION_COOKIE,PENDING_OAUTH_CONNECTION_MAX_AGE_SECONDS,@@ -46,11 +47,14 @@ from posthog.models.oauth import (revoke_application_sessions,revoke_oauth_session,)+from posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom posthog.scopes import get_oauth_scopes_supportedfrom posthog.settings.utils import generate_rsa_private_key_pemfrom posthog.utils import absolute_uri+from products.access_control.backend.models.access_control import AccessControl+def jwks_entry_to_public_key(key_data: dict):# Rebuild an RSA public key from a JWKS entry's modulus (n) and exponent (e).@@ -279,6 +283,33 @@ class TestOAuthAPI(APIBaseTest):template_context = mock_render.call_args.kwargs["context"]self.assertNotIn("oauth_mcp_consent", template_context)+ def test_authorize_reports_whether_access_controls_apply(self):+ def applies() -> bool:+ response = self.client.get(self.base_authorization_url)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ return json.loads(response.context["posthog_app_context"])["oauth_consent_access_controls_apply"]++ access_control_feature = [{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}]+ self.assertFalse(applies())++ self.organization.available_product_features = access_control_feature+ self.organization.save()+ # The feature alone changes nothing a person can reach; a rule does.+ self.assertFalse(applies())++ AccessControl.objects.create(team=self.team, resource="feature_flag", access_level="viewer")+ self.assertTrue(applies())++ # The grant can reach any organization the user belongs to, not only the current one.+ self.organization.available_product_features = []+ self.organization.save()+ self.assertFalse(applies())+ other_org, _, other_team = Organization.objects.bootstrap(self.user, name="Other Organization")+ other_org.available_product_features = access_control_feature+ other_org.save()+ AccessControl.objects.create(team=other_team, resource="insight", access_level="none")+ self.assertTrue(applies())+def test_first_party_app_auto_approves_with_org_scoped_grant(self):first_party_app = OAuthApplication.objects.create(name="First Party App",diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 9e33684413f9..b4cee6137e23 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -101,6 +101,8 @@ from posthog.user_permissions import UserPermissionsfrom posthog.utils import absolute_uri, get_instance_region, render_templatefrom posthog.views import login_required+from products.access_control.backend.facade.api import user_organizations_use_access_controls+logger = structlog.get_logger(__name__)@@ -1583,6 +1585,13 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):}}+ # Scopes cap what the token may do; access rules cap what the user may do. The grant can+ # reach any organization the user belongs to, so when any of them has rules the consent+ # screen says so, because a granted scope can still meet a 403.+ template_context["oauth_consent_access_controls_apply"] = user_organizations_use_access_controls(+ user_id=request.user.id+ )+requested_scope = (request.query_params.get("scope") or "").strip()if not requested_scope:oauth_mcp_consent = build_oauth_mcp_consent_context(request.query_params.get("resource"))diff --git a/posthog/utils.py b/posthog/utils.pyindex 784d51b3dc78..8c5cc0665807 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -694,6 +694,8 @@ def _build_template_context(posthog_app_context["oauth_application"] = context.pop("oauth_application")if "oauth_mcp_consent" in context:posthog_app_context["oauth_mcp_consent"] = context.pop("oauth_mcp_consent")+ if "oauth_consent_access_controls_apply" in context:+ posthog_app_context["oauth_consent_access_controls_apply"] = context.pop("oauth_consent_access_controls_apply")# JSON dumps here since there may be objects like Queries# that are not serializable by Django's JSON serializerdiff --git a/products/access_control/backend/facade/api.py b/products/access_control/backend/facade/api.pyindex d4a30cd5d0ae..d4bade238838 100644--- a/products/access_control/backend/facade/api.py+++ b/products/access_control/backend/facade/api.py@@ -23,7 +23,8 @@ from uuid import UUIDfrom django.shortcuts import get_object_or_404-from posthog.models import OrganizationMembership, PropertyDefinition, Team+from posthog.constants import AvailableFeature+from posthog.models import Organization, OrganizationMembership, PropertyDefinition, Teamfrom posthog.scopes import API_SCOPE_OBJECTS, INTERNAL_API_SCOPE_OBJECTS, APIScopeObjectfrom products.access_control.backend.models.role import Role@@ -145,6 +146,22 @@ def team_has_property_access_rules(*, team_id: int) -> bool:return PropertyAccessControl.objects.filter(team_id=team_id, property_definition__isnull=False).exists()+def user_organizations_use_access_controls(*, user_id: int) -> bool:+ """Whether access rules can narrow what the user reaches in one of their organizations.++ True only when an organization the user belongs to has the access-control feature AND+ at least one rule exists in one of its projects.+ """+ entitled = [+ org.id+ for org in Organization.objects.filter(members=user_id)+ if org.is_feature_available(AvailableFeature.ACCESS_CONTROL)+ ]+ if not entitled:+ return False+ return AccessControl.objects.filter(team__organization_id__in=entitled).exists()++# --- Write API ---