: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
feat: add optional description to personal API keys (#69405)
Alex Lider354525e74b35
diff --git a/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx b/frontend/src/scenes/settings/user/PersonalAPIKeys.tsxindex 2e273f7d11b6..fe937b03932d 100644--- a/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx+++ b/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx@@ -13,6 +13,7 @@ import {LemonSelect,LemonTableColumn,LemonTag,+ LemonTextArea,Tooltip,} from '@posthog/lemon-ui'@@ -20,6 +21,7 @@ import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'import { IconErrorOutline } from 'lib/lemon-ui/icons'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonField } from 'lib/lemon-ui/LemonField'+import { Link } from 'lib/lemon-ui/Link'import { API_KEY_SCOPE_PRESETS, MAX_API_KEYS_PER_USER } from 'lib/scopes'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'@@ -46,9 +48,17 @@ export function EditKeyModal({ zIndex }: EditKeyModalProps): JSX.Element {allOrganizations,filteredScopes,searchTerm,+ isDescriptionFieldVisible,} = useValues(personalAPIKeysLogic)- const { setEditingKeyId, setScopeRadioValue, submitEditingKey, resetScopes, setSearchTerm, rollKey } =- useActions(personalAPIKeysLogic)+ const {+ setEditingKeyId,+ setScopeRadioValue,+ submitEditingKey,+ resetScopes,+ setSearchTerm,+ rollKey,+ showDescriptionField,+ } = useActions(personalAPIKeysLogic)const { isCloudOrDev } = useValues(preflightLogic)const isNew = editingKeyId === 'new'@@ -135,6 +145,28 @@ export function EditKeyModal({ zIndex }: EditKeyModalProps): JSX.Element {<LemonField name="label" label="Label"><LemonInput placeholder='For example "Reports bot" or "Zapier"' maxLength={40} /></LemonField>+ {isDescriptionFieldVisible ? (+ <LemonField name="description" label="Description" showOptional className="mt-2">+ <LemonTextArea+ placeholder="What is this key used for, and where? For example a link to the integration using it"+ maxLength={1000}+ minRows={2}+ data-attr="personal-api-key-description"+ />+ </LemonField>+ ) : (+ <div className="mt-1">+ <LemonButton+ type="tertiary"+ size="xsmall"+ icon={<IconPlus />}+ onClick={() => showDescriptionField()}+ data-attr="personal-api-key-add-description"+ >+ Add description+ </LemonButton>+ </div>+ )}<ScopeAccessSelectoraccessType={editingKey.access_type}organizations={allOrganizations}@@ -486,6 +518,22 @@ function PersonalAPIKeysTable(): JSX.Element {showActionsrowClassName={(key) => (isPersonalApiKeyIdDisabled(key.id) ? 'opacity-50' : '')}deleteDescription="This action cannot be undone. Make sure to have removed the key from any live integrations first."+ renderLabel={(key) => (+ <div className="flex flex-col">+ <Link+ subtle+ className="text-left font-semibold truncate"+ onClick={() => setEditingKeyId(key.id)}+ >+ {key.label}+ </Link>+ {key.description && (+ <Tooltip title={key.description}>+ <span className="text-muted text-xs truncate max-w-60">{key.description}</span>+ </Tooltip>+ )}+ </div>+ )}renderMaskValue={(key) =>key.mask_value ? (<span className="font-mono ph-no-capture">{key.mask_value}</span>diff --git a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsxindex 4c3a98194ebe..1643c0b74cc0 100644--- a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx+++ b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx@@ -28,7 +28,7 @@ import type { personalAPIKeysLogicType } from './personalAPIKeysLogicType'export type EditingKeyFormValues = Pick<PersonalAPIKeyType,- 'label' | 'scopes' | 'scoped_organizations' | 'scoped_teams'+ 'label' | 'description' | 'scopes' | 'scoped_organizations' | 'scoped_teams'> & {preset?: stringaccess_type?: 'all' | 'organizations' | 'teams'@@ -54,6 +54,7 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([setScopeRadioValue: (key: string, action: string) => ({ key, action }),resetScopes: true,loadAllTeams: true,+ showDescriptionField: true,}),reducers({@@ -69,6 +70,14 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([setSearchTerm: (_, { searchTerm }) => searchTerm,},],+ // The description field is hidden behind an "Add description" button until used+ isDescriptionFieldVisible: [+ false,+ {+ showDescriptionField: () => true,+ setEditingKeyId: () => false,+ },+ ],}),loaders(({ values, actions }) => ({keys: [@@ -110,6 +119,7 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([editingKey: {defaults: {label: '',+ description: '',scopes: [],scoped_organizations: [],scoped_teams: [],@@ -444,6 +454,7 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([const key = values.keys.find((key) => key.id === id)const formValues: EditingKeyFormValues = {label: key?.label ?? '',+ description: key?.description ?? '',scopes: key?.scopes ?? [],preset: key?.scopes.includes('*') ? 'all_access' : undefined,scoped_organizations: key?.scoped_organizations ?? [],@@ -458,6 +469,9 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([}actions.resetEditingKey(formValues)+ if (key?.description) {+ actions.showDescriptionField()+ }actions.setSearchTerm('')} else {actions.setSearchTerm('')diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 142fe1bdaead..d1c39a59417f 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -506,6 +506,7 @@ export interface PluginAccess {export interface PersonalAPIKeyType {id: stringlabel: string+ description?: string | nullvalue?: stringis_legacy_hashing: booleanmask_value?: string | nulldiff --git a/posthog/api/personal_api_key.py b/posthog/api/personal_api_key.pyindex f66336645b96..f4a1eba61b78 100644--- a/posthog/api/personal_api_key.py+++ b/posthog/api/personal_api_key.py@@ -74,6 +74,13 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):is_legacy_hashing = serializers.SerializerMethodField(help_text="Whether this key uses legacy PBKDF2 hashing and should be rolled to upgrade.")+ description = serializers.CharField(+ required=False,+ allow_blank=True,+ allow_null=True,+ max_length=1000,+ help_text="Optional description of what the key is used for and where",+ )scopes = serializers.ListField(child=serializers.CharField(required=True), allow_empty=False)scoped_teams = serializers.ListField(child=serializers.IntegerField(required=False))scoped_organizations = serializers.ListField(child=serializers.CharField(required=False))@@ -83,6 +90,7 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):fields = ["id","label",+ "description","value","is_legacy_hashing","mask_value",@@ -112,6 +120,10 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):# Keys created before 2024-02 use PBKDF2 hashing, which is significantly slower per requestreturn bool(obj.secure_value and obj.secure_value.startswith(LEGACY_HASH_PREFIX))+ def validate_description(self, description: str | None) -> str | None:+ # Normalize "" to None so an absent description has a single canonical representation+ return description or None+def validate_scopes(self, scopes):requesting_user = self.context["request"].userexisting_scopes = list(self.instance.scopes or []) if self.instance is not None else Nonediff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.pyindex 7d29e50a8662..cc632243aaf6 100644--- a/posthog/api/test/test_personal_api_keys.py+++ b/posthog/api/test/test_personal_api_keys.py@@ -27,9 +27,16 @@ ErrorTrackingIssue = apps.get_model("error_tracking", "ErrorTrackingIssue")class TestPersonalAPIKeysAPI(APIBaseTest):def test_create_personal_api_key(self):label = "Test key uno"+ description = "Test description"response = self.client.post("/api/personal_api_keys",- {"label": label, "scopes": ["insight:read"], "scoped_organizations": [], "scoped_teams": []},+ {+ "label": label,+ "description": description,+ "scopes": ["insight:read"],+ "scoped_organizations": [],+ "scoped_teams": [],+ },)assert response.status_code == 201data = response.json()@@ -39,6 +46,7 @@ class TestPersonalAPIKeysAPI(APIBaseTest):assert response.json() == {"id": key.id,"label": label,+ "description": description,"created_at": data["created_at"],"last_used_at": None,"last_rolled_at": None,@@ -52,6 +60,20 @@ class TestPersonalAPIKeysAPI(APIBaseTest):}assert data["value"].startswith("phx_") # Personal API key prefix+ def test_create_personal_api_key_normalizes_blank_description_to_null(self):+ response = self.client.post(+ "/api/personal_api_keys",+ {+ "label": "test",+ "description": "",+ "scopes": ["insight:read"],+ "scoped_organizations": [],+ "scoped_teams": [],+ },+ )+ assert response.status_code == 201+ assert response.json()["description"] is None+def test_create_too_many_api_keys(self):for i in range(0, 10):self.client.post(@@ -207,6 +229,7 @@ class TestPersonalAPIKeysAPI(APIBaseTest):assert response_data[0] == {"id": my_key.id,"label": my_label,+ "description": None,"last_used_at": None,"last_rolled_at": None,"user_id": self.user.id,diff --git a/posthog/migrations/1248_personal_api_key_description.py b/posthog/migrations/1248_personal_api_key_description.pynew file mode 100644index 000000000000..7dd923cc35b0--- /dev/null+++ b/posthog/migrations/1248_personal_api_key_description.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-07-08 17:06++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1247_oauthaccesstoken_token_idx"),+ ]++ operations = [+ migrations.AddField(+ model_name="personalapikey",+ name="description",+ field=models.TextField(blank=True, max_length=1000, null=True),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex a1b3a1b5c29a..63da0a9c4fda 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1247_oauthaccesstoken_token_idx+1248_personal_api_key_descriptiondiff --git a/posthog/models/personal_api_key.py b/posthog/models/personal_api_key.pyindex 0a26ff6996d7..5e88b996a008 100644--- a/posthog/models/personal_api_key.py+++ b/posthog/models/personal_api_key.py@@ -35,6 +35,7 @@ class PersonalAPIKey(ModelActivityMixin, models.Model):id = models.CharField(primary_key=True, max_length=50, default=generate_random_token)user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="personal_api_keys")label = models.CharField(max_length=40)+ description = models.TextField(null=True, blank=True, max_length=1000)mask_value = models.CharField(max_length=11, editable=False, null=True)secure_value = models.CharField(unique=True,