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): Make first-party tokens org-scoped only (#59969)

Charles Vien313c5fcd1b2d
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index a1b4854a24c9..b18ba2489674 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -203,7 +203,7 @@ class TestOAuthAPI(APIBaseTest):
code = parse_qs(urlparse(location).query)["code"][0]
grant = OAuthGrant.objects.get(code=code)
- self.assertIn(self.team.pk, grant.scoped_teams)
+ self.assertEqual(grant.scoped_teams, [])
self.assertIn(str(self.organization.id), grant.scoped_organizations)
def test_authorize_missing_client_id(self):
@@ -430,8 +430,8 @@ class TestOAuthAPI(APIBaseTest):
self.assertIn("expires_in", data)
self.assertIn("refresh_token", data)
self.assertIn("scope", data)
- self.assertIn("scoped_teams", data)
self.assertIn("scoped_organizations", data)
+ self.assertIn("scoped_teams", data)
access_token = data["access_token"]
refresh_token = data["refresh_token"]
@@ -660,7 +660,6 @@ class TestOAuthAPI(APIBaseTest):
self.assertIn("access_token", token_response_data)
self.assertIn("refresh_token", token_response_data)
- self.assertIn("scoped_teams", token_response_data)
self.assertEqual(token_response_data["scoped_teams"], scoped_teams)
access_token = OAuthAccessToken.objects.get(token=token_response_data["access_token"])
@@ -686,7 +685,6 @@ class TestOAuthAPI(APIBaseTest):
self.assertIn("access_token", refresh_token_response_data)
self.assertIn("refresh_token", refresh_token_response_data)
- self.assertIn("scoped_teams", refresh_token_response_data)
self.assertEqual(refresh_token_response_data["scoped_teams"], scoped_teams)
access_token = OAuthAccessToken.objects.get(token=refresh_token_response_data["access_token"])
@@ -2190,11 +2188,11 @@ class TestOAuthAPI(APIBaseTest):
self.assertIn("access_token", response_data)
self.assertIn("refresh_token", response_data)
self.assertIn("token_type", response_data)
- self.assertIn("scoped_teams", response_data)
self.assertIn("scoped_organizations", response_data)
+ self.assertIn("scoped_teams", response_data)
self.assertEqual(response_data["token_type"], "Bearer")
- self.assertEqual(response_data["scoped_teams"], [])
self.assertEqual(response_data["scoped_organizations"], [])
+ self.assertEqual(response_data["scoped_teams"], [])
def test_token_endpoint_with_invalid_json_payload(self):
response = self.client.post(
@@ -2246,8 +2244,8 @@ class TestOAuthAPI(APIBaseTest):
self.assertTrue(data["active"])
self.assertEqual(data["client_id"], "test_confidential_client_id")
self.assertEqual(data["client_name"], "Test Confidential App")
- self.assertIn("scoped_teams", data)
self.assertIn("scoped_organizations", data)
+ self.assertIn("scoped_teams", data)
if token_type == "access_token":
self.assertEqual(data["token_type"], "access_token")
@@ -2810,6 +2808,113 @@ class TestOAuthAPI(APIBaseTest):
self.assertNotIn("posthog_region", data)
self.assertNotIn("posthog_base_url", data)
+ def _create_first_party_app(self, *, slug: str, is_first_party: bool = True) -> OAuthApplication:
+ return OAuthApplication.objects.create(
+ name=f"First Party App {slug}",
+ client_id=f"first_party_{slug}_client_id",
+ client_secret=f"first_party_{slug}_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=is_first_party,
+ )
+
+ @freeze_time("2025-01-01 00:00:00")
+ def test_token_response_derives_scoped_teams_for_first_party_app(self):
+ app = self._create_first_party_app(slug="first-party-derive")
+ grant = OAuthGrant.objects.create(
+ application=app,
+ user=self.user,
+ code="first_party_derive_code",
+ code_challenge=self.code_challenge,
+ code_challenge_method="S256",
+ redirect_uri="https://example.com/callback",
+ expires=timezone.now() + timedelta(minutes=5),
+ scoped_organizations=[str(self.organization.id)],
+ scoped_teams=[],
+ )
+
+ response = self.post(
+ "/oauth/token/",
+ {
+ **self.base_token_body,
+ "client_id": app.client_id,
+ "client_secret": "first_party_first-party-derive_client_secret",
+ "code": grant.code,
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertEqual(data["scoped_organizations"], [str(self.organization.id)])
+ self.assertIn(self.team.pk, data["scoped_teams"])
+
+ access_token = OAuthAccessToken.objects.get(token=data["access_token"])
+ self.assertEqual(access_token.scoped_teams, [])
+
+ @freeze_time("2025-01-01 00:00:00")
+ def test_token_response_does_not_derive_scoped_teams_for_third_party_app(self):
+ app = self._create_first_party_app(slug="third-party-no-derive", is_first_party=False)
+ grant = OAuthGrant.objects.create(
+ application=app,
+ user=self.user,
+ code="third_party_no_derive_code",
+ code_challenge=self.code_challenge,
+ code_challenge_method="S256",
+ redirect_uri="https://example.com/callback",
+ expires=timezone.now() + timedelta(minutes=5),
+ scoped_organizations=[str(self.organization.id)],
+ scoped_teams=[],
+ )
+
+ response = self.post(
+ "/oauth/token/",
+ {
+ **self.base_token_body,
+ "client_id": app.client_id,
+ "client_secret": "first_party_third-party-no-derive_client_secret",
+ "code": grant.code,
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertEqual(data["scoped_organizations"], [str(self.organization.id)])
+ self.assertEqual(data["scoped_teams"], [])
+
+ @freeze_time("2025-01-01 00:00:00")
+ def test_token_response_preserves_stored_scoped_teams_for_first_party_app(self):
+ app = self._create_first_party_app(slug="first-party-preserve")
+ grant = OAuthGrant.objects.create(
+ application=app,
+ user=self.user,
+ code="first_party_preserve_code",
+ code_challenge=self.code_challenge,
+ code_challenge_method="S256",
+ redirect_uri="https://example.com/callback",
+ expires=timezone.now() + timedelta(minutes=5),
+ scoped_organizations=[str(self.organization.id)],
+ scoped_teams=[self.team.pk],
+ )
+
+ response = self.post(
+ "/oauth/token/",
+ {
+ **self.base_token_body,
+ "client_id": app.client_id,
+ "client_secret": "first_party_first-party-preserve_client_secret",
+ "code": grant.code,
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertEqual(data["scoped_organizations"], [str(self.organization.id)])
+ self.assertEqual(data["scoped_teams"], [self.team.pk])
+
@override_settings(
OAUTH2_PROVIDER={
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 62072626b68f..78de1981f122 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -589,15 +589,9 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):
# First-party apps skip consent screen entirely
if application.is_first_party:
try:
- # Auto-approve with all user's accessible organizations.
org_ids = request.user.organizations.values_list("id", flat=True)
credentials["scoped_organizations"] = [str(org_id) for org_id in org_ids]
-
- # TODO(charlesvien): Populate scoped_teams for backwards compat with old
- # Code clients that throw "No team found in OAuth scopes" when
- # scoped_teams is empty. Remove once Code reads scoped_organizations.
- team_ids = Team.objects.filter(organization__members=request.user).values_list("pk", flat=True)
- credentials["scoped_teams"] = list(team_ids)
+ credentials["scoped_teams"] = []
uri, headers, body, status_code = self.create_authorization_response(
request=request, scopes=scope_str, credentials=credentials, allow=True
@@ -816,8 +810,27 @@ class OAuthTokenView(TokenView):
if access_token_value:
access_token = OAuthAccessToken.objects.get(token=access_token_value)
- response_data["scoped_teams"] = access_token.scoped_teams or []
- response_data["scoped_organizations"] = access_token.scoped_organizations or []
+ scoped_teams = list(access_token.scoped_teams or [])
+ scoped_organizations = list(access_token.scoped_organizations or [])
+
+ # First-party clients (PostHog Code) read scoped_teams from /oauth/token
+ # to populate the project selector. When the app is org-scoped only,
+ # access_token.scoped_teams is empty in the DB by design — derive teams
+ # from scoped_organizations so clients keep working without weakening
+ # the stored token scope.
+ # TODO(@charlesvien): remove this after a migration period in PostHog Code.
+ if (
+ not scoped_teams
+ and scoped_organizations
+ and access_token.application
+ and access_token.application.is_first_party
+ ):
+ scoped_teams = list(
+ Team.objects.filter(organization_id__in=scoped_organizations).values_list("pk", flat=True)
+ )
+
+ response_data["scoped_teams"] = scoped_teams
+ response_data["scoped_organizations"] = scoped_organizations
if region_info := get_region_info():
response_data.update(region_info)
diff --git a/posthog/api/test/test_organization.py b/posthog/api/test/test_organization.py
index f85359fddf26..b93bb1d3923a 100644
--- a/posthog/api/test/test_organization.py
+++ b/posthog/api/test/test_organization.py
@@ -356,6 +356,59 @@ class TestOrganizationAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ @parameterized.expand(
+ [
+ ("is_ai_data_processing_approved",),
+ ("is_ai_training_opted_in",),
+ ]
+ )
+ @override_settings(
+ OAUTH2_PROVIDER={
+ **settings.OAUTH2_PROVIDER,
+ "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
+ }
+ )
+ def test_org_scoped_oauth_token_can_patch_current_organization(self, field: str):
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ oauth_app = OAuthApplication.objects.create(
+ name="First Party Test App",
+ client_id=f"test_first_party_client_{field}",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ user=self.user,
+ is_first_party=True,
+ )
+
+ access_token = OAuthAccessToken.objects.create(
+ application=oauth_app,
+ user=self.user,
+ token=f"pha_test_first_party_token_{field}",
+ scope="organization:write",
+ expires=timezone.now() + timedelta(hours=1),
+ scoped_organizations=[str(self.organization.id)],
+ )
+
+ bearer = {"authorization": f"Bearer {access_token.token}"}
+
+ get_response = self.client.get("/api/organizations/@current/", headers=bearer)
+ self.assertEqual(get_response.status_code, status.HTTP_200_OK)
+ self.assertEqual(get_response.json()["id"], str(self.organization.id))
+
+ patch_response = self.client.patch(
+ "/api/organizations/@current/",
+ {field: True},
+ content_type="application/json",
+ headers=bearer,
+ )
+ self.assertEqual(patch_response.status_code, status.HTTP_200_OK, patch_response.content)
+
+ self.organization.refresh_from_db()
+ self.assertTrue(getattr(self.organization, field))
+
@patch("posthog.api.organization.delete_organization_data_and_notify_task")
def test_delete_organizations_and_verify_list(self, mock_delete_task):
self.organization_membership.level = OrganizationMembership.Level.OWNER