: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(settings): show server validation errors in the personal API key form (#126233)
Eleftheria Trivyzakibf976a762be0
diff --git a/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts b/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.tsindex 47163edd94bf..3912b8e070d4 100644--- a/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts+++ b/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts@@ -5,6 +5,7 @@ import { expectLogic } from 'kea-test-utils'import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'@@ -75,6 +76,71 @@ describe('personalAPIKeysLogic', () => {expect(capturedCreatePayload.scopes).not.toContain('llm_gateway:read')})+ it('shows a field error from the server under the field it names', async () => {+ useMocks({+ post: {+ '/api/personal_api_keys/': () => [+ 400,+ {+ type: 'validation_error',+ code: 'max_length',+ detail: 'Ensure this field has no more than 40 characters.',+ attr: 'label',+ },+ ],+ },+ })++ logic.actions.setEditingKeyId('new')+ logic.actions.setEditingKeyValues({+ label: 'A label that is a lot longer than the forty characters allowed',+ access_type: 'all',+ scopes: ['feature_flag:read'],+ })++ await logic.asyncActions.submitEditingKey()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.editingKeyManualErrors).toEqual({+ label: 'Ensure this field has no more than 40 characters.',+ })+ expect(logic.values.isEditingKeySubmitting).toBe(false)+ expect(logic.values.editingKeyId).toBe('new')++ logic.actions.setEditingKeyValue('label', 'Short label')+ expect(logic.values.editingKeyManualErrors).toEqual({})+ expect(logic.values.editingKeyHasErrors).toBe(false)+ })++ it('shows a server error that names no field as a toast', async () => {+ const toastError = jest.spyOn(lemonToast, 'error').mockImplementation(() => '')+ useMocks({+ post: {+ '/api/personal_api_keys/': () => [+ 400,+ {+ type: 'validation_error',+ code: 'invalid_input',+ detail: 'You can only have 10 personal API keys. Remove an existing key before creating a new one.',+ attr: null,+ },+ ],+ },+ })++ logic.actions.setEditingKeyId('new')+ logic.actions.setEditingKeyValues({ label: 'Test key', access_type: 'all', scopes: ['feature_flag:read'] })++ await logic.asyncActions.submitEditingKey()+ await expectLogic(logic).toFinishAllListeners()++ expect(toastError).toHaveBeenCalledWith(+ 'You can only have 10 personal API keys. Remove an existing key before creating a new one.'+ )+ expect(logic.values.editingKeyManualErrors).toEqual({})+ expect(logic.values.editingKeyId).toBe('new')+ })+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,diff --git a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsxindex 9616a92199a2..af1cbf64514d 100644--- a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx+++ b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx@@ -7,6 +7,7 @@ import { actionToUrl, router, urlToAction } from 'kea-router'import { LemonBanner, LemonDialog } from '@posthog/lemon-ui'import api from 'lib/api'+import { ApiError } from 'lib/api-error'import { CodeSnippet } from 'lib/components/CodeSnippet'import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'import { dayjs } from 'lib/dayjs'@@ -758,8 +759,24 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([}}},+ submitEditingKeyFailure: ({ error }) => {+ // kea-forms swallows the rejected API call, so the server's message has to be copied to the form here+ if (!(error instanceof ApiError)) {+ return+ }+ if (error.attr && error.attr in values.editingKey) {+ actions.setEditingKeyManualErrors({ [error.attr]: error.detail || error.message })+ } else {+ lemonToast.error(error.detail || 'Could not save the personal API key. Try again.')+ }+ },setEditingKeyValue: async ({ name, value }) => {const key = Array.isArray(name) ? name[0] : name+ // kea-forms only drops a manual error on blur, and a stale one blocks a resubmit from the Enter key+ if (key in values.editingKeyManualErrors) {+ const { [key]: _stale, ...remainingErrors } = values.editingKeyManualErrors+ actions.setEditingKeyManualErrors(remainingErrors)+ }// When we select a preset, update the scopesif (key === 'preset' && value) {const preset = API_KEY_SCOPE_PRESETS.find((preset) => preset.value === value)