: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
fix(llm-gateway): refuse oauth tokens minted under staff impersonation (#120740)
Brandon4e25d1e10380
diff --git a/posthog/storage/gateway_credential_cache.py b/posthog/storage/gateway_credential_cache.pyindex 0e65bfa4c7bb..12d3b8b06af9 100644--- a/posthog/storage/gateway_credential_cache.py+++ b/posthog/storage/gateway_credential_cache.py@@ -240,6 +240,9 @@ def _oauth_authorization_ok(credential: OAuthAccessToken, team: Any, team_id: inreturn Falseif credential.expires <= timezone.now():return False+ # Staff impersonation mints tokens as the customer. Gateway spend must not go to a user who did not authorize it.+ if credential.impersonated_by_id is not None:+ return False# scoped_* narrows below the user's membership. team_id is the gateway's canonical# (project-root) team, so a token scoped only to a child env fails closed here.@@ -336,8 +339,9 @@ def _team_tier_overrides() -> dict[str, str]:def oauth_credential_authorized(credential: OAuthAccessToken, team: Any) -> bool:"""Whether an OAuth credential is still authorized for team right now: the user- is active, a member, and still has project access. Callers outside the- projection need it because a token's scoped_teams is frozen at consent.+ is active, a member, and still has project access, and no staff impersonation+ minted the token. Callers outside the projection need it because a token's+ scoped_teams is frozen at consent."""return _oauth_authorization_ok(credential, team, team.id, None)diff --git a/posthog/storage/test/test_gateway_credential_cache.py b/posthog/storage/test/test_gateway_credential_cache.pyindex 4dbf3cd7de44..d46d77708bbf 100644--- a/posthog/storage/test/test_gateway_credential_cache.py+++ b/posthog/storage/test/test_gateway_credential_cache.py@@ -37,6 +37,7 @@ from posthog.storage.gateway_credential_cache import (drain_gateway_credential_last_used,format_overspend_allowance_usd,gateway_credential_hypercache as hypercache,+ oauth_credential_authorized,project_gateway_credential,refresh_all_gateway_credentials,validate_overspend_allowance_usd,@@ -79,6 +80,7 @@ class GatewayCredentialTestMixin(BaseTest):expires_in_hours: float = 1,token: str | None = None,user: User | None = None,+ impersonated_by: User | None = None,) -> OAuthAccessToken:token = token or f"pha_{generate_random_token()}"app = OAuthApplication.objects.create(@@ -96,6 +98,7 @@ class GatewayCredentialTestMixin(BaseTest):token=token,expires=timezone.now() + timedelta(hours=expires_in_hours),scope=scope,+ impersonated_by=impersonated_by,)def _read_blob(self, cache_hash: str | None) -> dict | None:@@ -356,6 +359,13 @@ class TestGatewayCredentialFailClosed(GatewayCredentialTestMixin):# The user / scope-narrowing / membership / RBAC enforcement only applies to OAuth# — project secret keys carry no user, no scoped_*, and no membership. These cases# exercise the surviving OAuth authorization path.+ def test_impersonation_token_never_projected_or_authorized(self):+ staff = User.objects.create_and_join(self.organization, "[email protected]", None, is_staff=True)+ credential = self._make_oauth(GATEWAY_SCOPE, impersonated_by=staff)+ project_gateway_credential(credential)+ self.assertIsNone(self._read_blob(credential_hash(credential)))+ self.assertFalse(oauth_credential_authorized(credential, self.team))+def test_inactive_user_clears(self):credential = self._make_oauth(GATEWAY_SCOPE)project_gateway_credential(credential)diff --git a/services/llm-gateway/src/llm_gateway/auth/authenticators.py b/services/llm-gateway/src/llm_gateway/auth/authenticators.pyindex 18468e06c3bf..ffff2ef23de6 100644--- a/services/llm-gateway/src/llm_gateway/auth/authenticators.py+++ b/services/llm-gateway/src/llm_gateway/auth/authenticators.py@@ -112,7 +112,7 @@ class OAuthAccessTokenAuthenticator(Authenticator):"""SELECT oat.id, oat.user_id, oat.scope, oat.expires,oat.application_id, oat.scoped_teams, oat.scoped_organizations,- oat.sandbox_task_id,+ oat.sandbox_task_id, oat.impersonated_by_id,u.current_team_id, u.distinct_id, u.is_staffFROM posthog_oauthaccesstoken oatJOIN posthog_user u ON oat.user_id = u.id@@ -132,6 +132,10 @@ class OAuthAccessTokenAuthenticator(Authenticator):if not row["application_id"]:return None+ # Staff impersonation mints tokens as the customer. Gateway spend must not go to that user.+ if row.get("impersonated_by_id") is not None:+ return None+scopes = row["scope"].split() if row["scope"] else []if not has_required_scope(scopes, allow_wildcard=True):return Nonediff --git a/services/llm-gateway/tests/test_auth.py b/services/llm-gateway/tests/test_auth.pyindex 595dffcb4f66..e1e771687b1d 100644--- a/services/llm-gateway/tests/test_auth.py+++ b/services/llm-gateway/tests/test_auth.py@@ -847,6 +847,41 @@ class TestOAuthAccessTokenAuthenticator:result = await authenticator.authenticate(token_hash, mock_pool)assert result is None+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "impersonated_by_id,authenticated",+ [+ pytest.param(None, True, id="own_token"),+ pytest.param(42, False, id="impersonation_token"),+ ],+ )+ async def test_impersonation_token_returns_none(+ self,+ authenticator: OAuthAccessTokenAuthenticator,+ mock_pool: MagicMock,+ impersonated_by_id: int | None,+ authenticated: bool,+ ) -> None:+ conn = mock_pool.acquire.return_value+ conn.fetchrow = AsyncMock(+ return_value={+ "id": 1,+ "user_id": 123,+ "scope": "llm_gateway:read",+ "expires": datetime.now(UTC) + timedelta(hours=1),+ "current_team_id": 456,+ "application_id": 789,+ "distinct_id": "test-distinct-id",+ "is_staff": False,+ "impersonated_by_id": impersonated_by_id,+ }+ )++ token_hash = authenticator.hash_token("pha_impersonation")+ result = await authenticator.authenticate(token_hash, mock_pool)+ assert (result is not None) is authenticated+ assert "oat.impersonated_by_id" in conn.fetchrow.call_args.args[0]+@pytest.mark.asyncio@pytest.mark.parametrize("scope",