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.9 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 posthog from 'posthog-js'

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

import { readableErrorMessage } from 'lib/api-error'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { API_SCOPES, ScopeAccessLevel, scopeMatchesSearch, scopesArrayToObject, scopesObjectToArray } from 'lib/scopes'
import { capitalizeFirstLetter } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'

import {
    workloadTrustPoliciesCreate,
    workloadTrustPoliciesDestroy,
    workloadTrustPoliciesList,
    workloadTrustPoliciesPartialUpdate,
    workloadTrustPoliciesProvidersRetrieve,
} from '~/generated/core/api'
import type {
    WorkloadProviderApi,
    WorkloadProvidersResponseApi,
    WorkloadTrustPolicyApi,
} from '~/generated/core/api.schemas'
import { APIScopeAction } from '~/types'

export type WorkloadTrustPolicyFormValues = Pick<
    WorkloadTrustPolicyApi,
    'name' | 'issuer' | 'subject_name' | 'subject' | 'scopes'
> & {
    /** Claim name to required value. A condition that isn't set has no key. */
    conditions: Record<string, string>
}

export interface WorkloadTrustPolicyConditionField {
    name: string
    label: string
    helpText: string
}

export interface WorkloadTrustPolicyScopeRow {
    key: string
    label: string
    disabledActions: APIScopeAction[]
}

const POLICIES_PAGE_SIZE = 100

