: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: exclude unavailable scopes from personal API key creation (#58531)
Reece Jones374d0c57ee6b
diff --git a/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts b/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.tsnew file mode 100644index 000000000000..217a81029374--- /dev/null+++ b/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts@@ -0,0 +1,101 @@+import { MOCK_DEFAULT_USER } from 'lib/api.mock'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { userLogic } from 'scenes/userLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { personalAPIKeysLogic } from './personalAPIKeysLogic'++describe('personalAPIKeysLogic', () => {+ let logic: ReturnType<typeof personalAPIKeysLogic.build>+ let capturedCreatePayload: any = null++ beforeEach(() => {+ capturedCreatePayload = null++ useMocks({+ get: {+ '/api/personal_api_keys/': [],+ '/api/projects/': { results: [], count: 0, next: null, previous: null },+ },+ post: {+ '/api/personal_api_keys/': async (req) => {+ capturedCreatePayload = await req.json()+ return [+ 200,+ {+ id: 'new-key-id',+ label: capturedCreatePayload?.label,+ scopes: capturedCreatePayload?.scopes,+ scoped_organizations: capturedCreatePayload?.scoped_organizations ?? [],+ scoped_teams: capturedCreatePayload?.scoped_teams ?? [],+ value: 'phx_test',+ },+ ]+ },+ },+ })++ initKeaTests()+ featureFlagLogic.mount()+ userLogic.mount()+ userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)++ logic = personalAPIKeysLogic()+ logic.mount()+ })++ it('strips llm_gateway scopes from create payload when GATEWAY_PERSONAL_API_KEY flag is disabled', async () => {+ featureFlagLogic.actions.setFeatureFlags([], {})++ logic.actions.setEditingKeyId('new')+ logic.actions.setEditingKeyValues({+ label: 'Test key',+ access_type: 'all',+ scopes: ['feature_flag:read', 'llm_gateway:read', 'insight:write'],+ })++ await logic.asyncActions.submitEditingKey()++ expect(capturedCreatePayload).not.toBeNull()+ expect(capturedCreatePayload.scopes).toEqual(['feature_flag:read', 'insight:write'])+ expect(capturedCreatePayload.scopes).not.toContain('llm_gateway:read')+ })++ it('preserves llm_gateway scopes from create payload when GATEWAY_PERSONAL_API_KEY flag is enabled', async () => {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.GATEWAY_PERSONAL_API_KEY], {+ [FEATURE_FLAGS.GATEWAY_PERSONAL_API_KEY]: true,+ })++ logic.actions.setEditingKeyId('new')+ logic.actions.setEditingKeyValues({+ label: 'Test key',+ access_type: 'all',+ scopes: ['feature_flag:read', 'llm_gateway:read'],+ })++ await logic.asyncActions.submitEditingKey()++ expect(capturedCreatePayload).not.toBeNull()+ expect(capturedCreatePayload.scopes).toEqual(['feature_flag:read', 'llm_gateway:read'])+ })++ it('preserves the `*` (all access) scope regardless of flag state', async () => {+ featureFlagLogic.actions.setFeatureFlags([], {})++ logic.actions.setEditingKeyId('new')+ logic.actions.setEditingKeyValues({+ label: 'Test key',+ access_type: 'all',+ scopes: ['*'],+ })++ await logic.asyncActions.submitEditingKey()++ expect(capturedCreatePayload).not.toBeNull()+ expect(capturedCreatePayload.scopes).toEqual(['*'])+ })+})diff --git a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsxindex bc37378deae7..b625cc31b2a6 100644--- a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx+++ b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx@@ -127,10 +127,25 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([return}+ // Sanitize scopes against `allowedScopeKeys` so flag-gated scopes+ // (e.g. `llm_gateway`) can't slip through via presets like+ // "Read-only access" that expand to every scope in API_SCOPES.+ // `*` (all access) is preserved as-is.+ const allowed = values.allowedScopeKeys+ const sanitizedScopes =+ payload.scopes?.filter((scope) => {+ if (scope === '*') {+ return true+ }+ const [object] = scope.split(':')+ return !!object && allowed.has(object)+ }) ?? []+ const sanitizedPayload = { ...payload, scopes: sanitizedScopes }+const key =values.editingKeyId === 'new'- ? await api.personalApiKeys.create(payload)- : await api.personalApiKeys.update(values.editingKeyId, payload)+ ? await api.personalApiKeys.create(sanitizedPayload)+ : await api.personalApiKeys.update(values.editingKeyId, sanitizedPayload)breakpoint()@@ -144,9 +159,9 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([},})),selectors(() => ({- filteredScopes: [- (s) => [s.searchTerm, s.featureFlags, s.hasAvailableFeature],- (searchTerm, featureFlags, hasAvailableFeature): APIScope[] => {+ allowedScopes: [+ (s) => [s.featureFlags, s.hasAvailableFeature],+ (featureFlags, hasAvailableFeature): APIScope[] => {let scopes = API_SCOPES// Filter out llm_gateway scope if feature flag is disabled@@ -159,6 +174,18 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([scopes = scopes.filter((scope) => scope.key !== 'approvals')}+ return scopes+ },+ ],+ allowedScopeKeys: [+ (s) => [s.allowedScopes],+ (allowedScopes): Set<string> => new Set(allowedScopes.map((scope) => scope.key)),+ ],+ filteredScopes: [+ (s) => [s.searchTerm, s.allowedScopes],+ (searchTerm, allowedScopes): APIScope[] => {+ const scopes = allowedScopes+if (!searchTerm.trim()) {return scopes}