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(activity-log): show workloads as the actor of workload token changes (#127787)

Rafael Audiberted03cfadf5e0
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.md
index 7ab1476ae60a..302aad4270f0 100644
--- a/docs/internal/activity-logging.md
+++ b/docs/internal/activity-logging.md
@@ -202,6 +202,17 @@ The request thread only appends to an in-process queue; a background thread writ
When the payload also sets `mcp_render_enabled`, the activity summary build reads the buffer and renders one line per MCP session in the summary input.
A failed read gives an empty section and sets `mcp_read_error` in the build's `inputs_used`; it never fails the build.
+### Workload writes
+
+A row written with a workload access token (credential type `oidc_workload`) records the workload on the row itself, so it renders after the token expires.
+When the product passes no trigger of its own, `log_activity` fills it with `Trigger(job_type="workload", job_id=<trust policy id>, payload=...)`.
+The payload holds the provider, the actor label, the subject name, the claims the provider's registry entry records (`claims`) with their labels (`claim_labels`), the run link, and the trust policy's id and name.
+The actor label and the run link come from the provider's templates, formatted with the recorded claims.
+A workload trigger comes before an agent trigger, because the server verified the workload and agent intent is a claim.
+The row also gets the server-derived client tag `workload:<subject name>`, and the API drops an `x-posthog-client` header that claims the `workload:` prefix.
+The activity log names the workload as the actor, using its provider's actor label, linked to its run and its trust policy, instead of the organization owner the token acts as.
+Filter these rows with the client filter, or with a detail filter on `trigger.payload.subject_name` or a recorded claim such as `trigger.payload.claims.run_id`.
+
### Client IP
`ActivityLoggingMiddleware` stores the request's client IP, and `log_activity` writes it to `ActivityLog.ip_address`.
diff --git a/ee/hogai/context/activity_log/context.py b/ee/hogai/context/activity_log/context.py
index c98069995626..1f6d6395f53d 100644
--- a/ee/hogai/context/activity_log/context.py
+++ b/ee/hogai/context/activity_log/context.py
@@ -30,6 +30,8 @@ MAX_VALUE_LENGTH = 200
SCOPE_DISPLAY_NAMES: dict[str, str] = {
"AlertConfiguration": "Alert",
"BatchExport": "Destination",
+ "WorkloadTrustPolicy": "Workload trust policy",
+ "WorkloadTrustPolicyRequest": "Workload trust policy request",
"ExternalDataSource": "Source",
"HogFunction": "Data pipeline",
"PersonalAPIKey": "Personal API key",
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 0b2b2b9f70a8..c8642bf82f12 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -392,6 +392,10 @@ snapshots:
hash: v1.k794b7964.4f7b276bd60977800b9ea20ddd221bffb6ccda7814b973e7b07bdaa85467996c.l51S8oLHNfi5ewuK9InQ4F9ixNJfXEeXnVLGXkyxucM
components-activitylogrow--narrow-dashboard-changes--light:
hash: v1.k794b7964.095ac6cc7ea7e35c94ab04aa2241c01e5ef3fdaa46d4fcde75ac76fae3ff01ad.F9DiID4HmI2V97skUnG3PT25MCLIAGxOda6D-BvVf_k
+ components-activitylogrow--workload-change--dark:
+ hash: v1.k794b7964.2c48852df684b5cabc7065e8d7c5a3ca4848a3a4f53f07ad9985c40a0d555b88.q1Nnm_FvhVo_ZMIEiSEciO0Hfj3aUXuwuymGb8ulvow
+ components-activitylogrow--workload-change--light:
+ hash: v1.k794b7964.f7d048fea6acf16f3410df1fa8e37280f05bf78742b5b5c21f1714b658ab637d.Br50Tw51CvI00fV_aQNViJrkePbIrujX4K17O-SBGcw
components-agentattribution--intent-and-task--dark:
hash: v1.k794b7964.0d80c815b27006d88f038af4b2d689f510f8bdf583d7fc830eb68942821b56e4.vFLLhu562dwroQu8TA_dLSIrYC3SgtRpKdZTB8ufS84
components-agentattribution--intent-and-task--light:
diff --git a/frontend/src/lib/components/ActivityLog/ActivityClientTag.tsx b/frontend/src/lib/components/ActivityLog/ActivityClientTag.tsx
index fef91acee365..55d70fdfd2c5 100644
--- a/frontend/src/lib/components/ActivityLog/ActivityClientTag.tsx
+++ b/frontend/src/lib/components/ActivityLog/ActivityClientTag.tsx
@@ -1,17 +1,24 @@
import { LemonTag, Tooltip } from '@posthog/lemon-ui'
-import { activityClientLabel, isScoutClient } from 'lib/components/ActivityLog/activityClientLabel'
+import { activityClientLabel, isWorkloadClient, isScoutClient } from 'lib/components/ActivityLog/activityClientLabel'
const SELF_REPORTED_TOOLTIP = 'Self-reported by the API client in the x-posthog-client request header'
const SCOUT_TOOLTIP = 'PostHog recognized this scout from the token its run used, so it is not self-reported'
+const WORKLOAD_TOOLTIP =
+ 'PostHog recognized this workload from the trust policy token it used, so it is not self-reported'
export interface ActivityClientTagProps {
client: string
}
export function ActivityClientTag({ client }: ActivityClientTagProps): JSX.Element {
+ const tooltip = isScoutClient(client)
+ ? SCOUT_TOOLTIP
+ : isWorkloadClient(client)
+ ? WORKLOAD_TOOLTIP
+ : SELF_REPORTED_TOOLTIP
return (
- <Tooltip title={isScoutClient(client) ? SCOUT_TOOLTIP : SELF_REPORTED_TOOLTIP}>
+ <Tooltip title={tooltip}>
<LemonTag size="small" type="muted">
via {activityClientLabel(client)}
</LemonTag>
diff --git a/frontend/src/lib/components/ActivityLog/ActivityLogRow.stories.tsx b/frontend/src/lib/components/ActivityLog/ActivityLogRow.stories.tsx
index 91441969b2a2..8ec51c46c6a7 100644
--- a/frontend/src/lib/components/ActivityLog/ActivityLogRow.stories.tsx
+++ b/frontend/src/lib/components/ActivityLog/ActivityLogRow.stories.tsx
@@ -296,3 +296,34 @@ export const NarrowAcrossProducts: Story = {
),
],
}
+
+export const WorkloadChange: Story = {
+ args: {
+ logItem: humanize(
+ [
+ {
+ ...dashboardEvents[0],
+ client: 'workload:acme/web',
+ detail: {
+ ...dashboardEvents[0].detail,
+ trigger: {
+ job_type: 'workload',
+ job_id: '019f4c2a-0000-7000-8000-0000000000bb',
+ payload: {
+ provider_name: 'Example CI',
+ actor_label: 'acme/web · deploy.yml run 1234',
+ subject_name: 'acme/web',
+ claims: { workflow: 'deploy.yml', run_id: '1234', ref: 'refs/heads/main' },
+ claim_labels: { workflow: 'Workflow', run_id: 'Run', ref: 'Branch or tag' },
+ run_url: 'https://ci.example.com/acme/web/runs/1234',
+ policy_id: '019f4c2a-0000-7000-8000-0000000000bb',
+ policy_name: 'Production deploys',
+ },
+ },
+ },
+ },
+ ],
+ () => dashboardActivityDescriber
+ )[0],
+ },
+}
diff --git a/frontend/src/lib/components/ActivityLog/ActivityLogRow.tsx b/frontend/src/lib/components/ActivityLog/ActivityLogRow.tsx
index 31ceaf8ea0ba..b39cb02db310 100644
--- a/frontend/src/lib/components/ActivityLog/ActivityLogRow.tsx
+++ b/frontend/src/lib/components/ActivityLog/ActivityLogRow.tsx
@@ -190,7 +190,8 @@ function RowActor({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Eleme
<ProfilePicture
showName={false}
user={{
- first_name: logItem.isSystem || logItem.wasImpersonated ? logItem.name : undefined,
+ first_name:
+ logItem.isSystem || logItem.wasImpersonated || !logItem.email ? logItem.name : undefined,
email: logItem.email ?? undefined,
}}
type={logItem.isSystem || logItem.wasImpersonated ? 'system' : 'person'}
diff --git a/frontend/src/lib/components/ActivityLog/WorkloadActorName.tsx b/frontend/src/lib/components/ActivityLog/WorkloadActorName.tsx
new file mode 100644
index 000000000000..3dfbb6d3b0d8
--- /dev/null
+++ b/frontend/src/lib/components/ActivityLog/WorkloadActorName.tsx
@@ -0,0 +1,58 @@
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { Link } from 'lib/lemon-ui/Link'
+import { addProjectIdIfMissing } from 'lib/utils/kea-router'
+import { urls } from 'scenes/urls'
+
+import { WorkloadAttribution, workloadActorLabel } from './parseWorkloadAttribution'
+
+/** The workload that made a change, in place of the organization owner its token acts as. */
+export function WorkloadActorName({
+ attribution,
+ teamId,
+}: {
+ attribution: WorkloadAttribution
+ /** The entry's project, which can differ from the current one in the organization audit log. */
+ teamId?: number | null
+}): JSX.Element {
+ const label = workloadActorLabel(attribution)
+ const actor = attribution.runUrl ? (
+ <Link to={attribution.runUrl} target="_blank" className="font-semibold">
+ {label}
+ </Link>
+ ) : (
+ <strong>{label}</strong>
+ )
+ return (
+ <span className="ph-no-capture">
+ {attribution.claims.length > 0 ? (
+ <Tooltip
+ title={
+ <dl className="m-0">
+ {attribution.claims.map((claim) => (
+ <div key={claim.name} className="flex gap-1">
+ <dt className="font-semibold">{claim.label}:</dt>
+ <dd className="m-0 break-all">{claim.value}</dd>
+ </div>
+ ))}
+ </dl>
+ }
+ >
+ <span>{actor}</span>
+ </Tooltip>
+ ) : (
+ actor
+ )}
+ {attribution.policyName ? (
+ <>
+ <span>, through trust policy </span>
+ <Link
+ to={addProjectIdIfMissing(urls.settings('environment-trusted-workloads'), teamId ?? undefined)}
+ >
+ <em>{attribution.policyName}</em>
+ </Link>
+ </>
+ ) : null}
+ </span>
+ )
+}
diff --git a/frontend/src/lib/components/ActivityLog/activityClientLabel.ts b/frontend/src/lib/components/ActivityLog/activityClientLabel.ts
index fafb947f914e..98354d60e886 100644
--- a/frontend/src/lib/components/ActivityLog/activityClientLabel.ts
+++ b/frontend/src/lib/components/ActivityLog/activityClientLabel.ts
@@ -9,10 +9,20 @@ export function isScoutClient(client: string): boolean {
return client.startsWith(SCOUT_CLIENT_PREFIX)
}
+/** Reserved for the backend, which derives it from the subject name a workload access token carries. */
+export const WORKLOAD_CLIENT_PREFIX = 'workload:'
+
+export function isWorkloadClient(client: string): boolean {
+ return client.startsWith(WORKLOAD_CLIENT_PREFIX)
+}
+
/** How a stored `client` value reads to a person. The stored value stays the filter key. */
export function activityClientLabel(client: string): string {
if (isScoutClient(client)) {
return `scout ${client.slice(SCOUT_CLIENT_PREFIX.length)}`
}
+ if (isWorkloadClient(client)) {
+ return `workload ${client.slice(WORKLOAD_CLIENT_PREFIX.length)}`
+ }
return client === 'mcp' ? 'MCP' : client
}
diff --git a/frontend/src/lib/components/ActivityLog/activityDescribers.ts b/frontend/src/lib/components/ActivityLog/activityDescribers.ts
index 2b36ba83321f..9a9228a76075 100644
--- a/frontend/src/lib/components/ActivityLog/activityDescribers.ts
+++ b/frontend/src/lib/components/ActivityLog/activityDescribers.ts
@@ -9,6 +9,14 @@ export type ActivityDescriberLoader = () => Promise<Describer>
const coreActivityDescribers: Partial<Record<ActivityScope, ActivityDescriberLoader>> = {
[ActivityScope.BILLING]: () =>
import('scenes/billing/activityDescriptions').then((m) => m.billingActivityDescriber),
+ [ActivityScope.WORKLOAD_TRUST_POLICY]: () =>
+ import('scenes/settings/project/workloadTrustPolicyActivityDescriptions').then(
+ (m) => m.workloadTrustPolicyActivityDescriber
+ ),
+ [ActivityScope.WORKLOAD_TRUST_POLICY_REQUEST]: () =>
+ import('scenes/settings/project/workloadTrustPolicyActivityDescriptions').then(
+ (m) => m.workloadTrustPolicyRequestActivityDescriber
+ ),
[ActivityScope.INSTANCE_SETTING]: () =>
import('./activityDescriptions/instanceSettingActivityDescriber').then(
(m) => m.instanceSettingActivityDescriber
diff --git a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
index 39facfd2dda8..d3777130b24f 100644
--- a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
+++ b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
@@ -7,6 +7,9 @@ import { ActivityScope, InsightShortId, PersonType, UserBasicType } from '~/type
import type { ActivityLogCredentialTypeEnumApi } from 'products/platform_features/frontend/generated/api.schemas'
+import { workloadActorLabel, parseWorkloadAttribution } from './parseWorkloadAttribution'
+import { WorkloadActorName } from './WorkloadActorName'
+
export interface ActivityChange {
type: ActivityScope
action: 'changed' | 'created' | 'deleted' | 'exported' | 'split' | 'merged' | 'copied'
@@ -143,14 +146,17 @@ export function humanize(
const { description, summary, extendedDescription, expandedView } = describer(logItem, asNotification)
if (description !== null) {
+ const workload = parseWorkloadAttribution(logItem)
const impersonatedUserName = logItem.user ? fullName(logItem.user) : undefined
logLines.push({
id: logItem.id,
email: actorEmailForLogItem(logItem),
emailToReveal: actorEmailToRevealForLogItem(logItem),
- name: logItem.was_impersonated
- ? `PostHog Support${impersonatedUserName ? ` (as ${impersonatedUserName})` : ''}`
- : impersonatedUserName,
+ name: workload
+ ? workloadActorLabel(workload)
+ : logItem.was_impersonated
+ ? `PostHog Support${impersonatedUserName ? ` (as ${impersonatedUserName})` : ''}`
+ : impersonatedUserName,
isSystem: logItem.is_system,
wasImpersonated: logItem.was_impersonated,
client: logItem.client,
@@ -171,6 +177,10 @@ export function userNameForLogItem(logItem: ActivityLogItem): string {
if (logItem.is_system) {
return 'PostHog'
}
+ const workload = parseWorkloadAttribution(logItem)
+ if (workload) {
+ return workloadActorLabel(workload)
+ }
if (logItem.was_impersonated) {
return `PostHog Support (as ${nameOrEmailForUser(logItem.user, 'a user')})`
}
@@ -194,7 +204,7 @@ function nameOrEmailForUser(
// surface that shows the email must use this, or a row can disclose it in one place and hide it
// in another.
export function actorEmailForLogItem(logItem: ActivityLogItem): string | null {
- if (logItem.is_system || logItem.was_impersonated) {
+ if (logItem.is_system || logItem.was_impersonated || parseWorkloadAttribution(logItem)) {
return null
}
return logItem.user?.email ?? null
@@ -209,6 +219,10 @@ export function actorEmailToRevealForLogItem(logItem: ActivityLogItem): string |
/** The person who did the thing, with their email on hover. */
export function ActivityLogUserName({ logItem }: { logItem: ActivityLogItem }): JSX.Element {
+ const workload = parseWorkloadAttribution(logItem)
+ if (workload) {
+ return <WorkloadActorName attribution={workload} teamId={logItem.team_id} />
+ }
return <UserNameWithEmail name={userNameForLogItem(logItem)} email={actorEmailForLogItem(logItem)} />
}
@@ -229,6 +243,11 @@ const SCOPE_DISPLAY_NAMES: Partial<Record<ActivityScope, { singular: string; plu
[ActivityScope.ALERT_CONFIGURATION]: { singular: 'Alert', plural: 'Alerts' },
[ActivityScope.BATCH_EXPORT]: { singular: 'Destination', plural: 'Destinations' },
[ActivityScope.CANVAS]: { singular: 'Canvas', plural: 'Canvases' },
+ [ActivityScope.WORKLOAD_TRUST_POLICY]: { singular: 'Trusted workload', plural: 'Trusted workloads' },
+ [ActivityScope.WORKLOAD_TRUST_POLICY_REQUEST]: {
+ singular: 'Trusted workload request',
+ plural: 'Trusted workload requests',
+ },
[ActivityScope.DEV_GATEWAY_TOKEN]: { singular: 'Developer mode token', plural: 'Developer mode tokens' },
[ActivityScope.EXTERNAL_DATA_SOURCE]: { singular: 'Source', plural: 'Sources' },
[ActivityScope.HOG_FUNCTION]: { singular: 'Data pipeline', plural: 'Data pipelines' },
diff --git a/frontend/src/lib/components/ActivityLog/parseWorkloadAttribution.test.ts b/frontend/src/lib/components/ActivityLog/parseWorkloadAttribution.test.ts
new file mode 100644
index 000000000000..1dc0fdd2bb40
--- /dev/null
+++ b/frontend/src/lib/components/ActivityLog/parseWorkloadAttribution.test.ts
@@ -0,0 +1,58 @@
+import { parseWorkloadAttribution, workloadActorLabel } from './parseWorkloadAttribution'
+
+describe('parseWorkloadAttribution', () => {
+ const workloadTrigger = {
+ job_type: 'workload',
+ job_id: 'policy-1',
+ payload: {
+ provider_name: 'Example CI',
+ subject_name: 'acme/web',
+ claims: { workflow: 'deploy.yml', ref: 'refs/heads/main', run_id: 1234 },
+ claim_labels: { workflow: 'Workflow', ref: 'Branch or tag' },
+ run_url: 'https://ci.example.com/acme/web/runs/1234',
+ policy_name: 'Production deploys',
+ },
+ }
+
+ it.each([
+ ['no trigger', null, null],
+ ['an agent trigger', { job_type: 'agent', job_id: 'task', payload: { subject_name: 'acme/web' } }, null],
+ ['a workload trigger without an actor label', workloadTrigger, 'Example CI · acme/web'],
+ [
+ 'a workload trigger with an actor label',
+ { ...workloadTrigger, payload: { ...workloadTrigger.payload, actor_label: 'acme/web · nightly' } },
+ 'Example CI · acme/web · nightly',
+ ],
+ ])('reads %s', (_name, trigger, expectedLabel) => {
+ const attribution = parseWorkloadAttribution({ detail: { merge: null, changes: null, name: null, trigger } })
+
+ expect(attribution ? workloadActorLabel(attribution) : null).toEqual(expectedLabel)
+ })
+
+ it('labels the recorded claims and skips values that are not text', () => {
+ const attribution = parseWorkloadAttribution({
+ detail: { merge: null, changes: null, name: null, trigger: workloadTrigger },
+ })
+
+ expect(attribution?.claims).toEqual([
+ { name: 'workflow', label: 'Workflow', value: 'deploy.yml' },
+ { name: 'ref', label: 'Branch or tag', value: 'refs/heads/main' },
+ ])
+ })
+
+ it('drops a run link that is not https', () => {
+ const attribution = parseWorkloadAttribution({
+ detail: {
+ merge: null,
+ changes: null,
+ name: null,
+ trigger: {
+ ...workloadTrigger,
+ payload: { ...workloadTrigger.payload, run_url: 'javascript:alert(1)' },
+ },
+ },
+ })
+
+ expect(attribution?.runUrl).toBeNull()
+ })
+})
diff --git a/frontend/src/lib/components/ActivityLog/parseWorkloadAttribution.ts b/frontend/src/lib/components/ActivityLog/parseWorkloadAttribution.ts
new file mode 100644
index 000000000000..ac5fc73d7a50
--- /dev/null
+++ b/frontend/src/lib/components/ActivityLog/parseWorkloadAttribution.ts
@@ -0,0 +1,73 @@
+import { isObject } from 'lib/utils/guards'
+
+import type { ActivityLogItem } from './humanizeActivity'
+
+// Matches WORKLOAD_TRIGGER_JOB_TYPE in posthog/models/activity_logging/activity_log.py.
+const WORKLOAD_TRIGGER_JOB_TYPE = 'workload'
+
+export interface WorkloadClaimValue {
+ name: string
+ /** What the provider calls the claim, for example "Branch or tag". */
+ label: string
+ value: string
+}
+
+export interface WorkloadAttribution {
+ providerName: string
+ /** How the provider names the workload, for example "acme/web · deploy.yml run 1234". */
+ actorLabel: string | null
+ subjectName: string
+ /** The claims the provider records, in the order the backend wrote them. */
+ claims: WorkloadClaimValue[]
+ runUrl: string | null
+ policyName: string | null
+}
+
+function stringField(payload: Record<string, unknown>, key: string): string | null {
+ const value = payload[key]
+ return typeof value === 'string' && value ? value : null
+}
+
+function stringMap(value: unknown): Record<string, string> {
+ if (!isObject(value)) {
+ return {}
+ }
+ return Object.fromEntries(
+ Object.entries(value).filter(
+ (entry): entry is [string, string] => typeof entry[1] === 'string' && entry[1] !== ''
+ )
+ )
+}
+
+/** The workload that made the change, when the row was written with a workload access token. */
+export function parseWorkloadAttribution(logItem: Pick<ActivityLogItem, 'detail'>): WorkloadAttribution | null {
+ const trigger = logItem.detail?.trigger
+ if (trigger?.job_type !== WORKLOAD_TRIGGER_JOB_TYPE) {
+ return null
+ }
+ const payload = (trigger.payload ?? {}) as Record<string, unknown>
+ const subjectName = stringField(payload, 'subject_name')
+ if (!subjectName) {
+ return null
+ }
+ const labels = stringMap(payload.claim_labels)
+ const runUrl = stringField(payload, 'run_url')
+ return {
+ providerName: stringField(payload, 'provider_name') ?? stringField(payload, 'provider') ?? 'Workload',
+ actorLabel: stringField(payload, 'actor_label'),
+ subjectName,
+ claims: Object.entries(stringMap(payload.claims)).map(([name, value]) => ({
+ name,
+ label: labels[name] ?? name,
+ value,
+ })),
+ // Only an https link is rendered, so a stored value can never become a script URL.
+ runUrl: runUrl?.startsWith('https://') ? runUrl : null,
+ policyName: stringField(payload, 'policy_name'),
+ }
+}
+
+/** For example "GitHub Actions · acme/web · deploy.yml run 1234". */
+export function workloadActorLabel(attribution: WorkloadAttribution): string {
+ return `${attribution.providerName} · ${attribution.actorLabel ?? attribution.subjectName}`
+}
diff --git a/frontend/src/scenes/data-warehouse/editor/insightHistoryLogic.ts b/frontend/src/scenes/data-warehouse/editor/insightHistoryLogic.ts
index 479109c5d6b5..727b4f5e24dd 100644
--- a/frontend/src/scenes/data-warehouse/editor/insightHistoryLogic.ts
+++ b/frontend/src/scenes/data-warehouse/editor/insightHistoryLogic.ts
@@ -2,8 +2,12 @@ import { MakeLogicType, events, kea, key, path, props, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
-import { ActivityChange, ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'
-import { fullName } from 'lib/utils/strings'
+import {
+ ActivityChange,
+ ActivityLogItem,
+ actorEmailForLogItem,
+ userNameForLogItem,
+} from 'lib/components/ActivityLog/humanizeActivity'
import { ActivityScope } from '~/types'
@@ -168,8 +172,8 @@ export const insightHistoryLogic = kea<insightHistoryLogicType>([
return {
id: logItem.id,
createdAt: logItem.created_at,
- authorName: logItem.is_system ? 'PostHog' : fullName(logItem.user),
- email: logItem.user?.email,
+ authorName: userNameForLogItem(logItem),
+ email: actorEmailForLogItem(logItem) ?? undefined,
isSystem: !!logItem.is_system,
beforeSql: getChangeSql(queryChange.before) ?? '',
afterSql: getChangeSql(queryChange.after) ?? '',
diff --git a/frontend/src/scenes/settings/project/workloadTrustPolicyActivityDescriptions.tsx b/frontend/src/scenes/settings/project/workloadTrustPolicyActivityDescriptions.tsx
new file mode 100644
index 000000000000..5efb9964d20a
--- /dev/null
+++ b/frontend/src/scenes/settings/project/workloadTrustPolicyActivityDescriptions.tsx
@@ -0,0 +1,45 @@
+import {
+ ActivityLogItem,
+ ActivityLogUserName,
+ Describer,
+ HumanizedChange,
+ activityLogSummary,
+ defaultDescriber,
+} from 'lib/components/ActivityLog/humanizeActivity'
+import { Link } from 'lib/lemon-ui/Link'
+import { addProjectIdIfMissing } from 'lib/utils/kea-router'
+import { urls } from 'scenes/urls'
+
+function workloadTrustDescriber(
+ verbs: Record<string, string>,
+ targetUrl: (logItem: ActivityLogItem) => string | null
+): Describer {
+ return (logItem: ActivityLogItem): HumanizedChange => {
+ const verb = verbs[logItem.activity]
+ if (!verb) {
+ return defaultDescriber(logItem)
+ }
+ const name = <strong>{logItem.detail?.name || 'a workload trust policy'}</strong>
+ const url = targetUrl(logItem)
+ // The organization audit log lists entries from every project, so links name the entry's own project.
+ const target = url ? <Link to={addProjectIdIfMissing(url, logItem.team_id ?? undefined)}>{name}</Link> : name
+ return {
+ summary: activityLogSummary(logItem, `${verb} the workload trust policy`, target),
+ description: (
+ <>
+ <ActivityLogUserName logItem={logItem} /> {verb} the workload trust policy {target}
+ </>
+ ),
+ }
+ }
+}
+
+export const workloadTrustPolicyActivityDescriber = workloadTrustDescriber(
+ { created: 'created', updated: 'updated', deleted: 'deleted' },
+ (logItem) => (logItem.activity === 'deleted' ? null : urls.settings('environment-trusted-workloads'))
+)
+
+export const workloadTrustPolicyRequestActivityDescriber = workloadTrustDescriber(
+ { created: 'asked for', approved: 'approved', rejected: 'rejected' },
+ (logItem) => (logItem.item_id ? urls.workloadTrustPolicyRequest(logItem.item_id) : null)
+)
diff --git a/posthog/auth.py b/posthog/auth.py
index 9817ebee51b3..e588fb267b57 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -1,6 +1,7 @@
import re
import hmac
import time
+import string
import logging
import functools
from abc import abstractmethod
@@ -39,7 +40,10 @@ from posthog.helpers.verified_domain_enforcement import enforce_verified_domain
from posthog.ingress.verify.schemes import hmac_sha256_signature, signatures_match
from posthog.internal_api_secret import usable_internal_api_secrets
from posthog.jwt import PosthogJwtAudience, decode_jwt, encode_jwt, get_oidc_verification_keys
+from posthog.models.activity_logging.activity_log import WORKLOAD_TRIGGER_JOB_TYPE, Trigger
from posthog.models.activity_logging.utils import (
+ ACTIVITY_LOG_CLIENT_MAX_LENGTH,
+ WORKLOAD_CLIENT_PREFIX,
ActivityCredentialMixin,
DeclaredCredentialType,
activity_storage,
@@ -822,6 +826,16 @@ class VerifiedWorkloadAccessToken:
workload_claims: dict[str, str]
+def _template_fields(template: str) -> set[str]:
+ return {name for _, name, _, _ in string.Formatter().parse(template) if name}
+
+
+def _format_with_claims(template: str, claims: dict[str, str]) -> str:
+ """Fill a provider template's `{claim}` fields with the recorded claims. A missing claim formats as an
+ empty string. The registry refuses templates whose fields aren't recorded claims."""
+ return template.format_map({name: claims.get(name, "") for name in _template_fields(template)})
+
+
class WorkloadAccessTokenAuthentication(ActivityCredentialMixin, authentication.BaseAuthentication):
"""
Authenticates API requests made with the short-lived token a workload gets by exchanging its
@@ -974,8 +988,54 @@ class WorkloadAccessTokenAuthentication(ActivityCredentialMixin, authentication.
user_id=verified.user.pk, team_id=verified.team_id, access_method=AccessMethod.OIDC_WORKLOAD
)
self.record_activity_actor(verified.user, verified.policy_id)
+ self._record_workload(verified)
return verified.user, None
+ @staticmethod
+ def _record_workload(verified: VerifiedWorkloadAccessToken) -> None:
+ """Put the workload on every activity row this request writes, so the row names the workload as
+ the actor after the token is gone, and can be filtered by the client tag."""
+ if not activity_storage.is_request_scoped():
+ return
+ subject_name = verified.workload_subject_name
+ if subject_name:
+ activity_storage.set_client(f"{WORKLOAD_CLIENT_PREFIX}{subject_name}"[:ACTIVITY_LOG_CLIENT_MAX_LENGTH])
+
+ def workload_trigger() -> Trigger:
+ # Deferred because `posthog.api.oauth` imports its views, which import this module.
+ from posthog.workload_identity.providers import get_workload_provider_by_key # noqa: PLC0415
+
+ provider = get_workload_provider_by_key(verified.workload_provider)
+ claims = verified.workload_claims
+ actor_label = (
+ _format_with_claims(provider.actor_label_template, claims).strip(" ·") if provider else ""
+ ) or subject_name
+ run_url_template = provider.run_url_template if provider else None
+ # A link with an empty path segment points nowhere useful, so it needs every claim it names.
+ run_url = (
+ _format_with_claims(run_url_template, claims)
+ if run_url_template and all(claims.get(name) for name in _template_fields(run_url_template))
+ else None
+ )
+ claim_labels = {claim.name: claim.label for claim in provider.recorded_claims} if provider else {}
+ return Trigger(
+ job_type=WORKLOAD_TRIGGER_JOB_TYPE,
+ job_id=verified.policy_id,
+ payload={
+ "provider": verified.workload_provider,
+ "provider_name": provider.name if provider else verified.workload_provider,
+ "actor_label": actor_label,
+ "subject_name": subject_name,
+ "claims": claims,
+ "claim_labels": {name: claim_labels.get(name, name) for name in claims},
+ "run_url": run_url,
+ "policy_id": verified.policy_id,
+ "policy_name": verified.policy_name,
+ },
+ )
+
+ activity_storage.set_verified_trigger_resolver(workload_trigger)
+
def authenticate_header(self, request) -> str:
return self.keyword
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 1120285bcb8b..20623519b0f5 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -1474,6 +1474,10 @@ def _handle_activity_log_transaction(
# The frontend matches on this job type to render the job id as a link to a sandbox task.
# Product triggers (`hog_flow`, `canvas_action`) carry job ids that point elsewhere.
AGENT_TRIGGER_JOB_TYPE = "agent"
+# A row written with a workload access token. The frontend shows the workload as the actor instead of the
+# organization owner the token acts as. `job_id` is the trust policy id, because a run id, when the provider
+# has one, is one of the recorded claims in the payload.
+WORKLOAD_TRIGGER_JOB_TYPE = "workload"
def agent_trigger() -> Optional[Trigger]:
@@ -1492,10 +1496,12 @@ def agent_trigger() -> Optional[Trigger]:
)
-def _with_agent_trigger(detail: Detail) -> Detail:
- """The row is written inside the user's save, so an error here must not fail that save."""
+def _with_request_trigger(detail: Detail) -> Detail:
+ """The row is written inside the user's save, so an error here must not fail that save.
+
+ A verified trigger, such as a CI job, comes before agent intent, which is the agent's own claim."""
try:
- trigger = agent_trigger()
+ trigger = activity_storage.get_verified_trigger() or agent_trigger()
return dataclasses.replace(detail, trigger=trigger) if trigger is not None else detail
except Exception as e:
capture_exception(e)
@@ -1532,7 +1538,7 @@ def log_activity(
credential = ActivityCredential(type="unattributed")
if detail.trigger is None:
# A product that sets its own trigger already says what drove the write.
- detail = _with_agent_trigger(detail)
+ detail = _with_request_trigger(detail)
if was_impersonated and user is None:
logger.warn(
"activity_log.failed_to_write_to_activity_log",
diff --git a/posthog/models/activity_logging/utils.py b/posthog/models/activity_logging/utils.py
index ce9dc06be77f..630111250198 100644
--- a/posthog/models/activity_logging/utils.py
+++ b/posthog/models/activity_logging/utils.py
@@ -31,10 +31,12 @@ ACTIVITY_LOG_CLIENT_MAX_LENGTH = 256
ACTIVITY_LOG_CLIENT_HEADER_MAX_LENGTH = 32
# Set by `OAuthAccessTokenAuthentication` from the scout run bound to a sandbox token.
SCOUT_CLIENT_PREFIX = "scout:"
+# Set by `WorkloadAccessTokenAuthentication` from the subject name the workload token's OIDC claims named.
+WORKLOAD_CLIENT_PREFIX = "workload:"
# Prefixes only the server may write. The activity log tells a reader that a tag carrying one of
# them comes from the authenticated request rather than from the client, so the two kinds of tag
# must not share a name.
-SERVER_DERIVED_CLIENT_PREFIXES = (SCOUT_CLIENT_PREFIX,)
+SERVER_DERIVED_CLIENT_PREFIXES = (SCOUT_CLIENT_PREFIX, WORKLOAD_CLIENT_PREFIX)
DeclaredCredentialType = Literal[
@@ -269,6 +271,27 @@ class ActivityLoggingStorage:
if hasattr(self._local, "trigger"):
delattr(self._local, "trigger")
+ def set_verified_trigger_resolver(self, resolver: Callable[[], Optional["Trigger"]]) -> None:
+ """Hand over a trigger the authenticated credential proves, such as the CI job behind a CI
+ access token, to build when a row first needs it. Unlike `set_trigger`, it applies to every row."""
+ self._local.verified_trigger_resolver = resolver
+
+ def get_verified_trigger(self) -> Optional["Trigger"]:
+ resolver = getattr(self._local, "verified_trigger_resolver", None)
+ if resolver is not None:
+ delattr(self._local, "verified_trigger_resolver")
+ try:
+ self._local.verified_trigger = resolver()
+ except Exception:
+ logger.warning("activity_log.verified_trigger_resolver_failed", exc_info=True)
+ self._local.verified_trigger = None
+ return getattr(self._local, "verified_trigger", None)
+
+ def clear_verified_trigger(self) -> None:
+ for name in ("verified_trigger_resolver", "verified_trigger"):
+ if hasattr(self._local, name):
+ delattr(self._local, name)
+
def clear_all(self) -> None:
self.clear_request_scoped()
self.clear_user()
@@ -279,6 +302,7 @@ class ActivityLoggingStorage:
self.clear_ip_address()
self.clear_credential()
self.clear_trigger()
+ self.clear_verified_trigger()
activity_storage = ActivityLoggingStorage()
diff --git a/posthog/workload_identity/test/test_token_exchange.py b/posthog/workload_identity/test/test_token_exchange.py
index bfda65f27618..1388032c5c20 100644
--- a/posthog/workload_identity/test/test_token_exchange.py
+++ b/posthog/workload_identity/test/test_token_exchange.py
@@ -140,6 +140,37 @@ class TestWorkloadTokenExchange(APIBaseTest):
assert annotation.created_by_id == self.user.id != newer_owner.id
entry = ActivityLog.objects.filter(scope="Annotation", item_id=str(annotation.pk)).get()
assert (entry.credential_type, entry.credential_id) == ("oidc_workload", str(self.policy.pk))
+ assert entry.client == "workload:acme/web"
+ assert entry.detail is not None
+ assert entry.detail["trigger"] == {
+ "job_type": "workload",
+ "job_id": str(self.policy.pk),
+ "payload": {
+ "provider": "fake_ci",
+ "provider_name": "Fake CI",
+ "actor_label": "acme/web · deploy.yml run 987",
+ "subject_name": "acme/web",
+ "claims": {
+ "repository": "acme/web",
+ "workflow": "deploy.yml",
+ "run_id": "987",
+ "sha": "abc123",
+ "ref": "refs/heads/main",
+ "environment": "production",
+ },
+ "claim_labels": {
+ "repository": "Repository",
+ "workflow": "Workflow",
+ "run_id": "Run",
+ "sha": "Commit",
+ "ref": "Branch or tag",
+ "environment": "Environment",
+ },
+ "run_url": "https://ci.example.com/acme/web/runs/987",
+ "policy_id": str(self.policy.pk),
+ "policy_name": "Production deploys",
+ },
+ }
@parameterized.expand(
[