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): add workload trust policies for oidc token exchange (#127777)

Rafael Audibert81d92f939a37
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 84458111ef75..51243651aeee 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -105,6 +105,7 @@ rules:
|BatchImport
|BriefConfig
|ButtonTile
+ |WorkloadTrustPolicy
|Canvas
|CanvasBuild
|CanvasHomePreference
@@ -613,6 +614,7 @@ rules:
|BatchImport
|BriefConfig
|ButtonTile
+ |WorkloadTrustPolicy
|Canvas
|CanvasBuild
|CanvasHomePreference
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 88eae823a3ef..89fa3e1f2f97 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -5763,6 +5763,165 @@ export interface UploadedMediaUploadStartedApi {
readonly expires_in: number
}
+/**
+ * The label of each condition claim the provider allows, keyed by claim name.
+ */
+export type WorkloadClaimLabelsApiConditions = { [key: string]: string }
+
+export interface WorkloadClaimLabelsApi {
+ /** What the provider calls the subject, for example Repository ID. */
+ subject: string
+ /** What the provider calls the subject name, for example Repository. */
+ subject_name: string
+ /** The label of each condition claim the provider allows, keyed by claim name. */
+ conditions: WorkloadClaimLabelsApiConditions
+}
+
+/**
+ * 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 WorkloadTrustPolicyApiConditions = { [key: string]: string }
+
+export interface WorkloadTrustPolicyApi {
+ readonly id: string
+ /**
+ * A name that says what the policy is for.
+ * @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 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?: WorkloadTrustPolicyApiConditions
+ /** How the provider names the subject, the subject name and each condition claim, for display. */
+ readonly claim_labels: WorkloadClaimLabelsApi
+ /**
+ * The scopes every token minted under this policy carries. Scopes that manage credentials or access are refused.
+ * @items.maxLength 100
+ */
+ scopes: string[]
+ /** Whether the policy can mint tokens. Disabling it cuts off its tokens. */
+ enabled?: boolean
+ readonly created_by: UserBasicApi | null
+ readonly created_at: string
+ readonly updated_at: string
+}
+
+export interface PaginatedWorkloadTrustPolicyListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: WorkloadTrustPolicyApi[]
+}
+
+/**
+ * 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 PatchedWorkloadTrustPolicyApiConditions = { [key: string]: string }
+
+export interface PatchedWorkloadTrustPolicyApi {
+ readonly id?: string
+ /**
+ * A name that says what the policy is for.
+ * @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 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?: PatchedWorkloadTrustPolicyApiConditions
+ /** How the provider names the subject, the subject name and each condition claim, for display. */
+ readonly claim_labels?: WorkloadClaimLabelsApi
+ /**
+ * The scopes every token minted under this policy carries. Scopes that manage credentials or access are refused.
+ * @items.maxLength 100
+ */
+ scopes?: string[]
+ /** Whether the policy can mint tokens. Disabling it cuts off its tokens. */
+ enabled?: boolean
+ readonly created_by?: UserBasicApi | null
+ readonly created_at?: string
+ readonly updated_at?: string
+}
+
+/**
+ * What each grantable risky scope lets a token do, keyed by scope. Show it so people add the scope with care.
+ */
+export type WorkloadProvidersResponseApiRiskyScopes = { [key: string]: string }
+
+export interface WorkloadClaimApi {
+ /** The claim's name in the provider's OIDC token. */
+ name: string
+ /** What to call the claim in the UI. */
+ label: string
+ /** A hint that says where to find the claim's value. */
+ help_text: string
+}
+
+export interface WorkloadProviderApi {
+ /** Stable identifier of the provider. */
+ key: string
+ /** Display name of the provider. */
+ name: string
+ /** OIDC issuer a policy for this provider uses. */
+ issuer: string
+ /** Where to read how to set the provider up. */
+ docs_url: string
+ /** The claim that carries the workload's immutable ID. */
+ subject_claim: WorkloadClaimApi
+ /** The claim that carries the workload's readable name. */
+ subject_name_claim: WorkloadClaimApi
+ /** The claims a policy can require an exact value for, in display order. */
+ condition_claims: WorkloadClaimApi[]
+}
+
+export interface WorkloadProvidersResponseApi {
+ /** Providers a policy can trust. */
+ supported: WorkloadProviderApi[]
+ /** Every scope a policy's ceiling may hold. */
+ grantable_scopes: string[]
+ /** What each grantable risky scope lets a token do, keyed by scope. Show it so people add the scope with care. */
+ risky_scopes: WorkloadProvidersResponseApiRiskyScopes
+}
+
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.
@@ -7320,6 +7479,17 @@ export type UploadedMediaCreateBody = {
purpose?: UploadedMediaCreateBodyPurpose
}
+export type WorkloadTrustPoliciesListParams = {
+ /**
+ * 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 9c8e9e99eee8..fd117b485ea4 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -82,6 +82,7 @@ import type {
PaginatedUploadedMediaListApi,
PaginatedUserGitHubIntegrationListResponseListApi,
PaginatedUserListApi,
+ PaginatedWorkloadTrustPolicyListApi,
PatchedCIMDVerificationTokenUpdateApi,
PatchedEnterprisePropertyDefinitionApi,
PatchedFileSystemApi,
@@ -92,6 +93,7 @@ import type {
PatchedProjectBackwardCompatApi,
PatchedProjectSecretAPIKeyApi,
PatchedUserApi,
+ PatchedWorkloadTrustPolicyApi,
ProductEnablementApi,
ProductEnablementResultApi,
ProjectApi,
@@ -137,6 +139,9 @@ import type {
UsersLoginSessionsListParams,
UsersProductIntroSeenPartialUpdate200,
VerifyEmailRequestApi,
+ WorkloadProvidersResponseApi,
+ WorkloadTrustPoliciesListParams,
+ WorkloadTrustPolicyApi,
} from './api.schemas'
// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
@@ -2991,6 +2996,130 @@ export const uploadedMediaStartUploadCreate = async (
})
}
+export const getWorkloadTrustPoliciesListUrl = (projectId: string, params?: WorkloadTrustPoliciesListParams) => {
+ 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_policies/?${stringifiedParams}`
+ : `/api/projects/${projectId}/workload_trust_policies/`
+}
+
+export const workloadTrustPoliciesList = async (
+ projectId: string,
+ params?: WorkloadTrustPoliciesListParams,
+ options?: RequestInit
+): Promise<PaginatedWorkloadTrustPolicyListApi> => {
+ return apiMutator<PaginatedWorkloadTrustPolicyListApi>(getWorkloadTrustPoliciesListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getWorkloadTrustPoliciesCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/workload_trust_policies/`
+}
+
+export const workloadTrustPoliciesCreate = async (
+ projectId: string,
+ workloadTrustPolicyApi: NonReadonly<WorkloadTrustPolicyApi>,
+ options?: RequestInit
+): Promise<WorkloadTrustPolicyApi> => {
+ return apiMutator<WorkloadTrustPolicyApi>(getWorkloadTrustPoliciesCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(workloadTrustPolicyApi),
+ })
+}
+
+export const getWorkloadTrustPoliciesRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/workload_trust_policies/${id}/`
+}
+
+export const workloadTrustPoliciesRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<WorkloadTrustPolicyApi> => {
+ return apiMutator<WorkloadTrustPolicyApi>(getWorkloadTrustPoliciesRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getWorkloadTrustPoliciesUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/workload_trust_policies/${id}/`
+}
+
+export const workloadTrustPoliciesUpdate = async (
+ projectId: string,
+ id: string,
+ workloadTrustPolicyApi: NonReadonly<WorkloadTrustPolicyApi>,
+ options?: RequestInit
+): Promise<WorkloadTrustPolicyApi> => {
+ return apiMutator<WorkloadTrustPolicyApi>(getWorkloadTrustPoliciesUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(workloadTrustPolicyApi),
+ })
+}
+
+export const getWorkloadTrustPoliciesPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/workload_trust_policies/${id}/`
+}
+
+export const workloadTrustPoliciesPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedWorkloadTrustPolicyApi?: NonReadonly<PatchedWorkloadTrustPolicyApi>,
+ options?: RequestInit
+): Promise<WorkloadTrustPolicyApi> => {
+ return apiMutator<WorkloadTrustPolicyApi>(getWorkloadTrustPoliciesPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedWorkloadTrustPolicyApi),
+ })
+}
+
+export const getWorkloadTrustPoliciesDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/workload_trust_policies/${id}/`
+}
+
+export const workloadTrustPoliciesDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getWorkloadTrustPoliciesDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getWorkloadTrustPoliciesProvidersRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/workload_trust_policies/providers/`
+}
+
+export const workloadTrustPoliciesProvidersRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<WorkloadProvidersResponseApi> => {
+ return apiMutator<WorkloadProvidersResponseApi>(getWorkloadTrustPoliciesProvidersRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
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 2b6007126f2d..53c1499da095 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -1330,6 +1330,140 @@ export const UploadedMediaStartUploadCreateBody = /* @__PURE__ */ zod.object({
.describe("Library to add this image to once uploaded, e.g. 'email'."),
})
+export const workloadTrustPoliciesCreateBodyNameMax = 200
+
+export const workloadTrustPoliciesCreateBodyIssuerMax = 255
+
+export const workloadTrustPoliciesCreateBodySubjectNameMax = 255
+
+export const workloadTrustPoliciesCreateBodySubjectMax = 255
+
+export const workloadTrustPoliciesCreateBodyScopesItemMax = 100
+
+export const WorkloadTrustPoliciesCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(workloadTrustPoliciesCreateBodyNameMax).describe('A name that says what the policy is for.'),
+ issuer: zod
+ .string()
+ .max(workloadTrustPoliciesCreateBodyIssuerMax)
+ .describe('The OIDC issuer of the workload provider, from the list of supported providers.'),
+ subject_name: zod
+ .string()
+ .max(workloadTrustPoliciesCreateBodySubjectNameMax)
+ .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(workloadTrustPoliciesCreateBodySubjectMax)
+ .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(workloadTrustPoliciesCreateBodyScopesItemMax))
+ .describe(
+ 'The scopes every token minted under this policy carries. Scopes that manage credentials or access are refused.'
+ ),
+ enabled: zod.boolean().optional().describe('Whether the policy can mint tokens. Disabling it cuts off its tokens.'),
+})
+
+export const workloadTrustPoliciesUpdateBodyNameMax = 200
+
+export const workloadTrustPoliciesUpdateBodyIssuerMax = 255
+
+export const workloadTrustPoliciesUpdateBodySubjectNameMax = 255
+
+export const workloadTrustPoliciesUpdateBodySubjectMax = 255
+
+export const workloadTrustPoliciesUpdateBodyScopesItemMax = 100
+
+export const WorkloadTrustPoliciesUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(workloadTrustPoliciesUpdateBodyNameMax).describe('A name that says what the policy is for.'),
+ issuer: zod
+ .string()
+ .max(workloadTrustPoliciesUpdateBodyIssuerMax)
+ .describe('The OIDC issuer of the workload provider, from the list of supported providers.'),
+ subject_name: zod
+ .string()
+ .max(workloadTrustPoliciesUpdateBodySubjectNameMax)
+ .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(workloadTrustPoliciesUpdateBodySubjectMax)
+ .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(workloadTrustPoliciesUpdateBodyScopesItemMax))
+ .describe(
+ 'The scopes every token minted under this policy carries. Scopes that manage credentials or access are refused.'
+ ),
+ enabled: zod.boolean().optional().describe('Whether the policy can mint tokens. Disabling it cuts off its tokens.'),
+})
+
+export const workloadTrustPoliciesPartialUpdateBodyNameMax = 200
+
+export const workloadTrustPoliciesPartialUpdateBodyIssuerMax = 255
+
+export const workloadTrustPoliciesPartialUpdateBodySubjectNameMax = 255
+
+export const workloadTrustPoliciesPartialUpdateBodySubjectMax = 255
+
+export const workloadTrustPoliciesPartialUpdateBodyScopesItemMax = 100
+
+export const WorkloadTrustPoliciesPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(workloadTrustPoliciesPartialUpdateBodyNameMax)
+ .optional()
+ .describe('A name that says what the policy is for.'),
+ issuer: zod
+ .string()
+ .max(workloadTrustPoliciesPartialUpdateBodyIssuerMax)
+ .optional()
+ .describe('The OIDC issuer of the workload provider, from the list of supported providers.'),
+ subject_name: zod
+ .string()
+ .max(workloadTrustPoliciesPartialUpdateBodySubjectNameMax)
+ .optional()
+ .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(workloadTrustPoliciesPartialUpdateBodySubjectMax)
+ .optional()
+ .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(workloadTrustPoliciesPartialUpdateBodyScopesItemMax))
+ .optional()
+ .describe(
+ 'The scopes every token minted under this policy carries. Scopes that manage credentials or access are refused.'
+ ),
+ enabled: zod.boolean().optional().describe('Whether the policy can mint tokens. Disabling it cuts off its tokens.'),
+})
+
/**
* 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 91973e3b6711..b941c49690af 100644
--- a/frontend/src/lib/oauthScopes.generated.ts
+++ b/frontend/src/lib/oauthScopes.generated.ts
@@ -242,6 +242,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'web_analytics:write',
'webhook:read',
'webhook:write',
+ 'workload_trust_policy:read',
+ 'workload_trust_policy: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 d0bbfa0c6adc..33fb054f7ce0 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -151,6 +151,12 @@ export const API_SCOPES: APIScope[] = [
{ key: 'billing', objectName: 'Billing', objectPlural: 'billing' },
{ key: 'business_knowledge', objectName: 'Business knowledge', objectPlural: 'business knowledge' },
{ key: 'canvas', objectName: 'Canvas', objectPlural: 'canvases' },
+ {
+ key: 'workload_trust_policy',
+ objectName: 'Workload trust policy',
+ objectPlural: 'workload trust policies',
+ disabledActions: ['write'],
+ },
{ key: 'cohort', objectName: 'Cohort', objectPlural: 'cohorts' },
{ key: 'comment', objectName: 'Comment', objectPlural: 'comments' },
{
@@ -677,6 +683,7 @@ export const API_SCOPE_GROUPS: APIScopeGroup[] = [
'organization',
'organization_member',
'project',
+ 'workload_trust_policy',
'user',
'billing',
'access_control',
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 3d2cc6b81824..4c06d4a2c671 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6142,6 +6142,7 @@ export enum ActivityScope {
ORGANIZATION_INVITE = 'OrganizationInvite',
ORGANIZATION_DOMAIN = 'OrganizationDomain',
OAUTH_APPLICATION = 'OAuthApplication',
+ WORKLOAD_TRUST_POLICY = 'WorkloadTrustPolicy',
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 91c6c601849a..8d0c1e061aaf 100644
--- a/posthog/api/rest_router.py
+++ b/posthog/api/rest_router.py
@@ -21,6 +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 ee.api.quota_limits import QuotaLimitsViewSet
from ee.api.vercel import vercel_installation, vercel_product, vercel_proxy, vercel_resource
@@ -548,6 +549,10 @@ projects_router.register(
["team_id"],
)
+projects_router.register(
+ r"workload_trust_policies", WorkloadTrustPolicyViewSet, "project_workload_trust_policies", ["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 3a248bd26b8f..6dd3fc37a844 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -2497,6 +2497,12 @@ class TestTimeSensitivePermissions(APIBaseTest):
("github_disconnect", "delete", "/api/users/@me/integrations/github/123/"),
("slack_start", "post", "/api/users/@me/integrations/slack/start/"),
("slack_disconnect", "delete", "/api/users/@me/integrations/slack/U0123ABC/"),
+ ("workload_trust_policy_create", "post", "/api/projects/@current/workload_trust_policies/"),
+ (
+ "workload_trust_policy_delete",
+ "delete",
+ "/api/projects/@current/workload_trust_policies/00000000-0000-0000-0000-000000000001/",
+ ),
]
)
def test_credential_writes_require_recent_authentication(self, _name, method, url):
diff --git a/posthog/email.py b/posthog/email.py
index 6bdc0565fed0..2b4d5e14f18f 100644
--- a/posthog/email.py
+++ b/posthog/email.py
@@ -170,6 +170,7 @@ CUSTOMER_IO_TEMPLATE_ID_MAP = {
"posthog_ai_access_requested": "72",
"wizard_pr_ready": "74",
"loop_run_summary": "77",
+ "workload_trust_policy_changed": "80",
}
# Message template ids in the US project, for templates that can send through Workflows instead of Customer.io.
@@ -211,6 +212,7 @@ WORKFLOWS_TEMPLATE_ID_MAP: dict[str, str] = {
"posthog_ai_access_requested": "01a16471-350d-0000-75a6-3ebb077c03a1",
"wizard_pr_ready": "01a16471-c17b-0000-8ee5-eb254065b7a1",
"loop_run_summary": "01a16473-9c4d-0000-99d8-958c03b0f1a0",
+ "workload_trust_policy_changed": "01a19e4f-595d-0000-bb58-5b9ae018bceb",
}
# Release conditions match the `email`, `transactional_email_template` and `region` person properties passed at
diff --git a/posthog/migrations/1424_workload_trust_policy.py b/posthog/migrations/1424_workload_trust_policy.py
new file mode 100644
index 000000000000..73810b6dd137
--- /dev/null
+++ b/posthog/migrations/1424_workload_trust_policy.py
@@ -0,0 +1,77 @@
+# Generated by Django 6.1.2 on 2026-11-02 17:20
+
+import django.db.models.deletion
+import django.contrib.postgres.fields
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1423_validate_oauthapplication_grant_types"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="WorkloadTrustPolicy",
+ 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
+ ),
+ ),
+ ("enabled", models.BooleanField(default=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ 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={
+ "constraints": [
+ models.UniqueConstraint(
+ fields=(
+ "team",
+ "issuer",
+ "subject",
+ "conditions",
+ ),
+ name="posthog_unique_workload_trust_policy_conditions",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 151d9f2b619f..214632be9e85 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1423_validate_oauthapplication_grant_types
+1424_workload_trust_policy
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index 4166dbc9ce63..36b0b65fd29b 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -10,6 +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 .column_configuration import ColumnConfiguration
from .comment import Comment, CommentSlackThread
from .core_event import CoreEvent
@@ -95,6 +96,7 @@ __all__ = [
"AsyncDeletion",
"AsyncMigration",
"AsyncMigrationError",
+ "WorkloadTrustPolicy",
"CIMDVerificationToken",
"ColumnConfiguration",
"CoreEvent",
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index d94c6333a835..e35d7c040b05 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -103,6 +103,7 @@ ActivityScope = Literal[
"PersonalAPIKey",
"ProjectSecretAPIKey",
"OAuthApplication",
+ "WorkloadTrustPolicy",
"User",
"Action",
"AccountView",
diff --git a/posthog/models/activity_logging/signal_handlers.py b/posthog/models/activity_logging/signal_handlers.py
index 4e53a0a2a989..da5410b1757d 100644
--- a/posthog/models/activity_logging/signal_handlers.py
+++ b/posthog/models/activity_logging/signal_handlers.py
@@ -53,6 +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.session.activity import session_activity_credential
from posthog.session.models import Session
from posthog.utils import get_ip_address, get_short_user_agent
@@ -494,6 +495,35 @@ def handle_oauth_application_scopes_change(
)
+@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:
+ policy = after_update or before_update
+ if policy is None:
+ return
+ log_activity(
+ organization_id=policy.team.organization_id,
+ team_id=policy.team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=policy.pk,
+ scope=scope,
+ activity=activity,
+ detail=Detail(
+ name=policy.name,
+ changes=changes_between(scope, previous=before_update, current=after_update),
+ ),
+ )
+
+
# --- 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
new file mode 100644
index 000000000000..a00d32396ed9
--- /dev/null
+++ b/posthog/models/workload_trust_policy.py
@@ -0,0 +1,110 @@
+from __future__ import annotations
+
+from collections.abc import Iterable
+
+from django.conf import settings
+from django.contrib.postgres.fields import ArrayField
+from django.db import models
+
+from posthog.models.activity_logging.model_activity import ModelActivityMixin
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+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.
+# - `task:write` starts an agent run from a prompt the caller writes, with its own longer-lived owner token.
+# `conversation:write` (PostHog AI can create such a task), `signal_scout:write`,
+# `business_knowledge:write` and `autoresearch:write` start the same kind of run.
+# - `conversation:read` and `task:read` read the owner's private PostHog AI chats and tasks, because the token
+# acts as the owner. Add them back if a workload needs them.
+# - `project:write` lets a token rotate the project's secret token.
+# - `user:write` changes the account of the owner the token acts as.
+# - `streamlit_app` returns a one-hour OAuth token to connect to a running app.
+# - `webhook:write`, `batch_export:write` and `subscription:write` set up feeds that keep sending after the
+# policy is revoked. A subscription can send to any email address.
+# - `sharing_configuration` creates and reveals public sharing links, which keep working after the policy is revoked.
+WORKLOAD_TRUST_POLICY_DENIED_SCOPES: frozenset[str] = frozenset(
+ {
+ "workload_trust_policy:read",
+ "workload_trust_policy:write",
+ "autoresearch:write",
+ "batch_export:write",
+ "business_knowledge:write",
+ "conversation:read",
+ "conversation:write",
+ "project:write",
+ "sharing_configuration:read",
+ "sharing_configuration:write",
+ "signal_scout:write",
+ "streamlit_app:read",
+ "streamlit_app:write",
+ "subscription:write",
+ "task:read",
+ "task:write",
+ "user:write",
+ "webhook:write",
+ }
+)
+
+
+# A policy's issuer, subject and conditions form one entry of the unique btree index below, which Postgres caps
+# at about 2.7 kB. With the 255-character issuer and subject, these limits keep the largest entry well below it.
+CONDITION_VALUE_MAX_LENGTH = 200
+CONDITIONS_MAX_BYTES = 1024
+
+
+def workload_trust_policy_grantable_scopes() -> frozenset[str]:
+ return UNPRIVILEGED_SCOPES - WORKLOAD_TRUST_POLICY_DENIED_SCOPES
+
+
+def workload_trust_policy_scopes_not_grantable(scopes: Iterable[str]) -> list[str]:
+ grantable = workload_trust_policy_grantable_scopes()
+ return sorted({scope for scope in scopes if scope not in grantable})
+
+
+def workload_trust_policies_settings_url(team_id: int) -> str:
+ return f"{settings.SITE_URL}/project/{team_id}/settings/environment-trusted-workloads"
+
+
+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
+ provider, and PyPI and npm trusted publishing.
+
+ The shape follows the common OIDC model: issuer, subject, claim conditions. A policy always pins the
+ subject by its immutable claim and by its name. Every key in `conditions` is a claim the token must
+ carry with exactly that value, and an empty map adds no conditions.
+ """
+
+ activity_logging_on_delete = True
+
+ # No standalone index: the unique constraint below leads on team_id.
+ 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)
+ # Claim name to required value. Write it only through `normalize_workload_conditions`, which drops empty
+ # values, so two policies with the same conditions always collide in the constraint.
+ conditions = models.JSONField(default=dict, blank=True)
+ scopes = ArrayField(models.CharField(max_length=100), default=list)
+ enabled = models.BooleanField(default=True)
+ created_by = models.ForeignKey(
+ settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ constraints = [
+ # jsonb equality ignores key order, so the constraint compares conditions by content.
+ models.UniqueConstraint(
+ fields=["team", "issuer", "subject", "conditions"],
+ name="posthog_unique_workload_trust_policy_conditions",
+ ),
+ ]
+
+ def __str__(self) -> str:
+ return f"WorkloadTrustPolicy(team={self.team_id}, name={self.name!r})"
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 83f000bba054..9633327f2290 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -154,6 +154,7 @@ APIScopeObject = Literal[
"webhook",
"wizard_session",
"wizard_run",
+ "workload_trust_policy",
]
@@ -329,6 +330,26 @@ OAUTH_SCOPES_HIDDEN: frozenset[str] = (
# independently of `application.scopes`.
UNPRIVILEGED_SCOPES: frozenset[str] = ALL_SCOPES - PRIVILEGED_SCOPES - OAUTH_SCOPES_HIDDEN
+# What a risky scope lets a token do, shown wherever a person grants scopes to a token so they add it with care.
+RISKY_SCOPE_WARNINGS: dict[str, str] = {
+ "access_control:write": "Changes who can access resources in this project.",
+ "approvals:write": "Approves or rejects change requests that gate other changes.",
+ "autoresearch:write": "Starts agent runs that get their own longer-lived token.",
+ "billing:read": "Reads the whole organization's billing details, not just this project's.",
+ "billing:write": "Changes the organization's subscription and payment details.",
+ "hog_flow:write": "Runs workflow code that can use the stored credentials of the project's integrations.",
+ "hog_function:write": "Runs code, including on your website, that can use the stored credentials of the project's integrations.",
+ "integration:write": "Connects and changes third-party integrations and their stored credentials.",
+ "llm_provider_key:write": "Stores and changes LLM provider API keys.",
+ "organization:write": "Changes organization settings, including roles and OAuth apps.",
+ "organization_integration:write": "Connects and changes organization-wide integrations and their stored credentials.",
+ "organization_member:write": "Invites and removes organization members and changes their roles, so it can give people access beyond this token's scopes.",
+ "sharing_configuration:read": "Reads the access tokens of public sharing links, which keep working after this token expires.",
+ "sharing_configuration:write": "Creates public sharing links that anyone with the link can open.",
+ "user:read": "Reads the account details of the user the token acts as, including every organization and project they belong to.",
+ "user:write": "Changes the account of the user the token acts as.",
+}
+
def get_scope_descriptions() -> dict[str, str]:
return {
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.py
index 1879061106b3..d4029346c492 100644
--- a/posthog/tasks/email.py
+++ b/posthog/tasks/email.py
@@ -59,6 +59,7 @@ from posthog.models.organization_notification_lock import (
pipeline_lock_for_team,
)
from posthog.models.scoping import with_team_scope
+from posthog.models.workload_trust_policy import workload_trust_policies_settings_url
from posthog.ph_client import feature_enabled_or_false, get_client, ph_scoped_capture
from posthog.scoping_audit import skip_team_scope_audit
from posthog.user_permissions import UserPermissions
@@ -3144,3 +3145,64 @@ def send_posthog_ai_access_request(organization_id: str, requesting_user_id: int
for user in recipients:
message.add_user_recipient(user)
message.send()
+
+
+WorkloadTrustPolicyChange = Literal["created", "updated", "deleted"]
+
+
+@shared_task(**EMAIL_TASK_KWARGS)
+@skip_team_scope_audit
+def send_workload_trust_policy_changed(
+ team_id: int, policy_id: str, policy_name: str, change: WorkloadTrustPolicyChange, actor_user_id: int | None
+) -> None:
+ """Tell every organization admin and owner that a workload trust policy changed.
+
+ A policy hands out tokens that act as the organization owner, so each change reaches every admin,
+ the one who made it included.
+ """
+ if not is_email_available(with_absolute_urls=True):
+ return
+ team = Team.objects.select_related("organization").filter(id=team_id).first()
+ if team is None:
+ return
+ actor = User.objects.filter(id=actor_user_id).first() if actor_user_id is not None else None
+
+ log_context = {"team_id": team_id, "policy_id": policy_id}
+ actor_name = sanitize_display_name(
+ actor.first_name if actor else "",
+ fallback="Someone",
+ context={"task": "send_workload_trust_policy_changed", "field": "actor_first_name", **log_context},
+ )
+ sanitized_policy_name = sanitize_display_name(
+ policy_name,
+ fallback="a trust policy",
+ context={"task": "send_workload_trust_policy_changed", "field": "policy_name", **log_context},
+ )
+
+ memberships = OrganizationMembership.objects.select_related("user").filter(
+ organization_id=team.organization_id,
+ level__gte=OrganizationMembership.Level.ADMIN,
+ user__is_active=True,
+ )
+ recipients = [membership.user for membership in memberships if membership.user.email]
+ if not recipients:
+ return
+
+ team_and_org_context = get_email_team_and_org_context(team=team)
+ message = EmailMessage(
+ campaign_key=f"workload_trust_policy_{change}_{policy_id}_{timezone.now().timestamp()}",
+ subject=f"A workload trust policy was {change} in {team_and_org_context.get('team_name', 'your project')}",
+ template_name="workload_trust_policy_changed",
+ use_http=True,
+ template_context={
+ "actor_name": actor_name,
+ "actor_email": actor.email if actor else "",
+ "policy_name": sanitized_policy_name,
+ "change": change,
+ "policies_url": workload_trust_policies_settings_url(team.id),
+ **team_and_org_context,
+ },
+ )
+ for user in recipients:
+ message.add_user_recipient(user)
+ message.send()
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 779a37f7081a..4cf192e3e691 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -81,6 +81,7 @@
'posthog.tasks.email.send_wizard_pr_ready_email',
'posthog.tasks.email.send_workflow_email_sending_paused',
'posthog.tasks.email.send_workflow_email_sending_warning',
+ 'posthog.tasks.email.send_workload_trust_policy_changed',
'posthog.tasks.exporter.export_asset',
'posthog.tasks.gateway_credential.drain_gateway_credential_last_used_task',
'posthog.tasks.gateway_credential.refresh_gateway_credentials',
diff --git a/posthog/templates/email/workload_trust_policy_changed.html b/posthog/templates/email/workload_trust_policy_changed.html
new file mode 100644
index 000000000000..2f6cc5d25941
--- /dev/null
+++ b/posthog/templates/email/workload_trust_policy_changed.html
@@ -0,0 +1,24 @@
+{% extends "email/base.html" %}
+{% block heading %}A workload trust policy was {{ change }}{% endblock %}
+{% block section %}
+ <!-- prettier-ignore -->
+ <p>
+ <strong>{{ actor_name }}</strong>{% if actor_email %} (<a href="mailto:{{ actor_email }}">{{ actor_email }}</a>){% endif %}
+ {{ change }} the workload trust policy <strong>{{ policy_name }}</strong> in <strong>{{ team_name }}</strong>.
+ </p>
+ <p>
+ A workload trust policy lets a workload you trust, such as a CI job, get short-lived access to this project. You're getting this
+ email because you're an admin or owner of {{ organization_name }}.
+ </p>
+ <p>If you don't recognize this change, review the project's trusted workloads.</p>
+ <div class="mb mt text-center">
+ <a class="button primary" href="{{ policies_url }}">Review trusted workloads</a>
+ </div>
+ <div class="mt">
+ <p>
+ If the button above doesn't work, paste this link into your browser:
+ <br />
+ <a href="{{ policies_url }}">{{ policies_url }}</a>
+ </p>
+ </div>
+{% endblock %}
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index 46d24b28acb0..d2947215f27d 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -4,6 +4,7 @@
# A receiver disappearing from this set means it connects in NO process (silent audit/cache loss):
# 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_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/test/test_scopes.py b/posthog/test/test_scopes.py
index 9e4be24839a3..5ff48d612cc4 100644
--- a/posthog/test/test_scopes.py
+++ b/posthog/test/test_scopes.py
@@ -17,6 +17,7 @@ from posthog.scopes import (
OAUTH_SCOPES_HIDDEN,
PRIVILEGED_SCOPES,
PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION,
+ RISKY_SCOPE_WARNINGS,
UNPRIVILEGED_SCOPES,
clamp_scopes_to_ceiling,
downgrade_scopes_to_read_only,
@@ -550,3 +551,10 @@ class TestProjectSecretAPIKeyScopeParity(SimpleTestCase):
frontend_scopes = set(re.findall(r"'([a-z_]+:[a-z]+)'", match.group(1)))
backend_scopes = {f"{obj}:{action}" for obj, action in PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION}
assert frontend_scopes == backend_scopes
+
+
+class TestRiskyScopeWarnings(SimpleTestCase):
+ def test_every_risky_scope_warning_names_a_grantable_scope(self) -> None:
+ stale = sorted(set(RISKY_SCOPE_WARNINGS) - UNPRIVILEGED_SCOPES)
+
+ assert not stale, f"{stale} have a risky-scope warning but are no longer grantable. Remove them."
diff --git a/posthog/workload_identity/__init__.py b/posthog/workload_identity/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/workload_identity/providers.py b/posthog/workload_identity/providers.py
new file mode 100644
index 000000000000..98fb21fc6797
--- /dev/null
+++ b/posthog/workload_identity/providers.py
@@ -0,0 +1,102 @@
+"""The workload providers whose OIDC tokens PostHog can exchange for a project token.
+
+Trust policy validation, the token exchange and the policy settings UI read providers only from
+this registry, so no provider name or issuer appears anywhere else in the backend. A provider is
+supported once it has an entry in `SUPPORTED_WORKLOAD_PROVIDERS`.
+"""
+
+from __future__ import annotations
+
+import string
+from enum import StrEnum
+
+from posthog.dataclasses import frozen
+
+
+class AudienceCheck(StrEnum):
+ # The token's `aud` must equal this deployment's SITE_URL, which the workload sets when it asks
+ # its provider for the token. A token minted for another service is then never accepted.
+ SITE_URL = "site_url"
+
+
+@frozen
+class WorkloadClaim:
+ """A claim of the provider's OIDC token, and how the UI names it."""
+
+ name: str
+ label: str
+ help_text: str = ""
+
+
+@frozen
+class WorkloadProvider:
+ key: str
+ name: str
+ # Compared with the token's `iss` claim after trailing slashes are stripped from both.
+ issuer: str
+ jwks_url: str
+ audience_check: AudienceCheck
+ # The claim every policy pins: the workload's immutable subject, for example a repository id. It
+ # survives a rename, and a re-created workload gets a new one, so nobody can take over a policy by
+ # claiming the old name.
+ subject_claim: WorkloadClaim
+ # The workload's human-readable name, for example a repository's full name. A policy pins it too,
+ # so an admin approves the name they read.
+ subject_name_claim: WorkloadClaim
+ condition_claims: tuple[WorkloadClaim, ...]
+ # The claims an activity log entry records and shows, read from the token at exchange time.
+ recorded_claims: tuple[WorkloadClaim, ...]
+ # How an activity log entry names the workload, formatted with the recorded claims, for example
+ # "{repository} · {workflow} run {run_id}". A claim the token lacks formats as an empty string.
+ actor_label_template: str
+ # Formatted with the recorded claims to link an activity log entry to its run, or `None` when the
+ # provider has no stable run URL.
+ run_url_template: str | None
+ docs_url: str
+
+ def __post_init__(self) -> None:
+ condition_names = [claim.name for claim in self.condition_claims]
+ if len(set(condition_names)) != len(condition_names):
+ raise ValueError(f"{self.key}: condition claims must be unique.")
+ if {self.subject_claim.name, self.subject_name_claim.name} & set(condition_names):
+ raise ValueError(f"{self.key}: the subject claims can't also be condition claims.")
+ # The activity log fills the templates with the recorded claims only, so a field outside them, or a
+ # positional, attribute or index field, would fail or render empty on the first workload write.
+ recorded_names = {claim.name for claim in self.recorded_claims}
+ for template in (self.actor_label_template, self.run_url_template or ""):
+ fields = [name for _, name, _, _ in string.Formatter().parse(template) if name is not None]
+ unknown = sorted(set(fields) - recorded_names)
+ if unknown:
+ raise ValueError(f"{self.key}: templates can only use recorded claims, not {unknown}.")
+
+
+# Planned: GitHub Actions, then GitLab.com.
+# Can't be supported with this design:
+# - Bitbucket Pipelines fixes the token's audience per workspace, so a token can't name this PostHog instance.
+# - Self-managed GitLab makes each instance its own issuer, and only the issuers listed here are trusted.
+SUPPORTED_WORKLOAD_PROVIDERS: tuple[WorkloadProvider, ...] = ()
+
+
+def normalize_issuer(issuer: str) -> str:
+ return issuer.rstrip("/")
+
+
+def get_supported_workload_providers() -> tuple[WorkloadProvider, ...]:
+ return SUPPORTED_WORKLOAD_PROVIDERS
+
+
+def get_workload_provider_by_issuer(issuer: str) -> WorkloadProvider | None:
+ normalized = normalize_issuer(issuer)
+ if not normalized:
+ return None
+ for provider in get_supported_workload_providers():
+ if normalize_issuer(provider.issuer) == normalized:
+ return provider
+ return None
+
+
+def get_workload_provider_by_key(key: str) -> WorkloadProvider | None:
+ for provider in get_supported_workload_providers():
+ if provider.key == key:
+ return provider
+ return None
diff --git a/posthog/workload_identity/test/__init__.py b/posthog/workload_identity/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/workload_identity/test/fixtures.py b/posthog/workload_identity/test/fixtures.py
new file mode 100644
index 000000000000..2927504fddae
--- /dev/null
+++ b/posthog/workload_identity/test/fixtures.py
@@ -0,0 +1,40 @@
+from typing import TYPE_CHECKING
+
+from unittest.mock import patch
+
+from posthog.workload_identity.providers import AudienceCheck, WorkloadClaim, WorkloadProvider
+
+if TYPE_CHECKING:
+ from unittest.mock import _patch
+
+# Tests register this provider so they do not depend on which real providers the registry lists.
+FAKE_WORKLOAD_ISSUER = "https://ci.example.com"
+
+FAKE_WORKLOAD_PROVIDER = WorkloadProvider(
+ key="fake_ci",
+ name="Fake CI",
+ issuer=FAKE_WORKLOAD_ISSUER,
+ jwks_url="https://ci.example.com/.well-known/jwks",
+ audience_check=AudienceCheck.SITE_URL,
+ subject_claim=WorkloadClaim(name="repository_id", label="Repository ID"),
+ subject_name_claim=WorkloadClaim(name="repository", label="Repository"),
+ condition_claims=(
+ WorkloadClaim(name="ref", label="Branch or tag", help_text="For example refs/heads/main."),
+ WorkloadClaim(name="environment", label="Environment"),
+ ),
+ recorded_claims=(
+ WorkloadClaim(name="repository", label="Repository"),
+ WorkloadClaim(name="workflow", label="Workflow"),
+ WorkloadClaim(name="run_id", label="Run"),
+ WorkloadClaim(name="sha", label="Commit"),
+ WorkloadClaim(name="ref", label="Branch or tag"),
+ WorkloadClaim(name="environment", label="Environment"),
+ ),
+ actor_label_template="{repository} · {workflow} run {run_id}",
+ run_url_template="https://ci.example.com/{repository}/runs/{run_id}",
+ docs_url="https://example.com/docs/fake-ci",
+)
+
+
+def with_fake_workload_provider() -> "_patch[tuple[WorkloadProvider, ...]]":
+ return patch("posthog.workload_identity.providers.SUPPORTED_WORKLOAD_PROVIDERS", (FAKE_WORKLOAD_PROVIDER,))
diff --git a/posthog/workload_identity/test/test_providers.py b/posthog/workload_identity/test/test_providers.py
new file mode 100644
index 000000000000..6ced82640380
--- /dev/null
+++ b/posthog/workload_identity/test/test_providers.py
@@ -0,0 +1,29 @@
+import dataclasses
+from typing import Any
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.workload_identity.providers import WorkloadClaim
+from posthog.workload_identity.test.fixtures import FAKE_WORKLOAD_PROVIDER
+
+
+class TestWorkloadProviderEntry(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("template_field_not_recorded", {"actor_label_template": "{repository} · {job}"}),
+ ("positional_template_field", {"run_url_template": "https://ci.example.com/{}"}),
+ ("attribute_template_field", {"run_url_template": "https://ci.example.com/{repository.name}"}),
+ (
+ "duplicate_condition_claim",
+ {"condition_claims": (WorkloadClaim(name="ref", label="Ref"), WorkloadClaim(name="ref", label="Ref"))},
+ ),
+ ("subject_as_condition_claim", {"condition_claims": (WorkloadClaim(name="repository_id", label="ID"),)}),
+ ]
+ )
+ def test_rejects_an_entry_the_exchange_or_activity_log_cannot_use(
+ self, _name: str, overrides: dict[str, Any]
+ ) -> None:
+ with self.assertRaises(ValueError):
+ dataclasses.replace(FAKE_WORKLOAD_PROVIDER, **overrides)
diff --git a/posthog/workload_identity/test/test_trust_policy.py b/posthog/workload_identity/test/test_trust_policy.py
new file mode 100644
index 000000000000..e5347a12edae
--- /dev/null
+++ b/posthog/workload_identity/test/test_trust_policy.py
@@ -0,0 +1,309 @@
+from datetime import timedelta
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.db import IntegrityError, transaction
+from django.utils import timezone
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.email import CUSTOMER_IO_TEMPLATE_ID_MAP, WORKFLOWS_TEMPLATE_ID_MAP
+from posthog.models import Organization, OrganizationMembership, Team, User
+from posthog.models.activity_logging.activity_log import ActivityLog
+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.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 (
+ FAKE_WORKLOAD_ISSUER,
+ FAKE_WORKLOAD_PROVIDER,
+ with_fake_workload_provider,
+)
+from posthog.workload_identity.trust_policy import DUPLICATE_POLICY_MESSAGE, normalize_workload_conditions
+
+
+def _payload(**overrides: Any) -> dict[str, Any]:
+ return {
+ "name": "Production deploys",
+ "issuer": FAKE_WORKLOAD_ISSUER,
+ "subject_name": "acme/web",
+ "subject": "1234",
+ "conditions": {"ref": "refs/heads/main"},
+ "scopes": ["error_tracking:write", "annotation:write"],
+ **overrides,
+ }
+
+
+@with_fake_workload_provider()
+class TestWorkloadTrustPolicyAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.url = f"/api/projects/{self.team.id}/workload_trust_policies/"
+
+ def _set_level(self, level: OrganizationMembership.Level) -> None:
+ self.organization_membership.level = level
+ self.organization_membership.save()
+
+ def _create_policy(self, team: Team | None = None, **overrides: Any) -> WorkloadTrustPolicy:
+ fields = {**_payload(), **overrides}
+ 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}")
+
+ @parameterized.expand(
+ [
+ ("member", OrganizationMembership.Level.MEMBER, status.HTTP_403_FORBIDDEN),
+ ("admin", OrganizationMembership.Level.ADMIN, status.HTTP_201_CREATED),
+ ("owner", OrganizationMembership.Level.OWNER, status.HTTP_201_CREATED),
+ ]
+ )
+ def test_only_organization_admins_and_owners_can_create(
+ self, _name: str, level: OrganizationMembership.Level, expected_status: int
+ ) -> None:
+ self._set_level(level)
+
+ response = self.client.post(self.url, _payload(), format="json")
+
+ assert response.status_code == expected_status, response.json()
+
+ def test_risky_scopes_are_grantable_and_come_with_a_warning(self) -> None:
+ self._set_level(OrganizationMembership.Level.ADMIN)
+
+ created = self.client.post(self.url, _payload(scopes=["organization_member:write"]), format="json")
+ providers = self.client.get(f"{self.url}providers/").json()
+
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+ assert "organization_member:write" in providers["risky_scopes"]
+ assert "task:write" not in providers["grantable_scopes"]
+ assert [claim["label"] for claim in providers["supported"][0]["condition_claims"]] == [
+ "Branch or tag",
+ "Environment",
+ ]
+
+ def test_members_can_neither_read_nor_change_policies(self) -> None:
+ policy = self._create_policy()
+
+ list_response = self.client.get(self.url)
+ retrieve_response = self.client.get(f"{self.url}{policy.id}/")
+ providers_response = self.client.get(f"{self.url}providers/")
+ patch_response = self.client.patch(f"{self.url}{policy.id}/", {"enabled": False}, format="json")
+ delete_response = self.client.delete(f"{self.url}{policy.id}/")
+
+ assert list_response.status_code == status.HTTP_403_FORBIDDEN
+ assert retrieve_response.status_code == status.HTTP_403_FORBIDDEN
+ assert providers_response.status_code == status.HTTP_403_FORBIDDEN
+ assert patch_response.status_code == status.HTTP_403_FORBIDDEN
+ assert delete_response.status_code == status.HTTP_403_FORBIDDEN
+ policy.refresh_from_db()
+ assert policy.enabled is True
+
+ @parameterized.expand([("personal_api_key",), ("oauth_token",)])
+ def test_tokens_can_read_but_never_write_even_for_an_owner(self, kind: str) -> None:
+ self._set_level(OrganizationMembership.Level.OWNER)
+ policy = self._create_policy()
+ self._use_token(kind)
+
+ list_response = self.client.get(self.url)
+ create_response = self.client.post(self.url, _payload(conditions={"ref": "refs/heads/other"}), format="json")
+ patch_response = self.client.patch(f"{self.url}{policy.id}/", {"enabled": False}, format="json")
+ delete_response = self.client.delete(f"{self.url}{policy.id}/")
+
+ assert list_response.status_code == status.HTTP_200_OK, list_response.json()
+ assert create_response.status_code == status.HTTP_403_FORBIDDEN
+ assert patch_response.status_code == status.HTTP_403_FORBIDDEN
+ assert delete_response.status_code == status.HTTP_403_FORBIDDEN
+ assert WorkloadTrustPolicy.objects.for_team(self.team.id).count() == 1
+
+ @parameterized.expand(
+ [
+ ("unsupported_issuer", {"issuer": "https://token.actions.example.org"}, "issuer"),
+ ("wildcard_subject_name", {"subject_name": "acme/*"}, "subject_name"),
+ ("empty_subject", {"subject": ""}, "subject"),
+ ("no_conditions", {"conditions": {}}, "conditions"),
+ ("only_empty_conditions", {"conditions": {"ref": "", "environment": ""}}, "conditions"),
+ ("conditions_not_an_object", {"conditions": ["ref"]}, "conditions"),
+ ("condition_claim_the_provider_does_not_allow", {"conditions": {"sha": "abc123"}}, "conditions"),
+ ("non_string_condition_value", {"conditions": {"ref": 1}}, "conditions"),
+ ("null_condition_value", {"conditions": {"ref": None}}, "conditions"),
+ ("wildcard_condition_value", {"conditions": {"ref": "refs/heads/*"}}, "conditions"),
+ ("padded_condition_value", {"conditions": {"ref": " refs/heads/main"}}, "conditions"),
+ ("null_character_in_condition_value", {"conditions": {"ref": "refs/heads/main\x00"}}, "conditions"),
+ ("overlong_condition_value", {"conditions": {"ref": "r" * 201}}, "conditions"),
+ ("no_scopes", {"scopes": []}, "scopes"),
+ ("unknown_scope", {"scopes": ["not_a_thing:read"]}, "scopes"),
+ ("privileged_scope", {"scopes": ["llm_gateway:read"]}, "scopes"),
+ ("credential_scope", {"scopes": ["project:write"]}, "scopes"),
+ ("own_policy_scope", {"scopes": ["workload_trust_policy:read"]}, "scopes"),
+ ("agent_run_scope", {"scopes": ["task:write"]}, "scopes"),
+ ("training_run_scope", {"scopes": ["autoresearch:write"]}, "scopes"),
+ ("owner_account_scope", {"scopes": ["user:write"]}, "scopes"),
+ ("app_token_scope", {"scopes": ["streamlit_app:read"]}, "scopes"),
+ ("webhook_feed_scope", {"scopes": ["webhook:write"]}, "scopes"),
+ ("batch_export_feed_scope", {"scopes": ["batch_export:write"]}, "scopes"),
+ ("subscription_feed_scope", {"scopes": ["subscription:write"]}, "scopes"),
+ ("sharing_link_scope", {"scopes": ["sharing_configuration:write"]}, "scopes"),
+ ("sharing_link_read_scope", {"scopes": ["sharing_configuration:read"]}, "scopes"),
+ ("owner_ai_chat_scope", {"scopes": ["conversation:read"]}, "scopes"),
+ ("owner_task_scope", {"scopes": ["task:read"]}, "scopes"),
+ ]
+ )
+ def test_rejects_invalid_policies(self, _name: str, overrides: dict[str, Any], field: str) -> None:
+ self._set_level(OrganizationMembership.Level.ADMIN)
+
+ response = self.client.post(self.url, _payload(**overrides), format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == field
+ assert not WorkloadTrustPolicy.objects.for_team(self.team.id).exists()
+
+ def test_impersonated_sessions_can_read_but_not_change_policies(self) -> None:
+ self._set_level(OrganizationMembership.Level.OWNER)
+ policy = self._create_policy()
+
+ with patch("posthog.workload_identity.trust_policy.is_impersonated", return_value=True):
+ list_response = self.client.get(self.url)
+ create_response = self.client.post(
+ self.url, _payload(conditions={"ref": "refs/heads/other"}), format="json"
+ )
+ patch_response = self.client.patch(f"{self.url}{policy.id}/", {"enabled": False}, format="json")
+ delete_response = self.client.delete(f"{self.url}{policy.id}/")
+
+ assert list_response.status_code == status.HTTP_200_OK
+ assert create_response.status_code == status.HTTP_403_FORBIDDEN
+ assert patch_response.status_code == status.HTTP_403_FORBIDDEN
+ assert delete_response.status_code == status.HTTP_403_FORBIDDEN
+ assert WorkloadTrustPolicy.objects.for_team(self.team.id).count() == 1
+
+ def test_rejects_a_second_policy_whose_conditions_differ_only_by_an_empty_value(self) -> None:
+ self._set_level(OrganizationMembership.Level.ADMIN)
+ self._create_policy()
+
+ response = self.client.post(
+ self.url,
+ _payload(name="Duplicate", conditions={"environment": "", "ref": "refs/heads/main"}),
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["detail"] == DUPLICATE_POLICY_MESSAGE
+
+ @parameterized.expand(
+ [
+ (
+ "key_order",
+ {"ref": "refs/heads/main", "environment": "production"},
+ {"environment": "production", "ref": "refs/heads/main"},
+ False,
+ ),
+ ("empty_valued_key", {"ref": "refs/heads/main"}, {"ref": "refs/heads/main", "environment": ""}, False),
+ ("different_value", {"ref": "refs/heads/main"}, {"ref": "refs/heads/release"}, True),
+ (
+ "extra_condition",
+ {"ref": "refs/heads/main"},
+ {"ref": "refs/heads/main", "environment": "production"},
+ True,
+ ),
+ ]
+ )
+ def test_unique_constraint_compares_conditions_by_content(
+ self, _name: str, stored: dict[str, str], second: dict[str, str], allowed: bool
+ ) -> None:
+ self._create_policy(conditions=stored)
+ normalized = normalize_workload_conditions(second, FAKE_WORKLOAD_PROVIDER)
+
+ if allowed:
+ self._create_policy(name="Second", conditions=normalized)
+ else:
+ with self.assertRaises(IntegrityError), transaction.atomic():
+ self._create_policy(name="Second", conditions=normalized)
+
+ assert "" not in normalized.values()
+ assert WorkloadTrustPolicy.objects.for_team(self.team.id).count() == (2 if allowed else 1)
+
+ def test_policies_of_other_projects_are_not_listed(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other project")
+ self._create_policy(team=other_team)
+ self._set_level(OrganizationMembership.Level.ADMIN)
+
+ response = self.client.get(self.url)
+
+ assert response.json()["results"] == []
+
+ @patch("posthog.workload_identity.trust_policy.send_workload_trust_policy_changed")
+ def test_every_change_is_logged_and_emailed_to_admins(self, mock_send: MagicMock) -> None:
+ self._set_level(OrganizationMembership.Level.ADMIN)
+
+ with self.captureOnCommitCallbacks(execute=True):
+ policy_id = self.client.post(self.url, _payload(), format="json").json()["id"]
+ with self.captureOnCommitCallbacks(execute=True):
+ self.client.patch(f"{self.url}{policy_id}/", {"scopes": ["annotation:write"]}, format="json")
+ with self.captureOnCommitCallbacks(execute=True):
+ self.client.delete(f"{self.url}{policy_id}/")
+
+ activities = list(
+ ActivityLog.objects.filter(scope="WorkloadTrustPolicy", item_id=policy_id)
+ .order_by("created_at")
+ .values_list("activity", flat=True)
+ )
+ assert activities == ["created", "updated", "deleted"]
+ assert [call.args[3] for call in mock_send.delay.call_args_list] == ["created", "updated", "deleted"]
+ assert {call.args[4] for call in mock_send.delay.call_args_list} == {self.user.id}
+
+
+class TestSendWorkloadTrustPolicyChangedEmail(APIBaseTest):
+ @patch("posthog.tasks.email.EmailMessage")
+ def test_emails_every_active_admin_and_owner(self, MockEmailMessage: MagicMock) -> None:
+ set_instance_setting("EMAIL_HOST", "fake_host")
+ set_instance_setting("EMAIL_ENABLED", True)
+ sent = mock_email_messages(MockEmailMessage)
+ self.organization_membership.level = OrganizationMembership.Level.OWNER
+ self.organization_membership.save()
+ admin = User.objects.create_and_join(self.organization, "[email protected]", None)
+ OrganizationMembership.objects.filter(user=admin).update(level=OrganizationMembership.Level.ADMIN)
+ User.objects.create_and_join(self.organization, "[email protected]", None)
+ inactive_admin = User.objects.create_and_join(self.organization, "[email protected]", None)
+ OrganizationMembership.objects.filter(user=inactive_admin).update(level=OrganizationMembership.Level.ADMIN)
+ inactive_admin.is_active = False
+ inactive_admin.save()
+ other_org = Organization.objects.create(name="Other")
+ User.objects.create_and_join(other_org, "[email protected]", None, level=OrganizationMembership.Level.OWNER)
+
+ send_workload_trust_policy_changed(self.team.id, "policy-id", "Production deploys", "created", self.user.id)
+
+ assert len(sent) == 1
+ assert sorted(recipient["raw_email"] for recipient in sent[0].to) == sorted(
+ [self.user.email, "[email protected]"]
+ )
+ assert "Production deploys" in sent[0].html_body
+ 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
diff --git a/posthog/workload_identity/trust_policy.py b/posthog/workload_identity/trust_policy.py
new file mode 100644
index 000000000000..3e97cb03e6f5
--- /dev/null
+++ b/posthog/workload_identity/trust_policy.py
@@ -0,0 +1,386 @@
+"""Workload trust policies: which workloads, such as CI jobs, may exchange an OIDC token for a project
+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.
+"""
+
+import json
+from typing import Any, cast
+
+from django.db import IntegrityError, transaction
+from django.db.models import QuerySet
+
+from drf_spectacular.utils import extend_schema, extend_schema_field
+from rest_framework import serializers, viewsets
+from rest_framework.permissions import SAFE_METHODS, BasePermission
+from rest_framework.request import Request
+from rest_framework.response import Response
+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.helpers.impersonation import is_impersonated
+from posthog.models import Team, User
+from posthog.models.workload_trust_policy import (
+ CONDITION_VALUE_MAX_LENGTH,
+ CONDITIONS_MAX_BYTES,
+ WorkloadTrustPolicy,
+ workload_trust_policy_grantable_scopes,
+ workload_trust_policy_scopes_not_grantable,
+)
+from posthog.permissions import OrganizationAdminReadPermissions, TimeSensitiveActionPermission
+from posthog.scopes import RISKY_SCOPE_WARNINGS
+from posthog.tasks.email import WorkloadTrustPolicyChange, send_workload_trust_policy_changed
+from posthog.workload_identity.providers import (
+ WorkloadProvider,
+ get_supported_workload_providers,
+ get_workload_provider_by_issuer,
+ normalize_issuer,
+)
+
+# 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("*?[]")
+DUPLICATE_POLICY_MESSAGE = "A policy for this workload with the same conditions already exists."
+FALLBACK_SUBJECT_LABEL = "Subject"
+FALLBACK_SUBJECT_NAME_LABEL = "Name"
+
+
+def _validate_exact_value(value: str, field_label: str) -> str:
+ stripped = value.strip()
+ if stripped != value:
+ raise serializers.ValidationError(f"{field_label} must not start or end with whitespace.")
+ if "\x00" in value:
+ raise serializers.ValidationError(f"{field_label} must not contain a null character.")
+ if any(character in WILDCARD_CHARACTERS for character in value):
+ raise serializers.ValidationError(f"{field_label} must be an exact value. Wildcards are not supported.")
+ return value
+
+
+def normalize_workload_conditions(conditions: Any, provider: WorkloadProvider) -> dict[str, str]:
+ """The only form a policy or a request stores: the provider's condition claims, each with a non-empty
+ exact string value, and the keys sorted. An empty value means the condition is not set, so it is
+ dropped rather than stored as `""`, which would match no token and break the uniqueness check."""
+ if not isinstance(conditions, dict):
+ raise serializers.ValidationError({"conditions": "Send conditions as an object of claim names and values."})
+ labels = {claim.name: claim.label for claim in provider.condition_claims}
+ normalized: dict[str, str] = {}
+ for claim, value in conditions.items():
+ if claim not in labels:
+ allowed = ", ".join(labels) or "none"
+ raise serializers.ValidationError(
+ {
+ "conditions": f"{provider.name} doesn't support a condition on {str(claim)[:100]!r}. Allowed: {allowed}."
+ }
+ )
+ label = labels[claim]
+ if not isinstance(value, str):
+ raise serializers.ValidationError({"conditions": f"{label} must be text."})
+ if not value:
+ continue
+ if len(value) > CONDITION_VALUE_MAX_LENGTH:
+ raise serializers.ValidationError(
+ {"conditions": f"{label} can be at most {CONDITION_VALUE_MAX_LENGTH} characters long."}
+ )
+ try:
+ normalized[claim] = _validate_exact_value(value, label)
+ except serializers.ValidationError as e:
+ raise serializers.ValidationError({"conditions": e.detail})
+ canonical = dict(sorted(normalized.items()))
+ if len(json.dumps(canonical, ensure_ascii=False).encode()) > CONDITIONS_MAX_BYTES:
+ raise serializers.ValidationError({"conditions": "The conditions are too long. Shorten the values."})
+ return canonical
+
+
+def validate_workload_trust_conditions(attrs: dict[str, Any], *, instance: Any | None = None) -> dict[str, Any]:
+ """Shared by policies and policy requests, so both enforce the same conditions. Normalizes
+ `attrs["conditions"]` against the issuer's provider whenever the issuer or the conditions change."""
+ if instance is not None and "issuer" not in attrs and "conditions" not in attrs:
+ # Disabling or renaming a policy stays possible after its provider leaves the registry.
+ return attrs
+ issuer = attrs["issuer"] if "issuer" in attrs else getattr(instance, "issuer", "")
+ provider = get_workload_provider_by_issuer(issuer)
+ if provider is None:
+ raise serializers.ValidationError({"issuer": "This issuer isn't a supported workload provider."})
+ raw_conditions = attrs["conditions"] if "conditions" in attrs else getattr(instance, "conditions", {})
+ attrs["conditions"] = normalize_workload_conditions(raw_conditions, provider)
+ if provider.condition_claims and not attrs["conditions"]:
+ labels = ", ".join(claim.label for claim in provider.condition_claims)
+ raise serializers.ValidationError(
+ {
+ "conditions": f"Set at least one condition ({labels}) so the policy doesn't match every token for this workload."
+ }
+ )
+ return attrs
+
+
+@extend_schema_field(serializers.DictField(child=serializers.CharField()))
+class WorkloadConditionsField(serializers.Field):
+ """Claim name to required value. The serializer's `validate` normalizes it once the provider is known."""
+
+ def to_internal_value(self, data: Any) -> Any:
+ return data
+
+ def to_representation(self, value: Any) -> dict[str, Any]:
+ return dict(sorted(value.items())) if isinstance(value, dict) else {}
+
+
+class WorkloadClaimLabelsSerializer(serializers.Serializer):
+ subject = serializers.CharField(help_text="What the provider calls the subject, for example Repository ID.")
+ subject_name = serializers.CharField(help_text="What the provider calls the subject name, for example Repository.")
+ conditions = serializers.DictField(
+ child=serializers.CharField(),
+ help_text="The label of each condition claim the provider allows, keyed by claim name.",
+ )
+
+
+def workload_claim_labels(issuer: str) -> dict[str, Any]:
+ provider = get_workload_provider_by_issuer(issuer)
+ if provider is None:
+ return {"subject": FALLBACK_SUBJECT_LABEL, "subject_name": FALLBACK_SUBJECT_NAME_LABEL, "conditions": {}}
+ return {
+ "subject": provider.subject_claim.label,
+ "subject_name": provider.subject_name_claim.label,
+ "conditions": {claim.name: claim.label for claim in provider.condition_claims},
+ }
+
+
+class CIScopeListField(serializers.ListField):
+ child = serializers.CharField(max_length=100)
+
+ def __init__(self, **kwargs: Any) -> None:
+ super().__init__(allow_empty=False, **kwargs)
+
+ def to_internal_value(self, data: Any) -> list[str]:
+ scopes = super().to_internal_value(data)
+ not_grantable = workload_trust_policy_scopes_not_grantable(scopes)
+ if not_grantable:
+ raise serializers.ValidationError(
+ f"These scopes can't be granted to workloads: {', '.join(not_grantable)}. "
+ "A workload token can't outlive itself or change its own policy, and can't use privileged or hidden scopes."
+ )
+ return sorted(set(scopes))
+
+
+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.",
+ )
+ provider = serializers.SerializerMethodField(help_text="The key of the workload provider the issuer belongs to.")
+ subject_name = serializers.CharField(
+ max_length=255,
+ help_text=(
+ "The workload's human-readable name, from the provider's subject name claim, for example a repository's "
+ "full name. Matched exactly."
+ ),
+ )
+ subject = serializers.CharField(
+ max_length=255,
+ help_text=(
+ "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 = WorkloadConditionsField(
+ required=False,
+ help_text=(
+ "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."
+ ),
+ )
+ claim_labels = serializers.SerializerMethodField(
+ help_text="How the provider names the subject, the subject name and each condition claim, for display."
+ )
+ scopes = CIScopeListField(
+ help_text=(
+ "The scopes every token minted under this policy carries. Scopes that manage credentials or access "
+ "are refused."
+ )
+ )
+ enabled = serializers.BooleanField(
+ required=False, help_text="Whether the policy can mint tokens. Disabling it cuts off its tokens."
+ )
+ created_by = UserBasicSerializer(read_only=True, allow_null=True)
+
+ class Meta:
+ model = WorkloadTrustPolicy
+ fields = [
+ "id",
+ "name",
+ "issuer",
+ "provider",
+ "subject_name",
+ "subject",
+ "conditions",
+ "claim_labels",
+ "scopes",
+ "enabled",
+ "created_by",
+ "created_at",
+ "updated_at",
+ ]
+ 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"]())
+ identity = {
+ field: attrs.get(field, getattr(self.instance, field, None))
+ for field in ("issuer", "subject", "conditions")
+ }
+ clash = WorkloadTrustPolicy.objects.filter(**identity)
+ if self.instance is not None:
+ clash = clash.exclude(pk=self.instance.pk)
+ if clash.exists():
+ raise serializers.ValidationError(DUPLICATE_POLICY_MESSAGE)
+ attrs["team"] = team
+ return attrs
+
+ def create(self, validated_data: dict[str, Any]) -> WorkloadTrustPolicy:
+ try:
+ return super().create(validated_data)
+ except IntegrityError:
+ # Two writes with the same conditions can both pass the check in `validate`.
+ raise serializers.ValidationError(DUPLICATE_POLICY_MESSAGE)
+
+ def update(self, instance: WorkloadTrustPolicy, validated_data: dict[str, Any]) -> WorkloadTrustPolicy:
+ try:
+ return super().update(instance, validated_data)
+ except IntegrityError:
+ raise serializers.ValidationError(DUPLICATE_POLICY_MESSAGE)
+
+
+class WorkloadClaimSerializer(serializers.Serializer):
+ name = serializers.CharField(help_text="The claim's name in the provider's OIDC token.")
+ label = serializers.CharField(help_text="What to call the claim in the UI.") # type: ignore[assignment]
+ help_text = serializers.CharField( # type: ignore[assignment]
+ allow_blank=True, help_text="A hint that says where to find the claim's value."
+ )
+
+
+class WorkloadProviderSerializer(serializers.Serializer):
+ key = serializers.CharField(help_text="Stable identifier of the provider.")
+ name = serializers.CharField(help_text="Display name of the provider.")
+ issuer = serializers.CharField(help_text="OIDC issuer a policy for this provider uses.")
+ docs_url = serializers.CharField(help_text="Where to read how to set the provider up.")
+ subject_claim = WorkloadClaimSerializer(help_text="The claim that carries the workload's immutable ID.")
+ subject_name_claim = WorkloadClaimSerializer(help_text="The claim that carries the workload's readable name.")
+ condition_claims = WorkloadClaimSerializer(
+ many=True, help_text="The claims a policy can require an exact value for, in display order."
+ )
+
+
+class WorkloadProvidersResponseSerializer(serializers.Serializer):
+ supported = WorkloadProviderSerializer(many=True, help_text="Providers a policy can trust.")
+ grantable_scopes = serializers.ListField(
+ child=serializers.CharField(), help_text="Every scope a policy's ceiling may hold."
+ )
+ risky_scopes = serializers.DictField(
+ child=serializers.CharField(),
+ help_text="What each grantable risky scope lets a token do, keyed by scope. Show it so people add the scope with care.",
+ )
+
+
+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."""
+
+ message = (
+ "Workload trust policies act as the organization owner, so they can't be changed while impersonating a user."
+ )
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ return request.method in SAFE_METHODS or not is_impersonated(request)
+
+
+class BrowserSessionWritePermission(BasePermission):
+ """Writes need a browser session. Every token type gets a 403, because a token can only ask for a
+ policy, which an admin then approves in the browser."""
+
+ message = "Workload trust policies can only be changed in the PostHog app, by an organization admin."
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ if request.method in SAFE_METHODS:
+ return True
+ return isinstance(request.successful_authenticator, SessionAuthentication)
+
+
+@extend_schema(extensions={"x-product": "core"})
+class WorkloadTrustPolicyViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+ scope_object = "workload_trust_policy"
+ queryset = WorkloadTrustPolicy.objects.unscoped()
+ serializer_class = WorkloadTrustPolicySerializer
+ lookup_field = "id"
+ permission_classes = [
+ BrowserSessionWritePermission,
+ NotImpersonatedWritePermission,
+ TimeSensitiveActionPermission,
+ OrganizationAdminReadPermissions,
+ ]
+
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ return WorkloadTrustPolicy.objects.all().select_related("created_by").order_by("-created_at")
+
+ def perform_create(self, serializer: serializers.BaseSerializer) -> None:
+ policy = serializer.save(created_by=self.request.user)
+ self._notify_admins(policy, "created")
+
+ def perform_update(self, serializer: serializers.BaseSerializer) -> None:
+ policy = serializer.save()
+ self._notify_admins(policy, "updated")
+
+ 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,
+ )
+
+ @extend_schema(responses={200: WorkloadProvidersResponseSerializer})
+ @action(methods=["GET"], detail=False, required_scopes=["workload_trust_policy:read"], pagination_class=None)
+ def providers(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ grantable = workload_trust_policy_grantable_scopes()
+ payload = {
+ "supported": get_supported_workload_providers(),
+ "grantable_scopes": sorted(grantable),
+ "risky_scopes": {scope: warning for scope, warning in RISKY_SCOPE_WARNINGS.items() if scope in grantable},
+ }
+ return Response(WorkloadProvidersResponseSerializer(payload).data)
diff --git a/products/access_control/frontend/generated/api.schemas.ts b/products/access_control/frontend/generated/api.schemas.ts
index 22247cfab34d..cb4b11806b75 100644
--- a/products/access_control/frontend/generated/api.schemas.ts
+++ b/products/access_control/frontend/generated/api.schemas.ts
@@ -165,6 +165,7 @@ export const ResolvedAccessSourceSubjectEnumApi = {
* * `webhook` - webhook
* * `wizard_session` - wizard_session
* * `wizard_run` - wizard_run
+ * * `workload_trust_policy` - workload_trust_policy
*/
export type ScopeObjectEnumApi = (typeof ScopeObjectEnumApi)[keyof typeof ScopeObjectEnumApi]
@@ -289,6 +290,7 @@ export const ScopeObjectEnumApi = {
Webhook: 'webhook',
WizardSession: 'wizard_session',
WizardRun: 'wizard_run',
+ WorkloadTrustPolicy: 'workload_trust_policy',
} as const
/**
@@ -435,7 +437,8 @@ export interface ProjectAccessSourceApi {
* * `web_analytics` - web_analytics
* * `webhook` - webhook
* * `wizard_session` - wizard_session
- * * `wizard_run` - wizard_run */
+ * * `wizard_run` - wizard_run
+ * * `workload_trust_policy` - workload_trust_policy */
source_resource: ScopeObjectEnumApi
/**
* The deciding rule's object id, when it is an object-level rule (e.g. the source a table inherits from).
@@ -602,7 +605,8 @@ export interface AccessControlObjectRuleApi {
* * `web_analytics` - web_analytics
* * `webhook` - webhook
* * `wizard_session` - wizard_session
- * * `wizard_run` - wizard_run */
+ * * `wizard_run` - wizard_run
+ * * `workload_trust_policy` - workload_trust_policy */
resource: ScopeObjectEnumApi
/** The object's primary key. */
resource_id: string
@@ -997,7 +1001,8 @@ export interface AccessControlObjectRuleResourceApi {
* * `web_analytics` - web_analytics
* * `webhook` - webhook
* * `wizard_session` - wizard_session
- * * `wizard_run` - wizard_run */
+ * * `wizard_run` - wizard_run
+ * * `workload_trust_policy` - workload_trust_policy */
resource: ScopeObjectEnumApi
/** The levels an object rule on this resource type accepts, lowest first. */
available_access_levels: string[]
@@ -1287,7 +1292,8 @@ export interface ResolvedAccessApi {
* * `web_analytics` - web_analytics
* * `webhook` - webhook
* * `wizard_session` - wizard_session
- * * `wizard_run` - wizard_run */
+ * * `wizard_run` - wizard_run
+ * * `workload_trust_policy` - workload_trust_policy */
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 6974740e3d57..3218707cf5c5 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -1594,6 +1594,7 @@ export type ActivityLogListParams = {
* * `PersonalAPIKey` - PersonalAPIKey
* * `ProjectSecretAPIKey` - ProjectSecretAPIKey
* * `OAuthApplication` - OAuthApplication
+ * * `WorkloadTrustPolicy` - WorkloadTrustPolicy
* * `User` - User
* * `Action` - Action
* * `AccountView` - AccountView
@@ -1712,6 +1713,7 @@ export const ActivityLogListScope = {
PersonalAPIKey: 'PersonalAPIKey',
ProjectSecretAPIKey: 'ProjectSecretAPIKey',
OAuthApplication: 'OAuthApplication',
+ WorkloadTrustPolicy: 'WorkloadTrustPolicy',
User: 'User',
Action: 'Action',
AccountView: 'AccountView',
@@ -1817,6 +1819,7 @@ export const ActivityLogListScope = {
* * `PersonalAPIKey` - PersonalAPIKey
* * `ProjectSecretAPIKey` - ProjectSecretAPIKey
* * `OAuthApplication` - OAuthApplication
+ * * `WorkloadTrustPolicy` - WorkloadTrustPolicy
* * `User` - User
* * `Action` - Action
* * `AccountView` - AccountView
@@ -1923,6 +1926,7 @@ export const ActivityLogListScopesItem = {
PersonalAPIKey: 'PersonalAPIKey',
ProjectSecretAPIKey: 'ProjectSecretAPIKey',
OAuthApplication: 'OAuthApplication',
+ WorkloadTrustPolicy: 'WorkloadTrustPolicy',
User: 'User',
Action: 'Action',
AccountView: 'AccountView',
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index be2c83a777c8..d7c32bf479ea 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -836,6 +836,7 @@ export namespace Schemas {
* * `webhook` - webhook
* * `wizard_session` - wizard_session
* * `wizard_run` - wizard_run
+ * * `workload_trust_policy` - workload_trust_policy
*/
export type ScopeObjectEnum = typeof ScopeObjectEnum[keyof typeof ScopeObjectEnum];
@@ -961,6 +962,7 @@ export namespace Schemas {
Webhook: 'webhook',
WizardSession: 'wizard_session',
WizardRun: 'wizard_run',
+ WorkloadTrustPolicy: 'workload_trust_policy',
} as const;
export interface AccessControlObjectRuleResource {
@@ -1085,7 +1087,8 @@ export namespace Schemas {
* * `web_analytics` - web_analytics
* * `webhook` - webhook
* * `wizard_session` - wizard_session
- * * `wizard_run` - wizard_run */
+ * * `wizard_run` - wizard_run
+ * * `workload_trust_policy` - workload_trust_policy */
resource: ScopeObjectEnum;
/** The levels an object rule on this resource type accepts, lowest first. */
available_access_levels: string[];
@@ -1333,7 +1336,8 @@ export namespace Schemas {
* * `web_analytics` - web_analytics
* * `webhook` - webhook
* * `wizard_session` - wizard_session
- * * `wizard_run` - wizard_run */
+ * * `wizard_run` - wizard_run
+ * * `workload_trust_policy` - workload_trust_policy */
source_resource: ScopeObjectEnum;
/**
* The deciding rule's object id, when it is an object-level rule (e.g. the source a table inherits from).
@@ -1747,7 +1751,8 @@ export namespace Schemas {
* * `web_analytics` - web_analytics
* * `webhook` - webhook
* * `wizard_session` - wizard_session
- * * `wizard_run` - wizard_run */
+ * * `wizard_run` - wizard_run
+ * * `workload_trust_policy` - workload_trust_policy */
resource: ScopeObjectEnum;
/** The object's primary key. */
resource_id: string;
@@ -65239,7 +65244,8 @@ export namespace Schemas {
* * `web_analytics` - web_analytics
* * `webhook` - webhook
* * `wizard_session` - wizard_session
- * * `wizard_run` - wizard_run */
+ * * `wizard_run` - wizard_run
+ * * `workload_trust_policy` - workload_trust_policy */
source_resource: ScopeObjectEnum;
/**
* The deciding rule's object id, when it is an object-level rule (e.g. the source a table inherits from).
@@ -78106,6 +78112,77 @@ export namespace Schemas {
results: WorkflowProposal[];
}
+ /**
+ * The label of each condition claim the provider allows, keyed by claim name.
+ */
+ export type WorkloadClaimLabelsConditions = {[key: string]: string};
+
+ export interface WorkloadClaimLabels {
+ /** What the provider calls the subject, for example Repository ID. */
+ subject: string;
+ /** What the provider calls the subject name, for example Repository. */
+ subject_name: string;
+ /** The label of each condition claim the provider allows, keyed by claim name. */
+ conditions: WorkloadClaimLabelsConditions;
+ }
+
+ /**
+ * 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 WorkloadTrustPolicyConditions = {[key: string]: string};
+
+ export interface WorkloadTrustPolicy {
+ readonly id: string;
+ /**
+ * A name that says what the policy is for.
+ * @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 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?: WorkloadTrustPolicyConditions;
+ /** How the provider names the subject, the subject name and each condition claim, for display. */
+ readonly claim_labels: WorkloadClaimLabels;
+ /**
+ * The scopes every token minted under this policy carries. Scopes that manage credentials or access are refused.
+ * @items.maxLength 100
+ */
+ scopes: string[];
+ /** Whether the policy can mint tokens. Disabling it cuts off its tokens. */
+ enabled?: boolean;
+ readonly created_by: UserBasic | null;
+ readonly created_at: string;
+ readonly updated_at: string;
+ }
+
+ export interface PaginatedWorkloadTrustPolicyList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: WorkloadTrustPolicy[];
+ }
+
/**
* * `sum` - Sum
* * `avg` - Avg
@@ -88541,6 +88618,54 @@ export namespace Schemas {
capture_workflows_engagement_events?: boolean;
}
+ /**
+ * 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 PatchedWorkloadTrustPolicyConditions = {[key: string]: string};
+
+ export interface PatchedWorkloadTrustPolicy {
+ readonly id?: string;
+ /**
+ * A name that says what the policy is for.
+ * @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 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?: PatchedWorkloadTrustPolicyConditions;
+ /** How the provider names the subject, the subject name and each condition claim, for display. */
+ readonly claim_labels?: WorkloadClaimLabels;
+ /**
+ * The scopes every token minted under this policy carries. Scopes that manage credentials or access are refused.
+ * @items.maxLength 100
+ */
+ scopes?: string[];
+ /** Whether the policy can mint tokens. Disabling it cuts off its tokens. */
+ enabled?: boolean;
+ readonly created_by?: UserBasic | null;
+ readonly created_at?: string;
+ readonly updated_at?: string;
+ }
+
export interface PathCleaningPreviewExample {
/** A real sampled path before the suggested rules are applied. */
before: string;
@@ -115398,6 +115523,46 @@ export namespace Schemas {
failed: number;
}
+ export interface WorkloadClaim {
+ /** The claim's name in the provider's OIDC token. */
+ name: string;
+ /** What to call the claim in the UI. */
+ label: string;
+ /** A hint that says where to find the claim's value. */
+ help_text: string;
+ }
+
+ export interface WorkloadProvider {
+ /** Stable identifier of the provider. */
+ key: string;
+ /** Display name of the provider. */
+ name: string;
+ /** OIDC issuer a policy for this provider uses. */
+ issuer: string;
+ /** Where to read how to set the provider up. */
+ docs_url: string;
+ /** The claim that carries the workload's immutable ID. */
+ subject_claim: WorkloadClaim;
+ /** The claim that carries the workload's readable name. */
+ subject_name_claim: WorkloadClaim;
+ /** The claims a policy can require an exact value for, in display order. */
+ condition_claims: WorkloadClaim[];
+ }
+
+ /**
+ * What each grantable risky scope lets a token do, keyed by scope. Show it so people add the scope with care.
+ */
+ export type WorkloadProvidersResponseRiskyScopes = {[key: string]: string};
+
+ export interface WorkloadProvidersResponse {
+ /** Providers a policy can trust. */
+ supported: WorkloadProvider[];
+ /** Every scope a policy's ceiling may hold. */
+ grantable_scopes: string[];
+ /** What each grantable risky scope lets a token do, keyed by scope. Show it so people add the scope with care. */
+ risky_scopes: WorkloadProvidersResponseRiskyScopes;
+ }
+
export interface ZendeskImportError {
/** Human-readable error message. */
detail: string;
@@ -119725,6 +119890,7 @@ export namespace Schemas {
* * `PersonalAPIKey` - PersonalAPIKey
* * `ProjectSecretAPIKey` - ProjectSecretAPIKey
* * `OAuthApplication` - OAuthApplication
+ * * `WorkloadTrustPolicy` - WorkloadTrustPolicy
* * `User` - User
* * `Action` - Action
* * `AccountView` - AccountView
@@ -119844,6 +120010,7 @@ export namespace Schemas {
PersonalAPIKey: 'PersonalAPIKey',
ProjectSecretAPIKey: 'ProjectSecretAPIKey',
OAuthApplication: 'OAuthApplication',
+ WorkloadTrustPolicy: 'WorkloadTrustPolicy',
User: 'User',
Action: 'Action',
AccountView: 'AccountView',
@@ -119949,6 +120116,7 @@ export namespace Schemas {
* * `PersonalAPIKey` - PersonalAPIKey
* * `ProjectSecretAPIKey` - ProjectSecretAPIKey
* * `OAuthApplication` - OAuthApplication
+ * * `WorkloadTrustPolicy` - WorkloadTrustPolicy
* * `User` - User
* * `Action` - Action
* * `AccountView` - AccountView
@@ -120056,6 +120224,7 @@ export namespace Schemas {
PersonalAPIKey: 'PersonalAPIKey',
ProjectSecretAPIKey: 'ProjectSecretAPIKey',
OAuthApplication: 'OAuthApplication',
+ WorkloadTrustPolicy: 'WorkloadTrustPolicy',
User: 'User',
Action: 'Action',
AccountView: 'AccountView',
@@ -134927,6 +135096,17 @@ export namespace Schemas {
hog_flow_id: string;
};
+ export type WorkloadTrustPoliciesListParams = {
+ /**
+ * 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 91973e3b6711..b941c49690af 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -242,6 +242,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'web_analytics:write',
'webhook:read',
'webhook:write',
+ 'workload_trust_policy:read',
+ 'workload_trust_policy:write',
] as const
export type OAuthScope = (typeof OAUTH_SCOPES_SUPPORTED)[number]