: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): send an insufficient_scope challenge to step-up apps (#127698)
Rafael Audibert709282ba4ae1
diff --git a/posthog/admin/admins/oauth_admin.py b/posthog/admin/admins/oauth_admin.pyindex 98ce967cb94f..351e609ca09c 100644--- a/posthog/admin/admins/oauth_admin.py+++ b/posthog/admin/admins/oauth_admin.py@@ -243,6 +243,7 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne"is_dcr_client","is_cimd_client","is_first_party",+ "supports_step_up","auth_brand","is_provisioning_partner",ProvisioningCapabilityFilter,@@ -361,7 +362,18 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne},),("Ownership", {"fields": ("user", "organization")}),- ("Status", {"fields": ("is_verified", "is_first_party", "is_dcr_client", "is_cimd_client")}),+ (+ "Status",+ {+ "fields": (+ "is_verified",+ "is_first_party",+ "supports_step_up",+ "is_dcr_client",+ "is_cimd_client",+ )+ },+ ),("Provisioning",{@@ -402,7 +414,7 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne},),("Ownership", {"fields": ("user", "organization")}),- ("Status", {"fields": ("is_verified", "is_first_party")}),+ ("Status", {"fields": ("is_verified", "is_first_party", "supports_step_up")}),)def get_form(self, request, obj=None, change=False, **kwargs):diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex 8c3e1fb1e929..a5a24f62a4b2 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -1837,6 +1837,24 @@ class TestOAuthAPI(APIBaseTest):refresh_token = refresh_response.json()["refresh_token"]+ @parameterized.expand([("rotating", False), ("non_rotating", True)])+ def test_supports_step_up_is_copied_from_the_app_at_every_mint(self, _name, is_dcr_client):+ self.confidential_application.is_dcr_client = is_dcr_client+ self.confidential_application.supports_step_up = True+ self.confidential_application.save()++ response = self.client.post("/oauth/authorize/", self.base_authorization_post_body)+ code = response.json()["redirect_to"].split("code=")[1].split("&")[0]+ token_response = self.post("/oauth/token/", {**self.base_token_body, "code": code}).json()++ self.assertTrue(OAuthAccessToken.objects.get(token=token_response["access_token"]).supports_step_up)++ self.confidential_application.supports_step_up = False+ self.confidential_application.save()+ refreshed = self._refresh(token_response["refresh_token"])++ self.assertFalse(OAuthAccessToken.objects.get(token=refreshed["access_token"]).supports_step_up)+def _create_refreshable_token_pair(self, scope: str) -> OAuthRefreshToken:suffix = scope.replace(" ", "_").replace("*", "star").replace(":", "_")access_token = OAuthAccessToken.objects.create(diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambrindex 9564f4014fbb..51ce3354d2b2 100644--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr@@ -30511,6 +30511,7 @@"posthog_oauthapplication"."dcr_client_id_issued_at","posthog_oauthapplication"."is_verified","posthog_oauthapplication"."is_first_party",+ "posthog_oauthapplication"."supports_step_up","posthog_oauthapplication"."auth_brand","posthog_oauthapplication"."scopes","posthog_oauthapplication"."optional_scopes",@@ -31109,6 +31110,7 @@"posthog_oauthapplication"."dcr_client_id_issued_at","posthog_oauthapplication"."is_verified","posthog_oauthapplication"."is_first_party",+ "posthog_oauthapplication"."supports_step_up","posthog_oauthapplication"."auth_brand","posthog_oauthapplication"."scopes","posthog_oauthapplication"."optional_scopes",diff --git a/posthog/exceptions.py b/posthog/exceptions.pyindex 1c71a1cb73fd..725bbacdccac 100644--- a/posthog/exceptions.py+++ b/posthog/exceptions.py@@ -6,7 +6,7 @@ from django.http.response import JsonResponseimport structlogfrom rest_framework import status-from rest_framework.exceptions import APIException, Throttled, ValidationError+from rest_framework.exceptions import APIException, PermissionDenied, Throttled, ValidationErrorfrom rest_framework.response import Responsefrom posthog.clickhouse.query_tagging import get_query_tags@@ -69,6 +69,18 @@ class PaidFeatureException(APIException):super().__init__(detail=f"{feature_name} requires a paid PostHog plan. Please upgrade to access this feature.")+class InsufficientScope(PermissionDenied):+ """A missing-scope 403 that carries an RFC 6750 section 3.1 `insufficient_scope` challenge.++ `scope` names every scope the request requires, not only the missing ones. The MCP step-up+ flow has the client union the challenge with the scopes it holds and ask the user for that.+ """++ def __init__(self, detail: str, required_scopes: list[str]) -> None:+ super().__init__(detail=detail)+ self.auth_header = f'Bearer error="insufficient_scope", scope="{" ".join(required_scopes)}"'++class Conflict(APIException):status_code = status.HTTP_409_CONFLICTdefault_code = "conflict"@@ -247,4 +259,7 @@ def exception_handler(exc: Exception, context: ExceptionContext) -> Optional[Res# attacker-controlled origin.metadata_url = absolute_uri("/.well-known/oauth-protected-resource")response["WWW-Authenticate"] = f'Bearer resource_metadata="{metadata_url}"'+ elif response is not None and (auth_header := getattr(exc, "auth_header", None)):+ # DRF's own handler honors `auth_header`, but drf-exceptions-hog drops it.+ response["WWW-Authenticate"] = auth_headerreturn responsediff --git a/posthog/migrations/1421_oauth_supports_step_up.py b/posthog/migrations/1421_oauth_supports_step_up.pynew file mode 100644index 000000000000..64006480a75e--- /dev/null+++ b/posthog/migrations/1421_oauth_supports_step_up.py@@ -0,0 +1,26 @@+# Generated by Django 6.1.2 on 2026-11-02 17:14++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1420_sharing_configuration_publisher_index"),+ ]++ operations = [+ migrations.AddField(+ model_name="oauthaccesstoken",+ name="supports_step_up",+ field=models.BooleanField(db_default=False, default=False),+ ),+ migrations.AddField(+ model_name="oauthapplication",+ name="supports_step_up",+ field=models.BooleanField(+ db_default=False,+ default=False,+ help_text="True if this client handles an insufficient_scope challenge by asking the user for more scopes. Its tokens then get a WWW-Authenticate challenge naming the required scopes on a missing-scope 403.",+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 8eba9ee7d488..1b984d2e36ad 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1420_sharing_configuration_publisher_index+1421_oauth_supports_step_updiff --git a/posthog/models/oauth.py b/posthog/models/oauth.pyindex 9728e5ccc6ba..27ff80778951 100644--- a/posthog/models/oauth.py+++ b/posthog/models/oauth.py@@ -143,6 +143,17 @@ class OAuthApplication(ModelActivityMixin, AbstractApplication): # type: ignoredefault=False, help_text="True if this is a first-party PostHog application that skips OAuth consent")+ # Set only by PostHog staff in the admin. No CIMD field, DCR field or API sets it, so a+ # client cannot opt itself in and a metadata refresh never changes it.+ supports_step_up: models.BooleanField = models.BooleanField(+ default=False,+ db_default=False,+ help_text=(+ "True if this client handles an insufficient_scope challenge by asking the user for more scopes. "+ "Its tokens then get a WWW-Authenticate challenge naming the required scopes on a missing-scope 403."+ ),+ )+auth_brand: models.CharField = models.CharField(max_length=32,choices=[(brand.value, brand.value) for brand in OAuthApplicationAuthBrand],@@ -557,6 +568,14 @@ class OAuthAccessToken(AbstractAccessToken):models.Index(fields=["token"], name="oauthaccesstoken_token_idx"),]+ def save(self, *args, **kwargs):+ # Copied from the application at every mint, refresh included, so a staff change to the+ # app reaches existing connections at their next refresh. Done here so every mint path,+ # including partner provisioning and direct mints, carries it.+ if self._state.adding and self.application_id is not None:+ self.supports_step_up = self.application.supports_step_up+ super().save(*args, **kwargs)+@classmethoddef with_scope(cls, scope: str) -> models.QuerySet["OAuthAccessToken"]:return cls.objects.alias(scope_tokens=oauth_scope_tokens_expression()).filter(@@ -589,6 +608,8 @@ class OAuthAccessToken(AbstractAccessToken):db_index=True,)+ supports_step_up: models.BooleanField = models.BooleanField(default=False, db_default=False)+# Optional user-facing label set at mint time. Carried across refreshes so# it persists for the life of the connection, not just one rotated token.label: models.CharField = models.CharField(diff --git a/posthog/permissions.py b/posthog/permissions.pyindex 73416338a6fb..4898f7674cbb 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -32,7 +32,7 @@ from posthog.auth import ()from posthog.cloud_utils import is_cloudfrom posthog.constants import AvailableFeature-from posthog.exceptions import Conflict, EnterpriseFeatureException, PaidFeatureException+from posthog.exceptions import Conflict, EnterpriseFeatureException, InsufficientScope, PaidFeatureExceptionfrom posthog.helpers.verified_domain_enforcement import VERIFIED_DOMAIN_REQUIRED_ERROR, is_enforcement_disable_requestfrom posthog.models import Organization, OrganizationDomain, OrganizationMembership, Project, Team, Userfrom posthog.models.oauth import OAuthAccessToken@@ -978,6 +978,14 @@ class APIScopePermission(ScopeBasePermission):missing_scopes = scopes_missing_after_legacy_fallback(request, view, key_scopes, required_scopes)if missing_scopes:self.message = f"API key missing required scope '{missing_scopes[0]}'"+ # Internal scopes cannot be granted at consent, so a challenge naming one could never succeed.+ if (+ isinstance(authenticator, OAuthAccessTokenAuthentication)+ and authenticator.access_token.supports_step_up+ and scope_object != "INTERNAL"+ and not action_targets_internal+ ):+ raise InsufficientScope(detail=self.message, required_scopes=required_scopes)return Falsereturn Truediff --git a/posthog/test/test_permissions.py b/posthog/test/test_permissions.pyindex 3b160202e493..b6c45e261d34 100644--- a/posthog/test/test_permissions.py+++ b/posthog/test/test_permissions.py@@ -1033,6 +1033,46 @@ class TestOAuthAccessTokenAPIScopePermission(BaseTest):self.assertEqual(response.status_code, 403)self.assertEqual(response.json()["detail"], "API key missing required scope 'feature_flag:write'")+ @parameterized.expand(+ [+ (+ "step_up",+ True,+ "GET",+ "persons/cohorts/?person_id=1",+ "API key missing required scope 'person:read'",+ 'Bearer error="insufficient_scope", scope="person:read cohort:read"',+ ),+ (+ "no_step_up",+ False,+ "GET",+ "persons/cohorts/?person_id=1",+ "API key missing required scope 'person:read'",+ None,+ ),+ (+ "step_up_internal_scope",+ True,+ "POST",+ "signals/scout/scratchpad/forget/",+ "API key missing required scope 'signal_scratchpad_internal:write'",+ None,+ ),+ ]+ )+ def test_missing_scope_challenge_names_every_required_scope(+ self, _name, supports_step_up, method, path, expected_detail, expected_challenge+ ):+ self.access_token.supports_step_up = supports_step_up+ self.access_token.save()++ response = self._do_request(f"/api/projects/{self.team.id}/{path}", method=method)++ self.assertEqual(response.status_code, 403)+ self.assertEqual(response.json()["detail"], expected_detail)+ self.assertEqual(response.headers.get("WWW-Authenticate"), expected_challenge)+def test_allows_action_with_required_scopes(self):"""OAuth token can access endpoints that match its scopes"""response = self._do_request(f"/api/projects/{self.team.id}/feature_flags/my_flags")