Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/34556-audit-ai-marks-three-rows.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@objectstack/plugin-audit': patch
'@objectstack/spec': patch
---

Clause-②: no
Metadata-protocol: none

The action-invocation, data-export and dataset-query rows in `sys_audit_log` now mark an in-product AI call the way the record-write row does. When the in-product AI performed the call for a person, `metadata` carries `performed_by` (the agent) beside `on_behalf_of` (the person), plus `conversation_id` and, when the person confirmed the call, `confirmation_id`. Before, these three rows read only an OAuth client from `performedBy` and recorded an in-product AI call as the person's own. An OAuth client stays the recorded performer, also when an envelope names both, and its rows never carry the two marks. A person's own call is unchanged. All four row kinds now apply one shared rule inside the package.

In `@objectstack/spec`, the `ExecutionContext.performedBy` describe no longer says these three rows record `clientId` only. It now says they record the performer and the two marks by the same rule. The reader rule there and in the `HookContext.provenance.performedByAgentId` describe now also says which tell decides when both apply. The change is describe text only, with no change to schema shape.
4 changes: 4 additions & 0 deletions content/docs/automation/hook-bodies.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ A hook body sees the same server-stamped write provenance an in-process handler
| `ctx.provenance.flowRunId` | The write comes from an automation flow's data node; the value is that flow run's id. |
| `ctx.provenance.attributedUserId` | The write is authorized as the system and credited to a real person (for example, the admin behind an identity-adapter call). |
| `ctx.provenance.performedByClientId` | An AI client acting through the MCP OAuth door performed the write on behalf of the user in `ctx.session.userId`. |
| `ctx.provenance.performedByAgentId` | The in-product AI agent performed the write for the signed-in person in `ctx.session.userId`, whose write it runs as; the value is the agent's name. |
| `ctx.provenance.performedByConversationId` | Set beside `performedByAgentId`: the AI conversation the write was performed in. |
| `ctx.provenance.performedByConfirmationId` | Set beside `performedByAgentId` when the person confirmed the call first: the id of the pending item their approval decided. Absent when the write needed no confirmation. |
| `ctx.provenance.impersonatedBy` | An administrator made the write from an impersonation session; the value is that administrator's `sys_user` id, while `ctx.session.userId` stays the impersonated user the write is authorized as. Attribution only: nothing authorizes on it. |

Each member is a string or absent, and `ctx.provenance` itself is **absent** when none applies — a plain REST write carries no provenance — so read it as `ctx.provenance?.flowRunId`. That is the guard that tells a flow's write apart from a user writing the same fields by hand, which matters most for a flow that runs `runAs: 'user'`: there `ctx.user`, `ctx.session` and `ctx.input` are identical for both writes.

