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.

feat(oauth): let members request trusted workloads for admin approval (#127781)

Rafael Audibert3f76a775a8d4
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 86b89cdd636f..6e82cb05ae9d 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -106,6 +106,7 @@ rules:
|BriefConfig
|ButtonTile
|WorkloadTrustPolicy
+ |WorkloadTrustPolicyRequest
|Canvas
|CanvasBuild
|CanvasHomePreference
@@ -618,6 +619,7 @@ rules:
|BriefConfig
|ButtonTile
|WorkloadTrustPolicy
+ |WorkloadTrustPolicyRequest
|Canvas
|CanvasBuild
|CanvasHomePreference
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 2c38e0495958..67d479d34a4f 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -5936,6 +5936,114 @@ export interface WorkloadProvidersResponseApi {
risky_scopes: WorkloadProvidersResponseApiRiskyScopes
}
+export type WorkloadTrustPolicyRequestStatusEnumApi =
+ (typeof WorkloadTrustPolicyRequestStatusEnumApi)[keyof typeof WorkloadTrustPolicyRequestStatusEnumApi]
+
+export const WorkloadTrustPolicyRequestStatusEnumApi = {
+ Pending: 'pending',
+ Approved: 'approved',
+ Rejected: 'rejected',
+ Expired: 'expired',
+} as const
+
+/**
+ * Claims the token must carry, as claim name to exact value, for example a branch or an environment. Only the provider's condition claims are allowed. An empty value removes the condition.
+ */
+export type WorkloadTrustPolicyRequestApiConditions = { [key: string]: string }
+
+/**
+ * What each risky scope in the request lets a token do, keyed by scope. Show it before approving.
+ */
+export type WorkloadTrustPolicyRequestApiRiskyScopes = { [key: string]: string }
+
+export interface WorkloadTrustPolicyRequestApi {
+ readonly id: string
+ /**
+ * The name the policy gets once approved.
+ * @maxLength 200
+ */
+ name: string
+ /**
+ * The OIDC issuer of the workload provider, from the list of supported providers.
+ * @maxLength 255
+ */
+ issuer: string
+ /**
+ * The key of the workload provider the issuer belongs to.
+ * @nullable
+ */
+ readonly provider: string | null
+ /**
+ * The display name of the workload provider, or null.
+ * @nullable
+ */
+ readonly provider_name: string | null
+ /**
+ * The workload's human-readable name, from the provider's subject name claim, for example a repository's full name. Matched exactly.
+ * @maxLength 255
+ */
+ subject_name: string
+ /**
+ * The workload's immutable ID, from the provider's subject claim, for example a repository ID. Matched exactly together with the name, so a deleted and re-created workload with the same name does not match.
+ * @maxLength 255
+ */
+ subject: string
+ /** Claims the token must carry, as claim name to exact value, for example a branch or an environment. Only the provider's condition claims are allowed. An empty value removes the condition. */
+ conditions?: WorkloadTrustPolicyRequestApiConditions
+ /** How the provider names the subject, the subject name and each condition claim, for display. */
+ readonly claim_labels: WorkloadClaimLabelsApi
+ /**
+ * The scopes the policy's tokens would carry.
+ * @items.maxLength 100
+ */
+ scopes: string[]
+ /** What each risky scope in the request lets a token do, keyed by scope. Show it before approving. */
+ readonly risky_scopes: WorkloadTrustPolicyRequestApiRiskyScopes
+ /** Where the request stands. A request expires after 24 hours. */
+ readonly status: WorkloadTrustPolicyRequestStatusEnumApi
+ /** The link to send to an admin to approve the request. */
+ readonly approval_url: string
+ /** Whether the current user's role lets them approve the request, in the browser. */
+ readonly can_approve: boolean
+ /** Names of the organization admins and owners who can approve, when the current user cannot. */
+ readonly approvers: readonly string[]
+ readonly requested_by: UserBasicApi | null
+ /**
+ * The name of the OAuth app the request came through, or null for other credentials.
+ * @nullable
+ */
+ readonly requested_via: string | null
+ /**
+ * Whether PostHog verified the OAuth app the request came through, or null for other credentials.
+ * @nullable
+ */
+ readonly requested_via_verified: boolean | null
+ /** When the request was made. */
+ readonly created_at: string
+ /** When a pending request stops being approvable. */
+ readonly expires_at: string
+ readonly resolved_by: UserBasicApi | null
+ /**
+ * When an admin approved or rejected the request.
+ * @nullable
+ */
+ readonly resolved_at: string | null
+ /**
+ * The policy created on approval.
+ * @nullable
+ */
+ readonly policy_id: string | null
+}
+
+export interface PaginatedWorkloadTrustPolicyRequestListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: WorkloadTrustPolicyRequestApi[]
+}
+
export interface LeakedKeyReportApi {
/**
* The leaked PostHog personal API key, project secret API key, legacy feature flags secure API key, or OAuth access/refresh token to revoke.
@@ -7487,6 +7595,17 @@ export type WorkloadTrustPoliciesListParams = {
offset?: number
}
+export type WorkloadTrustPolicyRequestsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type UsersListParams = {
email?: string
is_staff?: boolean
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 50af787c08bf..b375cc942c84 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -83,6 +83,7 @@ import type {
PaginatedUserGitHubIntegrationListResponseListApi,
PaginatedUserListApi,
PaginatedWorkloadTrustPolicyListApi,
+ PaginatedWorkloadTrustPolicyRequestListApi,
PatchedCIMDVerificationTokenUpdateApi,
PatchedEnterprisePropertyDefinitionApi,
PatchedFileSystemApi,
@@ -142,6 +143,8 @@ import type {
WorkloadProvidersResponseApi,
WorkloadTrustPoliciesListParams,
WorkloadTrustPolicyApi,
+ WorkloadTrustPolicyRequestApi,
+ WorkloadTrustPolicyRequestsListParams,
} from './api.schemas'
// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
@@ -3120,6 +3123,101 @@ export const workloadTrustPoliciesProvidersRetrieve = async (
})
}
+export const getWorkloadTrustPolicyRequestsListUrl = (
+ projectId: string,
+ params?: WorkloadTrustPolicyRequestsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/workload_trust_policy_requests/?${stringifiedParams}`
+ : `/api/projects/${projectId}/workload_trust_policy_requests/`
+}
+
+export const workloadTrustPolicyRequestsList = async (
+ projectId: string,
+ params?: WorkloadTrustPolicyRequestsListParams,
+ options?: RequestInit
+): Promise<PaginatedWorkloadTrustPolicyRequestListApi> => {
+ return apiMutator<PaginatedWorkloadTrustPolicyRequestListApi>(
+ getWorkloadTrustPolicyRequestsListUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getWorkloadTrustPolicyRequestsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/workload_trust_policy_requests/`
+}
+
+export const workloadTrustPolicyRequestsCreate = async (
+ projectId: string,
+ workloadTrustPolicyRequestApi: NonReadonly<WorkloadTrustPolicyRequestApi>,
+ options?: RequestInit
+): Promise<WorkloadTrustPolicyRequestApi> => {
+ return apiMutator<WorkloadTrustPolicyRequestApi>(getWorkloadTrustPolicyRequestsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(workloadTrustPolicyRequestApi),
+ })
+}
+
+export const getWorkloadTrustPolicyRequestsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/workload_trust_policy_requests/${id}/`
+}
+
+export const workloadTrustPolicyRequestsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<WorkloadTrustPolicyRequestApi> => {
+ return apiMutator<WorkloadTrustPolicyRequestApi>(getWorkloadTrustPolicyRequestsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getWorkloadTrustPolicyRequestsApproveCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/workload_trust_policy_requests/${id}/approve/`
+}
+
+export const workloadTrustPolicyRequestsApproveCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<WorkloadTrustPolicyRequestApi> => {
+ return apiMutator<WorkloadTrustPolicyRequestApi>(getWorkloadTrustPolicyRequestsApproveCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getWorkloadTrustPolicyRequestsRejectCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/workload_trust_policy_requests/${id}/reject/`
+}
+
+export const workloadTrustPolicyRequestsRejectCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<WorkloadTrustPolicyRequestApi> => {
+ return apiMutator<WorkloadTrustPolicyRequestApi>(getWorkloadTrustPolicyRequestsRejectCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getRevokeLeakedKeyCreateUrl = () => {
return `/api/revoke_leaked_key/`
}
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index a28f98fcea59..88cbc65454ea 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -1470,6 +1470,48 @@ export const WorkloadTrustPoliciesPartialUpdateBody = /* @__PURE__ */ zod.object
enabled: zod.boolean().optional().describe('Whether the policy can mint tokens. Disabling it cuts off its tokens.'),
})
+export const workloadTrustPolicyRequestsCreateBodyNameMax = 200
+
+export const workloadTrustPolicyRequestsCreateBodyIssuerMax = 255
+
+export const workloadTrustPolicyRequestsCreateBodySubjectNameMax = 255
+
+export const workloadTrustPolicyRequestsCreateBodySubjectMax = 255
+
+export const workloadTrustPolicyRequestsCreateBodyScopesItemMax = 100
+
+export const WorkloadTrustPolicyRequestsCreateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(workloadTrustPolicyRequestsCreateBodyNameMax)
+ .describe('The name the policy gets once approved.'),
+ issuer: zod
+ .string()
+ .max(workloadTrustPolicyRequestsCreateBodyIssuerMax)
+ .describe('The OIDC issuer of the workload provider, from the list of supported providers.'),
+ subject_name: zod
+ .string()
+ .max(workloadTrustPolicyRequestsCreateBodySubjectNameMax)
+ .describe(
+ "The workload's human-readable name, from the provider's subject name claim, for example a repository's full name. Matched exactly."
+ ),
+ subject: zod
+ .string()
+ .max(workloadTrustPolicyRequestsCreateBodySubjectMax)
+ .describe(
+ "The workload's immutable ID, from the provider's subject claim, for example a repository ID. Matched exactly together with the name, so a deleted and re-created workload with the same name does not match."
+ ),
+ conditions: zod
+ .record(zod.string(), zod.string())
+ .optional()
+ .describe(
+ "Claims the token must carry, as claim name to exact value, for example a branch or an environment. Only the provider's condition claims are allowed. An empty value removes the condition."
+ ),
+ scopes: zod
+ .array(zod.string().max(workloadTrustPolicyRequestsCreateBodyScopesItemMax))
+ .describe("The scopes the policy's tokens would carry."),
+})
+
/**
* Public, unauthenticated endpoint for self-service revocation of a leaked PostHog personal API key, project secret API key, legacy feature flags secure API key, or OAuth access/refresh token. If the token matches a real credential, it is revoked immediately and the owner is notified by email. This includes an expired OAuth access token: the paired refresh token it protects may still be live. A legacy feature flags secure API key is matched through its migrated project secret API key row; it cannot be rotated automatically, so its project admins get an email to rotate it.
*
diff --git a/frontend/src/lib/oauthScopes.generated.ts b/frontend/src/lib/oauthScopes.generated.ts
index ca0357cddd45..54e17add791e 100644
--- a/frontend/src/lib/oauthScopes.generated.ts
+++ b/frontend/src/lib/oauthScopes.generated.ts
@@ -246,6 +246,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'webhook:write',
'workload_trust_policy:read',
'workload_trust_policy:write',
+ 'workload_trust_policy_request:read',
+ 'workload_trust_policy_request:write',
] as const
export type OAuthScope = (typeof OAUTH_SCOPES_SUPPORTED)[number]
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index ddb27179d864..1d8ac98b4605 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -171,6 +171,12 @@ export const API_SCOPES: APIScope[] = [
objectPlural: 'workload trust policies',
disabledActions: ['write'],
},
+ {
+ key: 'workload_trust_policy_request',
+ objectName: 'Workload trust policy request',
+ objectPlural: 'workload trust policy requests',
+ info: 'Write access lets the key ask an organization admin for a workload trust policy. A request grants nothing until an admin approves it.',
+ },
{ key: 'cohort', objectName: 'Cohort', objectPlural: 'cohorts' },
{ key: 'comment', objectName: 'Comment', objectPlural: 'comments' },
{
@@ -699,6 +705,7 @@ export const API_SCOPE_GROUPS: APIScopeGroup[] = [
'organization_member',
'project',
'workload_trust_policy',
+ 'workload_trust_policy_request',
'user',
'billing',
'access_control',
diff --git a/frontend/src/scenes/appScenes.ts b/frontend/src/scenes/appScenes.ts
index fa8f59ceb9ad..3d975d9d747a 100644
--- a/frontend/src/scenes/appScenes.ts
+++ b/frontend/src/scenes/appScenes.ts
@@ -17,6 +17,7 @@ export const appScenes: Record<Scene | string, () => any> = {
[Scene.BillingSection]: () => import('./billing/BillingSection'),
[Scene.Billing]: () => import('./billing/Billing'),
[Scene.Canvas]: () => import('./notebooks/NotebookCanvasScene'),
+ [Scene.WorkloadTrustPolicyRequest]: () => import('./workload-trust-policy-request/WorkloadTrustPolicyRequestScene'),
[Scene.CLIAuthorize]: () => import('./authentication/cli/CLIAuthorize'),
[Scene.OAuthDeviceAuthorize]: () => import('./authentication/device/OAuthDeviceAuthorize'),
[Scene.CLILive]: () => import('./authentication/cli/CLILive'),
diff --git a/frontend/src/scenes/authentication/shared/authScene/authNotes.ts b/frontend/src/scenes/authentication/shared/authScene/authNotes.ts
index 3efee1d20439..971b86acdadc 100644
--- a/frontend/src/scenes/authentication/shared/authScene/authNotes.ts
+++ b/frontend/src/scenes/authentication/shared/authScene/authNotes.ts
@@ -49,6 +49,12 @@ export const AUTH_NOTES = {
done: ['2fa reset', 'back in you go'],
invalid: ['this link stopped working', 'ask for a new one'],
},
+ workloadTrustPolicyRequest: {
+ pending: ['a workload wants in', 'check it before you approve'],
+ approved: ['approved', 'the policy is live'],
+ closed: ['nothing to approve', 'this request is closed'],
+ missing: ['hmm', "this request isn't here"],
+ },
cliAuthorize: {
authorize: ['hello, terminal', 'only grant what you need'],
authorized: ['authorized', 'your terminal has a key now'],
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index 3f0997ab211b..c3ddcc75ed37 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -30,6 +30,7 @@ export enum Scene {
BillingSection = 'BillingSection',
BusinessIntelligence = 'BusinessIntelligence',
Canvas = 'Canvas',
+ WorkloadTrustPolicyRequest = 'WorkloadTrustPolicyRequest',
CLIAuthorize = 'CLIAuthorize',
OAuthDeviceAuthorize = 'OAuthDeviceAuthorize',
CLILive = 'CLILive',
diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.ts
index 41895e5c63e3..4b89e1d6c5b4 100644
--- a/frontend/src/scenes/scenes.ts
+++ b/frontend/src/scenes/scenes.ts
@@ -100,6 +100,12 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {
layout: 'app-full-scene-height',
hideProjectNotice: true,
},
+ [Scene.WorkloadTrustPolicyRequest]: {
+ projectBased: true,
+ layout: 'plain',
+ name: 'Trusted workload request',
+ description: 'Review a request to trust a workload',
+ },
[Scene.CLIAuthorize]: {
name: 'Authorize CLI',
projectBased: false,
@@ -852,6 +858,8 @@ export const routes: Record<string, [Scene | string, string]> = {
[urls.productTours()]: [Scene.ProductTours, 'productTours'],
[urls.productTour(':id')]: [Scene.ProductTour, 'productTour'],
[urls.approval(':id')]: [Scene.Approval, 'approval'],
+ // pinned: the backend builds this path into the approval link it returns, which people share
+ [urls.workloadTrustPolicyRequest(':id')]: [Scene.WorkloadTrustPolicyRequest, 'workloadTrustPolicyRequest'],
[urls.sqlEditor()]: [Scene.SQLEditor, 'sqlEditor'],
[urls.featureFlags()]: [Scene.FeatureFlags, 'featureFlags'],
[urls.featureFlagTemplates()]: ['FeatureFlagTemplates' as Scene, 'featureFlagTemplates'],
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index 73945daba339..0b89c9eed507 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -378,6 +378,7 @@ export const urls = {
projectPendingDeletion: (): string => '/project-pending-deletion',
approvals: (): string => '/settings/environment-approvals#change-requests',
approval: (id: string): string => `/approvals/${id}`,
+ workloadTrustPolicyRequest: (id: string): string => `/workload-trust-policy-requests/${id}`,
health: (): string => '/health',
healthCategory: (category: string): string => `/health/${category}`,
healthAlerts: (presetKinds?: string[]): string =>
diff --git a/frontend/src/scenes/workload-trust-policy-request/WorkloadTrustPolicyRequestScene.stories.tsx b/frontend/src/scenes/workload-trust-policy-request/WorkloadTrustPolicyRequestScene.stories.tsx
new file mode 100644
index 000000000000..c19e58f17b7c
--- /dev/null
+++ b/frontend/src/scenes/workload-trust-policy-request/WorkloadTrustPolicyRequestScene.stories.tsx
@@ -0,0 +1,71 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { useStorybookMocks } from '~/mocks/browser'
+
+import { WorkloadTrustPolicyRequestScene } from './WorkloadTrustPolicyRequestScene'
+
+const meta: Meta = {
+ title: 'Scenes-Other/Trusted workload request',
+ component: WorkloadTrustPolicyRequestScene,
+ parameters: {
+ mockDate: '2026-10-02T10:00:00Z',
+ layout: 'fullscreen',
+ testOptions: { snapshotBrowsers: [] },
+ },
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+const policyRequest = {
+ id: 'request-1',
+ name: 'Production deploys',
+ issuer: 'https://ci.example.com',
+ provider: 'example_ci',
+ provider_name: 'Example CI',
+ subject_name: 'acme/web',
+ subject: '123456',
+ conditions: { ref: 'refs/heads/main' },
+ claim_labels: {
+ subject: 'Repository ID',
+ subject_name: 'Repository',
+ conditions: { ref: 'Branch or tag', environment: 'Environment' },
+ },
+ scopes: ['annotation:write', 'error_tracking:write', 'organization_member:write'],
+ risky_scopes: {
+ 'organization_member:write': 'Invites and removes organization members and changes their roles.',
+ },
+ status: 'pending',
+ approval_url: 'http://localhost:8010/project/1/workload-trust-policy-requests/request-1',
+ requested_by: { id: 2, uuid: 'requester', first_name: 'Riley', last_name: 'Member', email: '[email protected]' },
+ requested_via: 'hog',
+ requested_via_verified: true,
+ created_at: '2026-10-01T10:00:00Z',
+ expires_at: '2026-10-08T10:00:00Z',
+ resolved_by: null,
+ resolved_at: null,
+ policy_id: null,
+}
+
+function renderWith(overrides: Record<string, unknown>): JSX.Element {
+ useStorybookMocks({
+ get: {
+ '/api/projects/:team_id/workload_trust_policy_requests/:id/': { ...policyRequest, ...overrides },
+ },
+ })
+ return <WorkloadTrustPolicyRequestScene id="request-1" />
+}
+
+export const PendingForAnAdmin: Story = {
+ render: () => renderWith({ can_approve: true, approvers: [] }),
+}
+
+export const PendingForAMember: Story = {
+ render: () =>
+ renderWith({
+ can_approve: false,
+ approvers: ['Olive Owner', 'Ada Admin'],
+ requested_via: 'Example agent',
+ requested_via_verified: false,
+ }),
+}
diff --git a/frontend/src/scenes/workload-trust-policy-request/WorkloadTrustPolicyRequestScene.tsx b/frontend/src/scenes/workload-trust-policy-request/WorkloadTrustPolicyRequestScene.tsx
new file mode 100644
index 000000000000..fd90afdbf49f
--- /dev/null
+++ b/frontend/src/scenes/workload-trust-policy-request/WorkloadTrustPolicyRequestScene.tsx
@@ -0,0 +1,270 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
+import { Link } from 'lib/lemon-ui/Link'
+import { fullNameOrEmail } from 'lib/utils/strings'
+import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'
+import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'
+import { AUTH_NOTES, type AuthNotes } from 'scenes/authentication/shared/authScene/authNotes'
+import { AuthScene, AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
+import { organizationLogic } from 'scenes/organizationLogic'
+import { SceneExport } from 'scenes/sceneTypes'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import type { WorkloadTrustPolicyRequestApi } from '~/generated/core/api.schemas'
+
+import {
+ WorkloadTrustPolicyRequestLogicProps,
+ workloadTrustPolicyRequestLogic,
+} from './workloadTrustPolicyRequestLogic'
+
+export const scene: SceneExport<WorkloadTrustPolicyRequestLogicProps> = {
+ component: WorkloadTrustPolicyRequestScene,
+ logic: workloadTrustPolicyRequestLogic,
+ paramsToProps: ({ params: { id } }) => ({ id }),
+}
+
+function DetailRow({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {
+ return (
+ <div className="flex flex-wrap gap-x-4 gap-y-1 py-2 border-b last:border-b-0">
+ <div className="w-28 shrink-0 text-secondary text-sm">{label}</div>
+ <div className="flex-1 min-w-0 break-words text-sm">{children}</div>
+ </div>
+ )
+}
+
+function RequesterLine({ policyRequest }: { policyRequest: WorkloadTrustPolicyRequestApi }): JSX.Element {
+ const requester = policyRequest.requested_by
+ return (
+ <>
+ Requested by <strong>{requester ? fullNameOrEmail(requester) : 'a former member'}</strong>
+ {requester ? ` (${requester.email})` : ''}
+ {policyRequest.requested_via ? ` through ${policyRequest.requested_via}` : ''}{' '}
+ {policyRequest.requested_via_verified === true ? (
+ <Tooltip title="This application has been verified by PostHog.">
+ <LemonTag type="success" size="small">
+ Verified
+ </LemonTag>
+ </Tooltip>
+ ) : policyRequest.requested_via_verified === false ? (
+ <Tooltip title="This application has not been verified by PostHog. Only approve if you recognize the requester and the application.">
+ <LemonTag type="warning" size="small">
+ Unverified application
+ </LemonTag>
+ </Tooltip>
+ ) : null}
+ </>
+ )
+}
+
+function notesFor(policyRequest: WorkloadTrustPolicyRequestApi | null, missing: boolean): AuthNotes {
+ if (missing) {
+ return AUTH_NOTES.workloadTrustPolicyRequest.missing
+ }
+ if (policyRequest?.status === 'approved') {
+ return AUTH_NOTES.workloadTrustPolicyRequest.approved
+ }
+ if (policyRequest && policyRequest.status !== 'pending') {
+ return AUTH_NOTES.workloadTrustPolicyRequest.closed
+ }
+ return AUTH_NOTES.workloadTrustPolicyRequest.pending
+}
+
+export function WorkloadTrustPolicyRequestScene({ id }: WorkloadTrustPolicyRequestLogicProps): JSX.Element {
+ const { policyRequest, policyRequestLoading, policyRequestMissing, resolving } = useValues(
+ workloadTrustPolicyRequestLogic({ id })
+ )
+ const { approve, reject } = useActions(workloadTrustPolicyRequestLogic({ id }))
+
+ return (
+ <AuthScene notes={notesFor(policyRequest, policyRequestMissing)}>
+ <AuthSceneCard>
+ {policyRequestMissing ? (
+ <>
+ <AuthCardTitle title="Request not found" />
+ <AuthBanner variant="danger">
+ Couldn't load this request. It may not exist, or you may not have access to this project.
+ </AuthBanner>
+ </>
+ ) : !policyRequest ? (
+ <LemonSkeleton className="h-60" active={policyRequestLoading} />
+ ) : (
+ <RequestDetails
+ policyRequest={policyRequest}
+ resolving={resolving}
+ onApprove={approve}
+ onReject={reject}
+ />
+ )}
+ </AuthSceneCard>
+ </AuthScene>
+ )
+}
+
+function RequestDetailTable({
+ policyRequest,
+ isPending,
+}: {
+ policyRequest: WorkloadTrustPolicyRequestApi
+ isPending: boolean
+}): JSX.Element {
+ const { currentTeam } = useValues(teamLogic)
+ const { currentOrganization } = useValues(organizationLogic)
+ const claimLabels = policyRequest.claim_labels
+ const conditions = policyRequest.conditions ?? {}
+ // A claim the provider no longer offers still shows, so the admin sees every condition they approve.
+ const conditionClaims = [...new Set([...Object.keys(claimLabels.conditions), ...Object.keys(conditions)])]
+
+ return (
+ <div className="border rounded px-3">
+ {/* An approval link can switch the app into another organization, so name where the access goes. */}
+ <DetailRow label="Project">
+ {currentTeam?.name} <span className="text-secondary">in {currentOrganization?.name}</span>
+ </DetailRow>
+ <DetailRow label="Name">{policyRequest.name}</DetailRow>
+ <DetailRow label="Provider">{policyRequest.provider_name ?? policyRequest.issuer}</DetailRow>
+ <DetailRow label={claimLabels.subject_name}>
+ <span className="font-mono">{policyRequest.subject_name}</span>
+ </DetailRow>
+ <DetailRow label={claimLabels.subject}>
+ <span className="font-mono">{policyRequest.subject}</span>
+ </DetailRow>
+ {conditionClaims.map((claim) => (
+ <DetailRow key={claim} label={claimLabels.conditions[claim] ?? claim}>
+ {conditions[claim] || <span className="text-secondary">Any value</span>}
+ </DetailRow>
+ ))}
+ <DetailRow label="Scopes">
+ <span className="flex flex-wrap gap-1">
+ {policyRequest.scopes.map((scope) => (
+ <LemonTag key={scope} type={scope in policyRequest.risky_scopes ? 'warning' : 'default'}>
+ {scope}
+ </LemonTag>
+ ))}
+ </span>
+ </DetailRow>
+ <DetailRow label={isPending ? 'Expires' : 'Requested'}>
+ <TZLabel time={isPending ? policyRequest.expires_at : policyRequest.created_at} />
+ </DetailRow>
+ </div>
+ )
+}
+
+function RequestActions({
+ policyRequest,
+ resolving,
+ onApprove,
+ onReject,
+}: {
+ policyRequest: WorkloadTrustPolicyRequestApi
+ resolving: 'approve' | 'reject' | null
+ onApprove: () => void
+ onReject: () => void
+}): JSX.Element {
+ if (!policyRequest.can_approve) {
+ return (
+ <AuthBanner variant="note">
+ Only organization admins and owners can approve this request
+ {policyRequest.approvers.length > 0 ? `: ${policyRequest.approvers.join(', ')}` : ''}. Send them this
+ page's link.
+ </AuthBanner>
+ )
+ }
+
+ return (
+ <div className="flex flex-col gap-2">
+ <LemonButton
+ type="primary"
+ size="large"
+ fullWidth
+ center
+ onClick={onApprove}
+ loading={resolving === 'approve'}
+ disabledReason={resolving ? 'Saving' : undefined}
+ data-attr="workload-trust-policy-request-approve"
+ >
+ Approve
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ status="danger"
+ fullWidth
+ center
+ onClick={onReject}
+ loading={resolving === 'reject'}
+ disabledReason={resolving ? 'Saving' : undefined}
+ data-attr="workload-trust-policy-request-reject"
+ >
+ Reject
+ </LemonButton>
+ </div>
+ )
+}
+
+function RequestDetails({
+ policyRequest,
+ resolving,
+ onApprove,
+ onReject,
+}: {
+ policyRequest: WorkloadTrustPolicyRequestApi
+ resolving: 'approve' | 'reject' | null
+ onApprove: () => void
+ onReject: () => void
+}): JSX.Element {
+ const isPending = policyRequest.status === 'pending'
+ const riskyScopes = Object.entries(policyRequest.risky_scopes)
+
+ return (
+ <div className="flex flex-col gap-4">
+ <AuthCardTitle
+ className="mb-0"
+ title={isPending ? 'Trust this workload?' : `This request was ${policyRequest.status}`}
+ sub={<RequesterLine policyRequest={policyRequest} />}
+ />
+
+ {isPending ? (
+ <p className="m-0 text-sm">
+ Approving adds a trusted workload to this project. Workloads that match it get short-lived tokens
+ that act as the organization owner, with only the scopes below.
+ </p>
+ ) : null}
+
+ <RequestDetailTable policyRequest={policyRequest} isPending={isPending} />
+
+ {isPending && riskyScopes.length > 0 ? (
+ <AuthBanner variant="warning">
+ <p className="m-0 font-semibold">Add these scopes with care</p>
+ <ul className="m-0 mt-1 pl-4 list-disc">
+ {riskyScopes.map(([scope, warning]) => (
+ <li key={scope}>
+ <code>{scope}</code>: {warning}
+ </li>
+ ))}
+ </ul>
+ </AuthBanner>
+ ) : null}
+
+ {policyRequest.status === 'approved' ? (
+ <AuthBanner variant="success">
+ Approved
+ {policyRequest.resolved_by ? ` by ${fullNameOrEmail(policyRequest.resolved_by)}` : ''}. The policy
+ is active. <Link to={urls.settings('environment-trusted-workloads')}>See trusted workloads</Link>
+ </AuthBanner>
+ ) : null}
+
+ {isPending ? (
+ <RequestActions
+ policyRequest={policyRequest}
+ resolving={resolving}
+ onApprove={onApprove}
+ onReject={onReject}
+ />
+ ) : null}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/workload-trust-policy-request/workloadTrustPolicyRequestLogic.ts b/frontend/src/scenes/workload-trust-policy-request/workloadTrustPolicyRequestLogic.ts
new file mode 100644
index 000000000000..7082ba64bb6c
--- /dev/null
+++ b/frontend/src/scenes/workload-trust-policy-request/workloadTrustPolicyRequestLogic.ts
@@ -0,0 +1,188 @@
+import { MakeLogicType, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import { readableErrorMessage } from 'lib/api-error'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { Scene } from 'scenes/sceneTypes'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import {
+ workloadTrustPolicyRequestsApproveCreate,
+ workloadTrustPolicyRequestsRejectCreate,
+ workloadTrustPolicyRequestsRetrieve,
+} from '~/generated/core/api'
+import type { WorkloadTrustPolicyRequestApi } from '~/generated/core/api.schemas'
+import { Breadcrumb } from '~/types'
+
+export interface WorkloadTrustPolicyRequestLogicProps {
+ id: string
+}
+
+async function resolveRequest(
+ resolve: () => Promise<WorkloadTrustPolicyRequestApi>,
+ event: string,
+ successMessage: string,
+ failureMessage: string
+): Promise<WorkloadTrustPolicyRequestApi> {
+ try {
+ const resolved = await resolve()
+ posthog.capture(event)
+ lemonToast.success(successMessage)
+ return resolved
+ } catch (error) {
+ lemonToast.error(readableErrorMessage(error) ?? failureMessage)
+ throw error
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workloadTrustPolicyRequestLogicValues {
+ currentTeamId: number | null // teamLogic
+ breadcrumbs: Breadcrumb[]
+ policyRequest: WorkloadTrustPolicyRequestApi | null
+ policyRequestLoading: boolean
+ policyRequestMissing: boolean
+ resolving: 'approve' | 'reject' | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workloadTrustPolicyRequestLogicActions {
+ approve: () => any
+ approveFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ approveSuccess: (
+ policyRequest: WorkloadTrustPolicyRequestApi,
+ payload?: any
+ ) => {
+ policyRequest: WorkloadTrustPolicyRequestApi
+ payload?: any
+ }
+ loadPolicyRequest: () => any
+ loadPolicyRequestFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPolicyRequestSuccess: (
+ policyRequest: WorkloadTrustPolicyRequestApi,
+ payload?: any
+ ) => {
+ policyRequest: WorkloadTrustPolicyRequestApi
+ payload?: any
+ }
+ reject: () => any
+ rejectFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ rejectSuccess: (
+ policyRequest: WorkloadTrustPolicyRequestApi,
+ payload?: any
+ ) => {
+ policyRequest: WorkloadTrustPolicyRequestApi
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface workloadTrustPolicyRequestLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ breadcrumbs: (policyRequest: WorkloadTrustPolicyRequestApi | null) => Breadcrumb[]
+ }
+}
+
+export type workloadTrustPolicyRequestLogicType = MakeLogicType<
+ workloadTrustPolicyRequestLogicValues,
+ workloadTrustPolicyRequestLogicActions,
+ WorkloadTrustPolicyRequestLogicProps,
+ workloadTrustPolicyRequestLogicMeta
+>
+
+export const workloadTrustPolicyRequestLogic = kea<workloadTrustPolicyRequestLogicType>([
+ path(['scenes', 'workload-trust-policy-request', 'workloadTrustPolicyRequestLogic']),
+ props({} as WorkloadTrustPolicyRequestLogicProps),
+ key(({ id }) => id),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId']],
+ })),
+
+ loaders(({ props, values }) => ({
+ policyRequest: [
+ null as WorkloadTrustPolicyRequestApi | null,
+ {
+ loadPolicyRequest: async () =>
+ await workloadTrustPolicyRequestsRetrieve(String(values.currentTeamId), props.id),
+ approve: async () =>
+ await resolveRequest(
+ () => workloadTrustPolicyRequestsApproveCreate(String(values.currentTeamId), props.id),
+ 'workload trust policy request approved',
+ 'Request approved. The workload is now trusted.',
+ "Couldn't approve the request. Try again."
+ ),
+ reject: async () =>
+ await resolveRequest(
+ () => workloadTrustPolicyRequestsRejectCreate(String(values.currentTeamId), props.id),
+ 'workload trust policy request rejected',
+ 'Request rejected',
+ "Couldn't reject the request. Try again."
+ ),
+ },
+ ],
+ })),
+
+ reducers({
+ resolving: [
+ null as 'approve' | 'reject' | null,
+ {
+ approve: () => 'approve',
+ reject: () => 'reject',
+ approveSuccess: () => null,
+ approveFailure: () => null,
+ rejectSuccess: () => null,
+ rejectFailure: () => null,
+ },
+ ],
+ policyRequestMissing: [
+ false,
+ {
+ loadPolicyRequest: () => false,
+ loadPolicyRequestFailure: () => true,
+ },
+ ],
+ }),
+
+ selectors({
+ breadcrumbs: [
+ (s) => [s.policyRequest],
+ (policyRequest: WorkloadTrustPolicyRequestApi | null): Breadcrumb[] => [
+ {
+ key: Scene.Settings,
+ name: 'Trusted workloads',
+ path: urls.settings('environment-trusted-workloads'),
+ },
+ {
+ key: Scene.WorkloadTrustPolicyRequest,
+ name: policyRequest ? `Request: ${policyRequest.name}` : 'Policy request',
+ },
+ ],
+ ],
+ }),
+
+ afterMount(({ actions }) => {
+ actions.loadPolicyRequest()
+ posthog.capture('workload trust policy request viewed')
+ }),
+])
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index f177776fb40d..83aedbe9db6c 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6152,6 +6152,7 @@ export enum ActivityScope {
ORGANIZATION_DOMAIN = 'OrganizationDomain',
OAUTH_APPLICATION = 'OAuthApplication',
WORKLOAD_TRUST_POLICY = 'WorkloadTrustPolicy',
+ WORKLOAD_TRUST_POLICY_REQUEST = 'WorkloadTrustPolicyRequest',
LEGAL_DOCUMENT = 'LegalDocument',
ERROR_TRACKING_ISSUE = 'ErrorTrackingIssue',
DATA_WAREHOUSE_EXPRESSION = 'DataWarehouseExpression',
diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.py
index 5a662a667fca..c5f8e6592005 100644
--- a/posthog/api/rest_router.py
+++ b/posthog/api/rest_router.py
@@ -21,7 +21,7 @@ from posthog.api.sdk_health import SdkHealthViewSet
from posthog.api.wizard import http as wizard
from posthog.products import load_product_modules
from posthog.settings import EE_AVAILABLE
-from posthog.workload_identity.trust_policy import WorkloadTrustPolicyViewSet
+from posthog.workload_identity.trust_policy import WorkloadTrustPolicyRequestViewSet, WorkloadTrustPolicyViewSet
from ee.api.quota_limits import QuotaLimitsViewSet
from ee.api.vercel import vercel_installation, vercel_product, vercel_proxy, vercel_resource
@@ -550,6 +550,12 @@ projects_router.register(
projects_router.register(
r"workload_trust_policies", WorkloadTrustPolicyViewSet, "project_workload_trust_policies", ["project_id"]
)
+projects_router.register(
+ r"workload_trust_policy_requests",
+ WorkloadTrustPolicyRequestViewSet,
+ "project_workload_trust_policy_requests",
+ ["project_id"],
+)
projects_router.register(
r"data_color_themes", data_color_theme.DataColorThemeViewSet, "project_data_color_themes", ["team_id"]
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index 6dd3fc37a844..1f35d0f37f1b 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -2503,6 +2503,11 @@ class TestTimeSensitivePermissions(APIBaseTest):
"delete",
"/api/projects/@current/workload_trust_policies/00000000-0000-0000-0000-000000000001/",
),
+ (
+ "workload_trust_policy_request_approve",
+ "post",
+ "/api/projects/@current/workload_trust_policy_requests/00000000-0000-0000-0000-000000000001/approve/",
+ ),
]
)
def test_credential_writes_require_recent_authentication(self, _name, method, url):
diff --git a/posthog/migrations/1425_workload_trust_policy_request.py b/posthog/migrations/1425_workload_trust_policy_request.py
new file mode 100644
index 000000000000..566d04e2a569
--- /dev/null
+++ b/posthog/migrations/1425_workload_trust_policy_request.py
@@ -0,0 +1,122 @@
+# Generated by Django 6.1.2 on 2026-11-02 19:49
+
+import django.db.models.deletion
+import django.contrib.postgres.fields
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+import posthog.models.workload_trust_policy
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1424_workload_trust_policy"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="WorkloadTrustPolicyRequest",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(max_length=200)),
+ ("issuer", models.CharField(max_length=255)),
+ ("subject_name", models.CharField(max_length=255)),
+ ("subject", models.CharField(max_length=255)),
+ ("conditions", models.JSONField(blank=True, default=dict)),
+ (
+ "scopes",
+ django.contrib.postgres.fields.ArrayField(
+ base_field=models.CharField(max_length=100), default=list
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("pending", "Pending"),
+ ("approved", "Approved"),
+ ("rejected", "Rejected"),
+ ("expired", "Expired"),
+ ],
+ default="pending",
+ max_length=16,
+ ),
+ ),
+ (
+ "expires_at",
+ models.DateTimeField(default=posthog.models.workload_trust_policy._default_request_expiry),
+ ),
+ ("resolved_at", models.DateTimeField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "policy",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="posthog.workloadtrustpolicy",
+ ),
+ ),
+ (
+ "requested_via_application",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="posthog.oauthapplication",
+ ),
+ ),
+ (
+ "requested_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "resolved_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ db_index=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "indexes": [
+ models.Index(
+ fields=["team", "status", "-created_at"],
+ name="posthog_workload_req_team_idx",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 214632be9e85..ac5fc3c07881 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1424_workload_trust_policy
+1425_workload_trust_policy_request
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index 36b0b65fd29b..3cb7bdf89975 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -10,7 +10,7 @@ from .activity_logging.activity_log import ActivityLog
from .activity_logging.notification_viewed import NotificationViewed
from .async_deletion import AsyncDeletion, DeletionType
from .async_migration import AsyncMigration, AsyncMigrationError, MigrationStatus
-from .workload_trust_policy import WorkloadTrustPolicy
+from .workload_trust_policy import WorkloadTrustPolicy, WorkloadTrustPolicyRequest
from .column_configuration import ColumnConfiguration
from .comment import Comment, CommentSlackThread
from .core_event import CoreEvent
@@ -97,6 +97,7 @@ __all__ = [
"AsyncMigration",
"AsyncMigrationError",
"WorkloadTrustPolicy",
+ "WorkloadTrustPolicyRequest",
"CIMDVerificationToken",
"ColumnConfiguration",
"CoreEvent",
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 2686bb74b58f..1120285bcb8b 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -104,6 +104,7 @@ ActivityScope = Literal[
"ProjectSecretAPIKey",
"OAuthApplication",
"WorkloadTrustPolicy",
+ "WorkloadTrustPolicyRequest",
"User",
"Action",
"AccountView",
diff --git a/posthog/models/activity_logging/signal_handlers.py b/posthog/models/activity_logging/signal_handlers.py
index da5410b1757d..5c3e9b8d7de3 100644
--- a/posthog/models/activity_logging/signal_handlers.py
+++ b/posthog/models/activity_logging/signal_handlers.py
@@ -53,7 +53,7 @@ from posthog.models.organization_invite import OrganizationInvite
from posthog.models.project_secret_api_key import ProjectSecretAPIKey
from posthog.models.signals import model_activity_signal, mutable_receiver
from posthog.models.user import User
-from posthog.models.workload_trust_policy import WorkloadTrustPolicy
+from posthog.models.workload_trust_policy import WorkloadTrustPolicy, WorkloadTrustPolicyRequest
from posthog.session.activity import session_activity_credential
from posthog.session.models import Session
from posthog.utils import get_ip_address, get_short_user_agent
@@ -495,35 +495,65 @@ def handle_oauth_application_scopes_change(
)
-@mutable_receiver(model_activity_signal, sender=WorkloadTrustPolicy)
-def handle_workload_trust_policy_change(
- sender: type[WorkloadTrustPolicy],
+def _log_workload_trust_activity(
scope: ActivityScope,
- before_update: WorkloadTrustPolicy | None,
- after_update: WorkloadTrustPolicy | None,
+ before_update: WorkloadTrustPolicy | WorkloadTrustPolicyRequest | None,
+ after_update: WorkloadTrustPolicy | WorkloadTrustPolicyRequest | None,
activity: str,
user: User | None,
- was_impersonated: bool = False,
- **kwargs,
+ was_impersonated: bool,
) -> None:
- policy = after_update or before_update
- if policy is None:
+ instance = after_update or before_update
+ if instance is None:
return
log_activity(
- organization_id=policy.team.organization_id,
- team_id=policy.team_id,
+ organization_id=instance.team.organization_id,
+ team_id=instance.team_id,
user=user,
was_impersonated=was_impersonated,
- item_id=policy.pk,
+ item_id=instance.pk,
scope=scope,
activity=activity,
detail=Detail(
- name=policy.name,
+ name=instance.name,
changes=changes_between(scope, previous=before_update, current=after_update),
),
)
+@mutable_receiver(model_activity_signal, sender=WorkloadTrustPolicy)
+def handle_workload_trust_policy_change(
+ sender: type[WorkloadTrustPolicy],
+ scope: ActivityScope,
+ before_update: WorkloadTrustPolicy | None,
+ after_update: WorkloadTrustPolicy | None,
+ activity: str,
+ user: User | None,
+ was_impersonated: bool = False,
+ **kwargs,
+) -> None:
+ _log_workload_trust_activity(scope, before_update, after_update, activity, user, was_impersonated)
+
+
+@mutable_receiver(model_activity_signal, sender=WorkloadTrustPolicyRequest)
+def handle_workload_trust_policy_request_change(
+ sender: type[WorkloadTrustPolicyRequest],
+ scope: ActivityScope,
+ before_update: WorkloadTrustPolicyRequest | None,
+ after_update: WorkloadTrustPolicyRequest | None,
+ activity: str,
+ user: User | None,
+ was_impersonated: bool = False,
+ **kwargs,
+) -> None:
+ if activity == "updated":
+ # A request is immutable apart from its resolution, so an update is an approval or a rejection.
+ if before_update is None or after_update is None or before_update.status == after_update.status:
+ return
+ activity = after_update.status
+ _log_workload_trust_activity(scope, before_update, after_update, activity, user, was_impersonated)
+
+
# --- Receivers relocated from posthog.api viewset modules ---------------------------------
# These used to live next to their viewsets and wired in as an import side effect of the
# eager API router. With the lazy router, AppConfig.ready() imports this module instead, so
diff --git a/posthog/models/workload_trust_policy.py b/posthog/models/workload_trust_policy.py
index efca621e0d26..7a2da3bfbee0 100644
--- a/posthog/models/workload_trust_policy.py
+++ b/posthog/models/workload_trust_policy.py
@@ -1,10 +1,12 @@
from __future__ import annotations
from collections.abc import Iterable
+from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from django.db import models
+from django.utils import timezone
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
@@ -13,7 +15,7 @@ from posthog.scopes import UNPRIVILEGED_SCOPES
# A policy can grant any unprivileged scope except the ones that let a workload token outlive itself or
# widen its own access. Risky scopes that stay grantable carry a warning from `RISKY_SCOPE_WARNINGS`.
-# - `workload_trust_policy` would let a workload change the policy behind its token.
+# - `workload_trust_policy` and `workload_trust_policy_request` 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`, `autoresearch:write` and `hog_flow:write` (a workflow can create a task) start the
@@ -30,6 +32,8 @@ WORKLOAD_TRUST_POLICY_DENIED_SCOPES: frozenset[str] = frozenset(
{
"workload_trust_policy:read",
"workload_trust_policy:write",
+ "workload_trust_policy_request:read",
+ "workload_trust_policy_request:write",
"autoresearch:write",
"batch_export:write",
"business_knowledge:write",
@@ -70,6 +74,10 @@ def workload_trust_policies_settings_url(team_id: int) -> str:
return f"{settings.SITE_URL}/project/{team_id}/settings/environment-trusted-workloads"
+def workload_trust_policy_request_url(team_id: int, request_id: str) -> str:
+ return f"{settings.SITE_URL}/project/{team_id}/workload-trust-policy-requests/{request_id}"
+
+
class WorkloadTrustPolicy(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
"""Lets a workload, such as a CI job, exchange its OIDC token for a short-lived project token. Azure
calls this a federated identity credential, AWS a role trust policy, Google Cloud a workload identity
@@ -110,3 +118,79 @@ class WorkloadTrustPolicy(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
def __str__(self) -> str:
return f"WorkloadTrustPolicy(team={self.team_id}, name={self.name!r})"
+
+
+WORKLOAD_TRUST_POLICY_REQUEST_LIFETIME = timedelta(hours=24)
+
+
+def _default_request_expiry() -> datetime:
+ return timezone.now() + WORKLOAD_TRUST_POLICY_REQUEST_LIFETIME
+
+
+class WorkloadTrustPolicyRequest(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
+ """A member's request for a workload trust policy. It grants nothing until an organization admin or owner
+ approves it in the browser, which creates the policy.
+
+ The requested conditions never change after creation, so the admin approves exactly what they saw.
+ """
+
+ class Status(models.TextChoices):
+ PENDING = "pending", "Pending"
+ APPROVED = "approved", "Approved"
+ REJECTED = "rejected", "Rejected"
+ EXPIRED = "expired", "Expired"
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, db_index=False)
+ name = models.CharField(max_length=200)
+ issuer = models.CharField(max_length=255)
+ subject_name = models.CharField(max_length=255)
+ subject = models.CharField(max_length=255)
+ # Normalized like `WorkloadTrustPolicy.conditions`, so approving copies it unchanged.
+ conditions = models.JSONField(default=dict, blank=True)
+ scopes = ArrayField(models.CharField(max_length=100), default=list)
+ # Never stored as `expired`: a pending request past `expires_at` reads as expired through `effective_status`.
+ status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING)
+ requested_by = models.ForeignKey(
+ settings.AUTH_USER_MODEL,
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ related_name="+",
+ )
+ # The OAuth app the request came through, so the approval page names it and shows whether PostHog
+ # verified it. Null when the request came through another credential.
+ requested_via_application = models.ForeignKey(
+ "posthog.OAuthApplication",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ related_name="+",
+ )
+ expires_at = models.DateTimeField(default=_default_request_expiry)
+ resolved_by = models.ForeignKey(
+ settings.AUTH_USER_MODEL,
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ related_name="+",
+ )
+ resolved_at = models.DateTimeField(null=True, blank=True)
+ policy = models.ForeignKey(WorkloadTrustPolicy, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ indexes = [models.Index(fields=["team", "status", "-created_at"], name="posthog_workload_req_team_idx")]
+
+ @property
+ def effective_status(self) -> str:
+ if self.status == self.Status.PENDING and timezone.now() >= self.expires_at:
+ return self.Status.EXPIRED
+ return self.status
+
+ def __str__(self) -> str:
+ return (
+ f"WorkloadTrustPolicyRequest(team={self.team_id}, subject_name={self.subject_name!r}, status={self.status})"
+ )
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index fe8f35012c71..c4b86ba687fc 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -451,6 +451,26 @@ class CodexConnectUserThrottle(UserRateThrottle):
rate = "10/hour"
+class _WorkloadTrustPolicyRequestThrottle(SimpleRateThrottle):
+ """One bucket per user and project, because each request asks the organization's admins to act."""
+
+ def get_cache_key(self, request: "Request", view: "APIView") -> str | None:
+ if not request.user.is_authenticated:
+ return None
+ team_id = PersonalApiKeyRateThrottle.safely_get_team_id_from_view(view)
+ return self.cache_format % {"scope": self.scope, "ident": f"{team_id}:{request.user.pk}"}
+
+
+class WorkloadTrustPolicyRequestBurstThrottle(_WorkloadTrustPolicyRequestThrottle):
+ scope = "workload_trust_policy_request_burst"
+ rate = "10/hour"
+
+
+class WorkloadTrustPolicyRequestSustainedThrottle(_WorkloadTrustPolicyRequestThrottle):
+ scope = "workload_trust_policy_request_sustained"
+ rate = "30/day"
+
+
class BurstRateThrottle(PersonalApiKeyRateThrottle):
# Throttle class that's applied on all endpoints (except for capture + decide)
# Intended to block quick bursts of requests, per project
diff --git a/posthog/scopes.py b/posthog/scopes.py
index a110cc69612e..f7044cae4817 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -156,6 +156,7 @@ APIScopeObject = Literal[
"wizard_session",
"wizard_run",
"workload_trust_policy",
+ "workload_trust_policy_request",
]
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index c6d381894c13..ec89e0469410 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -5,6 +5,7 @@
# restore its AppConfig.ready() wiring instead of deleting the line.
experiment_changed:ee.vercel.receivers.sync_experiment_experimentation_item
model_activity:posthog.models.activity_logging.signal_handlers.handle_workload_trust_policy_change
+model_activity:posthog.models.activity_logging.signal_handlers.handle_workload_trust_policy_request_change
model_activity:posthog.models.activity_logging.signal_handlers.handle_identity_provider_config_change
model_activity:posthog.models.activity_logging.signal_handlers.handle_oauth_application_scopes_change
model_activity:posthog.models.activity_logging.signal_handlers.handle_organization_change
diff --git a/posthog/workload_identity/test/test_trust_policy.py b/posthog/workload_identity/test/test_trust_policy.py
index 129f5a395ff0..da4abfc1967e 100644
--- a/posthog/workload_identity/test/test_trust_policy.py
+++ b/posthog/workload_identity/test/test_trust_policy.py
@@ -1,9 +1,10 @@
-from datetime import timedelta
+from datetime import UTC, datetime, timedelta
from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
+from django.core.cache import cache
from django.db import IntegrityError, transaction
from django.utils import timezone
@@ -17,7 +18,7 @@ from posthog.models.instance_setting import set_instance_setting
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
-from posthog.models.workload_trust_policy import WorkloadTrustPolicy
+from posthog.models.workload_trust_policy import WorkloadTrustPolicy, WorkloadTrustPolicyRequest
from posthog.tasks.email import send_workload_trust_policy_changed
from posthog.tasks.test.utils_email_tests import mock_email_messages
from posthog.workload_identity.test.fixtures import (
@@ -40,6 +41,32 @@ def _payload(**overrides: Any) -> dict[str, Any]:
}
+def use_token(test: APIBaseTest, kind: str, oauth_scope: str) -> None:
+ if kind == "personal_api_key":
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(user=test.user, label="ci", secure_value=hash_key_value(token), scopes=["*"])
+ else:
+ application = OAuthApplication.objects.create(
+ name="Test app",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ organization=test.organization,
+ user=test.user,
+ )
+ token = f"pha_workload_trust_test_{application.pk}"
+ OAuthAccessToken.objects.create(
+ user=test.user,
+ application=application,
+ token=token,
+ expires=timezone.now() + timedelta(hours=1),
+ scope=oauth_scope,
+ )
+ test.client.logout()
+ test.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
+
+
@with_fake_workload_provider()
class TestWorkloadTrustPolicyAPI(APIBaseTest):
def setUp(self) -> None:
@@ -55,29 +82,7 @@ class TestWorkloadTrustPolicyAPI(APIBaseTest):
return WorkloadTrustPolicy.objects.for_team((team or self.team).id).create(team=team or self.team, **fields)
def _use_token(self, kind: str) -> None:
- if kind == "personal_api_key":
- token = generate_random_token_personal()
- PersonalAPIKey.objects.create(user=self.user, label="ci", secure_value=hash_key_value(token), scopes=["*"])
- else:
- application = OAuthApplication.objects.create(
- name="Test app",
- client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
- authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
- redirect_uris="https://example.com/callback",
- algorithm="RS256",
- organization=self.organization,
- user=self.user,
- )
- token = "pha_workload_trust_policy_test_token"
- OAuthAccessToken.objects.create(
- user=self.user,
- application=application,
- token=token,
- expires=timezone.now() + timedelta(hours=1),
- scope="workload_trust_policy:read workload_trust_policy:write",
- )
- self.client.logout()
- self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
+ use_token(self, kind, "workload_trust_policy:read workload_trust_policy:write")
@parameterized.expand(
[
@@ -308,3 +313,212 @@ class TestSendWorkloadTrustPolicyChangedEmail(APIBaseTest):
assert sent[0].use_http is True
assert sent[0].template_name in CUSTOMER_IO_TEMPLATE_ID_MAP
assert sent[0].template_name in WORKFLOWS_TEMPLATE_ID_MAP
+
+
+@with_fake_workload_provider()
+class TestWorkloadTrustPolicyRequestAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+ self.url = f"/api/projects/{self.team.id}/workload_trust_policy_requests/"
+
+ def _set_level(self, level: OrganizationMembership.Level) -> None:
+ self.organization_membership.level = level
+ self.organization_membership.save()
+
+ def _create_request(self, **overrides: Any) -> WorkloadTrustPolicyRequest:
+ return WorkloadTrustPolicyRequest.objects.for_team(self.team.id).create(
+ team=self.team, requested_by=self.user, **{**_payload(), **overrides}
+ )
+
+ @parameterized.expand(
+ [
+ ("unverified_app", False, False, False),
+ ("verified_app", True, False, True),
+ ("first_party_app", False, True, True),
+ ]
+ )
+ def test_member_asks_for_a_policy_with_an_oauth_token(
+ self, _name: str, is_verified: bool, is_first_party: bool, expected_verified: bool
+ ) -> None:
+ owner = User.objects.create_and_join(
+ self.organization, "[email protected]", None, first_name="Olive", level=OrganizationMembership.Level.OWNER
+ )
+ owner.last_name = "Owner"
+ owner.save()
+ use_token(self, "oauth_token", "workload_trust_policy_request:write")
+ OAuthApplication.objects.filter(name="Test app").update(is_verified=is_verified, is_first_party=is_first_party)
+
+ response = self.client.post(self.url, _payload(), format="json")
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ body = response.json()
+ assert body["status"] == "pending"
+ assert body["can_approve"] is False
+ assert body["approvers"] == ["Olive Owner"]
+ assert body["requested_via"] == "Test app"
+ assert body["requested_via_verified"] is expected_verified
+ assert body["approval_url"].endswith(f"/project/{self.team.id}/workload-trust-policy-requests/{body['id']}")
+ assert not WorkloadTrustPolicy.objects.for_team(self.team.id).exists()
+
+ OAuthApplication.objects.filter(name="Test app").update(
+ name="Renamed app", is_verified=False, is_first_party=False
+ )
+ shown = self.client.get(f"{self.url}{body['id']}/").json()
+
+ assert (shown["requested_via"], shown["requested_via_verified"]) == ("Renamed app", False)
+
+ @parameterized.expand([("visible", None, ["Olive Owner"]), ("hidden_member_list", set(), [])])
+ def test_member_sees_only_the_approvers_the_members_list_shows_them(
+ self, _name: str, visible_membership_ids: set[str] | None, expected_approvers: list[str]
+ ) -> None:
+ owner = User.objects.create_and_join(
+ self.organization, "[email protected]", None, first_name="Olive", level=OrganizationMembership.Level.OWNER
+ )
+ owner.last_name = "Owner"
+ owner.save()
+ policy_request = self._create_request()
+
+ with patch(
+ "posthog.workload_identity.trust_policy.restricted_visible_membership_ids",
+ return_value=visible_membership_ids,
+ ):
+ body = self.client.get(f"{self.url}{policy_request.id}/").json()
+
+ assert body["approvers"] == expected_approvers
+
+ def test_admin_sees_they_can_approve_and_the_risky_scopes(self) -> None:
+ self._set_level(OrganizationMembership.Level.ADMIN)
+ policy_request = self._create_request(scopes=["organization_member:write", "annotation:write"])
+
+ body = self.client.get(f"{self.url}{policy_request.id}/").json()
+
+ assert body["can_approve"] is True
+ assert body["approvers"] == []
+ assert list(body["risky_scopes"]) == ["organization_member:write"]
+
+ def test_a_token_minted_while_impersonating_cannot_ask_for_a_policy(self) -> None:
+ staff = User.objects.create_user(email="[email protected]", password=None, first_name="Staff", is_staff=True)
+ use_token(self, "oauth_token", "workload_trust_policy_request:write")
+ OAuthAccessToken.objects.filter(user=self.user).update(impersonated_by=staff)
+
+ response = self.client.post(self.url, _payload(), format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert not WorkloadTrustPolicyRequest.objects.for_team(self.team.id).exists()
+
+ def test_creating_a_request_needs_the_request_scope(self) -> None:
+ use_token(self, "oauth_token", "workload_trust_policy:read")
+
+ response = self.client.post(self.url, _payload(), format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_requests_cannot_be_edited(self) -> None:
+ policy_request = self._create_request()
+
+ response = self.client.patch(f"{self.url}{policy_request.id}/", {"scopes": ["insight:write"]}, format="json")
+
+ assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
+
+ @parameterized.expand(
+ [
+ ("member_session", OrganizationMembership.Level.MEMBER, None),
+ ("owner_personal_api_key", OrganizationMembership.Level.OWNER, "personal_api_key"),
+ ("owner_oauth_token", OrganizationMembership.Level.OWNER, "oauth_token"),
+ ]
+ )
+ def test_only_an_admin_browser_session_can_approve(
+ self, _name: str, level: OrganizationMembership.Level, token_kind: str | None
+ ) -> None:
+ self._set_level(level)
+ policy_request = self._create_request()
+ if token_kind:
+ use_token(self, token_kind, "workload_trust_policy_request:write")
+
+ response = self.client.post(f"{self.url}{policy_request.id}/approve/")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ policy_request.refresh_from_db()
+ assert policy_request.status == WorkloadTrustPolicyRequest.Status.PENDING
+ assert not WorkloadTrustPolicy.objects.for_team(self.team.id).exists()
+
+ @parameterized.expand([("approve",), ("reject",)])
+ def test_impersonated_sessions_cannot_resolve_requests(self, resolution: str) -> None:
+ self._set_level(OrganizationMembership.Level.OWNER)
+ policy_request = self._create_request()
+
+ with patch("posthog.workload_identity.trust_policy.is_impersonated", return_value=True):
+ read_response = self.client.get(f"{self.url}{policy_request.id}/")
+ response = self.client.post(f"{self.url}{policy_request.id}/{resolution}/")
+
+ assert read_response.status_code == status.HTTP_200_OK
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ policy_request.refresh_from_db()
+ assert policy_request.status == WorkloadTrustPolicyRequest.Status.PENDING
+
+ @patch("posthog.workload_identity.trust_policy.send_workload_trust_policy_changed")
+ def test_admin_approves_their_own_request_which_creates_the_policy(self, mock_send: MagicMock) -> None:
+ self._set_level(OrganizationMembership.Level.ADMIN)
+ created = self.client.post(
+ self.url, _payload(conditions={"environment": "", "ref": "refs/heads/main"}), format="json"
+ )
+ policy_request = WorkloadTrustPolicyRequest.objects.for_team(self.team.id).get(pk=created.json()["id"])
+
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.post(f"{self.url}{policy_request.id}/approve/")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ policy = WorkloadTrustPolicy.objects.for_team(self.team.id).get()
+ assert response.json()["status"] == "approved"
+ assert response.json()["policy_id"] == str(policy.id)
+ assert policy_request.conditions == {"ref": "refs/heads/main"}
+ assert (policy.subject, policy.conditions, sorted(policy.scopes), policy.created_by_id) == (
+ "1234",
+ {"ref": "refs/heads/main"},
+ ["annotation:write", "error_tracking:write"],
+ self.user.id,
+ )
+ assert [call.args[3] for call in mock_send.delay.call_args_list] == ["created"]
+ assert list(
+ ActivityLog.objects.filter(scope="WorkloadTrustPolicyRequest", item_id=str(policy_request.id))
+ .order_by("created_at")
+ .values_list("activity", flat=True)
+ ) == ["created", "approved"]
+
+ def test_admin_rejects_a_request(self) -> None:
+ self._set_level(OrganizationMembership.Level.ADMIN)
+ policy_request = self._create_request()
+
+ response = self.client.post(f"{self.url}{policy_request.id}/reject/")
+
+ assert response.json()["status"] == "rejected"
+ assert not WorkloadTrustPolicy.objects.for_team(self.team.id).exists()
+
+ @parameterized.expand([("expired",), ("already_rejected",)])
+ def test_a_request_that_is_not_pending_cannot_be_approved(self, case: str) -> None:
+ self._set_level(OrganizationMembership.Level.ADMIN)
+ if case == "expired":
+ policy_request = self._create_request(expires_at=datetime(2020, 1, 1, tzinfo=UTC))
+ else:
+ policy_request = self._create_request()
+ self.client.post(f"{self.url}{policy_request.id}/reject/")
+
+ response = self.client.post(f"{self.url}{policy_request.id}/approve/")
+ status_shown = self.client.get(f"{self.url}{policy_request.id}/").json()["status"]
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert status_shown == ("expired" if case == "expired" else "rejected")
+ assert not WorkloadTrustPolicy.objects.for_team(self.team.id).exists()
+
+ def test_requests_are_rate_limited_per_user_and_project(self) -> None:
+ for _ in range(10):
+ assert self.client.post(self.url, _payload(), format="json").status_code == status.HTTP_201_CREATED
+
+ throttled = self.client.post(self.url, _payload(), format="json")
+ other_member = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self.client.force_login(other_member)
+ other_member_response = self.client.post(self.url, _payload(), format="json")
+
+ assert throttled.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+ assert other_member_response.status_code == status.HTTP_201_CREATED
diff --git a/posthog/workload_identity/trust_policy.py b/posthog/workload_identity/trust_policy.py
index 3e97cb03e6f5..86e0986a9d32 100644
--- a/posthog/workload_identity/trust_policy.py
+++ b/posthog/workload_identity/trust_policy.py
@@ -3,17 +3,19 @@ token.
A policy hands out tokens that act as the organization owner, so it is a standing credential. Only an
organization admin or owner can read or write one, and writes need a browser session with recent
-authentication, so no token can create or widen a policy.
+authentication, so no token can create or widen a policy. Any member can ask for a policy through a request.
"""
import json
+import functools
from typing import Any, cast
from django.db import IntegrityError, transaction
from django.db.models import QuerySet
+from django.utils import timezone
from drf_spectacular.utils import extend_schema, extend_schema_field
-from rest_framework import serializers, viewsets
+from rest_framework import mixins, serializers, viewsets
from rest_framework.permissions import SAFE_METHODS, BasePermission
from rest_framework.request import Request
from rest_framework.response import Response
@@ -22,17 +24,27 @@ from rest_framework.views import APIView
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import action
-from posthog.auth import SessionAuthentication
+from posthog.auth import OAuthAccessTokenAuthentication, SessionAuthentication
from posthog.helpers.impersonation import is_impersonated
-from posthog.models import Team, User
+from posthog.models import OrganizationMembership, Team, User
+from posthog.models.oauth import OAuthApplication
from posthog.models.workload_trust_policy import (
CONDITION_VALUE_MAX_LENGTH,
CONDITIONS_MAX_BYTES,
WorkloadTrustPolicy,
+ WorkloadTrustPolicyRequest,
workload_trust_policy_grantable_scopes,
+ workload_trust_policy_request_url,
workload_trust_policy_scopes_not_grantable,
)
-from posthog.permissions import OrganizationAdminReadPermissions, TimeSensitiveActionPermission
+from posthog.organization_caching import get_cached_organization_membership
+from posthog.permissions import (
+ OrganizationAdminReadPermissions,
+ TimeSensitiveActionPermission,
+ get_organization_from_view,
+ get_required_organization_membership,
+)
+from posthog.rate_limit import WorkloadTrustPolicyRequestBurstThrottle, WorkloadTrustPolicyRequestSustainedThrottle
from posthog.scopes import RISKY_SCOPE_WARNINGS
from posthog.tasks.email import WorkloadTrustPolicyChange, send_workload_trust_policy_changed
from posthog.workload_identity.providers import (
@@ -42,6 +54,8 @@ from posthog.workload_identity.providers import (
normalize_issuer,
)
+from products.access_control.backend.facade.subject_access_control import restricted_visible_membership_ids
+
# A policy matches claim values exactly, so a character that reads as a pattern is refused rather than
# taken literally: an admin who types `acme/*` expects every workload under `acme` to match, and none would.
WILDCARD_CHARACTERS = frozenset("*?[]")
@@ -167,25 +181,6 @@ class CIScopeListField(serializers.ListField):
class WorkloadConditionsSerializerMixin(serializers.Serializer):
- def validate_issuer(self, value: str) -> str:
- provider = get_workload_provider_by_issuer(value)
- if provider is None:
- raise serializers.ValidationError("This issuer isn't a supported workload provider.")
- return normalize_issuer(provider.issuer)
-
- def validate_subject_name(self, value: str) -> str:
- return _validate_exact_value(value, FALLBACK_SUBJECT_NAME_LABEL)
-
- def validate_subject(self, value: str) -> str:
- return _validate_exact_value(value, FALLBACK_SUBJECT_LABEL)
-
- @extend_schema_field(WorkloadClaimLabelsSerializer)
- def get_claim_labels(self, instance: Any) -> dict[str, Any]:
- return workload_claim_labels(instance.issuer)
-
-
-class WorkloadTrustPolicySerializer(WorkloadConditionsSerializerMixin, serializers.ModelSerializer):
- name = serializers.CharField(max_length=200, help_text="A name that says what the policy is for.")
issuer = serializers.CharField(
max_length=255,
help_text="The OIDC issuer of the workload provider, from the list of supported providers.",
@@ -215,6 +210,30 @@ class WorkloadTrustPolicySerializer(WorkloadConditionsSerializerMixin, serialize
claim_labels = serializers.SerializerMethodField(
help_text="How the provider names the subject, the subject name and each condition claim, for display."
)
+
+ def get_provider(self, instance: WorkloadTrustPolicy | WorkloadTrustPolicyRequest) -> str | None:
+ provider = get_workload_provider_by_issuer(instance.issuer)
+ return provider.key if provider else None
+
+ def validate_issuer(self, value: str) -> str:
+ provider = get_workload_provider_by_issuer(value)
+ if provider is None:
+ raise serializers.ValidationError("This issuer isn't a supported workload provider.")
+ return normalize_issuer(provider.issuer)
+
+ def validate_subject_name(self, value: str) -> str:
+ return _validate_exact_value(value, FALLBACK_SUBJECT_NAME_LABEL)
+
+ def validate_subject(self, value: str) -> str:
+ return _validate_exact_value(value, FALLBACK_SUBJECT_LABEL)
+
+ @extend_schema_field(WorkloadClaimLabelsSerializer)
+ def get_claim_labels(self, instance: Any) -> dict[str, Any]:
+ return workload_claim_labels(instance.issuer)
+
+
+class WorkloadTrustPolicySerializer(WorkloadConditionsSerializerMixin, serializers.ModelSerializer):
+ name = serializers.CharField(max_length=200, help_text="A name that says what the policy is for.")
scopes = CIScopeListField(
help_text=(
"The scopes every token minted under this policy carries. Scopes that manage credentials or access "
@@ -245,10 +264,6 @@ class WorkloadTrustPolicySerializer(WorkloadConditionsSerializerMixin, serialize
]
read_only_fields = ["id", "provider", "claim_labels", "created_by", "created_at", "updated_at"]
- def get_provider(self, policy: WorkloadTrustPolicy) -> str | None:
- provider = get_workload_provider_by_issuer(policy.issuer)
- return provider.key if provider else None
-
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
attrs = validate_workload_trust_conditions(attrs, instance=self.instance)
team = cast(Team, self.context["get_team"]())
@@ -309,6 +324,15 @@ class WorkloadProvidersResponseSerializer(serializers.Serializer):
)
+def notify_admins_of_policy_change(
+ team_id: int, policy_id: str, name: str, change: WorkloadTrustPolicyChange, actor_user_id: int | None
+) -> None:
+ # The change already happened, so a broker outage must not turn it into an error response.
+ transaction.on_commit(
+ lambda: send_workload_trust_policy_changed.delay(team_id, policy_id, name, change, actor_user_id), robust=True
+ )
+
+
class NotImpersonatedWritePermission(BasePermission):
"""A policy is a standing credential that acts as the owner, so staff impersonating a member can read
policies but not change them, or ask for them."""
@@ -351,28 +375,16 @@ class WorkloadTrustPolicyViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
def perform_create(self, serializer: serializers.BaseSerializer) -> None:
policy = serializer.save(created_by=self.request.user)
- self._notify_admins(policy, "created")
+ notify_admins_of_policy_change(self.team_id, str(policy.pk), policy.name, "created", self.request.user.pk)
def perform_update(self, serializer: serializers.BaseSerializer) -> None:
policy = serializer.save()
- self._notify_admins(policy, "updated")
+ notify_admins_of_policy_change(self.team_id, str(policy.pk), policy.name, "updated", self.request.user.pk)
def perform_destroy(self, instance: WorkloadTrustPolicy) -> None:
policy_id, name = str(instance.pk), instance.name
instance.delete()
- self._notify_admins_of(policy_id, name, "deleted")
-
- def _notify_admins(self, policy: WorkloadTrustPolicy, change: WorkloadTrustPolicyChange) -> None:
- self._notify_admins_of(str(policy.pk), policy.name, change)
-
- def _notify_admins_of(self, policy_id: str, name: str, change: WorkloadTrustPolicyChange) -> None:
- team_id = self.team_id
- actor_user_id = cast(User, self.request.user).pk
- # The change already happened, so a broker outage must not turn it into an error response.
- transaction.on_commit(
- lambda: send_workload_trust_policy_changed.delay(team_id, policy_id, name, change, actor_user_id),
- robust=True,
- )
+ notify_admins_of_policy_change(self.team_id, policy_id, name, "deleted", self.request.user.pk)
@extend_schema(responses={200: WorkloadProvidersResponseSerializer})
@action(methods=["GET"], detail=False, required_scopes=["workload_trust_policy:read"], pagination_class=None)
@@ -384,3 +396,258 @@ class WorkloadTrustPolicyViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"risky_scopes": {scope: warning for scope, warning in RISKY_SCOPE_WARNINGS.items() if scope in grantable},
}
return Response(WorkloadProvidersResponseSerializer(payload).data)
+
+
+def requesting_application(request: Request) -> OAuthApplication | None:
+ authenticator = request.successful_authenticator
+ if isinstance(authenticator, OAuthAccessTokenAuthentication):
+ return authenticator.access_token.application
+ return None
+
+
+class WorkloadTrustPolicyRequestSerializer(WorkloadConditionsSerializerMixin, serializers.ModelSerializer):
+ name = serializers.CharField(max_length=200, help_text="The name the policy gets once approved.")
+ provider_name = serializers.SerializerMethodField(help_text="The display name of the workload provider, or null.")
+ scopes = CIScopeListField(help_text="The scopes the policy's tokens would carry.")
+ status = serializers.SerializerMethodField(help_text="Where the request stands. A request expires after 24 hours.")
+ requested_via = serializers.SerializerMethodField(
+ help_text="The name of the OAuth app the request came through, or null for other credentials."
+ )
+ requested_via_verified = serializers.SerializerMethodField(
+ help_text="Whether PostHog verified the OAuth app the request came through, or null for other credentials."
+ )
+ approval_url = serializers.SerializerMethodField(help_text="The link to send to an admin to approve the request.")
+ can_approve = serializers.SerializerMethodField(
+ help_text="Whether the current user's role lets them approve the request, in the browser."
+ )
+ approvers = serializers.SerializerMethodField(
+ help_text="Names of the organization admins and owners who can approve, when the current user cannot."
+ )
+ risky_scopes = serializers.SerializerMethodField(
+ help_text="What each risky scope in the request lets a token do, keyed by scope. Show it before approving."
+ )
+ requested_by = UserBasicSerializer(read_only=True, allow_null=True)
+ resolved_by = UserBasicSerializer(read_only=True, allow_null=True)
+ policy_id = serializers.UUIDField(read_only=True, allow_null=True, help_text="The policy created on approval.")
+
+ class Meta:
+ model = WorkloadTrustPolicyRequest
+ fields = [
+ "id",
+ "name",
+ "issuer",
+ "provider",
+ "provider_name",
+ "subject_name",
+ "subject",
+ "conditions",
+ "claim_labels",
+ "scopes",
+ "risky_scopes",
+ "status",
+ "approval_url",
+ "can_approve",
+ "approvers",
+ "requested_by",
+ "requested_via",
+ "requested_via_verified",
+ "created_at",
+ "expires_at",
+ "resolved_by",
+ "resolved_at",
+ "policy_id",
+ ]
+ read_only_fields = [
+ "id",
+ "provider",
+ "provider_name",
+ "claim_labels",
+ "risky_scopes",
+ "status",
+ "approval_url",
+ "can_approve",
+ "approvers",
+ "requested_by",
+ "requested_via",
+ "requested_via_verified",
+ "created_at",
+ "expires_at",
+ "resolved_by",
+ "resolved_at",
+ "policy_id",
+ ]
+ extra_kwargs = {
+ "created_at": {"help_text": "When the request was made."},
+ "expires_at": {"help_text": "When a pending request stops being approvable."},
+ "resolved_at": {"help_text": "When an admin approved or rejected the request."},
+ }
+
+ def get_requested_via(self, policy_request: WorkloadTrustPolicyRequest) -> str | None:
+ application = policy_request.requested_via_application
+ return application.name if application else None
+
+ def get_requested_via_verified(self, policy_request: WorkloadTrustPolicyRequest) -> bool | None:
+ application = policy_request.requested_via_application
+ return bool(application.is_verified or application.is_first_party) if application else None
+
+ def get_provider_name(self, policy_request: WorkloadTrustPolicyRequest) -> str | None:
+ provider = get_workload_provider_by_issuer(policy_request.issuer)
+ return provider.name if provider else None
+
+ @extend_schema_field(serializers.ChoiceField(choices=WorkloadTrustPolicyRequest.Status.choices))
+ def get_status(self, policy_request: WorkloadTrustPolicyRequest) -> str:
+ return policy_request.effective_status
+
+ @extend_schema_field(serializers.DictField(child=serializers.CharField()))
+ def get_risky_scopes(self, policy_request: WorkloadTrustPolicyRequest) -> dict[str, str]:
+ return {scope: RISKY_SCOPE_WARNINGS[scope] for scope in policy_request.scopes if scope in RISKY_SCOPE_WARNINGS}
+
+ def get_approval_url(self, policy_request: WorkloadTrustPolicyRequest) -> str:
+ return workload_trust_policy_request_url(policy_request.team_id, str(policy_request.pk))
+
+ def get_can_approve(self, policy_request: WorkloadTrustPolicyRequest) -> bool:
+ return bool(self.context["can_approve"])
+
+ def get_approvers(self, policy_request: WorkloadTrustPolicyRequest) -> list[str]:
+ return [] if self.context["can_approve"] else self.context["approvers"]()
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ return validate_workload_trust_conditions(attrs)
+
+
+class WorkloadTrustPolicyRequestResolutionPermission(BasePermission):
+ """Approving or rejecting a request needs an organization admin or owner in a browser session. Asking
+ for a policy is open to every member, so the check applies to the resolving actions only."""
+
+ message = (
+ "Only an organization admin or owner can approve or reject a workload trust policy request, in the PostHog app."
+ )
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ if getattr(view, "action", None) not in WorkloadTrustPolicyRequestViewSet.RESOLVING_ACTIONS:
+ return True
+ if not isinstance(request.successful_authenticator, SessionAuthentication):
+ return False
+ membership = get_required_organization_membership(request, get_organization_from_view(view))
+ return membership.level >= OrganizationMembership.Level.ADMIN
+
+
+def resolve_workload_trust_policy_request(
+ *, team_id: int, request_id: str, approve: bool, resolver: User, policy_serializer_context: dict[str, Any]
+) -> WorkloadTrustPolicyRequest:
+ """Approve or reject a pending request. Approving creates the policy from the request's own values,
+ checked again against today's rules, in the same transaction that marks the request approved."""
+ with transaction.atomic():
+ policy_request = WorkloadTrustPolicyRequest.objects.select_for_update().get(pk=request_id, team_id=team_id)
+ if policy_request.effective_status != WorkloadTrustPolicyRequest.Status.PENDING:
+ raise serializers.ValidationError(f"This request is {policy_request.effective_status} and can't change.")
+ if approve:
+ policy_serializer = WorkloadTrustPolicySerializer(
+ data={
+ field: getattr(policy_request, field)
+ for field in ("name", "issuer", "subject_name", "subject", "conditions", "scopes")
+ },
+ context=policy_serializer_context,
+ )
+ policy_serializer.is_valid(raise_exception=True)
+ policy_request.policy = policy_serializer.save(created_by=resolver)
+ policy_request.status = (
+ WorkloadTrustPolicyRequest.Status.APPROVED if approve else WorkloadTrustPolicyRequest.Status.REJECTED
+ )
+ policy_request.resolved_by = resolver
+ policy_request.resolved_at = timezone.now()
+ policy_request.save()
+ return policy_request
+
+
+@extend_schema(extensions={"x-product": "core"})
+class WorkloadTrustPolicyRequestViewSet(
+ TeamAndOrgViewSetMixin,
+ mixins.CreateModelMixin,
+ mixins.RetrieveModelMixin,
+ mixins.ListModelMixin,
+ viewsets.GenericViewSet,
+):
+ RESOLVING_ACTIONS = frozenset({"approve", "reject"})
+
+ scope_object = "workload_trust_policy_request"
+ queryset = WorkloadTrustPolicyRequest.objects.unscoped()
+ serializer_class = WorkloadTrustPolicyRequestSerializer
+ lookup_field = "id"
+ permission_classes = [
+ NotImpersonatedWritePermission,
+ TimeSensitiveActionPermission,
+ WorkloadTrustPolicyRequestResolutionPermission,
+ ]
+ # Asking for a policy grants nothing, so it never needs a fresh login. Approving and rejecting do.
+ time_sensitive_exclude_actions = ["create"]
+
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ return (
+ WorkloadTrustPolicyRequest.objects.all()
+ .select_related("requested_by", "resolved_by", "requested_via_application")
+ .order_by("-created_at")
+ )
+
+ def get_throttles(self) -> list[Any]:
+ if self.action == "create":
+ return [WorkloadTrustPolicyRequestBurstThrottle(), WorkloadTrustPolicyRequestSustainedThrottle()]
+ return super().get_throttles()
+
+ def get_serializer_context(self) -> dict[str, Any]:
+ context = super().get_serializer_context()
+ organization_id = self.organization.id
+ membership = get_cached_organization_membership(organization_id, cast(User, self.request.user))
+ context["can_approve"] = membership is not None and membership.level >= OrganizationMembership.Level.ADMIN
+
+ @functools.cache
+ def approvers() -> list[str]:
+ memberships = (
+ OrganizationMembership.objects.filter(
+ organization_id=organization_id,
+ level__gte=OrganizationMembership.Level.ADMIN,
+ user__is_active=True,
+ )
+ .select_related("user")
+ .order_by("-level", "joined_at")
+ )
+ # Name only the admins this reader could see in the members list, when the organization hides it.
+ visible_membership_ids = restricted_visible_membership_ids(self.organization, cast(User, self.request.user))
+ if visible_membership_ids is not None:
+ memberships = memberships.filter(id__in=visible_membership_ids)
+ return [membership.user.get_full_name() or membership.user.email for membership in memberships]
+
+ context["approvers"] = approvers
+ return context
+
+ def perform_create(self, serializer: serializers.BaseSerializer) -> None:
+ serializer.save(
+ team=self.team,
+ requested_by=self.request.user,
+ requested_via_application=requesting_application(self.request),
+ )
+
+ def _resolve(self, approve: bool) -> Response:
+ policy_request = self.get_object()
+ resolved = resolve_workload_trust_policy_request(
+ team_id=policy_request.team_id,
+ request_id=str(policy_request.pk),
+ approve=approve,
+ resolver=cast(User, self.request.user),
+ policy_serializer_context=self.get_serializer_context(),
+ )
+ if resolved.policy is not None:
+ notify_admins_of_policy_change(
+ self.team_id, str(resolved.policy.pk), resolved.policy.name, "created", self.request.user.pk
+ )
+ return Response(self.get_serializer(resolved).data)
+
+ @extend_schema(request=None, responses={200: WorkloadTrustPolicyRequestSerializer})
+ @action(methods=["POST"], detail=True, required_scopes=["workload_trust_policy_request:write"])
+ def approve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ return self._resolve(approve=True)
+
+ @extend_schema(request=None, responses={200: WorkloadTrustPolicyRequestSerializer})
+ @action(methods=["POST"], detail=True, required_scopes=["workload_trust_policy_request:write"])
+ def reject(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ return self._resolve(approve=False)
diff --git a/products/access_control/frontend/generated/api.schemas.ts b/products/access_control/frontend/generated/api.schemas.ts
index 573860767e6f..58a5718d2fe8 100644
--- a/products/access_control/frontend/generated/api.schemas.ts
+++ b/products/access_control/frontend/generated/api.schemas.ts
@@ -167,6 +167,7 @@ export const ResolvedAccessSourceSubjectEnumApi = {
* * `wizard_session` - wizard_session
* * `wizard_run` - wizard_run
* * `workload_trust_policy` - workload_trust_policy
+ * * `workload_trust_policy_request` - workload_trust_policy_request
*/
export type ScopeObjectEnumApi = (typeof ScopeObjectEnumApi)[keyof typeof ScopeObjectEnumApi]
@@ -293,6 +294,7 @@ export const ScopeObjectEnumApi = {
WizardSession: 'wizard_session',
WizardRun: 'wizard_run',
WorkloadTrustPolicy: 'workload_trust_policy',
+ WorkloadTrustPolicyRequest: 'workload_trust_policy_request',
} as const
/**
@@ -441,7 +443,8 @@ export interface ProjectAccessSourceApi {
* * `webhook` - webhook
* * `wizard_session` - wizard_session
* * `wizard_run` - wizard_run
- * * `workload_trust_policy` - workload_trust_policy */
+ * * `workload_trust_policy` - workload_trust_policy
+ * * `workload_trust_policy_request` - workload_trust_policy_request */
source_resource: ScopeObjectEnumApi
/**
* The deciding rule's object id, when it is an object-level rule (e.g. the source a table inherits from).
@@ -610,7 +613,8 @@ export interface AccessControlObjectRuleApi {
* * `webhook` - webhook
* * `wizard_session` - wizard_session
* * `wizard_run` - wizard_run
- * * `workload_trust_policy` - workload_trust_policy */
+ * * `workload_trust_policy` - workload_trust_policy
+ * * `workload_trust_policy_request` - workload_trust_policy_request */
resource: ScopeObjectEnumApi
/** The object's primary key. */
resource_id: string
@@ -1007,7 +1011,8 @@ export interface AccessControlObjectRuleResourceApi {
* * `webhook` - webhook
* * `wizard_session` - wizard_session
* * `wizard_run` - wizard_run
- * * `workload_trust_policy` - workload_trust_policy */
+ * * `workload_trust_policy` - workload_trust_policy
+ * * `workload_trust_policy_request` - workload_trust_policy_request */
resource: ScopeObjectEnumApi
/** The levels an object rule on this resource type accepts, lowest first. */
available_access_levels: string[]
@@ -1299,7 +1304,8 @@ export interface ResolvedAccessApi {
* * `webhook` - webhook
* * `wizard_session` - wizard_session
* * `wizard_run` - wizard_run
- * * `workload_trust_policy` - workload_trust_policy */
+ * * `workload_trust_policy` - workload_trust_policy
+ * * `workload_trust_policy_request` - workload_trust_policy_request */
source_resource: ScopeObjectEnumApi
/**
* The deciding rule's object id, when it is an object-level rule (e.g. the source a table inherits from).
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 51d6d14e3c99..9ba13f4893b2 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -1570,6 +1570,7 @@ export type ActivityLogListParams = {
* * `ProjectSecretAPIKey` - ProjectSecretAPIKey
* * `OAuthApplication` - OAuthApplication
* * `WorkloadTrustPolicy` - WorkloadTrustPolicy
+ * * `WorkloadTrustPolicyRequest` - WorkloadTrustPolicyRequest
* * `User` - User
* * `Action` - Action
* * `AccountView` - AccountView
@@ -1689,6 +1690,7 @@ export const ActivityLogListScope = {
ProjectSecretAPIKey: 'ProjectSecretAPIKey',
OAuthApplication: 'OAuthApplication',
WorkloadTrustPolicy: 'WorkloadTrustPolicy',
+ WorkloadTrustPolicyRequest: 'WorkloadTrustPolicyRequest',
User: 'User',
Action: 'Action',
AccountView: 'AccountView',
@@ -1795,6 +1797,7 @@ export const ActivityLogListScope = {
* * `ProjectSecretAPIKey` - ProjectSecretAPIKey
* * `OAuthApplication` - OAuthApplication
* * `WorkloadTrustPolicy` - WorkloadTrustPolicy
+ * * `WorkloadTrustPolicyRequest` - WorkloadTrustPolicyRequest
* * `User` - User
* * `Action` - Action
* * `AccountView` - AccountView
@@ -1902,6 +1905,7 @@ export const ActivityLogListScopesItem = {
ProjectSecretAPIKey: 'ProjectSecretAPIKey',
OAuthApplication: 'OAuthApplication',
WorkloadTrustPolicy: 'WorkloadTrustPolicy',
+ WorkloadTrustPolicyRequest: 'WorkloadTrustPolicyRequest',
User: 'User',
Action: 'Action',
AccountView: 'AccountView',
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 93f6cf23cdca..bbff45726fad 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -838,6 +838,7 @@ export namespace Schemas {
* * `wizard_session` - wizard_session
* * `wizard_run` - wizard_run
* * `workload_trust_policy` - workload_trust_policy
+ * * `workload_trust_policy_request` - workload_trust_policy_request
*/
export type ScopeObjectEnum = typeof ScopeObjectEnum[keyof typeof ScopeObjectEnum];
@@ -965,6 +966,7 @@ export namespace Schemas {
WizardSession: 'wizard_session',
WizardRun: 'wizard_run',
WorkloadTrustPolicy: 'workload_trust_policy',
+ WorkloadTrustPolicyRequest: 'workload_trust_policy_request',
} as const;
export interface AccessControlObjectRuleResource {
@@ -1091,7 +1093,8 @@ export namespace Schemas {
* * `webhook` - webhook
* * `wizard_session` - wizard_session
* * `wizard_run` - wizard_run
- * * `workload_trust_policy` - workload_trust_policy */
+ * * `workload_trust_policy` - workload_trust_policy
+ * * `workload_trust_policy_request` - workload_trust_policy_request */
resource: ScopeObjectEnum;
/** The levels an object rule on this resource type accepts, lowest first. */
available_access_levels: string[];
@@ -1341,7 +1344,8 @@ export namespace Schemas {
* * `webhook` - webhook
* * `wizard_session` - wizard_session
* * `wizard_run` - wizard_run
- * * `workload_trust_policy` - workload_trust_policy */
+ * * `workload_trust_policy` - workload_trust_policy
+ * * `workload_trust_policy_request` - workload_trust_policy_request */
source_resource: ScopeObjectEnum;
/**
* The deciding rule's object id, when it is an object-level rule (e.g. the source a table inherits from).
@@ -1757,7 +1761,8 @@ export namespace Schemas {
* * `webhook` - webhook
* * `wizard_session` - wizard_session
* * `wizard_run` - wizard_run
- * * `workload_trust_policy` - workload_trust_policy */
+ * * `workload_trust_policy` - workload_trust_policy
+ * * `workload_trust_policy_request` - workload_trust_policy_request */
resource: ScopeObjectEnum;
/** The object's primary key. */
resource_id: string;
@@ -65513,7 +65518,8 @@ export namespace Schemas {
* * `webhook` - webhook
* * `wizard_session` - wizard_session
* * `wizard_run` - wizard_run
- * * `workload_trust_policy` - workload_trust_policy */
+ * * `workload_trust_policy` - workload_trust_policy
+ * * `workload_trust_policy_request` - workload_trust_policy_request */
source_resource: ScopeObjectEnum;
/**
* The deciding rule's object id, when it is an object-level rule (e.g. the source a table inherits from).
@@ -78488,6 +78494,114 @@ export namespace Schemas {
results: WorkloadTrustPolicy[];
}
+ export type WorkloadTrustPolicyRequestStatusEnum = typeof WorkloadTrustPolicyRequestStatusEnum[keyof typeof WorkloadTrustPolicyRequestStatusEnum];
+
+
+ export const WorkloadTrustPolicyRequestStatusEnum = {
+ Pending: 'pending',
+ Approved: 'approved',
+ Rejected: 'rejected',
+ Expired: 'expired',
+ } as const;
+
+ /**
+ * Claims the token must carry, as claim name to exact value, for example a branch or an environment. Only the provider's condition claims are allowed. An empty value removes the condition.
+ */
+ export type WorkloadTrustPolicyRequestConditions = {[key: string]: string};
+
+ /**
+ * What each risky scope in the request lets a token do, keyed by scope. Show it before approving.
+ */
+ export type WorkloadTrustPolicyRequestRiskyScopes = {[key: string]: string};
+
+ export interface WorkloadTrustPolicyRequest {
+ readonly id: string;
+ /**
+ * The name the policy gets once approved.
+ * @maxLength 200
+ */
+ name: string;
+ /**
+ * The OIDC issuer of the workload provider, from the list of supported providers.
+ * @maxLength 255
+ */
+ issuer: string;
+ /**
+ * The key of the workload provider the issuer belongs to.
+ * @nullable
+ */
+ readonly provider: string | null;
+ /**
+ * The display name of the workload provider, or null.
+ * @nullable
+ */
+ readonly provider_name: string | null;
+ /**
+ * The workload's human-readable name, from the provider's subject name claim, for example a repository's full name. Matched exactly.
+ * @maxLength 255
+ */
+ subject_name: string;
+ /**
+ * The workload's immutable ID, from the provider's subject claim, for example a repository ID. Matched exactly together with the name, so a deleted and re-created workload with the same name does not match.
+ * @maxLength 255
+ */
+ subject: string;
+ /** Claims the token must carry, as claim name to exact value, for example a branch or an environment. Only the provider's condition claims are allowed. An empty value removes the condition. */
+ conditions?: WorkloadTrustPolicyRequestConditions;
+ /** How the provider names the subject, the subject name and each condition claim, for display. */
+ readonly claim_labels: WorkloadClaimLabels;
+ /**
+ * The scopes the policy's tokens would carry.
+ * @items.maxLength 100
+ */
+ scopes: string[];
+ /** What each risky scope in the request lets a token do, keyed by scope. Show it before approving. */
+ readonly risky_scopes: WorkloadTrustPolicyRequestRiskyScopes;
+ /** Where the request stands. A request expires after 24 hours. */
+ readonly status: WorkloadTrustPolicyRequestStatusEnum;
+ /** The link to send to an admin to approve the request. */
+ readonly approval_url: string;
+ /** Whether the current user's role lets them approve the request, in the browser. */
+ readonly can_approve: boolean;
+ /** Names of the organization admins and owners who can approve, when the current user cannot. */
+ readonly approvers: readonly string[];
+ readonly requested_by: UserBasic | null;
+ /**
+ * The name of the OAuth app the request came through, or null for other credentials.
+ * @nullable
+ */
+ readonly requested_via: string | null;
+ /**
+ * Whether PostHog verified the OAuth app the request came through, or null for other credentials.
+ * @nullable
+ */
+ readonly requested_via_verified: boolean | null;
+ /** When the request was made. */
+ readonly created_at: string;
+ /** When a pending request stops being approvable. */
+ readonly expires_at: string;
+ readonly resolved_by: UserBasic | null;
+ /**
+ * When an admin approved or rejected the request.
+ * @nullable
+ */
+ readonly resolved_at: string | null;
+ /**
+ * The policy created on approval.
+ * @nullable
+ */
+ readonly policy_id: string | null;
+ }
+
+ export interface PaginatedWorkloadTrustPolicyRequestList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: WorkloadTrustPolicyRequest[];
+ }
+
/**
* * `sum` - Sum
* * `avg` - Avg
@@ -120496,6 +120610,7 @@ export namespace Schemas {
* * `ProjectSecretAPIKey` - ProjectSecretAPIKey
* * `OAuthApplication` - OAuthApplication
* * `WorkloadTrustPolicy` - WorkloadTrustPolicy
+ * * `WorkloadTrustPolicyRequest` - WorkloadTrustPolicyRequest
* * `User` - User
* * `Action` - Action
* * `AccountView` - AccountView
@@ -120616,6 +120731,7 @@ export namespace Schemas {
ProjectSecretAPIKey: 'ProjectSecretAPIKey',
OAuthApplication: 'OAuthApplication',
WorkloadTrustPolicy: 'WorkloadTrustPolicy',
+ WorkloadTrustPolicyRequest: 'WorkloadTrustPolicyRequest',
User: 'User',
Action: 'Action',
AccountView: 'AccountView',
@@ -120722,6 +120838,7 @@ export namespace Schemas {
* * `ProjectSecretAPIKey` - ProjectSecretAPIKey
* * `OAuthApplication` - OAuthApplication
* * `WorkloadTrustPolicy` - WorkloadTrustPolicy
+ * * `WorkloadTrustPolicyRequest` - WorkloadTrustPolicyRequest
* * `User` - User
* * `Action` - Action
* * `AccountView` - AccountView
@@ -120830,6 +120947,7 @@ export namespace Schemas {
ProjectSecretAPIKey: 'ProjectSecretAPIKey',
OAuthApplication: 'OAuthApplication',
WorkloadTrustPolicy: 'WorkloadTrustPolicy',
+ WorkloadTrustPolicyRequest: 'WorkloadTrustPolicyRequest',
User: 'User',
Action: 'Action',
AccountView: 'AccountView',
@@ -135728,6 +135846,17 @@ export namespace Schemas {
offset?: number;
};
+ export type WorkloadTrustPolicyRequestsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type PublicHogFunctionTemplatesListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index ca0357cddd45..54e17add791e 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -246,6 +246,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'webhook:write',
'workload_trust_policy:read',
'workload_trust_policy:write',
+ 'workload_trust_policy_request:read',
+ 'workload_trust_policy_request:write',
] as const
export type OAuthScope = (typeof OAUTH_SCOPES_SUPPORTED)[number]
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index aad87dc872e8..d63025f465d9 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -2078,5 +2078,10 @@
"template": "/workflows/library/templates/new",
"params": [],
"scope": "project"
+ },
+ "workloadTrustPolicyRequest": {
+ "template": "/workload-trust-policy-requests/{id}",
+ "params": ["id"],
+ "scope": "project"
}
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
index 772a7d745f19..e9105c22d238 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
@@ -13,7 +13,7 @@
"type": "object"
},
"url": {
- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/datasets/{id}\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/offline/experiments?tab=datasets\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/analytics\n/analytics/all\n/analytics/mine\n/analytics/product-analytics\n/analytics/spaces\n/application-observability\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/bi\n/bi/new\n/bi/{insightShortId}\n/billing/authorization_status\n/broadcasts\n/broadcasts/library/templates/{id}\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/cross-project-dashboards\n/cross-project-dashboards/{id}\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-catalog/new-metric\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/device\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}/ci-explorer\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error-tracking\n/error-tracking/alerts/new/{templateId}\n/error-tracking/alerts/{id}\n/error-tracking/fingerprint/{fingerprint}\n/error-tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature-flags\n/feature-flags/new\n/feature-flags/staff\n/feature-flags/staff/cohorts\n/feature-flags/templates\n/feature-flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scout-trials\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/slack/{integrationId}/setup\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/metrics/dashboard-review\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/organization/legal\n/organization/startups\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/platform-alerts\n/platform-alerts/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/goal\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/goal\n/replay-vision/{id}/overview\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/transactional\n/transactional/library/templates/{id}\n/transactional/new\n/unsubscribe\n/uptime-monitoring\n/verify_email\n/visual-review\n/visual-review/repos/{repoOwner}/{repoName}/flakiness\n/visual-review/repos/{repoOwner}/{repoName}/runs\n/visual-review/repos/{repoOwner}/{repoName}/runs/{runId}\n/visual-review/repos/{repoOwner}/{repoName}/snapshots\n/visual-review/repos/{repoOwner}/{repoName}/{runType}/snapshots/{identifier}\n/visual-review/runs/{runId}\n/visual-review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/welcome\n/wizard/runs\n/workflows\n/workflows/channels/email/{id}\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/datasets/{id}\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/offline/experiments?tab=datasets\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/analytics\n/analytics/all\n/analytics/mine\n/analytics/product-analytics\n/analytics/spaces\n/application-observability\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/bi\n/bi/new\n/bi/{insightShortId}\n/billing/authorization_status\n/broadcasts\n/broadcasts/library/templates/{id}\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/cross-project-dashboards\n/cross-project-dashboards/{id}\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-catalog/new-metric\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/device\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}/ci-explorer\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error-tracking\n/error-tracking/alerts/new/{templateId}\n/error-tracking/alerts/{id}\n/error-tracking/fingerprint/{fingerprint}\n/error-tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature-flags\n/feature-flags/new\n/feature-flags/staff\n/feature-flags/staff/cohorts\n/feature-flags/templates\n/feature-flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scout-trials\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/slack/{integrationId}/setup\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/metrics/dashboard-review\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/organization/legal\n/organization/startups\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/platform-alerts\n/platform-alerts/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/goal\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/goal\n/replay-vision/{id}/overview\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/transactional\n/transactional/library/templates/{id}\n/transactional/new\n/unsubscribe\n/uptime-monitoring\n/verify_email\n/visual-review\n/visual-review/repos/{repoOwner}/{repoName}/flakiness\n/visual-review/repos/{repoOwner}/{repoName}/runs\n/visual-review/repos/{repoOwner}/{repoName}/runs/{runId}\n/visual-review/repos/{repoOwner}/{repoName}/snapshots\n/visual-review/repos/{repoOwner}/{repoName}/{runType}/snapshots/{identifier}\n/visual-review/runs/{runId}\n/visual-review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/welcome\n/wizard/runs\n/workflows\n/workflows/channels/email/{id}\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}\n/workload-trust-policy-requests/{id}",
"type": "string"
}
},