: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(settings): add trusted workload settings for projects (#127779)
Rafael Audibert0ce823a85264
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex 33fb054f7ce0..a4aacfcf5753 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -128,6 +128,20 @@ export function scopeMatchesSearch(scope: ScopeSearchFields, searchTerm: string)return tokens.every((token) => haystack.includes(token))}+/**+ * The warning a scope picker row shows for a risky scope at the picked level. The backend owns the list of+ * risky scopes and their wording. Write access includes read, so a write pick also shows the read warning.+ */+export const riskyScopeWarning = (+ scopeObject: string,+ level: ScopeAccessLevel,+ riskyScopes: Record<string, string>+): string | undefined => {+ const actions: APIScopeAction[] = level === 'write' ? ['write', 'read'] : level === 'read' ? ['read'] : []+ const warnings = actions.map((action) => riskyScopes[`${scopeObject}:${action}`]).filter(Boolean)+ return warnings.length > 0 ? `Add with care: ${warnings.join(' ')}` : undefined+}+// Scopes whose write action also writes a feature flag as a side effect (survey targeting flag,// early access feature linked flag), so they imply `feature_flag:write`. Single source of truth for// both the picker warning (attached below) and the auto-select in personalAPIKeysLogic, so the rulediff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 1538424574e9..9597693c0aba 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -196,6 +196,7 @@ import { ProjectDangerZone } from './project/ProjectDangerZone'import { ProjectDetails } from './project/ProjectDetails'import { ProjectMove } from './project/ProjectMove'import { ProjectSecretAPIKeys } from './project/ProjectSecretAPIKeys'+import { WorkloadTrustPolicies } from './project/WorkloadTrustPolicies'import { SettingSection } from './types'import { AllowImpersonation } from './user/AllowImpersonation'import { ChangePassword, ChangePasswordTitle } from './user/ChangePassword'@@ -2225,6 +2226,33 @@ export const SETTINGS_MAP: SettingSection[] = [},],},+ {+ level: 'environment',+ id: 'environment-trusted-workloads',+ title: 'Trusted workloads',+ minimumAccessLevel: OrganizationMembershipLevel.Admin,+ settings: [+ {+ id: 'environment-trusted-workloads',+ title: 'Trusted workloads',+ description:+ 'Let workloads you trust, such as CI jobs, get short-lived tokens for this project without storing a secret.',+ component: <WorkloadTrustPolicies />,+ keywords: [+ 'workload',+ 'workload identity',+ 'federation',+ 'ci',+ 'oidc',+ 'github actions',+ 'gitlab',+ 'token',+ 'trust policy',+ 'deploy',+ ],+ },+ ],+ },{level: 'environment',id: 'environment-danger-zone',diff --git a/frontend/src/scenes/settings/project/WorkloadTrustPolicies.stories.tsx b/frontend/src/scenes/settings/project/WorkloadTrustPolicies.stories.tsxnew file mode 100644index 000000000000..cba911c24842--- /dev/null+++ b/frontend/src/scenes/settings/project/WorkloadTrustPolicies.stories.tsx@@ -0,0 +1,115 @@+import { MOCK_DEFAULT_USER } from 'lib/api.mock'++import { Meta, StoryObj } from '@storybook/react'+import { useState } from 'react'++import { userLogic } from 'scenes/userLogic'++import { useStorybookMocks } from '~/mocks/browser'++import { WorkloadTrustPolicies } from './WorkloadTrustPolicies'++const meta: Meta = {+ title: 'Scenes-Other/Settings/Project/Trusted workloads',+ component: WorkloadTrustPolicies,+ parameters: {+ testOptions: { snapshotBrowsers: [] },+ },+}+export default meta++type Story = StoryObj<{}>++const ISSUER = 'https://ci.example.com'++const providers = {+ supported: [+ {+ key: 'example_ci',+ name: 'Example CI',+ issuer: ISSUER,+ docs_url: 'https://example.com/docs',+ subject_claim: { name: 'repository_id', label: 'Repository ID', help_text: '' },+ subject_name_claim: { name: 'repository', label: 'Repository', help_text: 'For example acme/web.' },+ condition_claims: [+ { name: 'ref', label: 'Branch or tag', help_text: 'For example refs/heads/main.' },+ { name: 'environment', label: 'Environment', help_text: '' },+ ],+ },+ ],+ grantable_scopes: [+ 'annotation:read',+ 'annotation:write',+ 'error_tracking:read',+ 'error_tracking:write',+ 'organization_member:read',+ 'organization_member:write',+ ],+ risky_scopes: {+ 'organization_member:write': 'Invites and removes organization members and changes their roles.',+ },+}++const claimLabels = {+ subject: 'Repository ID',+ subject_name: 'Repository',+ conditions: { ref: 'Branch or tag', environment: 'Environment' },+}++const createdBy = { id: 1, uuid: 'test-user', first_name: 'Test', email: '[email protected]', hedgehog_config: null }++export const WithPolicies: Story = {+ render: () => {+ // The section asks for a recent login on mount, so the story user has a fresh session before it renders.+ useState(() => {+ userLogic.mount()+ userLogic.actions.loadUserSuccess({+ ...MOCK_DEFAULT_USER,+ sensitive_session_expires_at: '2099-01-01T00:00:00Z',+ })+ })+ useStorybookMocks({+ get: {+ '/api/projects/:team_id/workload_trust_policies/providers/': providers,+ '/api/projects/:team_id/workload_trust_policies/': {+ count: 2,+ next: null,+ previous: null,+ results: [+ {+ id: 'deploys',+ name: 'Production deploys',+ issuer: ISSUER,+ provider: 'example_ci',+ subject_name: 'acme/web',+ subject: '123456',+ conditions: { environment: 'production', ref: 'refs/heads/main' },+ claim_labels: claimLabels,+ scopes: ['annotation:write', 'error_tracking:write'],+ enabled: true,+ created_by: createdBy,+ created_at: '2026-10-01T10:00:00Z',+ updated_at: '2026-10-01T10:00:00Z',+ },+ {+ id: 'previews',+ name: 'Preview builds',+ issuer: ISSUER,+ provider: 'example_ci',+ subject_name: 'acme/web',+ subject: '123456',+ conditions: { environment: 'preview' },+ claim_labels: claimLabels,+ scopes: ['error_tracking:write'],+ enabled: false,+ created_by: createdBy,+ created_at: '2026-10-02T10:00:00Z',+ updated_at: '2026-10-02T10:00:00Z',+ },+ ],+ },+ },+ })+ return <WorkloadTrustPolicies />+ },+}diff --git a/frontend/src/scenes/settings/project/WorkloadTrustPolicies.tsx b/frontend/src/scenes/settings/project/WorkloadTrustPolicies.tsxnew file mode 100644index 000000000000..adc3ae53100c--- /dev/null+++ b/frontend/src/scenes/settings/project/WorkloadTrustPolicies.tsx@@ -0,0 +1,183 @@+import { useActions, useValues } from 'kea'++import { IconEllipsis, IconPlus } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonMenu, LemonSwitch, LemonTable, LemonTag } from '@posthog/lemon-ui'++import { TimeSensitiveAuthenticationArea } from 'lib/components/TimeSensitiveAuthentication/TimeSensitiveAuthentication'+import { TZLabel } from 'lib/components/TZLabel'+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'++import type { WorkloadProvidersResponseApi, WorkloadTrustPolicyApi } from '~/generated/core/api.schemas'++import { workloadTrustPoliciesLogic } from './workloadTrustPoliciesLogic'+import { WorkloadTrustPolicyModal } from './WorkloadTrustPolicyModal'++function getCreateDisabledReason(+ providers: WorkloadProvidersResponseApi | null,+ providersLoadFailed: boolean,+ policiesLoading: boolean+): string | undefined {+ if (providers === null) {+ return providersLoadFailed ? "Couldn't load the supported providers" : 'Loading the supported providers'+ }+ if (providers.supported.length === 0) {+ return 'No workload provider is supported on this instance'+ }+ // A list response that lands after a save would replace the new policy with an older snapshot.+ return policiesLoading ? 'Loading trusted workloads' : undefined+}++export function WorkloadTrustPolicies(): JSX.Element {+ const { policies, policiesLoading, policiesLoadFailed, providers, providersLoadFailed, providerNames } =+ useValues(workloadTrustPoliciesLogic)+ const { setEditingPolicyId, deletePolicy, setPolicyEnabled, loadPolicies, loadProviders } =+ useActions(workloadTrustPoliciesLogic)++ const createDisabledReason = getCreateDisabledReason(providers, providersLoadFailed, policiesLoading)++ // Policies hand out tokens that act as the organization owner, so the section asks for a recent login.+ return (+ <TimeSensitiveAuthenticationArea>+ <>+ <p>+ A trusted workload, such as a CI job, gets short-lived tokens for this project, so you don't have to+ store an API key with it. Tokens act as the organization owner and carry only the scopes the policy+ lists.+ </p>+ <LemonButton+ type="primary"+ icon={<IconPlus />}+ onClick={() => setEditingPolicyId('new')}+ disabledReason={createDisabledReason}+ data-attr="workload-trust-policy-create"+ className="mb-4"+ >+ Add trusted workload+ </LemonButton>+ {providersLoadFailed ? (+ <LemonBanner+ type="error"+ className="mb-4"+ action={{ children: 'Retry', onClick: () => loadProviders() }}+ >+ Couldn't load the supported providers.+ </LemonBanner>+ ) : null}+ {policiesLoadFailed ? (+ <LemonBanner type="error" action={{ children: 'Retry', onClick: () => loadPolicies() }}>+ Couldn't load trusted workloads.+ </LemonBanner>+ ) : (+ <LemonTable<WorkloadTrustPolicyApi>+ dataSource={policies ?? []}+ loading={policiesLoading && policies === null}+ rowKey="id"+ emptyState="No trusted workloads yet. No workload can get tokens for this project."+ columns={[+ {+ title: 'Name',+ key: 'name',+ render: (_, policy) => (+ <div className="flex flex-col">+ <span className="font-semibold">{policy.name}</span>+ <span className="text-secondary text-xs">+ {providerNames[policy.issuer] ?? policy.issuer}+ </span>+ </div>+ ),+ },+ {+ title: 'Workload',+ key: 'subject',+ render: (_, policy) => (+ <div className="flex flex-col">+ <span className="font-mono">{policy.subject_name}</span>+ <span className="text-secondary text-xs">+ {policy.claim_labels.subject} {policy.subject}+ </span>+ </div>+ ),+ },+ {+ title: 'Conditions',+ key: 'conditions',+ render: (_, policy) => (+ <span className="flex flex-wrap gap-1">+ {Object.entries(policy.conditions ?? {}).map(([claim, value]) => (+ <LemonTag key={claim}>+ {policy.claim_labels.conditions[claim] ?? claim}: {value}+ </LemonTag>+ ))}+ </span>+ ),+ },+ {+ title: 'Scopes',+ key: 'scopes',+ render: (_, policy) => (+ <span className="flex flex-wrap gap-1">+ {policy.scopes.map((scope) => (+ <LemonTag key={scope}>{scope}</LemonTag>+ ))}+ </span>+ ),+ },+ {+ title: 'Enabled',+ key: 'enabled',+ render: (_, policy) => (+ <LemonSwitch+ checked={!!policy.enabled}+ onChange={(enabled) => setPolicyEnabled({ policy, enabled })}+ disabledReason={policiesLoading ? 'Saving' : undefined}+ data-attr="workload-trust-policy-enabled"+ />+ ),+ },+ {+ title: 'Created',+ key: 'created',+ render: (_, policy) => (+ <div className="flex flex-col gap-1">+ {policy.created_by ? (+ <ProfilePicture+ user={{+ first_name: policy.created_by.first_name,+ last_name: policy.created_by.last_name,+ email: policy.created_by.email,+ }}+ size="sm"+ showName+ />+ ) : null}+ <TZLabel time={policy.created_at} className="text-secondary text-xs" />+ </div>+ ),+ },+ {+ key: 'actions',+ width: 0,+ render: (_, policy) => (+ <LemonMenu+ items={[+ { label: 'Edit', onClick: () => setEditingPolicyId(policy.id) },+ {+ label: 'Delete',+ status: 'danger',+ onClick: () => deletePolicy(policy),+ 'data-attr': 'workload-trust-policy-delete',+ },+ ]}+ >+ <LemonButton size="small" icon={<IconEllipsis />} aria-label="Policy actions" />+ </LemonMenu>+ ),+ },+ ]}+ />+ )}+ <WorkloadTrustPolicyModal />+ </>+ </TimeSensitiveAuthenticationArea>+ )+}diff --git a/frontend/src/scenes/settings/project/WorkloadTrustPolicyModal.tsx b/frontend/src/scenes/settings/project/WorkloadTrustPolicyModal.tsxnew file mode 100644index 000000000000..4674e4f4934f--- /dev/null+++ b/frontend/src/scenes/settings/project/WorkloadTrustPolicyModal.tsx@@ -0,0 +1,165 @@+import { useActions, useValues } from 'kea'+import { Form } from 'kea-forms'++import { LemonButton, LemonInput, LemonModal, LemonSelect } from '@posthog/lemon-ui'++import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { riskyScopeWarning } from 'lib/scopes'++import { workloadTrustPoliciesLogic } from './workloadTrustPoliciesLogic'++export function WorkloadTrustPolicyModal(): JSX.Element {+ const {+ editingPolicyId,+ editingPolicyChanged,+ isEditingPolicySubmitting,+ providers,+ scopeRows,+ scopeLevels,+ scopeSearchTerm,+ editingPolicy,+ editingProvider,+ conditionFields,+ claimLabels,+ } = useValues(workloadTrustPoliciesLogic)+ const { setEditingPolicyId, submitEditingPolicy, setScopeLevel, setScopeSearchTerm, setConditionValue } =+ useActions(workloadTrustPoliciesLogic)++ const isNew = editingPolicyId === 'new'++ return (+ <Form logic={workloadTrustPoliciesLogic} formKey="editingPolicy">+ <LemonModal+ title={isNew ? 'Add trusted workload' : 'Edit trusted workload'}+ isOpen={!!editingPolicyId}+ onClose={() => setEditingPolicyId(null)}+ width="40rem"+ hasUnsavedInput={editingPolicyChanged}+ footer={+ <>+ <LemonButton type="secondary" onClick={() => setEditingPolicyId(null)}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ htmlType="submit"+ loading={isEditingPolicySubmitting}+ disabledReason={!editingPolicyChanged ? 'No changes to save' : undefined}+ onClick={submitEditingPolicy}+ data-attr="workload-trust-policy-save"+ >+ {isNew ? 'Add trusted workload' : 'Save'}+ </LemonButton>+ </>+ }+ >+ <div className="deprecated-space-y-4">+ <LemonField name="name" label="Name">+ <LemonInput placeholder="Production deploys" maxLength={200} />+ </LemonField>+ <LemonField name="issuer" label="Provider">+ <LemonSelect+ fullWidth+ placeholder="Choose a provider"+ options={(providers?.supported ?? []).map((provider) => ({+ value: provider.issuer,+ label: provider.name,+ }))}+ />+ </LemonField>+ <div className="flex flex-wrap gap-4">+ <LemonField+ name="subject_name"+ label={claimLabels.subjectName}+ help={editingProvider?.subject_name_claim.help_text || undefined}+ className="flex-1 min-w-60"+ >+ <LemonInput />+ </LemonField>+ <LemonField+ name="subject"+ label={claimLabels.subject}+ help={editingProvider?.subject_claim.help_text || undefined}+ className="flex-1 min-w-60"+ >+ <LemonInput />+ </LemonField>+ </div>+ {conditionFields.length > 0 ? (+ <LemonField+ name="conditions"+ label="Conditions"+ help="A token matches only when it carries every value you set. Leave a field empty to allow any value."+ >+ {() => (+ <div className="flex flex-wrap gap-4 w-full">+ {conditionFields.map((claim) => (+ <LemonField.Pure+ key={claim.name}+ label={claim.label}+ help={claim.helpText || undefined}+ className="flex-1 min-w-60"+ >+ <LemonInput+ value={editingPolicy.conditions[claim.name] ?? ''}+ onChange={(value) => setConditionValue(claim.name, value)}+ data-attr={`workload-trust-policy-condition-${claim.name}`}+ />+ </LemonField.Pure>+ ))}+ </div>+ )}+ </LemonField>+ ) : null}+ <LemonField+ name="scopes"+ label="Scopes"+ help="Every token from this policy gets these scopes. Scopes that would let a token outlive itself aren't available."+ >+ <div className="w-full">+ <LemonInput+ type="search"+ placeholder="Search scopes"+ value={scopeSearchTerm}+ onChange={setScopeSearchTerm}+ className="mb-2"+ size="small"+ />+ <div className="max-h-[40vh] overflow-y-auto deprecated-space-y-2">+ {scopeRows.length === 0 ? (+ <div className="text-secondary text-sm py-2">No scopes match your search.</div>+ ) : (+ scopeRows.map(({ key, label, disabledActions }) => (+ <ScopeAccessRow+ key={key}+ row={{+ key,+ label,+ value: scopeLevels[key] ?? 'none',+ warning: riskyScopeWarning(+ key,+ scopeLevels[key] ?? 'none',+ providers?.risky_scopes ?? {}+ ),+ disabledReasons: {+ read: disabledActions.includes('read')+ ? 'Not available for workload tokens'+ : undefined,+ write: disabledActions.includes('write')+ ? 'Not available for workload tokens'+ : undefined,+ },+ }}+ onChange={setScopeLevel}+ />+ ))+ )}+ </div>+ </div>+ </LemonField>+ </div>+ </LemonModal>+ </Form>+ )+}diff --git a/frontend/src/scenes/settings/project/workloadTrustPoliciesLogic.ts b/frontend/src/scenes/settings/project/workloadTrustPoliciesLogic.tsnew file mode 100644index 000000000000..64c0305302df--- /dev/null+++ b/frontend/src/scenes/settings/project/workloadTrustPoliciesLogic.ts@@ -0,0 +1,516 @@+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()+ }),+])diff --git a/frontend/src/scenes/settings/sectionGating.ts b/frontend/src/scenes/settings/sectionGating.tsindex 8cb5a93f40dc..c852860acf29 100644--- a/frontend/src/scenes/settings/sectionGating.ts+++ b/frontend/src/scenes/settings/sectionGating.ts@@ -7,6 +7,7 @@ import { SettingSection, SettingSectionId, UnavailableSection } from '~/scenes/sexport const ADMIN_ONLY_SECTION_IDS: SettingSectionId[] = ['organization-legal-documents','organization-access-resolution',+ 'environment-trusted-workloads',]interface FindUnavailableSectionInput {diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex 280bbcd1be39..909fc0a0ff09 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -61,6 +61,7 @@ export type SettingSectionId =| 'environment-replay'| 'environment-revenue-analytics'| 'environment-secret-api-keys'+ | 'environment-trusted-workloads'| 'environment-surveys'| 'environment-task-agent-instructions'| 'environment-task-agents'@@ -181,6 +182,7 @@ export type SettingId =| 'environment-experiment-sequential-tuning-parameter'| 'environment-experiment-stats-method'| 'environment-secret-api-keys'+ | 'environment-trusted-workloads'| 'error-tracking-alerting'| 'error-tracking-auto-assignment'| 'error-tracking-custom-grouping'diff --git a/posthog/models/workload_trust_policy.py b/posthog/models/workload_trust_policy.pyindex a00d32396ed9..efca621e0d26 100644--- a/posthog/models/workload_trust_policy.py+++ b/posthog/models/workload_trust_policy.py@@ -16,7 +16,8 @@ from posthog.scopes import UNPRIVILEGED_SCOPES# - `workload_trust_policy` would let a workload change the policy behind its token.# - `task:write` starts an agent run from a prompt the caller writes, with its own longer-lived owner token.# `conversation:write` (PostHog AI can create such a task), `signal_scout:write`,-# `business_knowledge:write` and `autoresearch:write` start the same kind of run.+# `business_knowledge:write`, `autoresearch:write` and `hog_flow:write` (a workflow can create a task) start the+# same kind of run.# - `conversation:read` and `task:read` read the owner's private PostHog AI chats and tasks, because the token# acts as the owner. Add them back if a workload needs them.# - `project:write` lets a token rotate the project's secret token.@@ -34,6 +35,7 @@ WORKLOAD_TRUST_POLICY_DENIED_SCOPES: frozenset[str] = frozenset("business_knowledge:write","conversation:read","conversation:write",+ "hog_flow:write","project:write","sharing_configuration:read","sharing_configuration:write",diff --git a/posthog/workload_identity/test/test_trust_policy.py b/posthog/workload_identity/test/test_trust_policy.pyindex e5347a12edae..129f5a395ff0 100644--- a/posthog/workload_identity/test/test_trust_policy.py+++ b/posthog/workload_identity/test/test_trust_policy.py@@ -165,6 +165,7 @@ class TestWorkloadTrustPolicyAPI(APIBaseTest):("own_policy_scope", {"scopes": ["workload_trust_policy:read"]}, "scopes"),("agent_run_scope", {"scopes": ["task:write"]}, "scopes"),("training_run_scope", {"scopes": ["autoresearch:write"]}, "scopes"),+ ("workflow_task_scope", {"scopes": ["hog_flow:write"]}, "scopes"),("owner_account_scope", {"scopes": ["user:write"]}, "scopes"),("app_token_scope", {"scopes": ["streamlit_app:read"]}, "scopes"),("webhook_feed_scope", {"scopes": ["webhook:write"]}, "scopes"),