: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(auth): add optional expiry to personal api keys (#120878)
Alex Liderdb3894e5ddf4
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 39d7172ef03f..e978a748dd03 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -15023,9 +15023,9 @@ snapshots:scenes-app-settings-user--settings-user-api-keys--light:hash: v1.k794b7964.c56cd95732f9e4355cc2b62b37ae9c36394637d232ea0d75cfaa63ede57205f5.ZgEv-Uxm9273XkhrJDzf9Cj_DESxhuf6OO_1o_fTd4kscenes-app-settings-user--settings-user-api-keys-create-modal--dark:- hash: v1.k794b7964.0c60f46bd47ba425439c87fcb40dc1b7e215a81a128d11649402e515d2675432.Z1DsSFhodE7mOsQ1EnLFhrdbCKWRYMP2lB6clnbyMC8+ hash: v1.k794b7964.d68355857ceb67b500d63f93828eccda3be3b77c07e69be6320dc3943ae94fc1.OcuYkwdoiVWiZ_POzAQAu4-xxPxIuVMj7dsL7_G6jCQscenes-app-settings-user--settings-user-api-keys-create-modal--light:- hash: v1.k794b7964.d3f6e5103966ece2e3212959e66e7ae3e35ee71cb6d2c579b0871cc01601bda8.7jToX6wggX9huxSMWqwHFRxrXQL9d8EjJLrsruKVyAs+ hash: v1.k794b7964.c20a2cedf117fe050e309251aa7aee14b68f762c52ba578cd7b5355d29f6b513.gqb2QV_814xsEQB91U1DKCD7L-UuOVGsHsILowH1bksscenes-app-settings-user--settings-user-backup-codes-modal--dark:hash: v1.k794b7964.fee174652504bedf45b5050dae77b7f38ffaac07d04c14c8c77b010d565cba97.n_drnTbGpOMa04Hy05-KZlJhx74bmdscz3V2bjDSQiwscenes-app-settings-user--settings-user-backup-codes-modal--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 6f0bf745fbb2..ae5145ec85b4 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -6181,8 +6181,11 @@ const api = {async delete(id: PersonalAPIKeyType['id']): Promise<void> {await new ApiRequest().personalApiKey(id).delete()},- async roll(id: PersonalAPIKeyType['id']): Promise<PersonalAPIKeyType> {- return await new ApiRequest().personalApiKey(id).withAction('roll').create()+ async roll(+ id: PersonalAPIKeyType['id'],+ data: Pick<Partial<PersonalAPIKeyType>, 'expires_at'> = {}+ ): Promise<PersonalAPIKeyType> {+ return await new ApiRequest().personalApiKey(id).withAction('roll').create({ data })},},diff --git a/frontend/src/scenes/settings/shared/APIKeyTable.tsx b/frontend/src/scenes/settings/shared/APIKeyTable.tsxindex b912935d2ce3..d05d2ef36f34 100644--- a/frontend/src/scenes/settings/shared/APIKeyTable.tsx+++ b/frontend/src/scenes/settings/shared/APIKeyTable.tsx@@ -18,11 +18,15 @@ export interface APIKeyTableRow {last_rolled_at: string | null}-interface APIKeyTableProps<T extends APIKeyTableRow = APIKeyTableRow> {+/** Either confirm a roll with the default dialog and call `onRoll`, or replace that dialog entirely. */+type APIKeyTableRollProps<T> =+ | { onRoll: (id: string) => void; openRollDialog?: never }+ | { openRollDialog: (key: T) => void; onRoll?: never }++type APIKeyTableProps<T extends APIKeyTableRow = APIKeyTableRow> = APIKeyTableRollProps<T> & {keys: T[]loading: booleanonEdit: (id: string) => void- onRoll: (id: string) => voidonDelete: (id: string) => voidnoun: stringshowCreatedBy?: boolean@@ -75,6 +79,7 @@ export function APIKeyTable<T extends APIKeyTableRow = APIKeyTableRow>({extraColumnsAfterScopes,rowClassName,deleteDescription = 'This action cannot be undone.',+ openRollDialog,}: APIKeyTableProps<T>): JSX.Element {const labelColumn: LemonTableColumn<T, any> = {title: 'Label',@@ -190,13 +195,17 @@ export function APIKeyTable<T extends APIKeyTableRow = APIKeyTableRow>({{label: 'Roll',onClick: () => {+ if (openRollDialog) {+ openRollDialog(key)+ return+ }LemonDialog.open({title: `Roll key "${key.label}"?`,description: 'This will generate a new key. The old key will immediately stop working.',primaryButton: {status: 'danger',children: 'Roll',- onClick: () => onRoll(key.id),+ onClick: () => onRoll?.(key.id),},secondaryButton: {children: 'Cancel',diff --git a/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx b/frontend/src/scenes/settings/user/PersonalAPIKeys.tsxindex cb9e89479b5a..2b51c0bcf797 100644--- a/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx+++ b/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx@@ -11,6 +11,7 @@ import {LemonModal,LemonModalProps,LemonSelect,+ LemonSelectOption,LemonTableColumn,LemonTag,LemonTextArea,@@ -19,6 +20,8 @@ import {import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'import { ScopeAccessGroup } from 'lib/components/ScopeAccessRow/ScopeAccessGroup'+import { TZLabel } from 'lib/components/TZLabel'+import { dayjs } from 'lib/dayjs'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonField } from 'lib/lemon-ui/LemonField'import { Link } from 'lib/lemon-ui/Link'@@ -28,7 +31,7 @@ import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { PersonalAPIKeyType } from '~/types'import { APIKeyTable } from '../shared/APIKeyTable'-import { personalAPIKeysLogic } from './personalAPIKeysLogic'+import { KeyExpirationOption, expiresAtForOption, isExpired, personalAPIKeysLogic } from './personalAPIKeysLogic'import ScopeAccessSelector from './scopes/ScopeAccessSelector'interface EditKeyModalProps {@@ -48,6 +51,7 @@ export function EditKeyModal({ zIndex }: EditKeyModalProps): JSX.Element {filteredScopeGroups,searchTerm,isDescriptionFieldVisible,+ keys,} = useValues(personalAPIKeysLogic)const {setEditingKeyId,@@ -62,6 +66,7 @@ export function EditKeyModal({ zIndex }: EditKeyModalProps): JSX.Element {const { isCloudOrDev } = useValues(preflightLogic)const isNew = editingKeyId === 'new'+ const editingKeyRecord = isNew ? undefined : keys.find((key) => key.id === editingKeyId)const submitDisabledReason = !editingKeyChanged? 'No changes to save'@@ -112,28 +117,17 @@ export function EditKeyModal({ zIndex }: EditKeyModalProps): JSX.Element {action={{children: 'Roll key',onClick: () => {- if (editingKeyId) {- const id = editingKeyId- LemonDialog.open({- title: 'Roll key to upgrade hashing?',- description:- 'This will generate a new key. The old key will immediately stop working.',- primaryButton: {- status: 'danger',- children: 'Roll',- type: 'primary',- onClick: () => {- // Close the edit modal first so the post-roll new key value- // is shown via the table's standard roll confirmation flow.- setEditingKeyId(null)- rollKey(id)- },- },- secondaryButton: {- children: 'Cancel',- type: 'secondary',+ if (editingKeyRecord) {+ openRollKeyDialog(+ editingKeyRecord,+ (id, expiresAt) => {+ // Close the edit modal first so the post-roll new key value+ // is shown via the table's standard roll confirmation flow.+ setEditingKeyId(null)+ rollKey(id, expiresAt)},- })+ 'Roll key to upgrade hashing?'+ )}},}}@@ -167,6 +161,7 @@ export function EditKeyModal({ zIndex }: EditKeyModalProps): JSX.Element {</LemonButton></div>)}+ <KeyExpirationField currentExpiresAt={editingKeyRecord?.expires_at ?? null} /><ScopeAccessSelectoraccessType={editingKey.access_type}organizations={allOrganizations}@@ -247,6 +242,75 @@ export function EditKeyModal({ zIndex }: EditKeyModalProps): JSX.Element {)}+const EXPIRY_DATE_FORMAT = 'MMMM D, YYYY'+const EXPIRY_TIME_FORMAT = 'h:mm A'++const EXPIRATION_PRESETS: LemonSelectOption<KeyExpirationOption>[] = [+ { value: 'never', label: 'Never' },+ { value: '1', label: '1 day' },+ { value: '7', label: '7 days' },+ { value: '30', label: '30 days' },+ { value: '90', label: '90 days' },+ { value: '365', label: '1 year' },+]++function KeyExpirationField({ currentExpiresAt }: { currentExpiresAt: string | null }): JSX.Element {+ const { editingKey } = useValues(personalAPIKeysLogic)++ const options: LemonSelectOption<KeyExpirationOption>[] = currentExpiresAt+ ? [+ {+ value: 'keep',+ label: `${isExpired(currentExpiresAt) ? 'Expired' : 'Expires'} ${dayjs(currentExpiresAt).format(EXPIRY_DATE_FORMAT)}`,+ },+ ...EXPIRATION_PRESETS,+ ]+ : EXPIRATION_PRESETS++ const expiresAt = expiresAtForOption(editingKey.expiration)++ return (+ <div className="mt-4">+ <LemonField name="expiration" label="Expiration">+ <LemonSelect options={options} data-attr="personal-api-key-expiration" />+ </LemonField>+ {expiresAt !== undefined && (+ <p className="text-secondary text-xs mt-1 mb-0">+ {expiresAt ? (+ <>+ <span>The key stops working on </span>+ <TZLabel time={expiresAt} formatDate={EXPIRY_DATE_FORMAT} formatTime={EXPIRY_TIME_FORMAT} />+ <span>.</span>+ </>+ ) : (+ 'The key keeps working until you delete it.'+ )}+ </p>+ )}+ </div>+ )+}++/** Asks for the rolled key's expiry, the same way GitHub does when it regenerates a token. */+function openRollKeyDialog(+ key: PersonalAPIKeyType,+ onRoll: (id: PersonalAPIKeyType['id'], expiresAt: string | null | undefined) => void,+ title: string = `Roll key "${key.label}"?`+): void {+ LemonDialog.openForm({+ title,+ description: 'This will generate a new key. The old key will immediately stop working.',+ initialValues: { expiration: key.expires_at ? '30' : 'never' },+ content: (+ <LemonField name="expiration" label="New key expires">+ <LemonSelect options={EXPIRATION_PRESETS} data-attr="personal-api-key-roll-expiration" />+ </LemonField>+ ),+ primaryButtonProps: { children: 'Roll', status: 'danger' },+ onSubmit: ({ expiration }) => onRoll(key.id, expiresAtForOption(expiration)),+ })+}+type TagListProps = { onMoreClick?: () => void; tags: string[] }export function TagList({ tags, onMoreClick }: TagListProps): JSX.Element {@@ -329,7 +393,13 @@ function PersonalAPIKeysTable(): JSX.Element {let statusTag: JSX.Element | null = null- if (keyDisabled) {+ if (isExpired(key.expires_at)) {+ statusTag = (+ <Tooltip title="This key has expired and no longer works. Edit it to set a new expiry, or delete it.">+ <LemonTag type="danger">Expired</LemonTag>+ </Tooltip>+ )+ } else if (keyDisabled) {const orgNames = restrictedOrgs.map((org: any) => org.name)statusTag = (@@ -419,7 +489,7 @@ function PersonalAPIKeysTable(): JSX.Element {}const accessColumn: LemonTableColumn<PersonalAPIKeyType, any> = {- title: 'Organization & project access',+ title: 'Org & project access',key: 'access',dataIndex: 'id',render: function RenderAccess(_, key) {@@ -455,6 +525,24 @@ function PersonalAPIKeysTable(): JSX.Element {},}+ const expiresColumn: LemonTableColumn<PersonalAPIKeyType, any> = {+ title: 'Expires',+ key: 'expiresAt',+ dataIndex: 'expires_at',+ sorter: (a, b) => {+ if (!a.expires_at || !b.expires_at) {+ return Number(!a.expires_at) - Number(!b.expires_at)+ }+ return dayjs(a.expires_at).valueOf() - dayjs(b.expires_at).valueOf()+ },+ render: function RenderExpiresAt(_, key) {+ if (!key.expires_at) {+ return <span className="text-secondary">Never</span>+ }+ return <TZLabel time={key.expires_at} formatDate={EXPIRY_DATE_FORMAT} formatTime={EXPIRY_TIME_FORMAT} />+ },+ }+return (<>{keys.some((key) => key.is_legacy_hashing) && (@@ -467,10 +555,12 @@ function PersonalAPIKeysTable(): JSX.Element {loading={keysLoading}noun="personal API key"onEdit={setEditingKeyId}- onRoll={rollKey}+ openRollDialog={(key) => openRollKeyDialog(key, rollKey)}onDelete={deleteKey}showActions- rowClassName={(key) => (isPersonalApiKeyIdDisabled(key.id) ? 'opacity-50' : '')}+ rowClassName={(key) =>+ isPersonalApiKeyIdDisabled(key.id) || isExpired(key.expires_at) ? '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">@@ -519,7 +609,7 @@ function PersonalAPIKeysTable(): JSX.Element {)}extraColumnsAfterLabel={[statusColumn]}- extraColumnsAfterScopes={[accessColumn]}+ extraColumnsAfterScopes={[accessColumn, expiresColumn]}/></>)diff --git a/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts b/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.tsindex 148484b0efd6..47163edd94bf 100644--- a/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts+++ b/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts@@ -4,6 +4,7 @@ import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { FEATURE_FLAGS } from 'lib/constants'+import { dayjs } from 'lib/dayjs'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'@@ -12,7 +13,7 @@ import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { personalAPIKeysLogic } from './personalAPIKeysLogic'+import { expiresAtForOption, personalAPIKeysLogic } from './personalAPIKeysLogic'describe('personalAPIKeysLogic', () => {let logic: ReturnType<typeof personalAPIKeysLogic.build>@@ -168,4 +169,14 @@ describe('personalAPIKeysLogic', () => {expect(logic.values.editingKey.scopes).toContain('survey:write')expect(logic.values.editingKey.scopes).not.toContain('feature_flag:write')})++ it.each([+ ['keep', undefined],+ ['never', null],+ ['1', dayjs('2026-01-02T10:00:00Z').toISOString()],+ ['30', dayjs('2026-01-31T10:00:00Z').toISOString()],+ ['365', dayjs('2027-01-01T10:00:00Z').toISOString()],+ ] as const)('expiration %s sends expires_at %s', (expiration, expected) => {+ expect(expiresAtForOption(expiration, dayjs('2026-01-01T10:00:00Z'))).toEqual(expected)+ })})diff --git a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsxindex 4bbd058df89d..9616a92199a2 100644--- a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx+++ b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx@@ -9,6 +9,7 @@ import { LemonBanner, LemonDialog } from '@posthog/lemon-ui'import api from 'lib/api'import { CodeSnippet } from 'lib/components/CodeSnippet'import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'+import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import {@@ -39,6 +40,30 @@ export type EditingKeyFormValues = Pick<> & {preset?: stringaccess_type?: 'all' | 'organizations' | 'teams'+ expiration?: KeyExpirationOption+}++/** `keep` leaves an edited key's expiry as it is. The day counts start when the form is saved. */+export type KeyExpirationOption = 'keep' | 'never' | '1' | '7' | '30' | '90' | '365'++export function isExpired(expiresAt: string | null | undefined, now: dayjs.Dayjs = dayjs()): boolean {+ return !!expiresAt && !dayjs(expiresAt).isAfter(now)+}++/** The `expires_at` to send for the chosen option, or undefined to leave it unchanged. */+export function expiresAtForOption(+ expiration: KeyExpirationOption | undefined,+ now: dayjs.Dayjs = dayjs()+): string | null | undefined {+ switch (expiration) {+ case undefined:+ case 'keep':+ return undefined+ case 'never':+ return null+ default:+ return now.add(Number(expiration), 'day').toISOString()+ }}/** A picker row for a personal API key, with the scope it stands for so the search can match it. */@@ -182,7 +207,11 @@ export interface personalAPIKeysLogicActions {resetScopes: () => {value: true}- rollKey: (id: PersonalAPIKeyType['id']) => {+ rollKey: (+ id: PersonalAPIKeyType['id'],+ expiresAt?: string | null+ ) => {+ expiresAt: string | null | undefinedid: string}rollKeyFailure: (@@ -195,11 +224,13 @@ export interface personalAPIKeysLogicActions {rollKeySuccess: (keys: PersonalAPIKeyType[],payload?: {+ expiresAt: string | null | undefinedid: string}) => {keys: PersonalAPIKeyType[]payload?: {+ expiresAt: string | null | undefinedid: string}}@@ -331,7 +362,8 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([}),updateKey: (data: Partial<Pick<PersonalAPIKeyType, 'label' | 'scopes'>>) => data,deleteKey: (id: PersonalAPIKeyType['id']) => ({ id }),- rollKey: (id: PersonalAPIKeyType['id']) => ({ id }),+ // `expiresAt` undefined keeps the key's current expiry; null removes it.+ rollKey: (id: PersonalAPIKeyType['id'], expiresAt?: string | null) => ({ id, expiresAt }),setScopeRadioValue: (key: string, action: string) => ({ key, action }),setScopeGroupAccess: (keys: string[], level: ScopeAccessLevel) => ({ keys, level }),resetScopes: true,@@ -372,13 +404,16 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([await api.personalApiKeys.delete(id)return values.keys.filter((filteredKey) => filteredKey.id != id)},- rollKey: async ({ id }) => {+ rollKey: async ({ id, expiresAt }) => {const origKey = values.keys.find((filteredKey) => filteredKey.id == id)if (!origKey) {return values.keys}- const rolledKey = await api.personalApiKeys.roll(id)+ const rolledKey = await api.personalApiKeys.roll(+ id,+ expiresAt !== undefined ? { expires_at: expiresAt } : {}+ )actions.showRollKeySuccessDialog(rolledKey, origKey.mask_value)// avoid persisting the raw value in state@@ -407,6 +442,7 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([scoped_organizations: [],scoped_teams: [],access_type: undefined,+ expiration: 'never',} as EditingKeyFormValues,errors: ({ label, access_type, scopes, scoped_organizations, scoped_teams }) => ({label: !label ? 'Your personal API key needs a label' : undefined,@@ -439,7 +475,13 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([const [object] = scope.split(':')return !!object && allowed.has(object)}) ?? []- const sanitizedPayload = { ...payload, scopes: sanitizedScopes }+ const { expiration, ...rest } = payload+ const expiresAt = expiresAtForOption(expiration)+ const sanitizedPayload = {+ ...rest,+ scopes: sanitizedScopes,+ ...(expiresAt !== undefined ? { expires_at: expiresAt } : {}),+ }const key =values.editingKeyId === 'new'@@ -758,6 +800,7 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([: id !== 'new'? 'all': undefined,+ expiration: key?.expires_at ? 'keep' : 'never',}actions.resetEditingKey(formValues)diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 76729a4bee9b..19fac82fa5cd 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -583,6 +583,7 @@ export interface PersonalAPIKeyType {created_at: stringlast_used_at: string | nulllast_rolled_at: string | null+ expires_at: string | nullteam_id: numberuser_id: stringscopes: string[]diff --git a/posthog/admin/admins/personal_api_key_admin.py b/posthog/admin/admins/personal_api_key_admin.pyindex f13381923e3d..8820387a4e52 100644--- a/posthog/admin/admins/personal_api_key_admin.py+++ b/posthog/admin/admins/personal_api_key_admin.py@@ -20,6 +20,7 @@ class PersonalAPIKeyAdmin(RollApiKeyAdminMixin):"created_at","last_used_at","last_rolled_at",+ "expires_at","scopes","scoped_teams","scoped_organizations",diff --git a/posthog/api/personal_api_key.py b/posthog/api/personal_api_key.pyindex 37294041dbcd..86f431596e32 100644--- a/posthog/api/personal_api_key.py+++ b/posthog/api/personal_api_key.py@@ -1,5 +1,7 @@import uuid-from typing import cast+from datetime import datetime+from enum import Enum+from typing import Literal, castfrom django.utils import timezone@@ -74,6 +76,32 @@ def validate_personal_api_key_scopes()+class _KeepExpiry(Enum):+ """Default for `roll(expires_at=...)`, so "not passed" differs from `None` (never expires)."""++ KEEP = "keep"+++def validate_future_expiry(expires_at: datetime | None) -> datetime | None:+ if expires_at is not None and expires_at <= timezone.now():+ raise serializers.ValidationError("Expiry date must be in the future.")+ return expires_at+++class PersonalAPIKeyRollSerializer(serializers.Serializer):+ expires_at = serializers.DateTimeField(+ required=False,+ allow_null=True,+ help_text=(+ "When the rolled key stops working. Null means the key never expires. "+ "Omit it to keep the key's current expiry."+ ),+ )++ def validate_expires_at(self, expires_at: datetime | None) -> datetime | None:+ return validate_future_expiry(expires_at)++class PersonalAPIKeySerializer(serializers.ModelSerializer):# Specifying method name because the serializer class already has a get_value methodvalue = serializers.SerializerMethodField(method_name="get_key_value", read_only=True)@@ -96,6 +124,11 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):max_length=1000,help_text="Optional description of what the key is used for and where",)+ expires_at = serializers.DateTimeField(+ required=False,+ allow_null=True,+ help_text="When the key stops working. Null means the key never expires.",+ )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))@@ -117,6 +150,7 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):"scoped_teams","scoped_organizations","last_rolled_at",+ "expires_at",]read_only_fields = ["id",@@ -145,6 +179,12 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):# Normalize "" to None so an absent description has a single canonical representationreturn description or None+ def validate_expires_at(self, expires_at: datetime | None) -> datetime | None:+ # Leaving an already-expired value untouched on edit must not block saving other fields+ if self.instance is not None and expires_at == self.instance.expires_at:+ return expires_at+ return validate_future_expiry(expires_at)+def validate_scopes(self, scopes):requesting_user = self.context["request"].userexisting_scopes = list(self.instance.scopes or []) if self.instance is not None else None@@ -194,6 +234,7 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):scopes=validated_data["scopes"],teams=AccessibleTeams.for_request(request, validated_data.get("scoped_teams") or None),organization_ids=validated_data.get("scoped_organizations") or [],+ expires_at=validated_data.get("expires_at"),)except CredentialScopeDenied:raise serializers.ValidationError(SCOPE_ACCESS_ERROR) from None@@ -222,19 +263,25 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):user.save(update_fields=["credentials_reviewed_at"])return personal_api_key- def roll(self, personal_api_key: PersonalAPIKey) -> PersonalAPIKey:+ def roll(+ self,+ personal_api_key: PersonalAPIKey,+ *,+ expires_at: datetime | None | Literal[_KeepExpiry.KEEP] = _KeepExpiry.KEEP,+ ) -> PersonalAPIKey:value = generate_random_token_personal()mask_value = mask_key_value(value)secure_value = hash_key_value(value)- personal_api_key = super().update(- personal_api_key,- {- "secure_value": secure_value,- "mask_value": mask_value,- "last_rolled_at": timezone.now(),- },- )+ updates: dict[str, object] = {+ "secure_value": secure_value,+ "mask_value": mask_value,+ "last_rolled_at": timezone.now(),+ }+ if expires_at is not _KeepExpiry.KEEP:+ updates["expires_at"] = expires_at++ personal_api_key = super().update(personal_api_key, updates)personal_api_key._value = value # type: ignorereturn personal_api_key@@ -303,9 +350,12 @@ class PersonalAPIKeyViewSet(viewsets.ModelViewSet):serializer = self.get_serializer(queryset, many=True)return response.Response(serializer.data)+ @extend_schema(request=PersonalAPIKeyRollSerializer, responses=PersonalAPIKeySerializer)@action(methods=["POST"], detail=True, url_path="roll")def roll(self, request, *args, **kwargs):instance = self.get_object()+ roll_serializer = PersonalAPIKeyRollSerializer(data=request.data)+ roll_serializer.is_valid(raise_exception=True)serializer = cast(PersonalAPIKeySerializer, self.get_serializer(instance))- serializer.roll(instance)+ serializer.roll(instance, **roll_serializer.validated_data)return response.Response(serializer.data, status=status.HTTP_200_OK)diff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.pyindex 7b8117cd9eca..b100e99c1f07 100644--- a/posthog/api/test/test_personal_api_keys.py+++ b/posthog/api/test/test_personal_api_keys.py@@ -1,5 +1,6 @@-from datetime import timedelta+from datetime import UTC, datetime, timedelta+import time_machinefrom posthog.test.base import APIBaseTestfrom unittest.mock import patch@@ -58,6 +59,7 @@ class TestPersonalAPIKeysAPI(APIBaseTest):"created_at": data["created_at"],"last_used_at": None,"last_rolled_at": None,+ "expires_at": None,"user_id": self.user.id,"is_legacy_hashing": False,"scopes": ["insight:read"],@@ -288,6 +290,7 @@ class TestPersonalAPIKeysAPI(APIBaseTest):"description": None,"last_used_at": None,"last_rolled_at": None,+ "expires_at": None,"user_id": self.user.id,"is_legacy_hashing": False,"scopes": ["*"],@@ -401,8 +404,51 @@ class TestPersonalAPIKeysAPI(APIBaseTest):assert data["last_rolled_at"] is not Noneassert data["mask_value"] != original_key.mask_value+ @parameterized.expand(+ [+ ("sets_chosen_expiry", {"expires_at": "2026-04-21T00:00:00Z"}, 200, datetime(2026, 4, 21, tzinfo=UTC)),+ ("omitted_keeps_expiry", {}, 200, datetime(2026, 1, 31, tzinfo=UTC)),+ ("null_removes_expiry", {"expires_at": None}, 200, None),+ ("past_is_rejected", {"expires_at": "2026-01-01T00:00:00Z"}, 400, datetime(2026, 1, 31, tzinfo=UTC)),+ ]+ )+ def test_roll_sets_expiry_from_request(self, _, body, expected_status, expected_expires_at):+ original_secure_value = hash_key_value(generate_random_token_personal())+ key = PersonalAPIKey.objects.create(+ label="Test roll expiry",+ user=self.user,+ secure_value=original_secure_value,+ scopes=["insight:read"],+ expires_at=datetime(2026, 1, 31, tzinfo=UTC),+ )++ with time_machine.travel("2026-01-21T00:00:00Z", tick=False):+ response = self.client.post(f"/api/personal_api_keys/{key.id}/roll", body, format="json")++ assert response.status_code == expected_status, response.json()+ key.refresh_from_db()+ assert key.expires_at == expected_expires_at+ assert (key.secure_value == original_secure_value) == (expected_status == 400)+class TestPersonalAPIKeysAPIValidation(APIBaseTest):+ @parameterized.expand([("past", timedelta(days=-1), 400), ("future", timedelta(days=7), 201)])+ def test_create_key_with_expiry(self, _, offset, expected_status):+ expires_at = timezone.now() + offset+ response = self.client.post(+ "/api/personal_api_keys/",+ {+ "label": "expiring",+ "scopes": ["insight:read"],+ "scoped_organizations": [],+ "scoped_teams": [],+ "expires_at": expires_at.isoformat(),+ },+ )+ assert response.status_code == expected_status, response.json()+ if expected_status == 201:+ assert PersonalAPIKey.objects.get(id=response.json()["id"]).expires_at == expires_at+def test_cannot_create_key_with_empty_scopes(self):response = self.client.post("/api/personal_api_keys/",@@ -542,6 +588,17 @@ class TestPersonalAPIKeysAPIAuthentication(PersonalAPIKeysBaseTest):)assert response.status_code == 200+ @parameterized.expand([("expired", timedelta(minutes=-1), 401), ("not_yet_expired", timedelta(days=1), 200)])+ def test_key_expiry(self, _, offset, expected_status):+ self.key.expires_at = timezone.now() + offset+ self.key.save()+ response = self.client.get(+ f"/api/projects/{self.team.id}/dashboards/", headers={"authorization": f"Bearer {self.value}"}+ )+ assert response.status_code == expected_status+ if expected_status == 401:+ assert response.json()["detail"] == "Personal API key found in request Authorization header has expired."+def test_user_not_active(self):self.user.is_active = Falseself.user.save()diff --git a/posthog/auth.py b/posthog/auth.pyindex 380b34fee114..d9edf52243a2 100644--- a/posthog/auth.py+++ b/posthog/auth.py@@ -356,9 +356,11 @@ class PersonalAPIKeyAuthentication(ActivityCredentialMixin, authentication.BaseAif mode_used:db_span.set_attribute("auth.hash_mode_used", mode_used)+ source_display = cls._SOURCE_DISPLAY.get(source, source)if not personal_api_key_object:- source_display = cls._SOURCE_DISPLAY.get(source, source)raise AuthenticationFailed(detail=f"Personal API key found in request {source_display} is invalid.")+ if personal_api_key_object.is_expired:+ raise AuthenticationFailed(detail=f"Personal API key found in request {source_display} has expired.")# Upgrade the key if it's not in the latest mode. We can do this since above we've already checked# that the key is valid in some mode, and we do check for all modes one by one.@@ -1200,6 +1202,8 @@ class DelegatedPersonalAPIKeyAuthentication(PersonalAPIKeyAuthentication):)except (KeyError, PersonalAPIKey.DoesNotExist) as error:raise AuthenticationFailed(detail="Source personal API key is no longer valid.") from error+ if personal_api_key.is_expired:+ raise AuthenticationFailed(detail="Source personal API key is no longer valid.")refuse_blocked_account(request, personal_api_key.user, call_site="personal_api_key", impersonated=False)self.personal_api_key = personal_api_keydiff --git a/posthog/migrations/1411_personalapikey_expires_at.py b/posthog/migrations/1411_personalapikey_expires_at.pynew file mode 100644index 000000000000..f6b6e432fb7a--- /dev/null+++ b/posthog/migrations/1411_personalapikey_expires_at.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1410_deletion_run_log"),+ ]++ operations = [+ migrations.AddField(+ model_name="personalapikey",+ name="expires_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex b11bac36330d..a02049f1e561 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1410_deletion_run_log+1411_personalapikey_expires_atdiff --git a/posthog/models/personal_api_key.py b/posthog/models/personal_api_key.pyindex 988eba47a398..fddcf717cb3f 100644--- a/posthog/models/personal_api_key.py+++ b/posthog/models/personal_api_key.py@@ -50,6 +50,7 @@ class PersonalAPIKey(ModelActivityMixin, models.Model):created_at = models.DateTimeField(default=timezone.now)last_used_at = models.DateTimeField(null=True, blank=True)last_rolled_at = models.DateTimeField(null=True, blank=True)+ expires_at = models.DateTimeField(null=True, blank=True)scopes: ArrayField = ArrayField(models.CharField(max_length=100), default=list)scoped_teams: ArrayField = ArrayField(models.IntegerField(), null=True, blank=True)scoped_organizations: ArrayField = ArrayField(models.CharField(max_length=100), null=True, blank=True)@@ -65,6 +66,10 @@ class PersonalAPIKey(ModelActivityMixin, models.Model):blank=True,)+ @property+ def is_expired(self) -> bool:+ return self.expires_at is not None and self.expires_at <= timezone.now()+_LEGACY_PERSONAL_API_KEY_PATTERN = re.compile(r"^[A-Za-z0-9_-]{43}$")diff --git a/posthog/personal_api_key_minting.py b/posthog/personal_api_key_minting.pyindex 03896bbe379e..c7f648a6a947 100644--- a/posthog/personal_api_key_minting.py+++ b/posthog/personal_api_key_minting.py@@ -1,6 +1,7 @@import uuidfrom collections.abc import Sequencefrom dataclasses import field+from datetime import datetimefrom posthog.accessible_teams import AccessibleTeams, CredentialScopeDeniedfrom posthog.dataclasses import frozen@@ -22,6 +23,7 @@ def mint_personal_api_key(teams: AccessibleTeams,organization_ids: Sequence[str] = (),description: str | None = None,+ expires_at: datetime | None = None,) -> MintedPersonalAPIKey:"""Insert a personal API key and return it with its raw value.@@ -43,6 +45,7 @@ def mint_personal_api_key(scopes=list(scopes),scoped_teams=list(teams.team_ids or []),scoped_organizations=list(organization_ids),+ expires_at=expires_at,)return MintedPersonalAPIKey(key=key, value=value)diff --git a/posthog/test/repo_invariants/test_serializer_timestamp_guard.py b/posthog/test/repo_invariants/test_serializer_timestamp_guard.pyindex 8e0ba0ee5921..85b494e5730d 100644--- a/posthog/test/repo_invariants/test_serializer_timestamp_guard.py+++ b/posthog/test/repo_invariants/test_serializer_timestamp_guard.py@@ -80,6 +80,7 @@ REQUEST_BODY_SOURCE = "@extend_schema(request=...)"# every other entry records a value a client is supposed to set. Nothing is inferred,# so a field missing from here fails the build until a person classifies it.REVIEWED_WRITABLE: dict[str, str] = {+ "posthog.api.personal_api_key.PersonalAPIKeySerializer.expires_at": "Client picks when the key stops working, or null for never; a past date is rejected","products.cdp.backend.api.hog_function.HogFunctionSerializer.base_updated_at": "Optimistic-concurrency guard: the client echoes the timestamp it loaded, and the view pops it before save","products.managed_migrations.backend.api.batch_imports.BatchImportDateRangeSourceCreateSerializer.start_date": "Client picks the import window; write-only input, never stored on the model","products.managed_migrations.backend.api.batch_imports.BatchImportDateRangeSourceCreateSerializer.end_date": "Client picks the import window; write-only input, never stored on the model",diff --git a/products/exports/backend/source_authentication.py b/products/exports/backend/source_authentication.pyindex 77bb7259fd38..1b54f36a8b20 100644--- a/products/exports/backend/source_authentication.py+++ b/products/exports/backend/source_authentication.py@@ -89,11 +89,15 @@ def assert_export_authorization(exported_asset: ExportedAsset) -> None:_raise_invalid_export_authorization(exported_asset, "missing_export_creator")if source_authentication == ExportedAsset.SourceAuthentication.PERSONAL_API_KEY:- credential = PersonalAPIKey.objects.filter(- id=exported_asset.source_credential_id,- user_id=created_by.id,- user__is_active=True,- ).first()+ credential = (+ PersonalAPIKey.objects.filter(+ id=exported_asset.source_credential_id,+ user_id=created_by.id,+ user__is_active=True,+ )+ .exclude(expires_at__lte=timezone.now())+ .first()+ )granted_scopes = list(credential.scopes or []) if credential is not None else []elif source_authentication == ExportedAsset.SourceAuthentication.OAUTH_ACCESS_TOKEN:credential = OAuthAccessToken.objects.filter(diff --git a/products/exports/backend/tasks/test/test_csv_exporter.py b/products/exports/backend/tasks/test/test_csv_exporter.pyindex 1551a3cddd98..de8fd6aeaae2 100644--- a/products/exports/backend/tasks/test/test_csv_exporter.py+++ b/products/exports/backend/tasks/test/test_csv_exporter.py@@ -1,6 +1,6 @@import osfrom collections.abc import Generator-from datetime import datetime+from datetime import datetime, timedeltafrom io import BytesIOfrom typing import Any, Optional@@ -423,6 +423,12 @@ class TestCSVExporter(APIBaseTest):with pytest.raises(ValueError, match="could not verify its original authorization"):assert_export_authorization(exported_asset)+ personal_api_key.scoped_teams = [self.team.id]+ personal_api_key.expires_at = now() - timedelta(minutes=1)+ personal_api_key.save(update_fields=["scoped_teams", "expires_at"])+ with pytest.raises(ValueError, match="could not verify its original authorization"):+ assert_export_authorization(exported_asset)+personal_api_key.delete()with pytest.raises(ValueError, match="could not verify its original authorization"):assert_export_authorization(exported_asset)