Expand Down
24 changes: 12 additions & 12 deletions content/docs/references/data/data-engine.mdx

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion content/docs/references/data/hook.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities
| **flowRunId** | `string` | optional | Id of the automation flow run performing this write, when it originates from a flow data node. Lets a hook recognize the run that OWNS state that run itself opened — the approvals record lock exempts the run holding the pending request. |
| **attributedUserId** | `string` | optional | The real human credited for a write whose authorization subject was the SYSTEM — e.g. the admin whose better-auth `update-member-role` call the identity adapter executes as `isSystem`. ATTRIBUTION ONLY: the audit writer records it as `sys_audit_log.user_id`; no security middleware reads it, and it never becomes the subject the write is authorized as. |
| **performedByClientId** | `string` | optional | [ADR-0090 D10 rule 4] The AGENT that performed this write — the OAuth client (`azp`, the `client_id` of a registered sys_oauth_application) the access token was issued to, when an AI client acted on behalf of the human in `session.userId`. Copied from `ExecutionContext.performedBy.clientId`, which only the /mcp OAuth door sets. ATTRIBUTION ONLY, exactly like `attributedUserId`: the audit writer records it in `sys_audit_log.metadata` as `performed_by` beside `on_behalf_of`; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every non-delegated write, so a hook tells the two apart by the key being there rather than by guesswork. |
| **performedByAgentId** | `string` | optional | The in-product AI agent that performed this write for the signed-in person in `session.userId`, whose write it runs as: the agent the chat runs as. Copied from `ExecutionContext.performedBy.agentId`, which only the server-constructed in-product AI path sets, after resolving it as the agent it actually ran. ATTRIBUTION ONLY, exactly like `performedByClientId`: the record-write audit writer records it in `sys_audit_log.metadata` as `performed_by` beside `on_behalf_of`, the key an OAuth client id is also recorded in (when `performedByClientId` is also present the row records the client instead). A value matching the `client_id` of an existing `sys_oauth_application` row is an OAuth client, and a row carrying `conversation_id` or `confirmation_id` names an in-product agent; a row meeting neither may name an agent or the client of a since-deleted application, which the row alone cannot tell apart, and the contract does not keep an agent name and a `client_id` from being the same string; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every write the person made themselves. |
| **performedByAgentId** | `string` | optional | The in-product AI agent that performed this write for the signed-in person in `session.userId`, whose write it runs as: the agent the chat runs as. Copied from `ExecutionContext.performedBy.agentId`, which only the server-constructed in-product AI path sets, after resolving it as the agent it actually ran. ATTRIBUTION ONLY, exactly like `performedByClientId`: the record-write audit writer records it in `sys_audit_log.metadata` as `performed_by` beside `on_behalf_of`, the key an OAuth client id is also recorded in (when `performedByClientId` is also present the row records the client instead). A value matching the `client_id` of an existing `sys_oauth_application` row is an OAuth client, and a row carrying `conversation_id` or `confirmation_id` names an in-product agent; a row meeting neither may name an agent or the client of a since-deleted application, which the row alone cannot tell apart, and the contract does not keep an agent name and a `client_id` from being the same string (where both tells apply the mark decides, and a matching value with no mark is the client unless an agent shares that string); no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every write the person made themselves. |
| **performedByConversationId** | `string` | optional | The AI conversation an in-product AI write was performed in. Copied from `ExecutionContext.performedBy.conversationId`, set beside `performedByAgentId`. ATTRIBUTION ONLY: the record-write audit writer records it as `sys_audit_log.metadata.conversation_id`, only when `performed_by` names the in-product agent; no security middleware reads it. |
| **performedByConfirmationId** | `string` | optional | The confirmation the person gave before an AI-performed write ran: the id of the pending item their approval decided. Copied from `ExecutionContext.performedBy.confirmationId`; absent when the write needed no confirmation. ATTRIBUTION ONLY: the record-write audit writer records it as `sys_audit_log.metadata.confirmation_id`, only when `performed_by` names the in-product agent; no security middleware reads it, and it is never the authorization for the write, which runs as the person with every gate re-checked. |
| **impersonatedBy** | `string` | optional | The ADMINISTRATOR (a sys_user id) who made this write from an impersonation session, while `session.userId` is the impersonated user the write is authorized as. Copied from `ExecutionContext.impersonatedBy`, which the shared request-identity resolution sets from the session read. ATTRIBUTION ONLY, exactly like `performedByClientId`: the audit writer records it as `sys_audit_log.metadata.impersonated_by` and on the sys_activity row; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every write the user made themselves. |
Expand Down
2 changes: 1 addition & 1 deletion content/docs/references/kernel/execution-context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ const result = AuthGateCodeSchema.parse(data);
| **posture** | `Enum<'PLATFORM_ADMIN' \| 'TENANT_ADMIN' \| 'MEMBER' \| 'EXTERNAL'>` | optional | ADR-0095 D2 posture rung — PLATFORM_ADMIN crosses the tenant wall where object posture permits; TENANT_ADMIN sees all rows in the org; MEMBER gets business RLS; EXTERNAL (an external organization member) reaches explicit grants only — shares, sharing rules, and grant RLS — never the OWD baseline. |
| **authGate** | `{ code: Enum<'PASSWORD_EXPIRED' \| 'PASSWORD_RESET_REQUIRED' \| 'MFA_REQUIRED'>; message: string }` | optional | ADR-0069 authentication-policy gate: present only while the principal is blocked from protected resources until they remediate (expired password, enforced MFA), absent for every healthy session. `code` is the stable machine code the client branches on, from the closed vocabulary PASSWORD_EXPIRED / PASSWORD_RESET_REQUIRED (an administrator forced a password change) / MFA_REQUIRED, and `message` is what the blocked user reads; both are required because the transport seam renders them as the 403 body. Each code declares a scope: MFA_REQUIRED holds the account, so an API key whose owner holds it is refused with the same 403; PASSWORD_EXPIRED and PASSWORD_RESET_REQUIRED hold password sign-in alone, and API keys of that owner keep working. AUTHENTICATION, not authorization — it suspends access entirely rather than narrowing it, and nothing in the permission/RLS path reads it, while the allow-listed remediation endpoints stay reachable. Server-constructed only, never client-supplied; a guest/anonymous principal never carries one. |
| **onBehalfOf** | `{ userId: string; principalKind?: Enum<'human' \| 'agent' \| 'service' \| 'guest' \| 'system'> }` | optional | |
| **performedBy** | `{ clientId?: string; agentId?: string; conversationId?: string; confirmationId?: string }` | optional | ADR-0090 D10 rule 4 dual attribution: what PERFORMED this operation, when the performer is not the principal the write is authorized as. Two server-side producers set it: the /mcp OAuth door names the agent client in clientId, on the same branch that decides principalKind: agent and onBehalfOf; the server-constructed in-product AI path, acting for the signed-in person and running as them, names its agent in agentId with conversationId and, when the person confirmed the call, confirmationId. Absent everywhere else, and the absence is the record that the principal acted for itself; when present it names its performer, at least one of clientId and agentId, each set only by its own producer. ATTRIBUTION ONLY — no security middleware reads it, it never becomes the authorization subject, and userId stays the human so owner-stamping and current_user.* RLS still resolve to them. Server-constructed only, never client-supplied: an id a request named (an agent name, a conversation, a pending item) is stamped only after the server resolved it in its own store for the person in userId, and an unresolved id is not stamped. Surfaced to hooks as HookContext.provenance.performedByClientId / performedByAgentId / performedByConversationId / performedByConfirmationId. The record-write audit writer records the performer (clientId, or agentId for the in-product AI) as sys_audit_log.metadata.performed_by beside on_behalf_of, so that key holds two id kinds. Only when the agent is the recorded performer does the row also carry conversationId as metadata.conversation_id and confirmationId as metadata.confirmation_id (each when set); a client row never carries them. A reader can tell: a value matching the client_id of an existing sys_oauth_application row is an OAuth client; a row carrying conversation_id or confirmation_id names an in-product agent. A row meeting neither may name an agent or the client of a since-deleted application, and the row alone cannot tell which; nor does the contract keep an agent name and a client_id from being the same string. An envelope carrying both performers is recorded as the client. The action-invocation, data-export and dataset-query rows record clientId only. It does not move `actor`, which ADR-0118 D1/D5 keeps two-valued. |
| **performedBy** | `{ clientId?: string; agentId?: string; conversationId?: string; confirmationId?: string }` | optional | ADR-0090 D10 rule 4 dual attribution: what PERFORMED this operation, when the performer is not the principal the write is authorized as. Two server-side producers set it: the /mcp OAuth door names the agent client in clientId, on the same branch that decides principalKind: agent and onBehalfOf; the server-constructed in-product AI path, acting for the signed-in person and running as them, names its agent in agentId with conversationId and, when the person confirmed the call, confirmationId. Absent everywhere else, and the absence is the record that the principal acted for itself; when present it names its performer, at least one of clientId and agentId, each set only by its own producer. ATTRIBUTION ONLY — no security middleware reads it, it never becomes the authorization subject, and userId stays the human so owner-stamping and current_user.* RLS still resolve to them. Server-constructed only, never client-supplied: an id a request named (an agent name, a conversation, a pending item) is stamped only after the server resolved it in its own store for the person in userId, and an unresolved id is not stamped. Surfaced to hooks as HookContext.provenance.performedByClientId / performedByAgentId / performedByConversationId / performedByConfirmationId. The record-write audit writer records the performer (clientId, or agentId for the in-product AI) as sys_audit_log.metadata.performed_by beside on_behalf_of, so that key holds two id kinds. Only when the agent is the recorded performer does the row also carry conversationId as metadata.conversation_id and confirmationId as metadata.confirmation_id (each when set); a client row never carries them. A reader can tell: a value matching the client_id of an existing sys_oauth_application row is an OAuth client; a row carrying conversation_id or confirmation_id names an in-product agent. A row meeting neither may name an agent or the client of a since-deleted application, and the row alone cannot tell which; nor does the contract keep an agent name and a client_id from being the same string: where both tells apply the mark decides, and a matching value with no mark is the client unless an agent shares that string. An envelope carrying both performers is recorded as the client. The action-invocation, data-export and dataset-query rows record the performer and the two marks by the same rule. It does not move `actor`, which ADR-0118 D1/D5 keeps two-valued. |
| **surface** | `Enum<'rest' \| 'mcp'>` | optional | The door an action invocation came through: `rest` (the REST POST /actions/:object/:action door — console buttons, the SDK) or `mcp` (the /mcp bridge's run_action and resume_run tools — an AI client). Set only by those two doors, on the envelope of the invocation they hand the audit writer, from the door's own identity (an upstream value, header or body member never moves it); absent on every other operation. ATTRIBUTION ONLY — no security middleware reads it and it is never an authorization subject, scope or gate. Server-constructed only, never client-supplied. Recorded by the audit writer as sys_audit_log.metadata.surface on the action_invocation row. |
| **impersonatedBy** | `string` | optional | The administrator (a sys_user id) who started the impersonation session this request runs in — better-auth admin plugin session.impersonatedBy, stored as sys_session.impersonated_by. Absent on every other request; absence is the record that the user in userId acted themselves. userId stays the impersonated user, so ownership, current_user.* RLS and permissions still resolve to them. ATTRIBUTION ONLY — no security middleware reads it and it never becomes the authorization subject. Server-constructed only from the session read that admitted the caller, never client-supplied. Surfaced to hooks as HookContext.provenance.impersonatedBy and recorded by the audit writer as sys_audit_log.metadata.impersonated_by and on the sys_activity row metadata; it does not move actor or user_id. |
| **permissions** | `string[]` | optional (default: `[]`) | |
Expand Down
48 changes: 48 additions & 0 deletions packages/plugins/plugin-audit/src/action-invocation-audit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,3 +300,51 @@ describe('[#27908] the action_invocation row tells an agent\'s call from a click
expect(options).toContain(ACTION_INVOCATION_AUDIT_ACTION);
});
});

