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.

fix(oauth): correctly validate project/org scopes (#107993)

Reece Jonesda592f4ab1e5
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index c59fabebb333..437d5f645a16 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -3729,6 +3729,46 @@ class TestOAuthAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
mock_render.assert_called_once()
+ @parameterized.expand(
+ [
+ ("team", None, None),
+ ("team", "{ }", "{ }"),
+ ("organization", "invalid", "invalid"),
+ ]
+ )
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
+ def test_auto_approval_inherits_token_access_instead_of_query_parameters(
+ self, access_level: str, teams_param: str | None, orgs_param: str | None
+ ) -> None:
+ scoped_teams = [self.team.id] if access_level == "team" else []
+ scoped_organizations = [str(self.organization.id)] if access_level == "organization" else []
+ self._set_scope_split(["experiment:read"], [])
+ OAuthAccessToken.objects.create(
+ application=self.confidential_application,
+ user=self.user,
+ token=f"existing_{access_level}_token",
+ expires=timezone.now() + timedelta(hours=1),
+ scope="experiment:read",
+ scoped_teams=scoped_teams,
+ scoped_organizations=scoped_organizations,
+ )
+
+ url = f"{self.base_authorization_url}&scope=experiment:read&approval_prompt=auto"
+ if teams_param is not None and orgs_param is not None:
+ url += f"&scoped_teams={quote(teams_param)}&scoped_organizations={quote(orgs_param)}"
+ response = self.client.get(url)
+ self.assertEqual(response.status_code, status.HTTP_302_FOUND)
+ code = parse_qs(urlparse(response["Location"]).query)["code"][0]
+ grant = OAuthGrant.objects.get(code=code)
+ self.assertEqual(grant.scoped_teams, scoped_teams)
+ self.assertEqual(grant.scoped_organizations, scoped_organizations)
+
+ token_response = self.post("/oauth/token/", {**self.base_token_body, "code": code})
+ self.assertEqual(token_response.status_code, status.HTTP_200_OK)
+ token_data = token_response.json()
+ self.assertEqual(token_data["scoped_teams"], scoped_teams)
+ self.assertEqual(token_data["scoped_organizations"], scoped_organizations)
+
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:
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index e82a822ab857..5a16990ddb47 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -1244,19 +1244,18 @@ class OAuthValidator(OAuth2Validator):
"""Resolve the impersonator (staff user) that should be tagged on a newly-minted token.
Priority:
- 1. `impersonated_by_id` attribute set on the oauthlib request — populated from the
- `credentials` dict during `/oauth/authorize` POST and GET auto-approval paths.
+ 1. An explicit attribute set from server-side credentials during `/oauth/authorize`.
2. The previous refresh token (token rotation inherits the tag).
- 3. The authorization code grant referenced in the request body (code-exchange flow at
- `/oauth/token`, where there is no impersonated session to read from).
+ 3. The authorization code grant referenced during a code exchange at `/oauth/token`.
Returns the staff user's id, or None if not impersonator-issued.
"""
- impersonator_id = getattr(request, "impersonated_by_id", None)
- if impersonator_id:
- return impersonator_id
+ # oauthlib exposes body and query parameters as missing attributes. Only an
+ # attribute explicitly set by the authorization view can override stored tags.
+ if "impersonated_by_id" in request.__dict__:
+ return request.__dict__["impersonated_by_id"]
- if refresh_token and refresh_token.impersonated_by_id:
+ if refresh_token is not None:
return refresh_token.impersonated_by_id
# Code-exchange path: look up the grant via the `code` body param (same pattern
@@ -1264,12 +1263,12 @@ class OAuthValidator(OAuth2Validator):
# three calls per code exchange (`_get_token_expires_in`,
# `_should_skip_refresh_token`, `_create_access_token`), so the grant lookup is
# memoized on the oauthlib request.
- cached = getattr(request, "_posthog_impersonator_id", _IMPERSONATOR_CACHE_UNSET)
+ cached = request.__dict__.get("_posthog_impersonator_id", _IMPERSONATOR_CACHE_UNSET)
if cached is not _IMPERSONATOR_CACHE_UNSET:
return cached
resolved: int | None = None
- if request.decoded_body:
+ if getattr(request, "grant_type", None) == "authorization_code" and request.decoded_body:
try:
code = dict(request.decoded_body).get("code", None)
if code:
@@ -1291,9 +1290,11 @@ class OAuthValidator(OAuth2Validator):
scoped_teams = None
scoped_organizations = None
- if hasattr(request, "scoped_teams") and hasattr(request, "scoped_organizations"):
- scoped_teams = request.scoped_teams
- scoped_organizations = request.scoped_organizations
+ # oauthlib resolves missing attributes from URL parameters, so only explicit
+ # attributes set by the authorization view can supply consent scoping.
+ if "scoped_teams" in request.__dict__ and "scoped_organizations" in request.__dict__:
+ scoped_teams = request.__dict__["scoped_teams"]
+ scoped_organizations = request.__dict__["scoped_organizations"]
elif access_token:
scoped_teams = access_token.scoped_teams
scoped_organizations = access_token.scoped_organizations
@@ -1321,8 +1322,28 @@ class OAuthValidator(OAuth2Validator):
if scoped_teams is None and scoped_organizations is None:
raise OAuthToolkitError("Unable to find scoped_teams or scoped_organizations")
+ if scoped_teams is not None and (
+ not isinstance(scoped_teams, list) or any(type(team_id) is not int for team_id in scoped_teams)
+ ):
+ raise OAuthToolkitError("Invalid scoped_teams")
+ if scoped_organizations is not None and (
+ not isinstance(scoped_organizations, list)
+ or any(
+ not isinstance(org_id, str) or not self._is_valid_organization_uuid(org_id)
+ for org_id in scoped_organizations
+ )
+ ):
+ raise OAuthToolkitError("Invalid scoped_organizations")
+
return scoped_teams, scoped_organizations
+ @staticmethod
+ def _is_valid_organization_uuid(value: str) -> bool:
+ try:
+ return str(uuid.UUID(value)) == value
+ except ValueError:
+ return False
+
def _pending_connection_for_request(request) -> PendingOAuthConnection | None:
"""Public metadata of the application an unauthenticated authorize request names.
@@ -1633,7 +1654,11 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
# `scope_str` already reflects the read-only downgrade applied above (when
# impersonating), so its split form is the effective set we need to match.
for token in tokens:
- if token.allow_scopes(scope_str.split()):
+ if token.allow_scopes(scope_str.split()) and (
+ token.scoped_teams is not None or token.scoped_organizations is not None
+ ):
+ credentials["scoped_teams"] = token.scoped_teams
+ credentials["scoped_organizations"] = token.scoped_organizations
# Conservative fallback: check every org the impersonated user belongs to,
# not just the existing token's scope. Auto-approval during impersonation
# is a near-dead path (those tokens are short-lived, refresh-less, and
diff --git a/posthog/test/test_oauth_impersonation.py b/posthog/test/test_oauth_impersonation.py
index bfbf5490721e..1e16d33cd0ec 100644
--- a/posthog/test/test_oauth_impersonation.py
+++ b/posthog/test/test_oauth_impersonation.py
@@ -102,21 +102,15 @@ class TestImpersonationOAuthRevocation(BaseTest):
class TestImpersonationOAuthTokenIssuance(APIBaseTest):
- """Code-exchange flow: tokens minted from an impersonation-tagged grant must be
- short-lived and refresh-less, so they expire at the impersonation idle timeout
- even when the staff user never explicitly logs out. The 30min cap + refresh
- suppression key off the grant's `impersonated_by_id` alone, which is set during
- `/oauth/authorize` for both read-only and read-write impersonation — so this
- test implicitly covers both modes."""
-
@parameterized.expand(
[
- ("third_party", False),
- ("first_party", True),
+ ("third_party", False, True),
+ ("first_party", True, True),
+ ("ordinary", False, False),
]
)
- def test_code_exchange_caps_expiry_and_suppresses_refresh_for_impersonation_grants(
- self, _name: str, is_first_party: bool
+ def test_code_exchange_inherits_grant_impersonation_tag(
+ self, _name: str, is_first_party: bool, impersonated: bool
) -> None:
admin = User.objects.create_user(email="[email protected]", password="x", first_name="A")
admin.is_staff = True
@@ -153,7 +147,7 @@ class TestImpersonationOAuthTokenIssuance(APIBaseTest):
scope="feature_flag:read",
scoped_organizations=[str(self.organization.id)],
scoped_teams=[],
- impersonated_by=admin,
+ impersonated_by=admin if impersonated else None,
)
response = self.client.post(
@@ -166,6 +160,8 @@ class TestImpersonationOAuthTokenIssuance(APIBaseTest):
"redirect_uri": "https://example.com/callback",
"code_verifier": verifier,
"code": grant.code,
+ "impersonated_by_id": self.user.pk,
+ "_posthog_impersonator_id": self.user.pk,
}
),
content_type="application/x-www-form-urlencoded",
@@ -175,12 +171,16 @@ class TestImpersonationOAuthTokenIssuance(APIBaseTest):
body = response.json()
self.assertIn("access_token", body)
- self.assertNotIn("refresh_token", body)
- self.assertEqual(body["expires_in"], settings.IMPERSONATION_IDLE_TIMEOUT_SECONDS)
+ if impersonated:
+ self.assertNotIn("refresh_token", body)
+ self.assertEqual(body["expires_in"], settings.IMPERSONATION_IDLE_TIMEOUT_SECONDS)
+ else:
+ self.assertIn("refresh_token", body)
+ self.assertGreater(body["expires_in"], settings.IMPERSONATION_IDLE_TIMEOUT_SECONDS)
access_token = OAuthAccessToken.objects.get(token=body["access_token"])
- self.assertEqual(access_token.impersonated_by_id, admin.pk)
- self.assertFalse(OAuthRefreshToken.objects.filter(application=app, user=self.user).exists())
+ self.assertEqual(access_token.impersonated_by_id, admin.pk if impersonated else None)
+ self.assertEqual(OAuthRefreshToken.objects.filter(application=app, user=self.user).exists(), not impersonated)
class TestImpersonatorIdResolution(BaseTest):