Repository navigation
feat(audit): record the administrator on writes made while impersonating a user - #30800
Conversation
…ersonation session Carry the session's impersonatedBy as an attribution-only ExecutionContext.impersonatedBy, hand it to hooks as provenance.impersonatedBy, and stamp sys_audit_log.metadata.impersonated_by and the sys_activity row metadata. user_id, created_by and permissions stay the impersonated user's. Flows started by such a write carry it onto their own writes; action invocation rows carry it too. Claude-Session: https://claude.ai/code/session_016WV4cxMph1oXW6ujSSVm1G Co-authored-by: Claude <noreply@anthropic.com>
… rows Claude-Session: https://claude.ai/code/session_016WV4cxMph1oXW6ujSSVm1G Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016WV4cxMph1oXW6ujSSVm1G Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016WV4cxMph1oXW6ujSSVm1G Co-authored-by: Claude <noreply@anthropic.com>
…rence docs Claude-Session: https://claude.ai/code/session_016WV4cxMph1oXW6ujSSVm1G Co-authored-by: Claude <noreply@anthropic.com>
📓 Docs Drift CheckThis PR changes 7 package(s): 29 hand-written doc(s) name something this change touched — list omitted above 15 rows. Re-derive on the tree named below: ⛔ 12 release-owned page(s) also affected — read-only, see AGENTS.md Documentation Guardrails. What this run could not see
Coarse fallback — 184 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): Which tree this was computed onThis run read A worktree cut from an older # while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 1eb476bdca9f357364fa62453212f092dc66a963 && git checkout 1eb476bdca9f357364fa62453212f092dc66a963
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 3da9a4c132db7bf5ae1ca673930c1034e50d0195 9d945da817688a41fb0fcd36c9ead6a606f4bffe && git checkout -B drift-repro 3da9a4c132db7bf5ae1ca673930c1034e50d0195 && git merge --no-ff 9d945da817688a41fb0fcd36c9ead6a606f4bffe
node scripts/docs-audit/affected-docs.mjs --json 3da9a4c132db7bf5ae1ca673930c1034e50d0195
|
…protocol: added (#30213) ExecutionContext.impersonatedBy enters the kernel authorable-surface shard, so the change is a metadata-protocol widening: Clause-②: yes (widening), Metadata-protocol: added, @objectstack/spec at minor. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cxMph1oXW6ujSSVm1G
|
domain:server#4 · os-elon-musk · session_016WV4czvZykUqhYxYXSSDt4 Contract review for card #30213 · schema face ( Contract reviewServed-tier: The code was reviewed at ① Derived judgments
② Semver level
③ Boundary flags
④ Design judgment
Implemented-by: VERDICT: FAIL |
…rsonating administrator (#30213) Both doors build a run's AutomationContext by picking identity keys off the caller's ExecutionContext by name and dropped impersonatedBy, so a flow an impersonating administrator started through them wrote rows that read as the user's own. Forward it (non-blank, attribution only) and pin both doors with a no-impersonation control. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cxMph1oXW6ujSSVm1G
|
domain:server#4 · os-elon-musk · session_016WV4czvZykUqhYxYXSSDt4 Delta re-review for card #30213 over record 6676544432 (FAIL on Contract reviewServed-tier:
① Derived judgmentsUnchanged from 6676544432, except for the following.
② Semver levelUnchanged: ③ Boundary flagsUnchanged: the ④ Design judgment
Implemented-by: VERDICT: PASS |
|
domain:server#4 · os-elon-musk · session_016WV4czvZykUqhYxYXSSDt4 维护者速读
席位意见:ACCEPT(#30213,裁定 A)。 席位核对Head-sha:
|
…n AI service account is recognised as an agent (ADR-0151 O4) (objectstack-ai#32036) <!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9XmJcoZFjfvaX78SFvouo2e)_ Fixes objectstack-ai#31740 Clause-②: yes (widening) Metadata-protocol: added Skills-docs: follow-up owed — triage files the `domain:skills` child that teaches hook authors `ctx.session.principalKind` (triage comment 6730398547, rule 5) ## 维护者速读 - 改了什么:hook 现在能读 `ctx.session.principalKind`(human / agent / service / guest / system),从请求的执行上下文原样拷贝。OAuth 代理和 AI 服务账号都读 `agent`;管理员代查他人权限(explain `?userId=`)时,人类主体现在显示 `human`。审计行不变,只加 pin。 - 为什么改:ADR-0151 D5 / O4。以前 hook 只能从 `performedByClientId` 认出代理,服务账号永远没有它,看起来像人;O2 治理拦截和 O6 审批路由要对两类代理问同一个问题。 - 风险与回滚:新增一个可选的只读键,不读它的 hook 没有任何变化;不默认补 `human`,所以丢了 kind 的上下文不会把代理报成人。回滚就是 revert 本 PR。 - 先看:`packages/objectql/src/engine-execution-plumbing.ts`(buildSession 的拷贝点)、`packages/plugins/plugin-security/src/security-plugin-explain-access.ts`(代查分支盖 `human`)、`packages/spec/src/data/hook.zod.ts`(新键与说明)。 - 两分钟验证:`pnpm --filter @objectstack/plugin-audit exec vitest run src/agent-dual-attribution.integration.test.ts`,预期 9 个用例全过,其中账号写入的 hook 读到 `agent`、审计行 `user_id` 是账号本身。 - 需要你做的:无,席位落地。 ## What changes - **`@objectstack/spec`** — `HookContextSchema.session.principalKind`: `z.enum(['human','agent','service','guest','system']).optional()`, the envelope's own name and value set (`ExecutionContext.principalKind`), with a `.describe()` that says it is descriptive only and how the two kinds of agent differ (`provenance.performedByClientId` set for an OAuth client acting for a person, absent for an AI service account acting as itself). `content/docs/references/data/hook.mdx` regenerated (`check:generated --fix`, only `check:docs` was stale). - **`@objectstack/objectql`** — `buildSession()` copies `execCtx.principalKind` verbatim onto a session that already exists, after the presence test (the same placement `locale` has), so a kind alone never creates a session; it never defaults to `'human'`. - **`@objectstack/plugin-security`** — the explain-access branch that explains ANOTHER user (`?userId=`) stamps `principalKind: 'human'` when the resolver named no kind (the row's existence is already asserted there). An AI service account already read `'agent'` (O3). The exported `buildContextForUser` is untouched. Evaluation is unchanged: only `'agent'` and `'guest'` steer any decision, and `'human'` vs absent differ only in the permission-set memo key. - **Audit writers** (`plugin-audit` `audit-writers.ts`, `action-invocation-audit.ts`, `data-export-audit.ts`) — **no change**; each takes `user_id` from the envelope's `userId`, which for an account is the account. Pinned below. - Not built, per ADR-0151 D5: a `performedBy` naming the account, any audit kind column (ADR-0118 D5), a per-write key id. - Changeset `.changeset/31740-principal-kind-reaches-hooks-and-explain.md`: `@objectstack/spec` minor, `@objectstack/objectql` and `@objectstack/plugin-security` patch (`plugin-audit` changes tests only). - Seat rulings applied (claim amendment 6755781269): key name and placement, spec carried in this card (precedent objectstack-ai#30800, the `protocol:data` label is expected), no `'human'` default, explain stamp only in the query-for-another-user branch. ## Tests New pins, no existing assertion changed (no forced test edits): - `packages/spec/src/data/hook.test.ts` — the five values parse and survive, a sixth is refused at `['session','principalKind']`, the type carries the key. - `packages/objectql/src/engine-execution-plumbing.session-locale.test.ts` (top-level describe) — through the real assembler an account reads `agent` with itself as `userId`; CONTROL a person reads `human`; five values copied verbatim; no kind ⇒ no key (never a defaulted `human`); a kind alone ⇒ no session. - `packages/plugins/plugin-audit/src/agent-dual-attribution.integration.test.ts` (top-level describe, real ObjectQL + sqlite-wasm + the shipped writer, envelopes from the real assembler): a hook on the audited object reads `agent` + `performedByClientId` for the OAuth client, `agent` with no `performedByClientId` for the account, CONTROL `human` for the person; the account's ledger row has `user_id` = `actor` = the account, `metadata` null, no kind column. - `action-invocation-audit.test.ts`, `data-export-audit.test.ts` — an account's action call and export: `user_id` = `actor` = the account, no `performed_by`, no `on_behalf_of`. - `packages/plugins/plugin-security/src/explain-removed-member-principal.test.ts` — the rig gains an AI service account member (fixture addition only); new describe: an administrator's explanation of a person reads `human` (CONTROL: the person's own request through the door carries `human`), of the account `agent`. Ablations (each mutation landed on disk per `scripts/ablation-replace.mjs`, ran red, restored with blob == HEAD and `git diff HEAD` empty): | # | Mutation | Red | |:--|:--|:--| | A1 | `buildSession` defaults the kind to `'human'` | objectql: "never a defaulted human" | | A2 | kind copied before the presence test | objectql: "a kind alone does not make a session" + the existing guest CONTROL | | A3 | copy deleted | objectql: account `agent`, person `human`, five values | | B1 | CRUD writer writes metadata for an agent principal | plugin-audit integration: account row names no performer/delegator/kind | | B2 | export writer writes the delegation pair for an agent principal | export: account row names no performer/delegator | | B3 | action writer writes the delegation pair for an agent principal | action: account row names no performer/delegator | | C1 | explain stamp deleted | plugin-security: person explained by an administrator reads `human` | | C2 | copy removed in objectql, objectql rebuilt (plugin-audit reads objectql `dist/`) | plugin-audit hook pins (2 red); restore + rebuild ⇒ 9/9 green, `ablation-dist-preflight --absent` clean | C2 note: the first marker was a code comment the bundler strips, so the mutated-leg `ablation-dist-preflight` could not see it; the red-on-rebuild / green-on-restore-rebuild pair is the evidence the mutation reached `dist/`. ## Acceptance notes - The Console's access-explain panel (`ui/packages/app-shell/src/views/metadata-admin/AccessExplainPanel.tsx`) shows `onBehalfOf` and `posture` but not `principal.principalKind`. Showing it belongs to the UI lane; named as a follow-up by the seat, not built here. - An action body's `ctx.session` (`runtime/src/action-execution.ts` `buildActionSession`) is a different object from `HookContext.session` and does not carry the key; out of this card's scope. - `'service'` and `'system'` have no producer today; the key copies whatever the envelope says. ## Verification All at head `d9e058c0`, on `objectstack-ai/objectstack`, merge base `60f8149e` (origin/main had not moved). <details><summary>Package suites, typecheck, lint</summary> - `pnpm --filter @objectstack/{spec,objectql,plugin-security,plugin-audit} test` — each `VERDICT command-exit 0` under `os-verify-lock`. - `pnpm --filter … typecheck` for the same four — each `VERDICT command-exit 0` (spec's runs `check:test-typecheck`); `check-test-typecheck.mts --package` OK for objectql, plugin-security, plugin-audit. - These packages have no `lint` script; eslint (`--no-inline-config`, the root `pnpm lint` command) over each package directory and over every changed `.ts` file — exit 0. </details> <details><summary>Derived gates — 117 of 117, all exit 0</summary> `node scripts/pm/dispatch-gates.mjs --repo objectstack-ai/objectstack --ran FILE`: "117 derived famil(ies) accounted for — 117 run, 0 NOT-MEASURED (a DERIVED zero — all 117 recorded an exit code and none of them is 3)". Four first answered exit 3 PREREQUISITE NOT MET and were re-run after the prerequisite, then exit 0: `check-plugin-teardown-shape --self-test` (after fetching its pinned fixture commit), `check:skill-examples`, `check:dual-build-cjs-loads`, `check:i18n` (after a full `pnpm turbo run build`). </details> <details><summary>Not run here</summary> - Full dogfood: not owed (no `!`, no `(narrowing)` arm). - `test:repo`: not touched by the diff; CI runs it. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmPybDYNmViDiAJJT7S)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
Requested by Elon · project thread
Fixes #30213
Clause-②: yes (widening)
Metadata-protocol: added
维护者速读
sys_audit_log.metadata.impersonated_by)和记录动态(sys_activity)都记下这位管理员;记录详情页的动态与字段历史显示「Dev Admin 代王工操作」。数据归属、created_by、权限仍是员工本人,没有加列、没有迁移。packages/core/src/security/resolve-authz-context.ts(从会话读出管理员)、packages/plugins/plugin-audit/src/audit-writers.ts(写入审计与动态的那几行)、packages/services/service-automation/src/run-resume.ts(审批人接手后不再沿用管理员)。pnpm --filter @objectstack/plugin-audit exec vitest run src/activity-actor-name.test.ts,预期 15 个用例全绿,其中 5 个是本卡的(审计行带impersonated_by、动态行带管理员名、员工本人写入不带、钩子里的调用者仍是员工)。packages/spec,落地前欠一次契约级复核)。What changes
An administrator who impersonates a user writes as that user. Before this PR nothing on the write said otherwise: the
sys_audit_logrow (user_idandactorboth the user,metadataempty), thesys_activityrow and the record were byte-identical to the user's own work. Only the sign-in row named the administrator.This PR carries the administrator as an attribution-only fact, in the additive shape an agent's write already uses (
performed_by/on_behalf_of):ExecutionContext.impersonatedBy(optional string, asys_userid) andHookContext.provenance.impersonatedBy, both documented as attribution only.AutomationContext.impersonatedBylets a flow started by such a write carry it.resolveAuthzContext's session arm readssession.impersonatedByoff the same session read that admitted the caller (session credential only; an API key carries none).assembleExecutionContextemits it on both entries (never on a guest envelope). Every transport that uses the shared resolver (REST, the runtime dispatcher, MCP) gets it from that one place.buildProvenancecopies it into the hook context'sprovenance, never intosession. The sandbox body runner projects it like the other provenance members.sys_audit_log.metadata.impersonated_byand addsimpersonated_byplusimpersonated_by_name(the administrator's name, from the same memoizedsys_userread asactor_name) to thesys_activityrow's metadata. Theaction_invocationrow stampsimpersonated_bytoo. Each key appears only on such a write, so its absence means the user acted themselves.user_id,actorandactor_iddo not move (ADR-0118 D1/D5).provenance.impersonatedByinto the run'sAutomationContext;resolveRunDataContextputs it on every data node's context on bothrunAsarms; it survives suspension with the persisted context. When an approval decision hands the run to a decider, the decider's segment drops it (they act in their own name).record:activity, the console record page's merged feed),record:historyand the record page's field history (fromsys_audit_log) read 「Dev Admin 代王工操作」: new keydetail.impersonatedActorin all ten console languages. An administrator whose name the writer could not read shows as the unknown-user text, never as "System" or a raw id.What the audit reader shows now, for a ticket created by Dev Admin impersonating 王工:
sys_audit_logrowuser_id = 王工,actor = 王工,metadata = {"impersonated_by": "<Dev Admin's id>"};sys_activityrowactor_id = 王工,actor_name = 王工, metadata carryingimpersonated_byandimpersonated_by_name: "Dev Admin"; the record'screated_bystays 王工; the timeline line reads 「Dev Admin 代王工操作」.The ruling's verify list (comment 6647756733), item by item
buildActionExecutionContext), so its writes carry it; theaction_invocationrow carries it.runAsarms, until a decider takes over.beforeInserthook in an impersonated write seessession.userId= the user, nothing naming the administrator insession, andprovenance = { impersonatedBy }.performed_by); left out to keep this PR to the ruling.sys_activitymetadata is served to every reader of the row;sys_audit_log.metadatais not narrowed (audit-log-field-redaction.ts's note updated to say so).ip_addressif cheap. Not done. The hook context carries no request IP, so filling it means a second envelope field set at every door. That is not cheap, and the ruling says it must not hold the rest.Tests
plugin-auditactivity-actor-name.test.ts: five new cases. An impersonated insert stampssys_audit_log.metadata.impersonated_bywithuser_id/actorstill the user. Thesys_activityrow carriesimpersonated_byandimpersonated_by_name. The user's own write carries neither key (control). AbeforeInserthook sees the user insessionand the administrator only inprovenance.action-invocation-audit.test.ts: the invocation row stamps it.core:resolve-authz-context.test.ts(an impersonation session yields it with the user's grants; the user's own session does not) andassemble-execution-context.test.ts(both entries carry it, a guest envelope never does).trigger-record-change: the run'sAutomationContextcarries the write'sprovenance.impersonatedBy.service-automationresume-decider-identity.integration.test.ts: data nodes carry it on bothrunAsarms, and the decider's segment after an approval drops it (plus a control).clilowered-body-face-enumeration.test.ts: the provenance member set now includesimpersonatedBy.recordActivityFeed.actorId-12067.test.tsx(composed actor line, unknown administrator falls back to the unknown-user text, never "System") andauditHistoryDisplay.test.ts(auditImpersonatorId).audit-writers.tsturns the ledger pin red (1 failed / 14 passed); restored, blob equal to HEAD.Acceptance notes
sys_commentis in plugin-audit'sSKIP_OBJECTS, so a comment writes nosys_audit_logand nosys_activityrow at all, impersonated or not, and itsauthor_idis the impersonated user. The ruling's verify list names comments as a write door, so this is reported, not narrowed. Options:sys_commentin the audit mirror, so a comment gets the same ledger and activity rows (and the stamp) as any write. Widest change: every comment starts writing two rows.sys_commenthas no metadata or JSON field today, so this needs a new column and a migration, which ruling A excludes; it would need its own ruling.⛔ No column and no ledger row was added for comments in this PR.
performed_by) are not shown by the new console line; out of the ruling's scope.ip_addressis not filled (see the verify list).packages/spec(widening, optional members only): a contract-review-tier review is owed before the queue.Verification
turbo build119/119 on the merge head;typecheckexit 0 for spec, core, objectql, runtime, plugin-audit, trigger-record-change, service-automation,@object-ui/plugin-detail,@object-ui/i18n,@object-ui/app-shell.dispatch-gates.mjs --ran: 116 derived families, 116 run, 0 NOT-MEASURED.check-plugin-teardown-shape --self-testneeded its base commit fetched in the shallow clone; exit 0 after that (48 cases).specgen:docsregeneratedcontent/docs/references/{data/data-engine,data/hook,kernel/execution-context}.mdx.Changed lines: 45 files, 654 insertions, 28 deletions (682, under 3000).
🤖 Generated with Claude Code
https://claude.ai/code/session_016WV4cxMph1oXW6ujSSVm1G