: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
refactor(provisioning): enforce app.scopes ceiling on token mint (#61223)
Matt Brookerf6a2c3341aff
diff --git a/ee/api/agentic_provisioning/test/test_account_requests.py b/ee/api/agentic_provisioning/test/test_account_requests.pyindex 86ee9f2ae0b5..0cdc0a8fe3db 100644--- a/ee/api/agentic_provisioning/test/test_account_requests.py+++ b/ee/api/agentic_provisioning/test/test_account_requests.py@@ -357,6 +357,28 @@ class TestPKCEPartnerExistingUserConsent(ProvisioningTestBase):assert pending["partner_id"] == str(self.pkce_partner.id)assert pending["scopes"] == ["query:read"]+ def test_pkce_partner_within_ceiling_creates_pending_auth(self):+ self.pkce_partner.scopes = ["query:read", "insight:read"]+ self.pkce_partner.save()+ User.objects.create_and_join(+ organization=self.organization, email="[email protected]", password="testpass", first_name="Existing"+ )+ payload = self._account_request_payload(scopes=["query:read"])+ res = self._post_as_pkce_partner(payload)+ assert res.status_code == 200+ assert res.json()["type"] == "requires_auth"++ def test_pkce_partner_outside_ceiling_returns_invalid_scope(self):+ self.pkce_partner.scopes = ["query:read"]+ self.pkce_partner.save()+ User.objects.create_and_join(+ organization=self.organization, email="[email protected]", password="testpass", first_name="Existing"+ )+ payload = self._account_request_payload(scopes=["query:read", "insight:write"])+ res = self._post_as_pkce_partner(payload)+ assert res.status_code == 400+ assert res.json()["error"]["code"] == "invalid_scope"+def test_pkce_partner_new_user_still_gets_direct_code(self):payload = self._account_request_payload(email="[email protected]")res = self._post_as_pkce_partner(payload)diff --git a/ee/api/agentic_provisioning/test/test_oauth_token.py b/ee/api/agentic_provisioning/test/test_oauth_token.pyindex 5199891d4e96..7dd2b959de99 100644--- a/ee/api/agentic_provisioning/test/test_oauth_token.py+++ b/ee/api/agentic_provisioning/test/test_oauth_token.py@@ -4,13 +4,18 @@ from urllib.parse import urlencodefrom django.core.cache import cachefrom django.test import override_settings+from posthog.models.oauth import OAuthAccessToken, OAuthApplication+from ee.api.agentic_provisioning import AUTH_CODE_CACHE_PREFIXfrom ee.api.agentic_provisioning.signature import compute_signature-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase+from ee.api.agentic_provisioning.test.base import HMAC_SECRET, TEST_STRIPE_OAUTH_CLIENT_ID, ProvisioningTestBase@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)class TestOAuthTokenExchange(ProvisioningTestBase):+ def _set_app_ceiling(self, scopes: list[str]) -> None:+ OAuthApplication.objects.filter(client_id=TEST_STRIPE_OAUTH_CLIENT_ID).update(scopes=scopes)+def _store_auth_code(self, code: str = "test_code", **overrides):data = {"user_id": self.user.id,@@ -126,3 +131,41 @@ class TestOAuthTokenExchange(ProvisioningTestBase):headers={"api-version": "0.1d"},)assert res.status_code == 401++ def test_direct_mint_within_ceiling_grants_requested_scopes(self):+ self._set_app_ceiling(["query:read", "project:read"])+ self._store_auth_code("ceiling_ok", scopes=["query:read"])+ res = self._post_token(self._token_request_body(code="ceiling_ok"))+ assert res.status_code == 200+ token = OAuthAccessToken.objects.get(token=res.json()["access_token"])+ assert token.scope == "query:read"++ def test_direct_mint_outside_ceiling_returns_invalid_scope(self):+ self._set_app_ceiling(["query:read"])+ self._store_auth_code("ceiling_bad", scopes=["query:read", "insight:write"])+ res = self._post_token(self._token_request_body(code="ceiling_bad"))+ assert res.status_code == 400+ assert res.json()["error"] == "invalid_scope"++ def test_refresh_narrows_to_tightened_ceiling(self):+ self._store_auth_code("refresh_narrow", scopes=["query:read", "insight:write"])+ first = self._post_token(self._token_request_body(code="refresh_narrow"))+ refresh_token = first.json()["refresh_token"]++ self._set_app_ceiling(["query:read"])+ refresh_body = urlencode({"grant_type": "refresh_token", "refresh_token": refresh_token}).encode()+ res = self._post_token(refresh_body)+ assert res.status_code == 200+ token = OAuthAccessToken.objects.get(token=res.json()["access_token"])+ assert token.scope == "query:read"++ def test_refresh_rejected_when_scopes_outside_ceiling(self):+ self._store_auth_code("refresh_reject", scopes=["insight:write"])+ first = self._post_token(self._token_request_body(code="refresh_reject"))+ refresh_token = first.json()["refresh_token"]++ self._set_app_ceiling(["query:read"])+ refresh_body = urlencode({"grant_type": "refresh_token", "refresh_token": refresh_token}).encode()+ res = self._post_token(refresh_body)+ assert res.status_code == 400+ assert res.json()["error"] == "invalid_grant"diff --git a/ee/api/agentic_provisioning/test/test_scope_validation.py b/ee/api/agentic_provisioning/test/test_scope_validation.pydeleted file mode 100644index 6cd6a30ac88d..000000000000--- a/ee/api/agentic_provisioning/test/test_scope_validation.py+++ /dev/null@@ -1,33 +0,0 @@-import pytest--from ee.api.agentic_provisioning.views import ALLOWED_PROVISIONING_SCOPES, _validate_scopes--- "scopes,expected",- [- ([], []),- (["query:read"], ["query:read"]),- (["llm_gateway:read", "project:read"], ["llm_gateway:read", "project:read"]),- (["dashboard:write", "insight:write"], ["dashboard:write", "insight:write"]),- (["query:read", "made_up_scope"], None),- (["dashboard:read"], None),- (["INSIGHT:READ"], None),- # introspection is not a grantable OAuth scope (RFC 7662 endpoint, not a scope) — should be rejected.- (["introspection"], None),- ],-)-def test_validate_scopes(scopes, expected):- assert _validate_scopes(scopes) == expected---def test_allowlist_covers_wizard_required_scopes():- wizard_scopes = {- "user:read",- "project:read",- "llm_gateway:read",- "dashboard:write",- "insight:write",- "query:read",- }- assert wizard_scopes.issubset(ALLOWED_PROVISIONING_SCOPES)diff --git a/ee/api/agentic_provisioning/views.py b/ee/api/agentic_provisioning/views.pyindex 53a27b303fa3..8982fbd34816 100644--- a/ee/api/agentic_provisioning/views.py+++ b/ee/api/agentic_provisioning/views.py@@ -50,6 +50,7 @@ from posthog.models.utils import (mask_key_value,)from posthog.rbac.user_access_control import UserAccessControl+from posthog.scopes import narrow_scopes_to_ceiling, scopes_within_ceilingfrom posthog.tasks.email import send_provisioning_welcomefrom posthog.utils import get_instance_region@@ -532,20 +533,22 @@ def _handle_existing_user(},status=400,)- validated_scopes = _validate_scopes(scopes)- if validated_scopes is None:+ if not scopes_within_ceiling(scopes, partner.scopes):return Response({"id": request_id,"type": "error",- "error": {"code": "invalid_scope", "message": "One or more requested scopes are not recognized"},+ "error": {+ "code": "invalid_scope",+ "message": "One or more requested scopes exceed the application's allowed scopes",+ },},status=400,)return _require_user_consent(request_id,user,- validated_scopes,+ scopes,partner_account_id,region,partner,@@ -1057,7 +1060,21 @@ def _exchange_authorization_code(request: Request) -> Response:# Use partner's OAuth app if available, fall back to Stripeoauth_app = _get_oauth_app_for_code(code_data)- scope_str = " ".join(scopes) if scopes else StripeIntegration.SCOPES++ # 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 = oauth_app.scopes if oauth_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(+ {+ "error": "invalid_scope",+ "error_description": "Requested scopes exceed the application's allowed scopes",+ },+ status=400,+ )+ scope_str = " ".join(requested_scopes)token_expiry = (PARTNER_TOKEN_EXPIRY_SECONDS if oauth_app and oauth_app.is_provisioning_partner else ACCESS_TOKEN_EXPIRY_SECONDS@@ -1119,6 +1136,23 @@ def _exchange_refresh_token(request: Request) -> Response:scoped_teams = old_refresh.scoped_teamsold_scope = old_refresh.access_token.scope if old_refresh.access_token else StripeIntegration.SCOPES+ # Cap the refreshed scope at the app's current ceiling before touching any+ # 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 []+ 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")+ return Response(+ {+ "error": "invalid_grant",+ "error_description": "Token scopes are no longer within the application's allowed scopes; re-authorize.",+ },+ status=400,+ )+ new_scope = " ".join(narrowed_scopes)+# provisioning_partner_type is a stable marker set at partner registration;# checking it instead of is_provisioning_partner prevents a bypass when an admin# clears provisioning_auth_method to disable a partner without revoking tokens.@@ -1144,7 +1178,7 @@ def _exchange_refresh_token(request: Request) -> Response:token=new_access_value,user=user,expires=timezone.now() + timedelta(seconds=token_expiry),- scope=old_scope,+ scope=new_scope,scoped_teams=scoped_teams,)@@ -2176,38 +2210,6 @@ def _verify_hmac_if_present(request: Request) -> Response | None:return None-ALLOWED_PROVISIONING_SCOPES = {- "customer_journey:read",- "dashboard:write",- "query:read",- "conversation:read",- "conversation:write",- "experiment:read",- "feature_flag:read",- "insight:read",- "insight:write",- "llm_gateway:read",- "organization:read",- "person:read",- "project:read",- "ticket:read",- "ticket:write",- "user:read",- "hog_flow:read",- "hog_flow:write",-}---def _validate_scopes(scopes: list[str]) -> list[str] | None:- """Validate scopes against the allowlist. Returns filtered scopes or None if any are invalid."""- if not scopes:- return scopes- for scope in scopes:- if scope not in ALLOWED_PROVISIONING_SCOPES:- return None- return scopes--def _error_response(code: str, message: str, resource_id: str = "", status: int = 400) -> Response:logger.warning("provisioning.error_response", code=code, message=message, resource_id=resource_id, status=status)return Response({"status": "error", "id": resource_id, "error": {"code": code, "message": message}}, status=status)diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 984099b769e8..8acacec3dc53 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -49,7 +49,14 @@ from posthog.helpers.impersonation import get_original_user_from_session, is_impfrom posthog.middleware import is_read_only_impersonationfrom posthog.models import OAuthAccessToken, OAuthApplication, Organization, Team, Userfrom posthog.models.oauth import OAuthApplicationAccessLevel, OAuthGrant, OAuthRefreshToken-from posthog.scopes import OIDC_SCOPES, UNPRIVILEGED_SCOPES, downgrade_scopes_to_read_only, get_oauth_scopes_supported+from posthog.scopes import (+ ALWAYS_ALLOWED_SCOPES,+ downgrade_scopes_to_read_only,+ effective_ceiling,+ get_oauth_scopes_supported,+ narrow_scopes_to_ceiling,+ scopes_within_ceiling,+)from posthog.security.url_validation import has_authority_bypass_charsfrom posthog.user_permissions import UserPermissionsfrom posthog.utils import render_template@@ -359,43 +366,22 @@ class OAuthValidator(OAuth2Validator):return False- # OIDC + introspection are accepted independently of the per-app ceiling.- # They are identity / token-management scopes, not resource permissions.- _ALWAYS_ALLOWED_SCOPES: frozenset[str] = frozenset(OIDC_SCOPES) | {"introspection"}-def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs):"""Enforce the per-application scope ceiling from `OAuthApplication.scopes`.- Resolution:- - empty / omitted `scope=` -> grant the effective ceiling (mutate- `request.scopes` so oauthlib's default-resolution doesn't fall back- to just ["openid"] from DEFAULT_SCOPES).- - any subset of `effective_scopes` plus the always-allowed (OIDC,- introspection) -> grant as requested.- - any value outside that union (including `*` when the app has an- explicit ceiling) -> reject. oauthlib turns the False return into- `InvalidScopeError` / RFC 6749 `error=invalid_scope`.-- Empty `application.scopes` resolves to UNPRIVILEGED_SCOPES (the broad- default), and `*` is accepted in that mode so existing clients (the- PostHog Code CLI today) keep working until wildcard retirement.+ Delegates the ceiling resolution to `scopes_within_ceiling` so `/authorize`+ and the hand-rolled provisioning mint paths share one implementation. The+ only `/authorize`-specific bit kept here is mutating `request.scopes` when+ the client omits `scope=`, so oauthlib doesn't fall back to just `["openid"]`+ from `DEFAULT_SCOPES`. `*` is accepted under an empty ceiling here (legacy+ PostHog Code CLI) but not on the provisioning paths — see the flag."""app_scopes = getattr(client, "scopes", None) or []- has_ceiling = bool(app_scopes)- effective = frozenset(app_scopes) if has_ceiling else UNPRIVILEGED_SCOPES-requested = set(scopes or [])if not requested:- request.scopes = sorted(effective | self._ALWAYS_ALLOWED_SCOPES)- return True-- to_check = requested - self._ALWAYS_ALLOWED_SCOPES- if not to_check:+ request.scopes = sorted(effective_ceiling(app_scopes) | ALWAYS_ALLOWED_SCOPES)return True-- if has_ceiling:- return "*" not in to_check and to_check.issubset(effective)- return to_check.issubset(UNPRIVILEGED_SCOPES | {"*"})+ return scopes_within_ceiling(requested, app_scopes, allow_wildcard_under_empty_ceiling=True)def get_original_scopes(self, refresh_token, request, *args, **kwargs):"""Cap refreshed scopes at the application's current ceiling.@@ -428,23 +414,15 @@ class OAuthValidator(OAuth2Validator):rt = OAuthRefreshToken.objects.filter(token=refresh_token).select_related("application").first()application = rt.application if rt else None- app_scopes = set(getattr(application, "scopes", None) or [])- if not app_scopes:- return original_list-- original_set = set(original_list)- if "*" in original_set:- return original_list-- narrowed = (original_set & app_scopes) | (original_set & self._ALWAYS_ALLOWED_SCOPES)- if not narrowed:+ narrowed = narrow_scopes_to_ceiling(original_list, getattr(application, "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.raise InvalidGrantError(description="Token scopes are no longer within the application's allowed scopes; re-authorize.",request=request,)- return sorted(narrowed)+ return narroweddef rotate_refresh_token(self, request) -> bool:"""diff --git a/posthog/scopes.py b/posthog/scopes.pyindex 8de016f982ac..b1ee4053622a 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -1,3 +1,4 @@+from collections.abc import Iterablefrom typing import Literal, get_args## API Scopes@@ -238,6 +239,81 @@ def downgrade_scopes_to_read_only(scope_str: str) -> str:OIDC_SCOPES: tuple[str, ...] = ("openid", "profile", "email")+# OIDC + introspection are accepted independently of an app's scope ceiling:+# they are identity / token-management scopes, not resource permissions. Mirrors+# `OAuthValidator._ALWAYS_ALLOWED_SCOPES` in `posthog/api/oauth/views.py`.+ALWAYS_ALLOWED_SCOPES: frozenset[str] = frozenset(OIDC_SCOPES) | {"introspection"}+++def effective_ceiling(app_scopes: Iterable[str]) -> frozenset[str]:+ """The scope set a request resolves against: the explicit `app_scopes` ceiling,+ or the broad `UNPRIVILEGED_SCOPES` default when the app has none."""+ app = frozenset(app_scopes or [])+ return app if app else UNPRIVILEGED_SCOPES+++def scopes_within_ceiling(+ requested: Iterable[str],+ app_scopes: Iterable[str],+ *,+ allow_wildcard_under_empty_ceiling: bool = False,+) -> bool:+ """Whether every requested scope is grantable under an app's scope ceiling.++ The single source of truth for ceiling resolution: `/authorize`+ (`OAuthValidator.validate_scopes`) and the hand-rolled agentic-provisioning+ mint paths both call this so they enforce identical rules.++ - OIDC + introspection (`ALWAYS_ALLOWED_SCOPES`) are always granted.+ - An explicit `app_scopes` ceiling is an exhaustive allow-list: anything+ outside it is rejected, including `*`.+ - An empty `app_scopes` falls back to the broad `UNPRIVILEGED_SCOPES` default.++ `allow_wildcard_under_empty_ceiling` is the only resolution difference between+ the callers: `/authorize` passes `True` to grandfather legacy `*` clients (the+ PostHog Code CLI) until wildcard retirement; provisioning leaves it `False`+ (the default) since it never granted wildcard, so an unseeded ceiling must not+ silently become one.+ """+ app = frozenset(app_scopes or [])+ to_check = set(requested) - ALWAYS_ALLOWED_SCOPES+ if not to_check:+ return True+ if app:+ return "*" not in to_check and to_check.issubset(app)+ allowed = UNPRIVILEGED_SCOPES | {"*"} if allow_wildcard_under_empty_ceiling else UNPRIVILEGED_SCOPES+ return to_check.issubset(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).++ Mirrors `OAuthValidator.get_original_scopes` so hand-rolled refresh flows+ drop scopes that were valid when issued but fall outside a since-tightened+ ceiling, rather than refreshing the broader set forever.++ - Empty `app_scopes` (no cap) is a no-op: returns `original` as a list.+ - A `*` token is left untouched (narrowing it would strip all resource+ access; `*` retirement is handled separately).+ - Otherwise returns the sorted intersection with the ceiling plus any+ always-allowed scopes, or `None` when that intersection is empty (the+ caller should reject with `invalid_grant` and force re-authorization).+ """+ original_list = list(original)+ app = set(app_scopes or [])+ if not app:+ return original_list++ original_set = set(original_list)+ if "*" in original_set:+ return original_list++ narrowed = (original_set & app) | (original_set & ALWAYS_ALLOWED_SCOPES)+ if not narrowed:+ return None+ return sorted(narrowed)++def get_oauth_scopes_supported() -> list[str]:"""Full `scopes_supported` list published in OAuth metadata.diff --git a/posthog/test/test_scopes.py b/posthog/test/test_scopes.pyindex 34da4a68b633..b6590e609fb0 100644--- a/posthog/test/test_scopes.py+++ b/posthog/test/test_scopes.py@@ -18,8 +18,11 @@ from posthog.scopes import (PRIVILEGED_SCOPES,UNPRIVILEGED_SCOPES,downgrade_scopes_to_read_only,+ effective_ceiling,get_oauth_scopes_supported,get_scope_descriptions,+ narrow_scopes_to_ceiling,+ scopes_within_ceiling,)@@ -227,3 +230,71 @@ class TestGetScopeDescriptions(SimpleTestCase):continuefor action in ("read", "write"):assert f"{obj}:{action}" in descriptions+++class TestScopesWithinCeiling(SimpleTestCase):+ @parameterized.expand(+ [+ ("subset_of_explicit_ceiling", ["query:read"], ["query:read", "insight:read"], True),+ ("outside_explicit_ceiling", ["insight:write"], ["query:read"], False),+ ("empty_request_always_allowed", [], ["query:read"], True),+ ("privileged_rejected_without_ceiling", ["llm_gateway:read"], [], False),+ ("privileged_allowed_when_in_ceiling", ["llm_gateway:read"], ["llm_gateway:read"], True),+ ("wildcard_rejected_under_explicit_ceiling", ["*"], ["query:read"], False),+ # Provisioning never grandfathered `*`; an unseeded ceiling must not grant it.+ ("wildcard_rejected_under_empty_ceiling", ["*"], [], False),+ ("unprivileged_allowed_under_empty_ceiling", ["query:read", "insight:write"], [], True),+ ]+ )+ def test_resolution(self, _name: str, requested: list[str], app_scopes: list[str], expected: bool) -> None:+ assert scopes_within_ceiling(requested, app_scopes) is expected++ @parameterized.expand(+ [+ ("openid_and_introspection", ["openid", "introspection"], ["query:read"]),+ ("email_under_empty_ceiling", ["email"], []),+ ]+ )+ def test_oidc_and_introspection_always_allowed(+ self, _name: str, requested: list[str], app_scopes: list[str]+ ) -> None:+ assert scopes_within_ceiling(requested, app_scopes) is True++ def test_wildcard_under_empty_ceiling_gated_by_flag(self) -> None:+ # The one resolution difference between callers: /authorize grandfathers `*`+ # under an empty ceiling, provisioning (default) does not.+ assert scopes_within_ceiling(["*"], [], allow_wildcard_under_empty_ceiling=True) is True+ assert scopes_within_ceiling(["*"], [], allow_wildcard_under_empty_ceiling=False) is False++ def test_effective_ceiling(self) -> None:+ assert effective_ceiling([]) == UNPRIVILEGED_SCOPES+ assert effective_ceiling(["query:read", "insight:read"]) == frozenset({"query:read", "insight:read"})+++class TestNarrowScopesToCeiling(SimpleTestCase):+ @parameterized.expand(+ [+ ("empty_ceiling_is_noop", ["query:read", "insight:write"], [], ["query:read", "insight:write"]),+ ("narrows_to_tightened_ceiling", ["query:read", "insight:write"], ["query:read"], ["query:read"]),+ ("no_overlap_returns_none", ["insight:write"], ["query:read"], None),+ ("wildcard_left_untouched", ["*"], ["query:read"], ["*"]),+ (+ "always_allowed_survive_narrowing",+ ["openid", "query:read", "insight:write"],+ ["query:read"],+ ["openid", "query:read"],+ ),+ # OIDC alone keeps the token alive even when every resource scope falls+ # outside the ceiling — mirrors OAuthValidator.get_original_scopes.+ (+ "only_always_allowed_survive_when_resource_scopes_drop",+ ["openid", "insight:write"],+ ["query:read"],+ ["openid"],+ ),+ ]+ )+ def test_resolution(+ self, _name: str, requested: list[str], app_scopes: list[str], expected: list[str] | None+ ) -> None:+ assert narrow_scopes_to_ceiling(requested, app_scopes) == expected