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(ai-gateway): gate llm_gateway scope on project secret keys (#64216)

Richard Solomoue7fb8d125bcc
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index fff62cd22ebd..2f26b1c22ac5 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -341,9 +341,9 @@ snapshots:
components-definition-popover--action--light:
hash: v1.k794b7964.e04f3796a4f04cad8873ce1afdc158e4cc6a0540b8a920a8c5d918daf5199dbf.FAUSpdd2xVG1T6eZCXSQQBisUiX30_g-Q4BwRvRoE_g
components-definition-popover--data-warehouse-column-mapping--dark:
- hash: v1.k794b7964.6f535af764881ae419ed9ac52aeca390ef92f802fbe4691778cf79fb92b5422e.VDUBeHyJ28_h-hJCnxhRXHG4SiryFPiCOOrOIMVLPMo
+ hash: v1.k794b7964.c38f182b346c519d1332cfd066782c3b4b9e0b5661fbe926253da902fc3c388b.micG7HfZSdoQxZl9DsRJk9wX2So89qflq-sxr9DYS4A
components-definition-popover--data-warehouse-column-mapping--light:
- hash: v1.k794b7964.63a2124f9b72369793988678f8fc92999ae15d4812a53a3e17d2068bd3670b7d.gvgiL7tjCAmOdbH_2eMJsNb7nFdGojZs41KXBV2sbsM
+ hash: v1.k794b7964.3201bcfb76a5bc9e9144f88ccb819af400442196804dc0ab84e1ecac6e141e28.U68Q077AoH6AtdHda3iCWWJelz2JyHqHs8JpJA_Onao
components-definition-popover--event--dark:
hash: v1.k794b7964.3da91158e1c88f8e9827213de348d341a3b3d1d8f64e1d53211b298d465133d4.oU3XnkSjwx3rnKksGGv2QOtnpMPTICcd62RII4xBReU
components-definition-popover--event--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 14646df26260..cae2bec7768e 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -237,6 +237,7 @@ export const FEATURE_FLAGS = {
ACTION_REFERENCE_COUNT: 'action-reference-count', // owner: @andyzzhao #team-product-analytics, gates bulk action reference counting on actions list
ADVANCE_MARKETING_ANALYTICS_SETTINGS: 'advance-marketing-analytics-settings', // owner: @jabahamondes #team-web-analytics
AI_EVENTS_TABLE_ROLLOUT: 'ai-events-table-rollout', // owner: #team-ai-observability, gates reads off the dedicated ai_events table
+ AI_GATEWAY: 'ai-gateway', // owner: #team-ai-gateway, gates the AI gateway UI and llm_gateway:read on project secret API keys
/** Alert edit modal: check history chart + chart/table toggle (table remains when off). */
ALERTS_15_MINUTE_INTERVAL: 'alerts-15-minute-interval', // owner: #team-analytics-platform, gates 15-minute insight alert interval
ALERTS_ANOMALY_DETECTION: 'alerts-anomaly-detection', // owner: @andrewm4894
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 73155ac7edaa..2fa2e1bd3d62 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -212,12 +212,17 @@ export const APIScopeActionLabels: Record<APIScopeAction, string> = {
write: 'Write',
}
-export const PROJECT_SECRET_API_KEY_SCOPE_PRESETS: {
+export type ProjectSecretAPIKeyScopePreset = {
value: string
label: string
scopes: string[]
isCloudOnly?: boolean
-}[] = [{ value: 'endpoint_execution', label: 'Endpoint execution', scopes: ['endpoint:read'] }]
+}
+
+export const PROJECT_SECRET_API_KEY_SCOPE_PRESETS: ProjectSecretAPIKeyScopePreset[] = [
+ { value: 'endpoint_execution', label: 'Endpoint execution', scopes: ['endpoint:read'] },
+ { value: 'llm_gateway', label: 'AI gateway access', scopes: ['llm_gateway:read'] },
+]
export const DEFAULT_OAUTH_SCOPES = ['openid', 'email', 'profile']
diff --git a/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx b/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx
index 9498c1e8cdd5..00a0334302e2 100644
--- a/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx
+++ b/frontend/src/scenes/settings/project/ProjectSecretAPIKeys.tsx
@@ -7,8 +7,6 @@ import { LemonButton, LemonInput, LemonModal, LemonSelect } from '@posthog/lemon
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { TeamMembershipLevel } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
-import { PROJECT_SECRET_API_KEY_SCOPE_PRESETS } from 'lib/scopes'
-import { capitalizeFirstLetter } from 'lib/utils/strings'
import { APIKeyTable } from '../shared/APIKeyTable'
import { ScopeAccessRow } from '../shared/ScopeAccessRow'
@@ -22,6 +20,7 @@ function EditKeyModal(): JSX.Element {
editingKeyChanged,
formScopeRadioValues,
filteredScopes,
+ availablePresets,
searchTerm,
} = useValues(projectSecretAPIKeysLogic)
const { setEditingKeyId, setScopeRadioValue, submitEditingKey, setSearchTerm } =
@@ -72,7 +71,7 @@ function EditKeyModal(): JSX.Element {
<LemonSelect
size="small"
placeholder="Select preset"
- options={PROJECT_SECRET_API_KEY_SCOPE_PRESETS}
+ options={availablePresets}
dropdownMatchSelectWidth={false}
/>
</LemonField>
@@ -96,10 +95,10 @@ function EditKeyModal(): JSX.Element {
{filteredScopes.length === 0 ? (
<div className="text-muted text-sm py-2">No scopes match "{searchTerm}"</div>
) : (
- filteredScopes.map(({ key, disabledActions }) => (
+ filteredScopes.map(({ key, label, disabledActions }) => (
<ScopeAccessRow
key={key}
- label={capitalizeFirstLetter(key.replace(/_/g, ' '))}
+ label={label}
value={formScopeRadioValues[key] ?? 'none'}
onChange={(value) => setScopeRadioValue(key, value)}
readDisabledReason={
diff --git a/frontend/src/scenes/settings/project/projectSecretAPIKeysLogic.test.ts b/frontend/src/scenes/settings/project/projectSecretAPIKeysLogic.test.ts
new file mode 100644
index 000000000000..dc5d1cd31dcb
--- /dev/null
+++ b/frontend/src/scenes/settings/project/projectSecretAPIKeysLogic.test.ts
@@ -0,0 +1,58 @@
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { projectSecretAPIKeysLogic } from './projectSecretAPIKeysLogic'
+
+describe('projectSecretAPIKeysLogic', () => {
+ let logic: ReturnType<typeof projectSecretAPIKeysLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/project_secret_api_keys': [],
+ '/api/projects/:team_id/project_secret_api_keys/': [],
+ },
+ })
+
+ initKeaTests()
+ featureFlagLogic.mount()
+
+ logic = projectSecretAPIKeysLogic()
+ logic.mount()
+ })
+
+ it.each([
+ ['disabled', false],
+ ['enabled', true],
+ ])('gates the llm_gateway scope and preset on the AI_GATEWAY flag (%s)', (_label, flagEnabled) => {
+ featureFlagLogic.actions.setFeatureFlags(
+ flagEnabled ? [FEATURE_FLAGS.AI_GATEWAY] : [],
+ flagEnabled ? { [FEATURE_FLAGS.AI_GATEWAY]: true } : {}
+ )
+
+ const scopeKeys = logic.values.filteredScopes.map(({ key }) => key)
+ const presetValues = logic.values.availablePresets.map(({ value }) => value)
+
+ expect(scopeKeys.includes('llm_gateway')).toBe(flagEnabled)
+ expect(presetValues.includes('llm_gateway')).toBe(flagEnabled)
+
+ // endpoint access is always available regardless of the flag
+ expect(scopeKeys).toContain('endpoint')
+ expect(presetValues).toContain('endpoint_execution')
+ })
+
+ it('labels the llm_gateway scope as "AI gateway" and keeps it read-only when the flag is enabled', () => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.AI_GATEWAY], {
+ [FEATURE_FLAGS.AI_GATEWAY]: true,
+ })
+
+ const gatewayScope = logic.values.filteredScopes.find(({ key }) => key === 'llm_gateway')
+
+ expect(gatewayScope).not.toBeUndefined()
+ expect(gatewayScope?.label).toBe('AI gateway')
+ expect(gatewayScope?.disabledActions).toContain('write')
+ })
+})
diff --git a/frontend/src/scenes/settings/project/projectSecretAPIKeysLogic.tsx b/frontend/src/scenes/settings/project/projectSecretAPIKeysLogic.tsx
index ff0a0312dc56..c74cef372f4d 100644
--- a/frontend/src/scenes/settings/project/projectSecretAPIKeysLogic.tsx
+++ b/frontend/src/scenes/settings/project/projectSecretAPIKeysLogic.tsx
@@ -6,12 +6,16 @@ import { LemonDialog } from '@posthog/lemon-ui'
import api from 'lib/api'
import { CodeSnippet } from 'lib/components/CodeSnippet'
+import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import {
PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION,
PROJECT_SECRET_API_KEY_SCOPE_PRESETS,
ProjectSecretAPIKeyAllowedScope,
+ ProjectSecretAPIKeyScopePreset,
} from 'lib/scopes'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { ProjectSecretAPIKeyApi } from '~/generated/core/api.schemas'
@@ -25,10 +29,15 @@ export type EditingProjectKeyFormValues = ProjectSecretAPIKeyRequest & {
export const MAX_PROJECT_API_KEYS_PER_PROJECT = 10
+// llm_gateway powers the new AI gateway here, so label it "AI gateway" (PAKs keep "LLM gateway").
+const PROJECT_SECRET_SCOPE_OBJECT_NAMES: Record<string, string> = {
+ llm_gateway: 'AI gateway',
+}
+
export const projectSecretAPIKeysLogic = kea<projectSecretAPIKeysLogicType>([
path(['scenes', 'settings', 'project', 'projectSecretAPIKeysLogic']),
connect(() => ({
- values: [teamLogic, ['currentTeamId']],
+ values: [teamLogic, ['currentTeamId'], featureFlagLogic, ['featureFlags']],
})),
actions({
@@ -164,11 +173,16 @@ export const projectSecretAPIKeysLogic = kea<projectSecretAPIKeysLogicType>([
},
],
filteredScopes: [
- (s) => [s.searchTerm],
- (searchTerm: string): { key: string; disabledActions: APIScopeAction[] }[] => {
+ (s) => [s.searchTerm, s.featureFlags],
+ (searchTerm: string, featureFlags): { key: string; label: string; disabledActions: APIScopeAction[] }[] => {
const allActions: APIScopeAction[] = ['read', 'write']
+ // llm_gateway:read is added only when the ai-gateway flag is on, mirroring the backend.
+ const allowedScopeActions: string[] = [...PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION]
+ if (featureFlags[FEATURE_FLAGS.AI_GATEWAY]) {
+ allowedScopeActions.push('llm_gateway:read')
+ }
const allowedByKey = new Map<string, Set<APIScopeAction>>()
- for (const scopeAction of PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION) {
+ for (const scopeAction of allowedScopeActions) {
const [key, action] = scopeAction.split(':') as [string, APIScopeAction]
if (!allowedByKey.has(key)) {
allowedByKey.set(key, new Set())
@@ -177,15 +191,23 @@ export const projectSecretAPIKeysLogic = kea<projectSecretAPIKeysLogicType>([
}
const scopes = Array.from(allowedByKey.entries()).map(([key, allowed]) => ({
key,
+ label: PROJECT_SECRET_SCOPE_OBJECT_NAMES[key] ?? capitalizeFirstLetter(key.replace(/_/g, ' ')),
disabledActions: allActions.filter((a) => !allowed.has(a)),
}))
if (!searchTerm.trim()) {
return scopes
}
const lowerSearch = searchTerm.toLowerCase()
- return scopes.filter(({ key }) => key.replace(/_/g, ' ').toLowerCase().includes(lowerSearch))
+ return scopes.filter(({ label }) => label.toLowerCase().includes(lowerSearch))
},
],
+ availablePresets: [
+ (s) => [s.featureFlags],
+ (featureFlags): ProjectSecretAPIKeyScopePreset[] =>
+ PROJECT_SECRET_API_KEY_SCOPE_PRESETS.filter(
+ ({ value }) => value !== 'llm_gateway' || featureFlags[FEATURE_FLAGS.AI_GATEWAY]
+ ),
+ ],
})),
listeners(({ actions, values }) => ({
diff --git a/posthog/api/project_secret_api_key.py b/posthog/api/project_secret_api_key.py
index ec123cccd8a9..505bc5126138 100644
--- a/posthog/api/project_secret_api_key.py
+++ b/posthog/api/project_secret_api_key.py
@@ -4,6 +4,7 @@ from django.db import IntegrityError
from django.db.models import QuerySet
from django.utils import timezone
+import posthoganalytics
from rest_framework import response, serializers, status, viewsets
from rest_framework.exceptions import ValidationError
@@ -65,6 +66,12 @@ class ProjectSecretAPIKeySerializer(serializers.ModelSerializer):
return getattr(obj, "_value", None) # type: ignore
def validate_scopes(self, scopes):
+ allowed = set(PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION)
+ # Allow llm_gateway:read only when the flag is on or the key already has it, so a flag
+ # rollback can't make an existing key unsaveable. Flag is evaluated only when requested.
+ if any(s.startswith("llm_gateway:") for s in scopes) and self._llm_gateway_grantable():
+ allowed.add(("llm_gateway", "read"))
+
for scope in scopes:
if scope == "*":
raise serializers.ValidationError(
@@ -79,18 +86,37 @@ class ProjectSecretAPIKeySerializer(serializers.ModelSerializer):
):
raise serializers.ValidationError(f"Invalid scope: {scope}")
- if (scope_parts[0], scope_parts[1]) not in PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION:
- allowed_scopes = ", ".join(
- [
- f"{scope_object_action[0]}:{scope_object_action[1]}"
- for scope_object_action in PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION
- ]
- )
+ if (scope_parts[0], scope_parts[1]) not in allowed:
+ if (scope_parts[0], scope_parts[1]) == ("llm_gateway", "read"):
+ raise serializers.ValidationError(
+ "LLM gateway scope is not available for this project. Contact support to enable this feature."
+ )
+ allowed_scopes = ", ".join(f"{obj}:{action}" for obj, action in sorted(allowed))
raise serializers.ValidationError(
f"Scope '{scope}' can not be assigned to a project secret API key. Allowed scopes: {allowed_scopes}"
)
return scopes
+ def _llm_gateway_grantable(self) -> bool:
+ existing_has_llm_gateway = self.instance is not None and any(
+ s.startswith("llm_gateway:") for s in (self.instance.scopes or [])
+ )
+ return existing_has_llm_gateway or self._ai_gateway_enabled()
+
+ def _ai_gateway_enabled(self) -> bool:
+ team = self.context["view"].team
+ user = self.context["request"].user
+ return bool(
+ posthoganalytics.feature_enabled(
+ "ai-gateway",
+ str(user.distinct_id),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ group_properties={"organization": {"id": str(team.organization_id)}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+
def to_representation(self, instance):
ret = super().to_representation(instance)
ret["scopes"] = ret["scopes"] or []
diff --git a/posthog/api/test/test_project_secret_api_keys.py b/posthog/api/test/test_project_secret_api_keys.py
index 1b21479fcd53..48159e966a90 100644
--- a/posthog/api/test/test_project_secret_api_keys.py
+++ b/posthog/api/test/test_project_secret_api_keys.py
@@ -1,10 +1,13 @@
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
from posthog.api.project_secret_api_key import MAX_PROJECT_SECRET_API_KEYS_PER_TEAM
from posthog.models import Organization, OrganizationMembership, Team
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.project_secret_api_key import ProjectSecretAPIKey
-from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.models.utils import generate_random_token_personal, generate_random_token_secret, hash_key_value
class TestProjectSecretAPIKeysAPIMember(APIBaseTest):
@@ -124,6 +127,97 @@ class TestProjectSecretAPIKeysAPI(APIBaseTest):
assert response.status_code == 400
assert "Invalid scope" in response.json()["detail"]
+ @parameterized.expand(
+ [
+ ("blocked_when_flag_disabled", False, 400),
+ ("allowed_when_flag_enabled", True, 201),
+ ]
+ )
+ @patch("posthog.api.project_secret_api_key.posthoganalytics.feature_enabled")
+ def test_create_llm_gateway_scope_gated_on_flag(self, _name, flag_enabled, expected_status, mock_feature_enabled):
+ mock_feature_enabled.return_value = flag_enabled
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/project_secret_api_keys",
+ {"label": "my key", "scopes": ["llm_gateway:read"]},
+ )
+ assert response.status_code == expected_status, response.json()
+ if expected_status == 201:
+ assert response.json()["scopes"] == ["llm_gateway:read"]
+ else:
+ assert "LLM gateway scope is not available" in response.json()["detail"]
+ mock_feature_enabled.assert_called_once()
+
+ @patch("posthog.api.project_secret_api_key.posthoganalytics.feature_enabled")
+ def test_update_keeps_existing_llm_gateway_scope_when_flag_disabled(self, mock_feature_enabled):
+ mock_feature_enabled.return_value = False
+
+ key = ProjectSecretAPIKey.objects.create(
+ team=self.team,
+ label="existing",
+ secure_value=hash_key_value(generate_random_token_secret()),
+ scopes=["llm_gateway:read"],
+ created_by=self.user,
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/project_secret_api_keys/{key.id}",
+ {"label": "renamed", "scopes": ["llm_gateway:read"]},
+ )
+ assert response.status_code == 200
+ assert response.json()["label"] == "renamed"
+ assert response.json()["scopes"] == ["llm_gateway:read"]
+ mock_feature_enabled.assert_not_called()
+
+ @patch("posthog.api.project_secret_api_key.posthoganalytics.feature_enabled")
+ def test_update_adding_llm_gateway_scope_blocked_when_flag_disabled(self, mock_feature_enabled):
+ mock_feature_enabled.return_value = False
+
+ key = ProjectSecretAPIKey.objects.create(
+ team=self.team,
+ label="existing",
+ secure_value=hash_key_value(generate_random_token_secret()),
+ scopes=["endpoint:read"],
+ created_by=self.user,
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/project_secret_api_keys/{key.id}",
+ {"scopes": ["endpoint:read", "llm_gateway:read"]},
+ )
+ assert response.status_code == 400
+ assert "LLM gateway scope is not available" in response.json()["detail"]
+ mock_feature_enabled.assert_called_once()
+
+ @patch("posthog.api.project_secret_api_key.posthoganalytics.feature_enabled")
+ def test_update_adding_llm_gateway_scope_to_key_with_null_scopes(self, mock_feature_enabled):
+ mock_feature_enabled.return_value = True
+
+ key = ProjectSecretAPIKey.objects.create(
+ team=self.team,
+ label="existing",
+ secure_value=hash_key_value(generate_random_token_secret()),
+ scopes=None,
+ created_by=self.user,
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/project_secret_api_keys/{key.id}",
+ {"scopes": ["llm_gateway:read"]},
+ )
+ assert response.status_code == 200
+ assert response.json()["scopes"] == ["llm_gateway:read"]
+
+ @patch("posthog.api.project_secret_api_key.posthoganalytics.feature_enabled")
+ def test_non_gateway_scope_unaffected_by_flag(self, mock_feature_enabled):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/project_secret_api_keys",
+ {"label": "my key", "scopes": ["endpoint:read"]},
+ )
+ assert response.status_code == 201
+ assert response.json()["scopes"] == ["endpoint:read"]
+ mock_feature_enabled.assert_not_called()
+
def test_update_label(self):
create_response = self.client.post(
f"/api/projects/{self.team.id}/project_secret_api_keys",
diff --git a/posthog/scopes.py b/posthog/scopes.py
index e60d933b5947..1820df962dea 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -146,9 +146,10 @@ INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset(
# clients (the consent screen, MCP, third-party apps) to discover it.
OAUTH_HIDDEN_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset({"wizard_session"})
+# llm_gateway:read is omitted on purpose: it's alpha/privileged and granted only behind the
+# ai-gateway flag in ProjectSecretAPIKeySerializer, not unconditionally like the entries here.
PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIScopeActions]] = [
("endpoint", "read"),
- ("llm_gateway", "read"),
]
# Server-side scope assignment string-set constants (see RFC: server-side scope