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.

19.8 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import type { JSX } from 'react'

import { LemonDialog } from '@posthog/lemon-ui'

import api from 'lib/api'
import { CodeSnippet } from 'lib/components/CodeSnippet'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import {
    API_SCOPES,
    PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION,
    PROJECT_SECRET_API_KEY_SCOPE_PRESETS,
    ProjectSecretAPIKeyAllowedScope,
    ProjectSecretAPIKeyScopePreset,
    scopeMatchesSearch,
} from 'lib/scopes'
import { capitalizeFirstLetter } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { ProjectSecretAPIKeyApi } from '~/generated/core/api.schemas'
import { APIScopeAction, ProjectSecretAPIKeyRequest, UserType } from '~/types'

export type EditingProjectKeyFormValues = ProjectSecretAPIKeyRequest & {
    preset?: string
}

export const MAX_PROJECT_API_KEYS_PER_PROJECT = 50

const GATEWAY_SCOPE = 'llm_gateway:read'

// Rows that differ from API_SCOPES here. PAKs label llm_gateway "LLM gateway", but here it is the AI gateway
// service credential. messaging_preference is OAuth-hidden, so it has no API_SCOPES row and only this picker offers it.
const PROJECT_SECRET_SCOPE_ROWS: Record<string, { label: string; info?: string }> = {
    llm_gateway: { label: 'AI gateway' },
    messaging_preference: {
        label: 'Recipient preference',
        info: "Opt email recipients in or out of your message topics. This scope can't send email.",
    },
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface projectSecretAPIKeysLogicValues {
    currentTeamId: number | null // teamLogic
    user: UserType | null // userLogic
    availablePresets: ProjectSecretAPIKeyScopePreset[]
    editingKey: EditingProjectKeyFormValues
    editingKeyAllErrors: Record<string, any>
    editingKeyChanged: boolean
    editingKeyErrors: DeepPartialMap<EditingProjectKeyFormValues, ValidationErrorType>
    editingKeyHasErrors: boolean
    editingKeyId: ProjectSecretAPIKeyApi['id'] | null
    editingKeyManualErrors: Record<string, any>
    editingKeyTouched: boolean
    editingKeyTouches: Record<string, boolean>
    editingKeyValidationErrors: DeepPartialMap<EditingProjectKeyFormValues, ValidationErrorType>
    filteredScopes: {
        disabledActions: APIScopeAction[]
        info: string | JSX.Element | undefined
        key: string
        label: string
    }[]
    formScopeRadioValues: Record<string, string>
    gatewayScopeConfirmed: boolean
    isEditingKeySubmitting: boolean
    isEditingKeyValid: boolean
    keys: ProjectSecretAPIKeyApi[]
    keysLoading: boolean
    searchTerm: string
    showEditingKeyErrors: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface projectSecretAPIKeysLogicActions {
    confirmGatewayScope: () => {
        value: true
    }
    createKeySuccess: (key: ProjectSecretAPIKeyApi) => {
        key: ProjectSecretAPIKeyApi
    }
    deleteKey: (id: ProjectSecretAPIKeyApi['id']) => {
        id: string
    }
    deleteKeyFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteKeySuccess: (
        keys: ProjectSecretAPIKeyApi[],
        payload?: {
            id: string
        }
    ) => {
        keys: ProjectSecretAPIKeyApi[]
        payload?: {
            id: string
        }
    }
    loadKeys: () => {
        value: true
    }
    loadKeysFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadKeysSuccess: (
        keys: ProjectSecretAPIKeyApi[],
        payload?: {
            value: true
        }
    ) => {
        keys: ProjectSecretAPIKeyApi[]
        payload?: {
            value: true
        }
    }
    resetEditingKey: (values?: EditingProjectKeyFormValues) => {
        values?: EditingProjectKeyFormValues
    }
    resetScopes: () => {
        value: true
    }
    rollKey: (id: ProjectSecretAPIKeyApi['id']) => {
        id: string
    }
    rollKeyFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    rollKeySuccess: (
        keys: ProjectSecretAPIKeyApi[],
        payload?: {
            id: string
        }
    ) => {
        keys: ProjectSecretAPIKeyApi[]
        payload?: {
            id: string
        }
    }
    setEditingKeyId: (id: ProjectSecretAPIKeyApi['id'] | null) => {
        id: string | null
    }
    setEditingKeyManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setEditingKeyValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setEditingKeyValues: (values: DeepPartial<EditingProjectKeyFormValues>) => {
        values: DeepPartial<EditingProjectKeyFormValues>
    }
    setScopeRadioValue: (
        key: string,
        action: string
    ) => {
        action: string
        key: string
    }
    setSearchTerm: (searchTerm: string) => {
        searchTerm: string
    }
    showGatewayScopeDialog: () => {
        value: true
    }
    showRollKeySuccessDialog: (key: ProjectSecretAPIKeyApi) => {
        key: ProjectSecretAPIKeyApi
    }
    submitEditingKey: () => {
        value: boolean
    }
    submitEditingKeyFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitEditingKeyRequest: (editingKey: EditingProjectKeyFormValues) => {
        editingKey: EditingProjectKeyFormValues
    }
    submitEditingKeySuccess: (editingKey: EditingProjectKeyFormValues) => {
        editingKey: EditingProjectKeyFormValues
    }
    touchEditingKeyField: (key: string) => {
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface projectSecretAPIKeysLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        formScopeRadioValues: (editingKey: EditingProjectKeyFormValues) => Record<string, string>
        filteredScopes: (
            searchTerm: string,
            user: UserType | null
        ) => {
            disabledActions: APIScopeAction[]
            info: string | JSX.Element | undefined
            key: string
            label: string
        }[]
        availablePresets: (user: UserType | null) => ProjectSecretAPIKeyScopePreset[]
    }
}

export type projectSecretAPIKeysLogicType = MakeLogicType<
    projectSecretAPIKeysLogicValues,
    projectSecretAPIKeysLogicActions,
    Record<string, any>,
    projectSecretAPIKeysLogicMeta
>

export const projectSecretAPIKeysLogic = kea<projectSecretAPIKeysLogicType>([
    path(['scenes', 'settings', 'project', 'projectSecretAPIKeysLogic']),
    connect(() => ({
        values: [teamLogic, ['currentTeamId'], userLogic, ['user']],
    })),

    actions({
        setEditingKeyId: (id: ProjectSecretAPIKeyApi['id'] | null) => ({ id }),
        loadKeys: true,
        createKeySuccess: (key: ProjectSecretAPIKeyApi) => ({ key }),
        showRollKeySuccessDialog: (key: ProjectSecretAPIKeyApi) => ({ key }),
        deleteKey: (id: ProjectSecretAPIKeyApi['id']) => ({ id }),
        rollKey: (id: ProjectSecretAPIKeyApi['id']) => ({ id }),
        setScopeRadioValue: (key: string, action: string) => ({ key, action }),
        resetScopes: true,
        setSearchTerm: (searchTerm: string) => ({ searchTerm }),
        showGatewayScopeDialog: true,
        confirmGatewayScope: true,
    }),

    reducers({
        editingKeyId: [
            null as ProjectSecretAPIKeyApi['id'] | null,
            {
                setEditingKeyId: (_, { id }) => id,
            },
        ],
        searchTerm: [
            '',
            {
                setSearchTerm: (_, { searchTerm }) => searchTerm,
                setEditingKeyId: () => '',
            },
        ],
        gatewayScopeConfirmed: [
            false,
            {
                confirmGatewayScope: () => true,
                setEditingKeyId: () => false,
            },
        ],
    }),

    loaders(({ values, actions }) => ({
        keys: [
            [] as ProjectSecretAPIKeyApi[],
            {
                loadKeys: async () => {
                    if (!values.currentTeamId) {
                        return []
                    }
                    try {
                        return await api.projectSecretApiKeys.list()
                    } catch (error: any) {
                        lemonToast.error('Failed to load project secret API keys')
                        throw error
                    }
                },
                deleteKey: async ({ id }: { id: string }) => {
                    try {
                        await api.projectSecretApiKeys.delete(id)
                        lemonToast.success('Project secret API key deleted')
                        return values.keys.filter((key: ProjectSecretAPIKeyApi) => key.id !== id)
                    } catch (error: any) {
                        lemonToast.error('Failed to delete project secret API key')
                        throw error
                    }
                },
                rollKey: async ({ id }: { id: string }) => {
                    const origKey = values.keys.find((key: ProjectSecretAPIKeyApi) => key.id === id)
                    if (!origKey) {
                        return values.keys
                    }

                    try {
                        const rolledKey = await api.projectSecretApiKeys.roll(id)
                        actions.showRollKeySuccessDialog(rolledKey)

                        const storedKey = { ...rolledKey, value: '' }
                        return values.keys.map((key: ProjectSecretAPIKeyApi) => (key.id === id ? storedKey : key))
                    } catch (error: any) {
                        lemonToast.error('Failed to roll project secret API key')
                        throw error
                    }
                },
            },
        ],
    })),

    forms(({ values, actions }) => ({
        editingKey: {
            defaults: {
                label: '',
                scopes: [],
                preset: undefined,
            } as EditingProjectKeyFormValues,
            errors: ({ label, scopes }) => ({
                label: !label ? 'Your API key needs a label' : undefined,
                scopes: !scopes?.length ? ('Your API key needs at least one scope' as any) : undefined,
            }),
            submit: async (payload, breakpoint) => {
                if (!values.editingKeyId || !values.currentTeamId) {
                    return
                }

                // The generated scope type omits staff-only scopes, so compare as plain strings.
                const savedScopes: string[] = values.keys.find((k) => k.id === values.editingKeyId)?.scopes ?? []
                const addsGatewayScope =
                    (payload.scopes as string[] | undefined)?.includes(GATEWAY_SCOPE) &&
                    !savedScopes.includes(GATEWAY_SCOPE)
                if (addsGatewayScope && !values.gatewayScopeConfirmed) {
                    actions.showGatewayScopeDialog()
                    return
                }

                try {
                    // Remove preset from payload as it's frontend-only
                    const { preset, ...apiPayload } = payload

                    const key =
                        values.editingKeyId === 'new'
                            ? await api.projectSecretApiKeys.create(apiPayload)
                            : await api.projectSecretApiKeys.update(values.editingKeyId, apiPayload)

                    breakpoint()

                    if (values.editingKeyId === 'new') {
                        actions.createKeySuccess(key)
                    } else {
                        lemonToast.success('Project secret API key updated')
                    }

                    actions.loadKeysSuccess([
                        key,
                        ...values.keys.filter((k: ProjectSecretAPIKeyApi) => k.id !== values.editingKeyId),
                    ])
                    actions.setEditingKeyId(null)
                } catch (error: any) {
                    lemonToast.error('Failed to save project secret API key')
                    throw error
                }
            },
        },
    })),

    selectors(() => ({
        formScopeRadioValues: [
            (s) => [s.editingKey],
            (editingKey: EditingProjectKeyFormValues): Record<string, string> => {
                const result: Record<string, string> = {}
                editingKey.scopes?.forEach((scope: string) => {
                    const [key, action] = scope.split(':')
                    result[key] = action
                })
                return result
            },
        ],
        filteredScopes: [
            (s) => [s.searchTerm, s.user],
            (
                searchTerm: string,
                user: UserType | null
            ): {
                key: string
                label: string
                info: string | JSX.Element | undefined
                disabledActions: APIScopeAction[]
            }[] => {
                const allActions: APIScopeAction[] = ['read', 'write']
                // llm_gateway:read is staff-only, mirroring the backend.
                const allowedScopeActions: string[] = [...PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION]
                if (user?.is_staff) {
                    allowedScopeActions.push('llm_gateway:read')
                }
                const allowedByKey = new Map<string, Set<APIScopeAction>>()
                for (const scopeAction of allowedScopeActions) {
                    const [key, action] = scopeAction.split(':') as [string, APIScopeAction]
                    if (!allowedByKey.has(key)) {
                        allowedByKey.set(key, new Set())
                    }
                    allowedByKey.get(key)!.add(action)
                }
                const scopes = Array.from(allowedByKey.entries()).map(([key, allowed]) => {
                    const apiScope = API_SCOPES.find((scope) => scope.key === key)
                    const row = PROJECT_SECRET_SCOPE_ROWS[key]
                    return {
                        key,
                        label: row?.label ?? apiScope?.objectName ?? capitalizeFirstLetter(key.replace(/_/g, ' ')),
                        info: row?.info ?? apiScope?.info,
                        disabledActions: allActions.filter((a) => !allowed.has(a)),
                    }
                })
                return scopes.filter((scope) => scopeMatchesSearch(scope, searchTerm))
            },
        ],
        availablePresets: [
            (s) => [s.user],
            (user: UserType | null): ProjectSecretAPIKeyScopePreset[] =>
                PROJECT_SECRET_API_KEY_SCOPE_PRESETS.filter(({ value }) => value !== 'llm_gateway' || user?.is_staff),
        ],
    })),

    listeners(({ actions, values }) => ({
        setEditingKeyValue: async ({ name, value }) => {
            const key = Array.isArray(name) ? name[0] : name

            if (key === 'preset' && value) {
                const preset = PROJECT_SECRET_API_KEY_SCOPE_PRESETS.find((p) => p.value === value)
                if (preset) {
                    actions.setEditingKeyValue('scopes', preset.scopes)
                }
            }

            if (key === 'scopes' && values.editingKey.preset) {
                const preset = PROJECT_SECRET_API_KEY_SCOPE_PRESETS.find((p) => p.value === values.editingKey.preset)
                if (preset?.scopes.join(',') !== value.join(',')) {
                    actions.setEditingKeyValue('preset', undefined)
                }
            }
        },

        setEditingKeyId: ({ id }: { id: string | null }) => {
            if (id) {
                const key = values.keys.find((k: ProjectSecretAPIKeyApi) => k.id === id)
                actions.resetEditingKey({
                    label: key?.label ?? '',
                    scopes: (key?.scopes ?? []) as ProjectSecretAPIKeyAllowedScope[],
                    preset: undefined,
                })
            }
        },

        setScopeRadioValue: ({ key, action }: { key: string; action: string }) => {
            const newScopes = (values.editingKey.scopes || []).filter((s: string) => !s.startsWith(key + ':'))
            if (action !== 'none') {
                newScopes.push(`${key}:${action}` as ProjectSecretAPIKeyAllowedScope)
            }
            actions.setEditingKeyValue('scopes', newScopes)
        },

        resetScopes: () => {
            actions.setEditingKeyValue('scopes', [])
        },

        createKeySuccess: ({ key }) => {
            if (!key.value) {
                return
            }

            LemonDialog.open({
                title: 'Project secret API key ready',
                width: 536,
                content: (
                    <>
                        <p>Copy your new project secret API key:</p>
                        <CodeSnippet className="ph-no-capture" thing="project secret API key">
                            {key.value}
                        </CodeSnippet>
                        <p className="text-warning mt-4">
                            <strong>Warning:</strong> This key will never be shown again. Copy it now.
                        </p>
                    </>
                ),
            })
        },

        showGatewayScopeDialog: () => {
            LemonDialog.open({
                title: 'This key is for PostHog products only',
                width: 536,
                content: (
                    <>
                        <p>
                            Use AI gateway keys for PostHog services that call the gateway in production. These keys
                            don't expire and their requests aren't attributed to a person.
                        </p>
                        <p className="mb-0">
                            To test against the gateway from your machine, create a developer mode token instead. It
                            expires after a few hours and its requests are attributed to you.
                        </p>
                    </>
                ),
                primaryButton: {
                    children: 'Create a developer mode token',
                    onClick: () => {
                        actions.setEditingKeyId(null)
                        router.actions.push(urls.settings('user-ai-gateway-dev-mode'))
                    },
                },
                secondaryButton: {
                    children: 'Create key for a PostHog product',
                    onClick: () => {
                        actions.confirmGatewayScope()
                        actions.submitEditingKey()
                    },
                },
            })
        },

        showRollKeySuccessDialog: ({ key }) => {
            if (!key.value) {
                return
            }

            LemonDialog.open({
                title: 'Project secret API key rolled',
                width: 536,
                content: (
                    <>
                        <p>Your new key for "{key.label}":</p>
                        <CodeSnippet className="ph-no-capture" thing="project secret API key">
                            {key.value}
                        </CodeSnippet>
                        <p className="text-warning mt-4">
                            <strong>Warning:</strong> The previous key is no longer valid. This key will never be shown
                            again. Copy it now.
                        </p>
                    </>
                ),
            })
        },
    })),

    afterMount(({ actions }) => {
        actions.loadKeys()
    }),
])