Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(oauth): narrow wildcard scope requests to the app scope ceiling (#70538)

Matt Brooker09316a612867
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 7e4c6fa34dc0..4e9ebd200492 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -2680,13 +2680,87 @@ class TestOAuthAPI(APIBaseTest):
self.assertNotIn("error=invalid_scope", redirect_to)
self.assertIn("code=", redirect_to)
- def test_authorize_wildcard_rejected_when_app_ceiling_set(self):
- self._set_ceiling("experiment:read")
- response = self.client.get(f"{self.base_authorization_url}&scope=*")
+ def _create_first_party_app_with_ceiling(self, *scopes: str) -> OAuthApplication:
+ return OAuthApplication.objects.create(
+ name="First Party App",
+ client_id="first_party_narrow_client_id",
+ client_secret="first_party_narrow_client_secret",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ user=self.user,
+ hash_client_secret=True,
+ algorithm="RS256",
+ is_first_party=True,
+ scopes=list(scopes),
+ )
+
+ def _first_party_authorize_grant(self, app: OAuthApplication, scope: str) -> OAuthGrant:
+ url = self.replace_param_in_url(self.base_authorization_url, "client_id", app.client_id)
+ response = self.client.get(f"{url}&scope={scope}")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
- location = response.get("Location")
- assert location
- self.assertIn("error=invalid_scope", location)
+ location = response["Location"]
+ self.assertNotIn("error=invalid_scope", location)
+ self.assertIn("code=", location)
+ code = parse_qs(urlparse(location).query)["code"][0]
+ return OAuthGrant.objects.get(code=code)
+
+ def test_authorize_wildcard_narrowed_to_seeded_ceiling(self):
+ # A `*` request against a seeded ceiling is narrowed to the resolved ceiling
+ # rather than rejected. First-party apps skip consent, so the grant is the
+ # cleanest place to observe the narrowed scope set.
+ app = self._create_first_party_app_with_ceiling("experiment:read", "dashboard:read")
+ grant = self._first_party_authorize_grant(app, "*")
+ self.assertEqual(set(grant.scope.split()), {"experiment:read", "dashboard:read"})
+ self.assertNotIn("*", grant.scope.split())
+
+ def test_authorize_wildcard_narrowed_ceiling_includes_privileged_scope(self):
+ # A `@default` ceiling with a privileged extra: narrowing grants the extra too.
+ app = self._create_first_party_app_with_ceiling("@default", "llm_gateway:read")
+ grant = self._first_party_authorize_grant(app, "*")
+ granted = set(grant.scope.split())
+ self.assertIn("llm_gateway:read", granted)
+ self.assertIn("insight:read", granted)
+ self.assertNotIn("*", granted)
+ self.assertNotIn("@default", granted)
+
+ def test_authorize_wildcard_never_grants_star_listed_in_ceiling(self):
+ # A ceiling that literally lists `*` must not grant `*` back on a `*` request:
+ # `*` is never grantable under an explicit ceiling. Only the real scopes remain.
+ app = self._create_first_party_app_with_ceiling("experiment:read", "*")
+ grant = self._first_party_authorize_grant(app, "*")
+ granted = set(grant.scope.split())
+ self.assertNotIn("*", granted)
+ self.assertEqual(granted, {"experiment:read"})
+
+ def test_authorize_wildcard_narrowing_captures_event(self):
+ self._set_ceiling("experiment:read")
+ with patch("posthog.api.oauth.views.render_template", return_value=HttpResponse("")):
+ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:
+ response = self.client.get(f"{self.base_authorization_url}&scope=*")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ narrowed = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "oauth_wildcard_scopes_narrowed"]
+ self.assertEqual(len(narrowed), 1)
+ props = narrowed[0].kwargs["properties"]
+ self.assertEqual(props["client_name"], self.confidential_application.name)
+ self.assertEqual(props["is_first_party"], self.confidential_application.is_first_party)
+ self.assertEqual(props["narrowed_scope_count"], 1)
+ rejected = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "oauth_authorization_rejected"]
+ self.assertEqual(rejected, [])
+
+ def test_authorize_wildcard_empty_ceiling_does_not_narrow_or_capture(self):
+ # Empty ceiling keeps the legacy `*` grandfathering: `*` is accepted verbatim
+ # and no narrowing event fires. POST grants it directly.
+ with patch("posthog.api.oauth.views.render_template", return_value=HttpResponse("")):
+ with patch("posthog.api.oauth.views.posthoganalytics.capture") as mock_capture:
+ get_response = self.client.get(f"{self.base_authorization_url}&scope=*")
+ self.assertEqual(get_response.status_code, status.HTTP_200_OK)
+ narrowed = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "oauth_wildcard_scopes_narrowed"]
+ self.assertEqual(narrowed, [])
+
+ post_response = self._authorize_post("*")
+ self.assertEqual(post_response.status_code, status.HTTP_200_OK)
+ self.assertNotIn("error=invalid_scope", post_response.json()["redirect_to"])
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:
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 6f136df75024..7ae6877f4ae9 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -59,6 +59,7 @@ from posthog.scopes import (
get_oauth_scopes_supported,
get_scope_descriptions,
narrow_scopes_to_ceiling,
+ resolve_ceiling,
scopes_outside_ceiling,
scopes_within_ceiling,
)
@@ -436,17 +437,30 @@ class OAuthValidator(OAuth2Validator):
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. 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.
+ and the hand-rolled provisioning mint paths share one implementation. Two
+ `/authorize`-specific mutations of `request.scopes` live here:
+ - the client omitting `scope=`, so oauthlib doesn't fall back to just
+ `["openid"]` from `DEFAULT_SCOPES`.
+ - a `*` request against a *seeded* (non-empty) ceiling, narrowed down to the
+ resolved ceiling rather than rejected. This keeps legacy first-party
+ clients still sending `*` signing in once a ceiling is seeded, granting
+ strictly less than the empty-ceiling `*` grandfathering below. The token
+ response carries the actual (narrowed) `scope`, so this stays spec-valid.
+
+ `*` is still accepted verbatim under an empty ceiling here (legacy PostHog
+ Code CLI) but never on the provisioning paths — see the flag.
"""
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)
return True
+ ceiling = resolve_ceiling(app_scopes)
+ if ceiling is not None and "*" in requested:
+ # `*` is never grantable under an explicit ceiling, even if the ceiling itself
+ # lists it — mirrors the guard in `scopes_within_ceiling`/`scopes_outside_ceiling`.
+ request.scopes = sorted((ceiling - {"*"}) | (requested & ALWAYS_ALLOWED_SCOPES))
+ return True
return scopes_within_ceiling(requested, app_scopes, allow_wildcard_under_empty_ceiling=True)
def get_original_scopes(self, refresh_token, request, *args, **kwargs):
@@ -953,6 +967,26 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
},
)
+ # `validate_scopes` narrows a `*` request to the app's ceiling instead of rejecting it
+ # (only when the ceiling is seeded); track that volume so `*` can be retired once it drains.
+ if (
+ "*" in (request.query_params.get("scope") or "").split()
+ and resolve_ceiling(application.ceiling_scopes) is not None
+ ):
+ posthoganalytics.capture(
+ distinct_id=str(request.user.distinct_id),
+ event="oauth_wildcard_scopes_narrowed",
+ properties={
+ "client_name": application.name,
+ "app_id": str(application.pk),
+ "registration_type": registration_type,
+ "is_verified": application.is_verified,
+ "is_first_party": application.is_first_party,
+ "narrowed_scope_count": len(scopes),
+ **(get_region_info() or {}),
+ },
+ )
+
impersonator_id = _impersonator_id_for_request(request)
credentials["impersonated_by_id"] = impersonator_id
diff --git a/posthog/management/commands/seed_oauth_app_scopes.py b/posthog/management/commands/seed_oauth_app_scopes.py
new file mode 100644
index 000000000000..755cf27890fa
--- /dev/null
+++ b/posthog/management/commands/seed_oauth_app_scopes.py
@@ -0,0 +1,117 @@
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+
+from posthog.models.oauth import OAuthApplication
+from posthog.scopes import (
+ ALL_SCOPES,
+ DEFAULT_CEILING_SENTINEL,
+ OAUTH_SCOPES_HIDDEN,
+ PRIVILEGED_SCOPES,
+ effective_ceiling,
+)
+
+
+def parse_scope_list(raw: str) -> list[str]:
+ """Split a comma-separated ceiling into deduped, order-preserving entries."""
+ seen: set[str] = set()
+ result: list[str] = []
+ for token in raw.split(","):
+ entry = token.strip()
+ if not entry or entry in seen:
+ continue
+ seen.add(entry)
+ result.append(entry)
+ return result
+
+
+class Command(BaseCommand):
+ help = (
+ "Seed an OAuth application's scope ceiling (OAuthApplication.scopes) with a validated list. "
+ "Every entry must be '@default' or a known obj:action scope; '*', typos, and unknown strings "
+ "are rejected. A bad ceiling entry (e.g. '@defalt') would make wildcard narrowing treat the "
+ "ceiling as an exhaustive allow-list and strip normal API scopes from existing clients, so "
+ "this command validates before writing."
+ )
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument(
+ "--client-id",
+ required=True,
+ help="client_id of the OAuthApplication to seed.",
+ )
+ parser.add_argument(
+ "--scopes",
+ required=True,
+ help='Comma-separated scope ceiling, e.g. "@default,llm_gateway:read".',
+ )
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Print the planned change and effective ceiling without writing.",
+ )
+ parser.add_argument(
+ "--clear-optional-scopes",
+ action="store_true",
+ help=(
+ "Also clear the app's optional_scopes. Required when the app has any: the enforced "
+ "ceiling is scopes + optional_scopes, so leftover optional scopes would stay grantable "
+ "outside the seeded list."
+ ),
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ client_id: str = options["client_id"]
+ dry_run: bool = options["dry_run"]
+ clear_optional: bool = options["clear_optional_scopes"]
+
+ new_scopes = parse_scope_list(options["scopes"])
+ if not new_scopes:
+ raise CommandError(
+ "Refusing to seed an empty ceiling. Use the Django admin to intentionally clear an "
+ "app's scopes; this command only seeds a non-empty ceiling."
+ )
+
+ invalid = [s for s in new_scopes if s != DEFAULT_CEILING_SENTINEL and s not in ALL_SCOPES]
+ if invalid:
+ raise CommandError(
+ f"Invalid ceiling {'entry' if len(invalid) == 1 else 'entries'}: {invalid}. "
+ f"Each entry must be '{DEFAULT_CEILING_SENTINEL}' or a known obj:action scope "
+ f"(e.g. 'insight:read'); '*' is not a valid ceiling entry."
+ )
+
+ try:
+ app = OAuthApplication.objects.get(client_id=client_id)
+ except OAuthApplication.DoesNotExist:
+ raise CommandError(f"No OAuthApplication found with client_id={client_id!r}.")
+
+ existing_optional = list(app.optional_scopes)
+ if existing_optional and not clear_optional:
+ raise CommandError(
+ f"App has optional_scopes {existing_optional}, which stay grantable alongside the "
+ "seeded list (the enforced ceiling is scopes + optional_scopes). Re-run with "
+ "--clear-optional-scopes to clear them, or adjust them in the Django admin first."
+ )
+
+ ceiling = sorted(effective_ceiling(new_scopes))
+ privileged = sorted(PRIVILEGED_SCOPES.intersection(ceiling))
+ hidden = sorted(OAUTH_SCOPES_HIDDEN.intersection(ceiling))
+
+ self.stdout.write(f"Application: {app.name} (client_id={client_id})")
+ self.stdout.write(f" current scopes: {list(app.scopes)}")
+ self.stdout.write(
+ f" current optional: {existing_optional or 'none'}{' (will clear)' if existing_optional else ''}"
+ )
+ self.stdout.write(f" new scopes: {new_scopes}")
+ self.stdout.write(f" effective ceiling: {len(ceiling)} scopes grantable")
+ self.stdout.write(f" privileged in ceiling: {privileged or 'none'}")
+ self.stdout.write(f" hidden in ceiling: {hidden or 'none'}")
+
+ if dry_run:
+ self.stdout.write("Dry run: no changes written.")
+ return
+
+ app.scopes = new_scopes
+ app.optional_scopes = []
+ app.save(update_fields=["scopes", "optional_scopes"])
+ self.stdout.write(self.style.SUCCESS(f"Seeded {app.name} scopes to {new_scopes}."))
diff --git a/posthog/management/commands/test/test_seed_oauth_app_scopes.py b/posthog/management/commands/test/test_seed_oauth_app_scopes.py
new file mode 100644
index 000000000000..4f44151294d8
--- /dev/null
+++ b/posthog/management/commands/test/test_seed_oauth_app_scopes.py
@@ -0,0 +1,122 @@
+from io import StringIO
+
+from posthog.test.base import BaseTest
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from parameterized import parameterized
+
+from posthog.models.oauth import OAuthApplication
+
+
+class TestSeedOAuthAppScopes(BaseTest):
+ def _create_app(
+ self,
+ client_id: str = "seed_test_client",
+ scopes: list[str] | None = None,
+ optional_scopes: list[str] | None = None,
+ ) -> OAuthApplication:
+ return OAuthApplication.objects.create(
+ name="Seed test app",
+ client_id=client_id,
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://localhost",
+ algorithm="RS256",
+ organization=self.organization,
+ scopes=scopes if scopes is not None else [],
+ optional_scopes=optional_scopes if optional_scopes is not None else [],
+ )
+
+ def _run(self, **kwargs: str | bool) -> str:
+ out = StringIO()
+ call_command("seed_oauth_app_scopes", stdout=out, **kwargs)
+ return out.getvalue()
+
+ def test_happy_path_sets_scopes(self):
+ app = self._create_app()
+ output = self._run(client_id="seed_test_client", scopes="@default,llm_gateway:read")
+
+ app.refresh_from_db()
+ assert app.scopes == ["@default", "llm_gateway:read"]
+ assert "Seeded Seed test app scopes to ['@default', 'llm_gateway:read']" in output
+ assert "privileged in ceiling: ['llm_gateway:read']" in output
+ assert "hidden in ceiling: none" in output
+
+ def test_existing_optional_scopes_block_seed_without_flag(self):
+ app = self._create_app(scopes=["insight:read"], optional_scopes=["dashboard:read"])
+
+ with self.assertRaises(CommandError) as ctx:
+ self._run(client_id="seed_test_client", scopes="@default,llm_gateway:read")
+
+ assert "optional_scopes ['dashboard:read']" in str(ctx.exception)
+ app.refresh_from_db()
+ assert app.scopes == ["insight:read"]
+ assert app.optional_scopes == ["dashboard:read"]
+
+ def test_clear_optional_scopes_flag_clears_and_seeds(self):
+ app = self._create_app(scopes=["insight:read"], optional_scopes=["dashboard:read"])
+ output = self._run(client_id="seed_test_client", scopes="@default,llm_gateway:read", clear_optional_scopes=True)
+
+ app.refresh_from_db()
+ assert app.scopes == ["@default", "llm_gateway:read"]
+ assert app.optional_scopes == []
+ assert "current optional: ['dashboard:read'] (will clear)" in output
+
+ def test_hidden_scope_surfaced_in_output(self):
+ app = self._create_app()
+ output = self._run(client_id="seed_test_client", scopes="@default,wizard_session:read")
+
+ app.refresh_from_db()
+ assert app.scopes == ["@default", "wizard_session:read"]
+ assert "hidden in ceiling: ['wizard_session:read']" in output
+
+ def test_dedupes_and_preserves_order(self):
+ self._create_app()
+ self._run(client_id="seed_test_client", scopes=" @default , llm_gateway:read , @default ")
+
+ app = OAuthApplication.objects.get(client_id="seed_test_client")
+ assert app.scopes == ["@default", "llm_gateway:read"]
+
+ @parameterized.expand(
+ [
+ ("default_typo", "@defalt,llm_gateway:read"),
+ ("wildcard", "*"),
+ ("wildcard_with_default", "@default,*"),
+ ("unknown_scope", "@default,not_a_real:scope"),
+ ]
+ )
+ def test_rejects_invalid_entries(self, _name, scopes):
+ app = self._create_app(scopes=["insight:read"])
+
+ with self.assertRaises(CommandError):
+ self._run(client_id="seed_test_client", scopes=scopes)
+
+ app.refresh_from_db()
+ assert app.scopes == ["insight:read"]
+
+ @parameterized.expand([("empty_string", ""), ("only_separators", " , , ")])
+ def test_rejects_empty_list(self, _name, scopes):
+ app = self._create_app(scopes=["insight:read"])
+
+ with self.assertRaises(CommandError):
+ self._run(client_id="seed_test_client", scopes=scopes)
+
+ app.refresh_from_db()
+ assert app.scopes == ["insight:read"]
+
+ def test_dry_run_writes_nothing(self):
+ app = self._create_app(scopes=["insight:read"])
+ output = self._run(client_id="seed_test_client", scopes="@default,llm_gateway:read", dry_run=True)
+
+ app.refresh_from_db()
+ assert app.scopes == ["insight:read"]
+ assert "Dry run: no changes written." in output
+ assert "new scopes:" in output
+ assert "effective ceiling:" in output
+
+ def test_missing_client_id_errors(self):
+ with self.assertRaises(CommandError):
+ self._run(client_id="does_not_exist", scopes="@default")