describe('[#33694] an in-product AI call is marked on the action_invocation row by the CRUD mirror\'s rule', () => {
const AI_CALL: ActionInvocationAuditEvent = {
...CLICK,
context: {
userId: 'usr_1',
tenantId: 'org_1',
surface: 'rest',
performedBy: { agentId: 'sales_assistant', conversationId: 'conv_1', confirmationId: 'pend_1' },
},
};
const PERFORMER_KEYS = ['performed_by', 'on_behalf_of', 'conversation_id', 'confirmation_id'];
const metaOf = (row: Record<string, unknown>) => JSON.parse(String(row.metadata));

it('an AI-performed call records the agent, the person, the conversation and the confirmation', async () => {
const engine = await boot();
const writer = createActionInvocationAuditWriter({ getEngine: () => engine as any });

await writer.recordActionInvocation(AI_CALL);

const [row] = await ledgerRows(engine);
expect(row.user_id).toBe('usr_1');
expect(row.actor).toBe('usr_1');
expect(JSON.parse(row.metadata)).toMatchObject({
performed_by: 'sales_assistant',
on_behalf_of: 'usr_1',
conversation_id: 'conv_1',
confirmation_id: 'pend_1',
});
});

it('CONTROL: an OAuth client — alone, or beside an agent — is the performer, with no conversation or confirmation', () => {
for (const performedBy of [
{ clientId: 'cli_agent', conversationId: 'conv_1', confirmationId: 'pend_1' },
{ clientId: 'cli_agent', agentId: 'sales_assistant', conversationId: 'conv_1', confirmationId: 'pend_1' },
]) {
const meta = metaOf(buildActionInvocationAuditRow({ ...AI_CALL, context: { ...AI_CALL.context, performedBy } }));
expect(meta).toMatchObject({ performed_by: 'cli_agent', on_behalf_of: 'usr_1' });
expect(meta).not.toHaveProperty('conversation_id');
expect(meta).not.toHaveProperty('confirmation_id');
}
});

it('CONTROL: a person\'s own call carries no performer key at all', () => {
const meta = metaOf(buildActionInvocationAuditRow(CLICK));
for (const key of PERFORMER_KEYS) expect(meta).not.toHaveProperty(key);
});
});
Loading
Loading