const EMPTY_FORM: WorkloadTrustPolicyFormValues = {
    name: '',
    issuer: '',
    subject_name: '',
    subject: '',
    conditions: {},
    scopes: [],
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface workloadTrustPoliciesLogicValues {
    currentTeamId: number | null // teamLogic
    claimLabels: {
        subject: string
        subjectName: string
    }
    conditionFields: WorkloadTrustPolicyConditionField[]
    editingPolicy: WorkloadTrustPolicyFormValues
    editingPolicyAllErrors: Record<string, any>
    editingPolicyChanged: boolean
    editingPolicyErrors: DeepPartialMap<WorkloadTrustPolicyFormValues, ValidationErrorType>
    editingPolicyHasErrors: boolean
    editingPolicyId: WorkloadTrustPolicyApi['id'] | 'new' | null
    editingPolicyManualErrors: Record<string, any>
    editingPolicyTouched: boolean
    editingPolicyTouches: Record<string, boolean>
    editingPolicyValidationErrors: DeepPartialMap<WorkloadTrustPolicyFormValues, ValidationErrorType>
    editingProvider: WorkloadProviderApi | null
    isEditingPolicySubmitting: boolean
    isEditingPolicyValid: boolean
    policies: WorkloadTrustPolicyApi[] | null
    policiesLoadFailed: boolean
    policiesLoading: boolean
    providerNames: Record<string, string>
    providers: WorkloadProvidersResponseApi | null
    providersLoadFailed: boolean
    providersLoading: boolean
    scopeLevels: Record<string, ScopeAccessLevel>
    scopeRows: WorkloadTrustPolicyScopeRow[]
    scopeSearchTerm: string
    showEditingPolicyErrors: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface workloadTrustPoliciesLogicActions {
    deletePolicy: (policy: WorkloadTrustPolicyApi) => {
        policy: WorkloadTrustPolicyApi
    }
    loadPolicies: () => any
    loadPoliciesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadPoliciesSuccess: (
        policies: WorkloadTrustPolicyApi[],
        payload?: any
    ) => {
        policies: WorkloadTrustPolicyApi[]
        payload?: any
    }
    loadProviders: () => any
    loadProvidersFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadProvidersSuccess: (
        providers: WorkloadProvidersResponseApi,
        payload?: any
    ) => {
        providers: WorkloadProvidersResponseApi
        payload?: any
    }
    resetEditingPolicy: (values?: WorkloadTrustPolicyFormValues) => {
        values?: WorkloadTrustPolicyFormValues
    }
    setConditionValue: (
        claim: string,
        value: string
    ) => {
        claim: string
        value: string
    }
    setEditingPolicyId: (id: WorkloadTrustPolicyApi['id'] | 'new' | null) => {
        id: string | null
    }
    setEditingPolicyManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setEditingPolicyValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setEditingPolicyValues: (values: DeepPartial<WorkloadTrustPolicyFormValues>) => {
        values: DeepPartial<WorkloadTrustPolicyFormValues>
    }
    setPolicyEnabled: ({ policy, enabled }: { enabled: boolean; policy: WorkloadTrustPolicyApi }) => {
        policy: WorkloadTrustPolicyApi
        enabled: boolean
    }
    setPolicyEnabledFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    setPolicyEnabledSuccess: (
        policies: WorkloadTrustPolicyApi[],
        payload?: {
            policy: WorkloadTrustPolicyApi
            enabled: boolean
        }
    ) => {
        policies: WorkloadTrustPolicyApi[]
        payload?: {
            policy: WorkloadTrustPolicyApi
            enabled: boolean
        }
    }
    setScopeLevel: (
        key: string,
        level: ScopeAccessLevel
    ) => {
        key: string
        level: ScopeAccessLevel
    }
    setScopeSearchTerm: (searchTerm: string) => {
        searchTerm: string
    }
    submitEditingPolicy: () => {
        value: boolean
    }
    submitEditingPolicyFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitEditingPolicyRequest: (editingPolicy: WorkloadTrustPolicyFormValues) => {
        editingPolicy: WorkloadTrustPolicyFormValues
    }
    submitEditingPolicySuccess: (editingPolicy: WorkloadTrustPolicyFormValues) => {
        editingPolicy: WorkloadTrustPolicyFormValues
    }
    touchEditingPolicyField: (key: string) => {
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface workloadTrustPoliciesLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        scopeLevels: (editingPolicy: WorkloadTrustPolicyFormValues) => Record<string, ScopeAccessLevel>
        scopeRows: (
            providers: WorkloadProvidersResponseApi | null,
            scopeSearchTerm: string
        ) => WorkloadTrustPolicyScopeRow[]
        editingProvider: (
            providers: WorkloadProvidersResponseApi | null,
            editingPolicy: WorkloadTrustPolicyFormValues
        ) => WorkloadProviderApi | null
        conditionFields: (
            editingProvider: WorkloadProviderApi | null,
            editingPolicy: WorkloadTrustPolicyFormValues
        ) => WorkloadTrustPolicyConditionField[]
        claimLabels: (editingProvider: WorkloadProviderApi | null) => {
            subject: string
            subjectName: string
        }
        providerNames: (providers: WorkloadProvidersResponseApi | null) => Record<string, string>
    }
}

export type workloadTrustPoliciesLogicType = MakeLogicType<
    workloadTrustPoliciesLogicValues,
    workloadTrustPoliciesLogicActions,
    Record<string, any>,
    workloadTrustPoliciesLogicMeta
>

export const workloadTrustPoliciesLogic = kea<workloadTrustPoliciesLogicType>([
    path(['scenes', 'settings', 'project', 'workloadTrustPoliciesLogic']),
    connect(() => ({
        values: [teamLogic, ['currentTeamId']],
    })),

    actions({
        setEditingPolicyId: (id: WorkloadTrustPolicyApi['id'] | 'new' | null) => ({ id }),
        setScopeLevel: (key: string, level: ScopeAccessLevel) => ({ key, level }),
        setConditionValue: (claim: string, value: string) => ({ claim, value }),
        setScopeSearchTerm: (searchTerm: string) => ({ searchTerm }),
        deletePolicy: (policy: WorkloadTrustPolicyApi) => ({ policy }),
    }),

    reducers({
        editingPolicyId: [
            null as WorkloadTrustPolicyApi['id'] | 'new' | null,
            {
                setEditingPolicyId: (_, { id }) => id,
            },
        ],
        scopeSearchTerm: [
            '',
            {
                setScopeSearchTerm: (_, { searchTerm }) => searchTerm,
                setEditingPolicyId: () => '',
            },
        ],
    }),

    loaders(({ values }) => ({
        policies: [
            null as WorkloadTrustPolicyApi[] | null,
            {
                loadPolicies: async () => {
                    const projectId = String(values.currentTeamId)
                    // Every policy stays active until someone disables it, so the list must show all of them.
                    const policies: WorkloadTrustPolicyApi[] = []
                    let hasNextPage = true
                    while (hasNextPage) {
                        const page = await workloadTrustPoliciesList(projectId, {
                            limit: POLICIES_PAGE_SIZE,
                            offset: policies.length,
                        })
                        policies.push(...page.results)
                        hasNextPage = !!page.next && page.results.length > 0
                    }
                    return policies
                },
                setPolicyEnabled: async ({ policy, enabled }: { policy: WorkloadTrustPolicyApi; enabled: boolean }) => {
                    try {
                        const updated = await workloadTrustPoliciesPartialUpdate(
                            String(values.currentTeamId),
                            policy.id,
                            {
                                enabled,
                            }
                        )
                        posthog.capture('workload trust policy enabled changed', { enabled })
                        return (values.policies ?? []).map((row) => (row.id === updated.id ? updated : row))
                    } catch (error) {
                        lemonToast.error(readableErrorMessage(error) ?? "Couldn't update the policy. Try again.")
                        throw error
                    }
                },
            },
        ],
        providers: [
            null as WorkloadProvidersResponseApi | null,
            {
                loadProviders: async () => await workloadTrustPoliciesProvidersRetrieve(String(values.currentTeamId)),
            },
        ],
    })),

    reducers({
        policiesLoadFailed: [
            false,
            {
                loadPolicies: () => false,
                loadPoliciesFailure: () => true,
            },
        ],
        providersLoadFailed: [
            false,
            {
                loadProviders: () => false,
                loadProvidersFailure: () => true,
            },
        ],
    }),

    forms(({ values, actions }) => ({
        editingPolicy: {
            defaults: EMPTY_FORM,
            errors: ({ name, issuer, subject_name, subject, conditions, scopes }) => ({
                name: !name ? 'Give the policy a name' : undefined,
                issuer: !issuer ? 'Choose a provider' : undefined,
                subject_name: !subject_name ? `${values.claimLabels.subjectName} is required` : undefined,
                subject: !subject ? `${values.claimLabels.subject} is required` : undefined,
                conditions:
                    values.editingProvider?.condition_claims.length && Object.keys(conditions).length === 0
                        ? ('Set at least one condition' as any)
                        : undefined,
                scopes: !scopes.length ? ('Choose at least one scope' as any) : undefined,
            }),
            submit: async (payload, breakpoint) => {
                const projectId = String(values.currentTeamId)
                const isNew = values.editingPolicyId === 'new'
                try {
                    const saved = isNew
                        ? await workloadTrustPoliciesCreate(projectId, payload)
                        : await workloadTrustPoliciesPartialUpdate(projectId, values.editingPolicyId as string, payload)
                    breakpoint()
                    posthog.capture('workload trust policy saved', { is_new: isNew, scope_count: saved.scopes.length })
                    lemonToast.success(isNew ? 'Trusted workload added' : 'Trusted workload updated')
                    actions.loadPoliciesSuccess([
                        saved,
                        ...(values.policies ?? []).filter((policy) => policy.id !== saved.id),
                    ])
                    actions.setEditingPolicyId(null)
                } catch (error) {
                    lemonToast.error(readableErrorMessage(error) ?? "Couldn't save the policy. Try again.")
                    throw error
                }
            },
        },
    })),

    selectors({
        scopeLevels: [
            (s) => [s.editingPolicy],
            (editingPolicy: WorkloadTrustPolicyFormValues): Record<string, ScopeAccessLevel> =>
                scopesArrayToObject(editingPolicy.scopes) as Record<string, ScopeAccessLevel>,
        ],
        scopeRows: [
            (s) => [s.providers, s.scopeSearchTerm],
            (
                providers: WorkloadProvidersResponseApi | null,
                scopeSearchTerm: string
            ): WorkloadTrustPolicyScopeRow[] => {
                const allowedByKey = new Map<string, Set<APIScopeAction>>()
                for (const scope of providers?.grantable_scopes ?? []) {
                    const [key, action] = scope.split(':') as [string, APIScopeAction]
                    allowedByKey.set(key, (allowedByKey.get(key) ?? new Set()).add(action))
                }
                const allActions: APIScopeAction[] = ['read', 'write']
                return Array.from(allowedByKey.entries())
                    .map(([key, allowed]) => {
                        const apiScope = API_SCOPES.find((scope) => scope.key === key)
                        return {
                            key,
                            label: apiScope?.objectName ?? capitalizeFirstLetter(key.replace(/_/g, ' ')),
                            objectPlural: apiScope?.objectPlural,
                            disabledActions: allActions.filter((action) => !allowed.has(action)),
                        }
                    })
                    .filter((row) => scopeMatchesSearch(row, scopeSearchTerm))
                    .sort((a, b) => a.label.localeCompare(b.label))
            },
        ],
        editingProvider: [
            (s) => [s.providers, s.editingPolicy],
            (
                providers: WorkloadProvidersResponseApi | null,
                editingPolicy: WorkloadTrustPolicyFormValues
            ): WorkloadProviderApi | null =>
                providers?.supported.find((provider) => provider.issuer === editingPolicy.issuer) ?? null,
        ],
        conditionFields: [
            (s) => [s.editingProvider, s.editingPolicy],
            (
                editingProvider: WorkloadProviderApi | null,
                editingPolicy: WorkloadTrustPolicyFormValues
            ): WorkloadTrustPolicyConditionField[] => {
                const offered = (editingProvider?.condition_claims ?? []).map((claim) => ({
                    name: claim.name,
                    label: claim.label,
                    helpText: claim.help_text,
                }))
                // A stored condition the provider no longer offers stays visible, so the admin can clear it.
                const offeredNames = new Set(offered.map((field) => field.name))
                const leftover = Object.keys(editingPolicy.conditions)
                    .filter((name) => !offeredNames.has(name))
                    .map((name) => ({
                        name,
                        label: name,
                        helpText: "The provider doesn't offer this condition anymore. Clear it to save the policy.",
                    }))
                return [...offered, ...leftover]
            },
        ],
        claimLabels: [
            (s) => [s.editingProvider],
            (editingProvider: WorkloadProviderApi | null): { subject: string; subjectName: string } => ({
                subject: editingProvider?.subject_claim.label ?? 'Subject',
                subjectName: editingProvider?.subject_name_claim.label ?? 'Name',
            }),
        ],
        providerNames: [
            (s) => [s.providers],
            (providers: WorkloadProvidersResponseApi | null): Record<string, string> =>
                Object.fromEntries((providers?.supported ?? []).map((provider) => [provider.issuer, provider.name])),
        ],
    }),

    listeners(({ actions, values, selectors }) => ({
        setEditingPolicyValue: ({ name }, _, __, previousState) => {
            const field = Array.isArray(name) ? name[0] : name
            // Condition claims belong to one provider, so switching provider starts from no conditions.
            if (field === 'issuer' && selectors.editingPolicy(previousState).issuer !== values.editingPolicy.issuer) {
                actions.setEditingPolicyValue('conditions', {})
            }
        },
        setEditingPolicyId: ({ id }) => {
            if (id === null) {
                return
            }
            const policy = id === 'new' ? null : values.policies?.find((row) => row.id === id)
            actions.resetEditingPolicy(
                policy
                    ? {
                          name: policy.name,
                          issuer: policy.issuer,
                          subject_name: policy.subject_name,
                          subject: policy.subject,
                          conditions: { ...policy.conditions },
                          scopes: policy.scopes,
                      }
                    : { ...EMPTY_FORM, issuer: values.providers?.supported[0]?.issuer ?? '' }
            )
            posthog.capture('workload trust policy form opened', { is_new: id === 'new' })
        },
        setConditionValue: ({ claim, value }) => {
            // An empty input means the condition isn't set, so the form never holds an empty value.
            const { [claim]: _, ...others } = values.editingPolicy.conditions
            actions.setEditingPolicyValue('conditions', value ? { ...others, [claim]: value } : others)
        },
        setScopeLevel: ({ key, level }) => {
            const levels = scopesArrayToObject(values.editingPolicy.scopes)
            if (level === 'none') {
                delete levels[key]
            } else {
                levels[key] = level
            }
            actions.setEditingPolicyValue('scopes', scopesObjectToArray(levels))
        },
        deletePolicy: ({ policy }) => {
            LemonDialog.open({
                title: `Delete "${policy.name}"?`,
                description:
                    'Workloads that match this policy stop getting tokens, and tokens it already issued stop working.',
                primaryButton: {
                    children: 'Delete policy',
                    status: 'danger',
                    onClick: async () => {
                        try {
                            await workloadTrustPoliciesDestroy(String(values.currentTeamId), policy.id)
                            posthog.capture('workload trust policy deleted')
                            lemonToast.success('Trusted workload deleted')
                            actions.loadPoliciesSuccess((values.policies ?? []).filter((row) => row.id !== policy.id))
                        } catch (error) {
                            lemonToast.error(readableErrorMessage(error) ?? "Couldn't delete the policy. Try again.")
                        }
                    },
                },
                secondaryButton: { children: 'Cancel' },
            })
        },
    })),

    afterMount(({ actions }) => {
        actions.loadPolicies()
        actions.loadProviders()
    }),
])