From 77b7a8a1631e59a352b6dba4c04a68e1d2d44555 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 08:50:51 +0000 Subject: [PATCH 01/16] feat(mcp): the read tools admit a system object that declares enable.aiReadable list_objects, describe_object, query_records, get_record and aggregate_records ask the bridge's new aiReadExposed attestation (isAiReadExposed over the whole served definition) before refusing a sys_* name; every write tool keeps refusing. Both bridges answer it. sys_approval_request declares enable.aiReadable: true. query_records names the approvals-waiting-on-you filter shape. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- packages/mcp/src/mcp-http-tools.ts | 75 ++++- .../mcp/src/mcp-system-object-ai-read.test.ts | 192 +++++++++++ packages/mcp/src/stdio-data-bridge.ts | 11 + .../src/sys-approval-request.object.ts | 9 + .../approval-read-over-mcp.dogfood.test.ts | 301 ++++++++++++++++++ packages/runtime/src/domains/mcp.ts | 13 + 6 files changed, 594 insertions(+), 7 deletions(-) create mode 100644 packages/mcp/src/mcp-system-object-ai-read.test.ts create mode 100644 packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 9e582d09845..b30d24beaca 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -30,7 +30,12 @@ * action tools yield PER ACTION: a `sys_*` action whose author declared * `ai.exposed: true` (the bridge attests it as `aiExposed`) is listed and * run like any other exposed action (#27681, ADR-0011) — no other key and - * no deployment switch opens one. + * no deployment switch opens one. The READ tools (list, describe, query, + * get one, aggregate) yield PER OBJECT the same way: a `sys_*` object whose + * author declared `enable.aiReadable: true` (the bridge attests it through + * `isAiReadExposed`, {@link McpDataBridge.aiReadExposed}) is read like any + * other object, under every later gate (#32442). No write tool ever opens a + * `sys_*` object. * - The bridge is bound to the caller's principal; tools cannot widen it. * - Errors are returned as tool errors (text), never thrown across the wire, * and never include secrets. @@ -140,6 +145,24 @@ export interface McpDataBridge { */ listObjectsDiagnosed?(): Promise>; describeObject(name: string): Promise; + /** + * [#32442, ruling A] Has the system object `name` opted its records into the + * AI READ tools? The bridge answers with `isAiReadExposed` + * (`@objectstack/spec/data`), the ONE reading of `enable.aiReadable`, over + * the object's whole served definition: the stored-metadata family answers + * `false` before the key is read, and only the boolean `true` opens. + * + * The read tools (`list_objects`, `describe_object`, `query_records`, + * `get_record`, `aggregate_records`) ask it only for a `sys_*` name their + * fail-closed guard would otherwise refuse. An attested object is then read + * exactly like a business object: AS the caller, under the caller's + * permissions, row-level security, the object's own read gates and field + * masking. It never opens a write: every write tool keeps refusing `sys_*`. + * + * OPTIONAL and fail-closed: a bridge that omits it, or whose answer throws, + * keeps every system object refused, exactly as before. + */ + aiReadExposed?(name: string): Promise; /** * [#28715] The fields of `name` that declare options — the fields a * formula's `label(record.)` can answer on — or `null` when no such @@ -471,6 +494,12 @@ function isSystemObject(name: string): boolean { return /^sys_/i.test(name); } +/** `items` kept where `keep` answers true, asked concurrently, in order. */ +async function filterAsync(items: readonly T[], keep: (item: T) => Promise): Promise { + const verdicts = await Promise.all(items.map(keep)); + return items.filter((_, i) => verdicts[i]); +} + /** * [#27681] Whether the action tools may list a summary with `allowSystemObjects` * off: any action not on a `sys_*` object, and a `sys_*` one only when the @@ -2187,6 +2216,30 @@ export function registerObjectTools( } return undefined; }; + /** + * [#32442] Does the bridge attest this system object's read opt-in + * ({@link McpDataBridge.aiReadExposed})? Fail-closed: no member, or a throw, + * is `false`. + */ + const attestsAiRead = async (objectName: string): Promise => { + if (typeof bridge.aiReadExposed !== 'function') return false; + try { + return (await bridge.aiReadExposed(objectName)) === true; + } catch { + return false; + } + }; + /** + * [#32442] The guard of the READ tools only (`describe_object`, + * `query_records`, `get_record`, `aggregate_records`): {@link guard}, except + * that a `sys_*` object the bridge attests as AI-readable is admitted. Every + * write tool keeps {@link guard}, so no declaration opens a system write. + */ + const readGuard = async (objectName: string): Promise => { + const bad = guard(objectName); + if (bad === undefined || !isSystemObject(objectName)) return bad; + return (await attestsAiRead(objectName)) ? undefined : bad; + }; if (canRead) { server.registerTool( @@ -2225,9 +2278,11 @@ export function registerObjectTools( const diagnosed = bridge.listObjectsDiagnosed ? await bridge.listObjectsDiagnosed() : { objects: await bridge.listObjects(), degraded: false, errors: [] }; + // [#32442] A system object is listed only where the bridge attests + // its read opt-in, the same admission `readGuard` makes. const visible = allowSystem ? diagnosed.objects - : diagnosed.objects.filter((o) => !isSystemObject(o.name)); + : await filterAsync(diagnosed.objects, async (o) => !isSystemObject(o.name) || await attestsAiRead(o.name)); if (!diagnosed.degraded) { return textResult({ objects: visible, totalCount: visible.length }); } @@ -2261,7 +2316,7 @@ export function registerObjectTools( annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, }, async ({ objectName }) => { - const bad = guard(objectName); + const bad = await readGuard(objectName); if (bad) return errorResult(bad); try { const def = await bridge.describeObject(objectName); @@ -2441,7 +2496,13 @@ export function registerObjectTools( { description: 'Query records from an object with optional filter, field selection, sorting and pagination. ' + - 'Runs under the caller\'s permissions and row-level security.', + 'Runs under the caller\'s permissions and row-level security. ' + + 'A filter value "{current_user_id}" stands for you. ' + + // [#32442] The console's My Pending list, filter for filter: the + // participant read alone also serves requests the caller submitted + // or already decided, so an agent must not guess "mine" from it. + 'The approvals waiting on you (where the app has approvals): objectName "sys_approval_request", where ' + + '{"status":"pending","pending_approvers":{"$contains":"{current_user_id}"}}; decide one with run_action.', inputSchema: strictToolInput( { surface: 'this query_records call', @@ -2487,7 +2548,7 @@ export function registerObjectTools( annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, }, async ({ objectName, where, fields, limit, offset, orderBy }) => { - const bad = guard(objectName); + const bad = await readGuard(objectName); if (bad) return errorResult(bad); try { const result = await bridge.query(objectName, { @@ -2588,7 +2649,7 @@ export function registerObjectTools( annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, }, async ({ objectName, aggregations, groupBy, where, timezone }) => { - const bad = guard(objectName); + const bad = await readGuard(objectName); if (bad) return errorResult(bad); try { const rows = (await aggregateFn(objectName, { @@ -2626,7 +2687,7 @@ export function registerObjectTools( annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, }, async ({ objectName, recordId }) => { - const bad = guard(objectName); + const bad = await readGuard(objectName); if (bad) return errorResult(bad); try { const record = await bridge.get(objectName, recordId); diff --git a/packages/mcp/src/mcp-system-object-ai-read.test.ts b/packages/mcp/src/mcp-system-object-ai-read.test.ts new file mode 100644 index 00000000000..7b4becea9c4 --- /dev/null +++ b/packages/mcp/src/mcp-system-object-ai-read.test.ts @@ -0,0 +1,192 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#32442, ruling A — the read half] The object tools' `sys_*` refusal yields + * PER OBJECT to the author's read opt-in, `enable.aiReadable: true`, which the + * bridge attests through `aiReadExposed` (its answer is `isAiReadExposed`, + * `@objectstack/spec/data`). + * + * The READ tools only: `list_objects`, `describe_object`, `query_records`, + * `get_record` and `aggregate_records` admit an attested system object; every + * write tool keeps refusing it, attested or not, and a bridge that attests + * nothing (or throws) keeps every system object refused, exactly as before. + * The rows themselves are the bridge's to serve: this layer adds no gate and + * removes none. + * + * Driven through `MCPServerRuntime.handleHttpRequest` over JSON-RPC, the path + * an external client hits. The runtime half (the bridge reading the + * declaration) and the end-to-end gates are pinned in + * `packages/runtime/src/mcp-system-object-ai-read.test.ts` and the dogfood + * `approval-read-over-mcp.dogfood.test.ts`. + */ + +import { describe, it, expect } from 'vitest'; + +import { MCPServerRuntime } from './mcp-server-runtime.js'; +import type { McpDataBridge } from './mcp-http-tools.js'; + +const READABLE = 'sys_approval_request'; +const SEALED = 'sys_approval_action'; +const APP = 'todo_task'; +const REFUSAL = 'is a system object and is not exposed via MCP'; + +type Calls = { reads: string[]; writes: string[] }; + +function makeBridge(attest: McpDataBridge['aiReadExposed'] | 'omit'): McpDataBridge & { calls: Calls } { + const calls: Calls = { reads: [], writes: [] }; + const bridge: McpDataBridge & { calls: Calls } = { + calls, + async listObjects() { + return [ + { name: APP, label: 'Task', fieldCount: 2 }, + { name: READABLE, label: 'Approval Request', fieldCount: 3 }, + { name: SEALED, label: 'Approval Action', fieldCount: 3 }, + ]; + }, + async describeObject(name: string) { + calls.reads.push(`describe:${name}`); + return { name, fields: [] }; + }, + async query(object: string) { + calls.reads.push(`query:${object}`); + return { records: [{ id: 'r1' }] }; + }, + async get(object: string, id: string) { + calls.reads.push(`get:${object}`); + return { id }; + }, + async aggregate(object: string) { + calls.reads.push(`aggregate:${object}`); + return [{ n: 1 }]; + }, + async create(object: string) { + calls.writes.push(`create:${object}`); + return {}; + }, + async update(object: string) { + calls.writes.push(`update:${object}`); + return {}; + }, + async remove(object: string) { + calls.writes.push(`remove:${object}`); + return {}; + }, + }; + if (attest !== 'omit') bridge.aiReadExposed = attest; + return bridge; +} + +/** The bridge attests exactly one system object, as the runtime bridge would for `enable.aiReadable: true`. */ +const attestsOne = async (name: string) => name === READABLE; + +async function call(bridge: McpDataBridge, name: string, args: Record) { + const body = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }; + const runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' }); + const req = new Request('http://localhost/api/v1/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: JSON.stringify(body), + }); + const res = await runtime.handleHttpRequest(req, { bridge, parsedBody: body }); + const json = (await res.json()) as any; + return { isError: json.result?.isError === true, text: String(json.result?.content?.[0]?.text ?? '') }; +} + +const READS: Array<[string, (o: string) => Record]> = [ + ['describe_object', (o) => ({ objectName: o })], + ['query_records', (o) => ({ objectName: o, where: { status: 'pending' } })], + ['get_record', (o) => ({ objectName: o, recordId: 'r1' })], + ['aggregate_records', (o) => ({ objectName: o, aggregations: [{ function: 'count', alias: 'n' }] })], +]; +const WRITES: Array<[string, Record]> = [ + ['create_record', { objectName: READABLE, data: { status: 'approved' } }], + ['update_record', { objectName: READABLE, recordId: 'r1', data: { status: 'approved' } }], + ['delete_record', { objectName: READABLE, recordId: 'r1' }], +]; + +describe('an attested system object is read by the read tools (#32442)', () => { + it.each(READS)('%s reaches the bridge for the attested object', async (tool, args) => { + const bridge = makeBridge(attestsOne); + const answer = await call(bridge, tool, args(READABLE)); + expect(answer.isError, answer.text).toBe(false); + expect(bridge.calls.reads).toEqual([`${tool === 'describe_object' ? 'describe' : tool.split('_')[0]}:${READABLE}`]); + }); + + it('list_objects lists the attested system object and no other', async () => { + const answer = await call(makeBridge(attestsOne), 'list_objects', {}); + expect(answer.isError, answer.text).toBe(false); + const names = (JSON.parse(answer.text).objects as Array<{ name: string }>).map((o) => o.name); + expect(names).toEqual([APP, READABLE]); + expect(JSON.parse(answer.text).totalCount).toBe(2); + }); +}); + +describe('everything else about system objects stays refused (#32442)', () => { + it.each(READS)('%s refuses a system object the bridge does not attest, without reaching the bridge', async (tool, args) => { + const bridge = makeBridge(attestsOne); + const answer = await call(bridge, tool, args(SEALED)); + expect(answer.isError).toBe(true); + expect(answer.text).toContain(REFUSAL); + expect(bridge.calls.reads).toEqual([]); + }); + + it.each(WRITES)('%s refuses the attested system object: no declaration opens a write', async (tool, args) => { + const bridge = makeBridge(async () => true); + const answer = await call(bridge, tool, args); + expect(answer.isError).toBe(true); + expect(answer.text).toContain(REFUSAL); + expect(bridge.calls.writes).toEqual([]); + }); + + it('a bridge with no attestation keeps every system object refused and unlisted, as before', async () => { + const bridge = makeBridge('omit'); + for (const [tool, args] of READS) { + const answer = await call(bridge, tool, args(READABLE)); + expect(answer.isError, tool).toBe(true); + expect(answer.text).toContain(REFUSAL); + } + const listed = await call(bridge, 'list_objects', {}); + expect((JSON.parse(listed.text).objects as Array<{ name: string }>).map((o) => o.name)).toEqual([APP]); + expect(bridge.calls.reads).toEqual([]); + }); + + it('an attestation that throws fails closed', async () => { + const bridge = makeBridge(async () => { + throw new Error('metadata store unreadable'); + }); + const answer = await call(bridge, 'query_records', { objectName: READABLE }); + expect(answer.isError).toBe(true); + expect(answer.text).toContain(REFUSAL); + const listed = await call(bridge, 'list_objects', {}); + expect((JSON.parse(listed.text).objects as Array<{ name: string }>).map((o) => o.name)).toEqual([APP]); + expect(bridge.calls.reads).toEqual([]); + }); + + it('a business object never asks the attestation', async () => { + const asked: string[] = []; + const bridge = makeBridge(async (name) => { + asked.push(name); + return false; + }); + const answer = await call(bridge, 'query_records', { objectName: APP }); + expect(answer.isError, answer.text).toBe(false); + expect(asked).toEqual([]); + }); +}); + +describe('the query tool names the "pending for me" filter shape (#32442)', () => { + it('query_records text carries the My Pending filter on sys_approval_request', async () => { + const body = { jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }; + const runtime = new MCPServerRuntime({ name: 'objectstack-test', version: '9.9.9' }); + const req = new Request('http://localhost/api/v1/mcp', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, + body: JSON.stringify(body), + }); + const res = await runtime.handleHttpRequest(req, { bridge: makeBridge(attestsOne), parsedBody: body }); + const tools = ((await res.json()) as any).result.tools as Array<{ name: string; description: string }>; + const description = tools.find((t) => t.name === 'query_records')?.description ?? ''; + expect(description).toContain('"sys_approval_request"'); + expect(description).toContain('{"status":"pending","pending_approvers":{"$contains":"{current_user_id}"}}'); + }); +}); diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 02a9bb2b8a5..db8d4d8eb7e 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -129,6 +129,8 @@ import { } from '@objectstack/spec/kernel'; import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; import { resolveObjectSortability } from '@objectstack/spec/api'; +// [#32442] The ONE reading of `enable.aiReadable` (ruling A, #32865). +import { isAiReadExposed } from '@objectstack/spec/data'; // [commit 4810dd628] The repo's ONE single-record 404 (#4435/#5138/#7867). Imported from // `@objectstack/core` rather than re-minted here or reached via // `@objectstack/metadata-protocol`'s re-export: this package already declares @@ -1156,6 +1158,15 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge return { objects, degraded, errors }; }, + // [#32442, ruling A] The read opt-in of a system object, judged by + // `isAiReadExposed` over its whole definition (the view the gates read, + // not the masked one discovery serves), as on the HTTP bridge. The read + // tools then read it through the engine as the principal, under every + // gate below, so this admits the object and nothing else. + async aiReadExposed(name: string): Promise { + return isAiReadExposed(await objectView.getObject(name)); + }, + // [#25138] Answered from the listing `list_objects` serves // ({@link readMergedObjects}), so every object an agent is listed it can // describe, and a name the listing omits (a disabled package's object among diff --git a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts index 225528b9740..4eb0c60b07f 100644 --- a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts +++ b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts @@ -905,5 +905,14 @@ export const SysApprovalRequest = ObjectSchema.create({ // generic CRUD. Reads stay open, and serve each caller only the requests // the approvals door would (#22559, `request-read-gate.ts`). apiMethods: ['get', 'list'], + // [#32442, ruling A] An approver's agent reads the requests waiting on + // them with the MCP record tools (list, describe, query, get one, + // aggregate), as the console's My Pending list does. Read only: every gate + // above still decides the rows and their values (the caller's permissions, + // `request-read-gate.ts`, the payload redaction), and no MCP write tool + // opens this object; a decision goes through the decide actions, which + // declare their own `ai.exposed`. `sys_approval_action` declares nothing: + // an approver lists and decides without reading the decision trail. + aiReadable: true, }, }); diff --git a/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts new file mode 100644 index 00000000000..06a7be53822 --- /dev/null +++ b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts @@ -0,0 +1,301 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// #32442 (ruling A, the read half) — an approver's agent lists the approval +// requests waiting on them over MCP, with the existing record tools, and then +// decides one. +// +// `sys_approval_request` declares `enable.aiReadable: true` (#32865), so the +// MCP read tools (list, describe, query, get one, aggregate) admit it past the +// `sys_*` refusal. Nothing else changes after admission: the caller's +// permissions, the approvals request-read gate (`request-read-gate.ts`, the +// participant set) and the payload redaction still decide which rows and which +// field values the caller is served. Every write tool still refuses the object. +// +// "Pending for me" is the console's My Pending list view, filter for filter: +// `status = pending` and `pending_approvers` contains `{current_user_id}`. The +// engine resolves the placeholder against the caller, so the MCP door reaches +// it without a resolver of its own. +// +// Real `SecurityPlugin`, real flows, real approvals plugin, real MCP plugin. A +// one-step flow waits on one approver, addressed by email. +// +// ⭐ the approver's "pending for me" query returns exactly the requests +// waiting on them, with the display fields the inbox row shows; +// ⭐ the same query as the submitter returns nothing; +// ⭐ a member on no request reads nothing, by query or by id; +// ⭐ the object is listed, described and countable; no write tool opens it, +// and its sibling `sys_approval_action` stays refused; +// ⭐ the query tool's text names the "pending for me" filter shape; +// ⭐ end to end: the submitter files over MCP, the approver lists, approves +// with confirmation, and the record's run resumes. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { type VerifyStack } from '@objectstack/verify'; +import { bootStack } from '@objectstack/verify'; +import { ApprovalsServicePlugin } from '@objectstack/plugin-approvals'; +import { RecordChangeTriggerPlugin } from '@objectstack/trigger-record-change'; +import { MCPServerPlugin } from '@objectstack/mcp'; +import { defineStack, defineFlow } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; +import { PermissionSetSchema, type PermissionSet } from '@objectstack/spec/security'; +import { AI_ACTION_CONFIRMATION_MEMBER } from '@objectstack/spec/contracts'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; +import { catalogPermissionSet } from './catalog-permission-set.js'; + +const OBJECT = 'aprmcp_overtime'; +const REQUEST = 'sys_approval_request'; +const SYS = { context: { isSystem: true } } as const; +const rowsOf = (r: any): any[] => (Array.isArray(r) ? r : Array.isArray(r?.records) ? r.records : Array.isArray(r?.value) ? r.value : []); + +const SUBMITTER = 'aprmcp-submitter@verify.test'; +const APPROVER = 'aprmcp-approver@verify.test'; +const STRANGER = 'aprmcp-stranger@verify.test'; + +/** The console's My Pending filter, spelled as an MCP `where`. */ +const PENDING_FOR_ME = { status: 'pending', pending_approvers: { $contains: '{current_user_id}' } }; + +const overtime = ObjectSchema.create({ + name: OBJECT, + label: 'Overtime Request', + pluralLabel: 'Overtime Requests', + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); + +const flow = defineFlow({ + name: `${OBJECT}_flow`, + label: 'Overtime approval', + description: 'Fires on insert and waits on one approver.', + type: 'autolaunched', + status: 'active', + nodes: [ + { id: 'start', type: 'start', label: 'On Create', config: { objectName: OBJECT, triggerType: 'record-after-create' } }, + { + id: 'manager', + type: 'approval', + label: 'Manager review', + config: { approvers: [{ type: 'user', value: APPROVER }], behavior: 'first_response', lockRecord: false }, + }, + { id: 'approved', type: 'end', label: 'Approved' }, + { id: 'rejected', type: 'end', label: 'Rejected' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'manager' }, + { id: 'e2', source: 'manager', target: 'approved', label: 'approve' }, + { id: 'e3', source: 'manager', target: 'rejected', label: 'reject' }, + ], +}); + +const stackConfig = defineStack({ + manifest: { + id: 'com.dogfood.approval-read-over-mcp', + namespace: 'aprmcp', + version: '0.0.0', + type: 'app', + name: 'Approval Read Over MCP Fixture', + description: 'A one-step approval flow on one object, listed and decided over MCP.', + }, + requires: ['automation', 'triggers'], + objects: [overtime], + flows: [flow], +}); + +const baselineSet: PermissionSet = PermissionSetSchema.parse({ + name: 'aprmcp_baseline', + label: 'Approval Read Over MCP Baseline — CRUD on the fixture object', + objects: { + [OBJECT]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false }, + // PROBE: the app grants read on the request object (a member holds none by default). + [REQUEST]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + }, +}); + +type Caller = { bearer: string }; + +describe('an approver\'s agent lists the approvals waiting on them over MCP (#32442, read half)', () => { + let stack: VerifyStack; + let ql: any; + let submitter: string; + let approver: string; + let stranger: string; + let submitterId: string; + + const idOf = async (email: string): Promise => + String((await ql.findOne('sys_user', { where: { email }, context: SYS.context }))?.id ?? ''); + + /** One MCP JSON-RPC call over the live transport, as a bearer. */ + const rpc = async (as: Caller, method: string, params: Record) => { + const res = await stack.api('/mcp', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + Authorization: `Bearer ${as.bearer}`, + }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }), + }); + expect(res.status).toBe(200); + const body: any = await res.json(); + expect(body.error, JSON.stringify(body.error)).toBeUndefined(); + return body.result; + }; + /** One `tools/call`, its first content block parsed. */ + const tool = async (as: Caller, name: string, args: Record) => { + const result = await rpc(as, 'tools/call', { name, arguments: args }); + const text = String(result?.content?.[0]?.text ?? ''); + let payload: any; + try { payload = JSON.parse(text); } catch { payload = { message: text }; } + return { isError: result?.isError === true, payload, text }; + }; + const pendingForMe = (as: Caller) => + tool(as, 'query_records', { objectName: REQUEST, where: PENDING_FOR_ME }); + + const requestRow = async (requestId: string) => + rowsOf(await ql.find(REQUEST, { where: { id: requestId }, context: SYS.context }))[0]; + + /** The submitter files one overtime request over MCP; the flow opens its pending step. */ + const fileOverMcp = async (name: string): Promise<{ recordId: string; requestId: string }> => { + const created = await tool({ bearer: submitter }, 'create_record', { objectName: OBJECT, data: { name } }); + expect(created.isError, created.text).toBe(false); + const recordId = String(created.payload?.id ?? created.payload?.record?.id ?? ''); + expect(recordId).not.toBe(''); + const [opened] = rowsOf(await ql.find(REQUEST, { where: { object_name: OBJECT, record_id: recordId }, context: SYS.context })); + expect(opened, 'the flow opened the approval step').toBeTruthy(); + expect(opened.status).toBe('pending'); + return { recordId, requestId: String(opened.id) }; + }; + + let first: { recordId: string; requestId: string }; + let second: { recordId: string; requestId: string }; + + beforeAll(async () => { + stack = await bootStack(stackConfig as unknown as Parameters[0], { + automation: true, + security: new SecurityPlugin({ + defaultPermissionSets: [...securityDefaultPermissionSets, baselineSet], + fallbackPermissionSet: baselineSet.name, + }), + extraPlugins: [new RecordChangeTriggerPlugin(), new ApprovalsServicePlugin(), new MCPServerPlugin()], + }); + ql = await stack.kernel.getServiceAsync('objectql'); + await stack.signIn(); + submitter = await stack.signUp(SUBMITTER); + approver = await stack.signUp(APPROVER); + stranger = await stack.signUp(STRANGER); + for (const email of [SUBMITTER, APPROVER, STRANGER]) { + expect(await catalogPermissionSet(ql, baselineSet.name), `${baselineSet.name} is served by the catalog`).toBeTruthy(); + await ql.insert('sys_user_permission_set', { user_id: await idOf(email), permission_set: baselineSet.name }, SYS); + } + submitterId = await idOf(SUBMITTER); + first = await fileOverMcp('saturday shift'); + second = await fileOverMcp('sunday shift'); + }, 300_000); + + afterAll(async () => { + await stack?.stop?.(); + }); + + it('⭐ the approver\'s "pending for me" query returns exactly the requests waiting on them, with the inbox row\'s display fields', async () => { + const answer = await pendingForMe({ bearer: approver }); + expect(answer.isError, answer.text).toBe(false); + const rows = rowsOf(answer.payload); + expect(rows.map((r) => String(r.id)).sort()).toEqual([first.requestId, second.requestId].sort()); + for (const row of rows) { + expect(row.status).toBe('pending'); + // What an agent tells its user without a second lookup: which flow, + // which step, who submitted, and which record. + expect(row.process_label).toBe('Overtime approval'); + expect(row.current_step_label).toBe('Manager review'); + expect(String(row.submitter_id?.id ?? row.submitter_id)).toBe(submitterId); + expect(row.object_name).toBe(OBJECT); + expect([first.recordId, second.recordId]).toContain(String(row.record_id)); + } + }); + + it('⭐ the same query as the submitter returns nothing, though the submitter reads their own requests', async () => { + const mine = await pendingForMe({ bearer: submitter }); + expect(mine.isError, mine.text).toBe(false); + expect(rowsOf(mine.payload)).toEqual([]); + // The participant read is wider: the submitter's untargeted read serves + // the requests they filed. "Pending for me" is the filter, not the gate. + const all = await tool({ bearer: submitter }, 'query_records', { objectName: REQUEST }); + expect(all.isError, all.text).toBe(false); + expect(rowsOf(all.payload).map((r) => String(r.id)).sort()).toEqual([first.requestId, second.requestId].sort()); + }); + + it('⭐ a member on no request reads nothing new: no rows, and a by-id read answers as missing', async () => { + const listed = await tool({ bearer: stranger }, 'query_records', { objectName: REQUEST }); + expect(listed.isError, listed.text).toBe(false); + expect(rowsOf(listed.payload)).toEqual([]); + const byId = await tool({ bearer: stranger }, 'get_record', { objectName: REQUEST, recordId: first.requestId }); + const served = byId.isError ? undefined : (byId.payload?.record ?? byId.payload); + expect(served?.id, byId.text).toBeUndefined(); + }); + + it('⭐ the object is listed, described and countable for the approver; no write tool opens it, and sys_approval_action stays refused', async () => { + const listed = await tool({ bearer: approver }, 'list_objects', {}); + expect(listed.isError, listed.text).toBe(false); + const names = (listed.payload.objects as any[]).map((o) => o.name); + expect(names).toContain(REQUEST); + expect(names.filter((n) => /^sys_/i.test(n))).toEqual([REQUEST]); + + const described = await tool({ bearer: approver }, 'describe_object', { objectName: REQUEST }); + expect(described.isError, described.text).toBe(false); + expect(JSON.stringify(described.payload)).toContain('pending_approvers'); + + const counted = await tool({ bearer: approver }, 'aggregate_records', { + objectName: REQUEST, + where: PENDING_FOR_ME, + aggregations: [{ function: 'count', alias: 'n' }], + }); + expect(counted.isError, counted.text).toBe(false); + expect(JSON.stringify(counted.payload)).toContain('"n":2'); + + const writes: Array<[string, Record]> = [ + ['create_record', { objectName: REQUEST, data: { status: 'approved' } }], + ['update_record', { objectName: REQUEST, recordId: first.requestId, data: { status: 'approved' } }], + ['delete_record', { objectName: REQUEST, recordId: first.requestId }], + ]; + for (const [name, args] of writes) { + const refused = await tool({ bearer: approver }, name, args); + expect(refused.isError, `${name}: ${refused.text}`).toBe(true); + expect(refused.text).toContain('is a system object and is not exposed via MCP'); + } + expect((await requestRow(first.requestId)).status).toBe('pending'); + + const sibling = await tool({ bearer: approver }, 'query_records', { objectName: 'sys_approval_action' }); + expect(sibling.isError, sibling.text).toBe(true); + expect(sibling.text).toContain('is a system object and is not exposed via MCP'); + }); + + it('⭐ the query tool\'s text tells an agent the "pending for me" filter shape', async () => { + const listed = await rpc({ bearer: approver }, 'tools/list', {}); + const query = (listed.tools as any[]).find((t) => t.name === 'query_records'); + expect(query?.description).toContain(REQUEST); + expect(query?.description).toContain('{current_user_id}'); + expect(query?.description).toContain('pending_approvers'); + }); + + it('⭐ end to end: the approver lists what waits on them, approves one with confirmation, and the run resumes', async () => { + const before = rowsOf((await pendingForMe({ bearer: approver })).payload); + const target = before.find((r) => String(r.record_id) === first.recordId); + expect(target, 'the approver sees the request in their pending list').toBeTruthy(); + + const decided = await tool({ bearer: approver }, 'run_action', { + actionName: 'approval_approve', + objectName: REQUEST, + recordId: String(target.id), + params: { comment: 'approved over MCP' }, + [AI_ACTION_CONFIRMATION_MEMBER]: true, + }); + expect(decided.isError, decided.text).toBe(false); + + const row = await requestRow(first.requestId); + expect(row.status).toBe('approved'); + // The run resumed past the approval node and finished on its approve edge. + const run = rowsOf(await ql.find('sys_automation_run', { where: { id: row.flow_run_id }, context: SYS.context }))[0]; + expect(run?.status, JSON.stringify(run)).toBe('completed'); + + const after = rowsOf((await pendingForMe({ bearer: approver })).payload).map((r) => String(r.id)); + expect(after).toEqual([second.requestId]); + }); +}); diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index db6c35ea19d..27460ace073 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -12,6 +12,8 @@ import { isMcpServerEnabled } from '@objectstack/types'; import { MCP_OAUTH_SCOPES, deriveAiFaceName } from '@objectstack/spec/ai'; import type { ErrorCode, MetadataProtocol } from '@objectstack/spec/api'; import type { ISecurityService } from '@objectstack/spec/contracts'; +// [#32442] The ONE reading of `enable.aiReadable` (ruling A, #32865). +import { isAiReadExposed } from '@objectstack/spec/data'; import type { AIActionConfirmation, IExternalDatasourceService } from '@objectstack/spec/contracts'; import { FEDERATION_READ_CAPABILITY, @@ -925,6 +927,17 @@ export function buildMcpBridge( // can describe, and a name the listing omits (a disabled package's // object among them) is "not found" here too. // [ADR-0106 D1/D5] …as this caller is served it ({@link readObjectForCaller}). + /** + * [#32442, ruling A] The read opt-in of a system object, judged by + * `isAiReadExposed` over its WHOLE served definition (the read that + * judges a call, not the masked one this caller is served): the + * stored-metadata family is refused before the key is read, and only + * `enable.aiReadable: true` opens. The read tools then read the object + * through {@link callData} as the caller, under every gate they always + * ran (permissions, RLS, the object's own read middleware, field + * masking), so this admits the object and nothing else. + */ + aiReadExposed: async (name: string): Promise => isAiReadExposed(await readServedObject(name)), describeObject: async (name: string) => { const def: any = await readObjectForCaller(name); if (!def) return null; From a5d8f6a0af0fd58fea81a69da1116d93d4b2595a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 08:54:34 +0000 Subject: [PATCH 02/16] test: pin the read admission in runtime and approvals; changeset The runtime bridge's aiReadExposed answer and the approvals declaration get their own pins; the end-to-end dogfood pin moves out of this change. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- ...cp-read-tools-ai-readable-system-object.md | 10 + .../mcp/src/mcp-system-object-ai-read.test.ts | 4 +- .../src/sys-approval-request.object.test.ts | 13 + .../approval-read-over-mcp.dogfood.test.ts | 301 ------------------ .../src/mcp-system-object-ai-read.test.ts | 83 +++++ 5 files changed, 107 insertions(+), 304 deletions(-) create mode 100644 .changeset/mcp-read-tools-ai-readable-system-object.md delete mode 100644 packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts create mode 100644 packages/runtime/src/mcp-system-object-ai-read.test.ts diff --git a/.changeset/mcp-read-tools-ai-readable-system-object.md b/.changeset/mcp-read-tools-ai-readable-system-object.md new file mode 100644 index 00000000000..62892fd45b3 --- /dev/null +++ b/.changeset/mcp-read-tools-ai-readable-system-object.md @@ -0,0 +1,10 @@ +--- +'@objectstack/mcp': patch +'@objectstack/runtime': patch +'@objectstack/plugin-approvals': patch +--- + +Clause-②: yes (widening) +Metadata-protocol: none + +The MCP read tools (`list_objects`, `describe_object`, `query_records`, `get_record`, `aggregate_records`) now admit a system object whose author declared `enable.aiReadable: true`, asked through a new optional bridge member `aiReadExposed` that both bridges answer with `isAiReadExposed`. Every gate after admission is unchanged (the caller's permissions, row-level security, the object's own read gates, field masking), and every write tool still refuses every `sys_*` object. `sys_approval_request` declares the key, so an approver's agent can read the requests a read grant on that object serves them; `query_records` names the "waiting on you" filter shape. diff --git a/packages/mcp/src/mcp-system-object-ai-read.test.ts b/packages/mcp/src/mcp-system-object-ai-read.test.ts index 7b4becea9c4..48f2726940b 100644 --- a/packages/mcp/src/mcp-system-object-ai-read.test.ts +++ b/packages/mcp/src/mcp-system-object-ai-read.test.ts @@ -15,9 +15,7 @@ * * Driven through `MCPServerRuntime.handleHttpRequest` over JSON-RPC, the path * an external client hits. The runtime half (the bridge reading the - * declaration) and the end-to-end gates are pinned in - * `packages/runtime/src/mcp-system-object-ai-read.test.ts` and the dogfood - * `approval-read-over-mcp.dogfood.test.ts`. + * declaration) is pinned in `packages/runtime/src/mcp-system-object-ai-read.test.ts`. */ import { describe, it, expect } from 'vitest'; diff --git a/packages/plugins/plugin-approvals/src/sys-approval-request.object.test.ts b/packages/plugins/plugin-approvals/src/sys-approval-request.object.test.ts index 17474fcc3d0..28ccddd65b9 100644 --- a/packages/plugins/plugin-approvals/src/sys-approval-request.object.test.ts +++ b/packages/plugins/plugin-approvals/src/sys-approval-request.object.test.ts @@ -23,7 +23,9 @@ import { describe, it, expect } from 'vitest'; import { templateSlotSource } from '@objectstack/spec/automation'; +import { isAiReadExposed } from '@objectstack/spec/data'; import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; const actions = (SysApprovalRequest as any).actions as any[]; const byName = (n: string) => actions.find((a) => a.name === n); @@ -282,3 +284,14 @@ describe('sys_approval_request AI exposure (#32442)', () => { expect(byName('approval_reassign').ai.paramHints?.to?.description).toMatch(/user id/); }); }); + +describe('[#32442, ruling A] the AI read declaration', () => { + it('sys_approval_request opts its records into the AI read tools, and the decision trail does not', () => { + expect(SysApprovalRequest.enable?.aiReadable).toBe(true); + expect(isAiReadExposed(SysApprovalRequest)).toBe(true); + // Read only: the generic write methods stay closed, decisions go through + // the decide actions. + expect(SysApprovalRequest.enable?.apiMethods).toEqual(['get', 'list']); + expect(isAiReadExposed(SysApprovalAction)).toBe(false); + }); +}); diff --git a/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts deleted file mode 100644 index 06a7be53822..00000000000 --- a/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// -// #32442 (ruling A, the read half) — an approver's agent lists the approval -// requests waiting on them over MCP, with the existing record tools, and then -// decides one. -// -// `sys_approval_request` declares `enable.aiReadable: true` (#32865), so the -// MCP read tools (list, describe, query, get one, aggregate) admit it past the -// `sys_*` refusal. Nothing else changes after admission: the caller's -// permissions, the approvals request-read gate (`request-read-gate.ts`, the -// participant set) and the payload redaction still decide which rows and which -// field values the caller is served. Every write tool still refuses the object. -// -// "Pending for me" is the console's My Pending list view, filter for filter: -// `status = pending` and `pending_approvers` contains `{current_user_id}`. The -// engine resolves the placeholder against the caller, so the MCP door reaches -// it without a resolver of its own. -// -// Real `SecurityPlugin`, real flows, real approvals plugin, real MCP plugin. A -// one-step flow waits on one approver, addressed by email. -// -// ⭐ the approver's "pending for me" query returns exactly the requests -// waiting on them, with the display fields the inbox row shows; -// ⭐ the same query as the submitter returns nothing; -// ⭐ a member on no request reads nothing, by query or by id; -// ⭐ the object is listed, described and countable; no write tool opens it, -// and its sibling `sys_approval_action` stays refused; -// ⭐ the query tool's text names the "pending for me" filter shape; -// ⭐ end to end: the submitter files over MCP, the approver lists, approves -// with confirmation, and the record's run resumes. - -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import { type VerifyStack } from '@objectstack/verify'; -import { bootStack } from '@objectstack/verify'; -import { ApprovalsServicePlugin } from '@objectstack/plugin-approvals'; -import { RecordChangeTriggerPlugin } from '@objectstack/trigger-record-change'; -import { MCPServerPlugin } from '@objectstack/mcp'; -import { defineStack, defineFlow } from '@objectstack/spec'; -import { ObjectSchema, Field } from '@objectstack/spec/data'; -import { PermissionSetSchema, type PermissionSet } from '@objectstack/spec/security'; -import { AI_ACTION_CONFIRMATION_MEMBER } from '@objectstack/spec/contracts'; -import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; -import { catalogPermissionSet } from './catalog-permission-set.js'; - -const OBJECT = 'aprmcp_overtime'; -const REQUEST = 'sys_approval_request'; -const SYS = { context: { isSystem: true } } as const; -const rowsOf = (r: any): any[] => (Array.isArray(r) ? r : Array.isArray(r?.records) ? r.records : Array.isArray(r?.value) ? r.value : []); - -const SUBMITTER = 'aprmcp-submitter@verify.test'; -const APPROVER = 'aprmcp-approver@verify.test'; -const STRANGER = 'aprmcp-stranger@verify.test'; - -/** The console's My Pending filter, spelled as an MCP `where`. */ -const PENDING_FOR_ME = { status: 'pending', pending_approvers: { $contains: '{current_user_id}' } }; - -const overtime = ObjectSchema.create({ - name: OBJECT, - label: 'Overtime Request', - pluralLabel: 'Overtime Requests', - fields: { name: Field.text({ label: 'Name', required: true }) }, -}); - -const flow = defineFlow({ - name: `${OBJECT}_flow`, - label: 'Overtime approval', - description: 'Fires on insert and waits on one approver.', - type: 'autolaunched', - status: 'active', - nodes: [ - { id: 'start', type: 'start', label: 'On Create', config: { objectName: OBJECT, triggerType: 'record-after-create' } }, - { - id: 'manager', - type: 'approval', - label: 'Manager review', - config: { approvers: [{ type: 'user', value: APPROVER }], behavior: 'first_response', lockRecord: false }, - }, - { id: 'approved', type: 'end', label: 'Approved' }, - { id: 'rejected', type: 'end', label: 'Rejected' }, - ], - edges: [ - { id: 'e1', source: 'start', target: 'manager' }, - { id: 'e2', source: 'manager', target: 'approved', label: 'approve' }, - { id: 'e3', source: 'manager', target: 'rejected', label: 'reject' }, - ], -}); - -const stackConfig = defineStack({ - manifest: { - id: 'com.dogfood.approval-read-over-mcp', - namespace: 'aprmcp', - version: '0.0.0', - type: 'app', - name: 'Approval Read Over MCP Fixture', - description: 'A one-step approval flow on one object, listed and decided over MCP.', - }, - requires: ['automation', 'triggers'], - objects: [overtime], - flows: [flow], -}); - -const baselineSet: PermissionSet = PermissionSetSchema.parse({ - name: 'aprmcp_baseline', - label: 'Approval Read Over MCP Baseline — CRUD on the fixture object', - objects: { - [OBJECT]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false }, - // PROBE: the app grants read on the request object (a member holds none by default). - [REQUEST]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, - }, -}); - -type Caller = { bearer: string }; - -describe('an approver\'s agent lists the approvals waiting on them over MCP (#32442, read half)', () => { - let stack: VerifyStack; - let ql: any; - let submitter: string; - let approver: string; - let stranger: string; - let submitterId: string; - - const idOf = async (email: string): Promise => - String((await ql.findOne('sys_user', { where: { email }, context: SYS.context }))?.id ?? ''); - - /** One MCP JSON-RPC call over the live transport, as a bearer. */ - const rpc = async (as: Caller, method: string, params: Record) => { - const res = await stack.api('/mcp', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - Authorization: `Bearer ${as.bearer}`, - }, - body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }), - }); - expect(res.status).toBe(200); - const body: any = await res.json(); - expect(body.error, JSON.stringify(body.error)).toBeUndefined(); - return body.result; - }; - /** One `tools/call`, its first content block parsed. */ - const tool = async (as: Caller, name: string, args: Record) => { - const result = await rpc(as, 'tools/call', { name, arguments: args }); - const text = String(result?.content?.[0]?.text ?? ''); - let payload: any; - try { payload = JSON.parse(text); } catch { payload = { message: text }; } - return { isError: result?.isError === true, payload, text }; - }; - const pendingForMe = (as: Caller) => - tool(as, 'query_records', { objectName: REQUEST, where: PENDING_FOR_ME }); - - const requestRow = async (requestId: string) => - rowsOf(await ql.find(REQUEST, { where: { id: requestId }, context: SYS.context }))[0]; - - /** The submitter files one overtime request over MCP; the flow opens its pending step. */ - const fileOverMcp = async (name: string): Promise<{ recordId: string; requestId: string }> => { - const created = await tool({ bearer: submitter }, 'create_record', { objectName: OBJECT, data: { name } }); - expect(created.isError, created.text).toBe(false); - const recordId = String(created.payload?.id ?? created.payload?.record?.id ?? ''); - expect(recordId).not.toBe(''); - const [opened] = rowsOf(await ql.find(REQUEST, { where: { object_name: OBJECT, record_id: recordId }, context: SYS.context })); - expect(opened, 'the flow opened the approval step').toBeTruthy(); - expect(opened.status).toBe('pending'); - return { recordId, requestId: String(opened.id) }; - }; - - let first: { recordId: string; requestId: string }; - let second: { recordId: string; requestId: string }; - - beforeAll(async () => { - stack = await bootStack(stackConfig as unknown as Parameters[0], { - automation: true, - security: new SecurityPlugin({ - defaultPermissionSets: [...securityDefaultPermissionSets, baselineSet], - fallbackPermissionSet: baselineSet.name, - }), - extraPlugins: [new RecordChangeTriggerPlugin(), new ApprovalsServicePlugin(), new MCPServerPlugin()], - }); - ql = await stack.kernel.getServiceAsync('objectql'); - await stack.signIn(); - submitter = await stack.signUp(SUBMITTER); - approver = await stack.signUp(APPROVER); - stranger = await stack.signUp(STRANGER); - for (const email of [SUBMITTER, APPROVER, STRANGER]) { - expect(await catalogPermissionSet(ql, baselineSet.name), `${baselineSet.name} is served by the catalog`).toBeTruthy(); - await ql.insert('sys_user_permission_set', { user_id: await idOf(email), permission_set: baselineSet.name }, SYS); - } - submitterId = await idOf(SUBMITTER); - first = await fileOverMcp('saturday shift'); - second = await fileOverMcp('sunday shift'); - }, 300_000); - - afterAll(async () => { - await stack?.stop?.(); - }); - - it('⭐ the approver\'s "pending for me" query returns exactly the requests waiting on them, with the inbox row\'s display fields', async () => { - const answer = await pendingForMe({ bearer: approver }); - expect(answer.isError, answer.text).toBe(false); - const rows = rowsOf(answer.payload); - expect(rows.map((r) => String(r.id)).sort()).toEqual([first.requestId, second.requestId].sort()); - for (const row of rows) { - expect(row.status).toBe('pending'); - // What an agent tells its user without a second lookup: which flow, - // which step, who submitted, and which record. - expect(row.process_label).toBe('Overtime approval'); - expect(row.current_step_label).toBe('Manager review'); - expect(String(row.submitter_id?.id ?? row.submitter_id)).toBe(submitterId); - expect(row.object_name).toBe(OBJECT); - expect([first.recordId, second.recordId]).toContain(String(row.record_id)); - } - }); - - it('⭐ the same query as the submitter returns nothing, though the submitter reads their own requests', async () => { - const mine = await pendingForMe({ bearer: submitter }); - expect(mine.isError, mine.text).toBe(false); - expect(rowsOf(mine.payload)).toEqual([]); - // The participant read is wider: the submitter's untargeted read serves - // the requests they filed. "Pending for me" is the filter, not the gate. - const all = await tool({ bearer: submitter }, 'query_records', { objectName: REQUEST }); - expect(all.isError, all.text).toBe(false); - expect(rowsOf(all.payload).map((r) => String(r.id)).sort()).toEqual([first.requestId, second.requestId].sort()); - }); - - it('⭐ a member on no request reads nothing new: no rows, and a by-id read answers as missing', async () => { - const listed = await tool({ bearer: stranger }, 'query_records', { objectName: REQUEST }); - expect(listed.isError, listed.text).toBe(false); - expect(rowsOf(listed.payload)).toEqual([]); - const byId = await tool({ bearer: stranger }, 'get_record', { objectName: REQUEST, recordId: first.requestId }); - const served = byId.isError ? undefined : (byId.payload?.record ?? byId.payload); - expect(served?.id, byId.text).toBeUndefined(); - }); - - it('⭐ the object is listed, described and countable for the approver; no write tool opens it, and sys_approval_action stays refused', async () => { - const listed = await tool({ bearer: approver }, 'list_objects', {}); - expect(listed.isError, listed.text).toBe(false); - const names = (listed.payload.objects as any[]).map((o) => o.name); - expect(names).toContain(REQUEST); - expect(names.filter((n) => /^sys_/i.test(n))).toEqual([REQUEST]); - - const described = await tool({ bearer: approver }, 'describe_object', { objectName: REQUEST }); - expect(described.isError, described.text).toBe(false); - expect(JSON.stringify(described.payload)).toContain('pending_approvers'); - - const counted = await tool({ bearer: approver }, 'aggregate_records', { - objectName: REQUEST, - where: PENDING_FOR_ME, - aggregations: [{ function: 'count', alias: 'n' }], - }); - expect(counted.isError, counted.text).toBe(false); - expect(JSON.stringify(counted.payload)).toContain('"n":2'); - - const writes: Array<[string, Record]> = [ - ['create_record', { objectName: REQUEST, data: { status: 'approved' } }], - ['update_record', { objectName: REQUEST, recordId: first.requestId, data: { status: 'approved' } }], - ['delete_record', { objectName: REQUEST, recordId: first.requestId }], - ]; - for (const [name, args] of writes) { - const refused = await tool({ bearer: approver }, name, args); - expect(refused.isError, `${name}: ${refused.text}`).toBe(true); - expect(refused.text).toContain('is a system object and is not exposed via MCP'); - } - expect((await requestRow(first.requestId)).status).toBe('pending'); - - const sibling = await tool({ bearer: approver }, 'query_records', { objectName: 'sys_approval_action' }); - expect(sibling.isError, sibling.text).toBe(true); - expect(sibling.text).toContain('is a system object and is not exposed via MCP'); - }); - - it('⭐ the query tool\'s text tells an agent the "pending for me" filter shape', async () => { - const listed = await rpc({ bearer: approver }, 'tools/list', {}); - const query = (listed.tools as any[]).find((t) => t.name === 'query_records'); - expect(query?.description).toContain(REQUEST); - expect(query?.description).toContain('{current_user_id}'); - expect(query?.description).toContain('pending_approvers'); - }); - - it('⭐ end to end: the approver lists what waits on them, approves one with confirmation, and the run resumes', async () => { - const before = rowsOf((await pendingForMe({ bearer: approver })).payload); - const target = before.find((r) => String(r.record_id) === first.recordId); - expect(target, 'the approver sees the request in their pending list').toBeTruthy(); - - const decided = await tool({ bearer: approver }, 'run_action', { - actionName: 'approval_approve', - objectName: REQUEST, - recordId: String(target.id), - params: { comment: 'approved over MCP' }, - [AI_ACTION_CONFIRMATION_MEMBER]: true, - }); - expect(decided.isError, decided.text).toBe(false); - - const row = await requestRow(first.requestId); - expect(row.status).toBe('approved'); - // The run resumed past the approval node and finished on its approve edge. - const run = rowsOf(await ql.find('sys_automation_run', { where: { id: row.flow_run_id }, context: SYS.context }))[0]; - expect(run?.status, JSON.stringify(run)).toBe('completed'); - - const after = rowsOf((await pendingForMe({ bearer: approver })).payload).map((r) => String(r.id)); - expect(after).toEqual([second.requestId]); - }); -}); diff --git a/packages/runtime/src/mcp-system-object-ai-read.test.ts b/packages/runtime/src/mcp-system-object-ai-read.test.ts new file mode 100644 index 00000000000..ffc99ac0878 --- /dev/null +++ b/packages/runtime/src/mcp-system-object-ai-read.test.ts @@ -0,0 +1,83 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#32442, ruling A — the read half] The runtime's MCP bridge attests a system + * object's read opt-in, `enable.aiReadable: true`, through `isAiReadExposed` + * (`@objectstack/spec/data`) over the object's whole served definition. + * + * The tool layer (`packages/mcp`, `mcp-system-object-ai-read.test.ts`) admits a + * `sys_*` object to the five read tools exactly when this answers `true`. This + * file pins the answer the one production HTTP bridge gives: + * + * - a system object that declares `enable.aiReadable: true` → `true`; + * - a system object that declares nothing, or `false`, or a truthy + * non-boolean → `false`; + * - the stored-metadata family → `false`, declared or not (refused before + * the key is read); + * - a business object → `false` (the key means nothing there; the tool layer + * never asks for one); + * - a name nothing serves → `false`. + * + * The objects here are test doubles, never the platform's. + */ + +import { describe, it, expect, vi } from 'vitest'; + +import { STORED_METADATA_BODY_OBJECTS } from '@objectstack/spec/kernel'; + +import { HttpDispatcher } from './http-dispatcher.js'; + +const [FAMILY] = [...STORED_METADATA_BODY_OBJECTS]; + +function bridgeOver(objects: any[]) { + const byName = (n: string) => objects.find((o) => o.name === n); + const metadata: any = { + load: vi.fn(async () => null), + loadMany: vi.fn(async () => []), + listObjects: vi.fn(async () => objects), + getObject: vi.fn(async (n: string) => byName(n)), + }; + const ql: any = { getSchema: byName, registry: { getObject: byName, getItem: () => undefined } }; + const kernel: any = { + context: { + getService: (n: string) => (n === 'objectql' || n === 'data' ? ql : n === 'metadata' ? metadata : null), + }, + }; + const ctx: any = { + request: {}, + environmentId: 'platform', + executionContext: { userId: 'u_agent', permissions: [], systemPermissions: [] }, + }; + return (new HttpDispatcher(kernel) as any).buildMcpBridge(ctx); +} + +describe('[#32442] the HTTP MCP bridge attests enable.aiReadable with isAiReadExposed', () => { + const bridge = bridgeOver([ + { name: 'sys_probe_request', fields: {}, enable: { aiReadable: true } }, + { name: 'sys_probe_closed', fields: {}, enable: { aiReadable: false } }, + { name: 'sys_probe_silent', fields: {} }, + { name: 'sys_probe_stringly', fields: {}, enable: { aiReadable: 'true' } }, + { name: FAMILY, fields: {}, enable: { aiReadable: true } }, + { name: 'probe_task', fields: {}, enable: { aiReadable: true } }, + ]); + + it('answers true for a system object that declares aiReadable: true', async () => { + expect(await bridge.aiReadExposed('sys_probe_request')).toBe(true); + }); + + it.each(['sys_probe_closed', 'sys_probe_silent', 'sys_probe_stringly'])( + 'answers false for %s (declared false, nothing, or a non-boolean)', + async (name) => { + expect(await bridge.aiReadExposed(name)).toBe(false); + }, + ); + + it('answers false for the stored-metadata family even when it declares the key', async () => { + expect(await bridge.aiReadExposed(FAMILY)).toBe(false); + }); + + it('answers false for a business object and for a name nothing serves', async () => { + expect(await bridge.aiReadExposed('probe_task')).toBe(false); + expect(await bridge.aiReadExposed('sys_probe_missing')).toBe(false); + }); +}); From 55a470c17c22052dec54c30310596cea98acf490 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 08:58:50 +0000 Subject: [PATCH 03/16] docs(mcp): a system object that declares enable.aiReadable is open to the read tools Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- content/docs/ai/connect-mcp.mdx | 9 ++++++++- packages/mcp/README.md | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index faceec7f522..394f904e4da 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -330,7 +330,14 @@ usable on an app with hundreds of objects. Which objects and actions that spine can reach is the **default exposure policy (v1)**: - **Objects are exposed automatically** — except `sys_*` system objects, which - are blocked fail-closed. + are blocked fail-closed. A system object whose author declared + `enable.aiReadable: true` is open to the read tools only (`list_objects`, + `describe_object`, `query_records`, `get_record`, `aggregate_records`), read + as you under every gate a read already runs (your permissions, row-level + security, the object's own read rules, field masking); no write tool opens + it, and the stored-metadata tables stay refused. `sys_approval_request` + declares it, so an agent can list the approvals waiting on you where your + permissions let you read that object. - **Actions require the author's opt-in**: `ai: { exposed: true }` plus an `ai.description` of at least 40 characters, and the action must be callable without a UI. In the open framework that means three types — `script` diff --git a/packages/mcp/README.md b/packages/mcp/README.md index cbd4f8920f6..c860b3559aa 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -109,7 +109,7 @@ apply): ```typescript // Object data -'list_objects' // List objects (system sys_* objects hidden by default) +'list_objects' // List objects (sys_* hidden unless declared enable.aiReadable) 'describe_object' // Object schema: fields + features 'validate_expression' // Check a CEL expression against a schema before authoring it 'query_records' // Filter / sort / paginate From 5d0be8a93cae0dd0d9f161a5223f73ebbd2cdf7c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 09:30:55 +0000 Subject: [PATCH 04/16] test(mcp): classify aiReadExposed in the bridge-member tripwires Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- .../mcp/src/mcp-write-response-internal-fields.tripwire.test.ts | 2 ++ packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts | 1 + 2 files changed, 3 insertions(+) diff --git a/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts b/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts index 7943913908e..4e62af790fa 100644 --- a/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts +++ b/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts @@ -153,6 +153,8 @@ const RECIPES: Record = { // share is what keeps a stored field off this response in the first place. listObjectsDiagnosed: { invoke: (b) => b.listObjectsDiagnosed(), writesRecords: false }, describeObject: { invoke: (b) => b.describeObject('vault'), writesRecords: false }, + // [#32442] A boolean off the object definition: no record body. + aiReadExposed: { invoke: (b) => b.aiReadExposed('vault'), writesRecords: false }, // [#28715] Field NAMES off the object definition `describeObject` reads: no // engine read, no record, so nothing stored can ride this answer. optionFieldsOf: { invoke: (b) => b.optionFieldsOf('vault'), writesRecords: false }, diff --git a/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts b/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts index 3e30be9e62b..5b0afee25c1 100644 --- a/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts +++ b/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts @@ -466,6 +466,7 @@ const BRIDGE_MEMBERS: Record = { listObjects: 'no row body — object definitions from the metadata service', listObjectsDiagnosed: 'no row body — object definitions from the metadata service', describeObject: 'no row body — one object definition from the metadata service', + aiReadExposed: 'no row body — a boolean read off one object definition (isAiReadExposed)', optionFieldsOf: 'no row body — field names from the same object definition describeObject reads', query: 'seam — serveStoredMetadataRows; filter / sort on the body column refused', get: 'seam — serveStoredMetadataRow', From a332db45f532128bb341853e3c4731519bba99b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 09:57:11 +0000 Subject: [PATCH 05/16] test(runtime): pay the metadata load at collection in the read-admission pin Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- packages/runtime/src/mcp-system-object-ai-read.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/runtime/src/mcp-system-object-ai-read.test.ts b/packages/runtime/src/mcp-system-object-ai-read.test.ts index ffc99ac0878..cb7ac40a1ec 100644 --- a/packages/runtime/src/mcp-system-object-ai-read.test.ts +++ b/packages/runtime/src/mcp-system-object-ai-read.test.ts @@ -23,6 +23,9 @@ import { describe, it, expect, vi } from 'vitest'; +// Paid at collection: the dispatcher's reach loads it lazily (check:test-source-alias). +import '@objectstack/metadata'; + import { STORED_METADATA_BODY_OBJECTS } from '@objectstack/spec/kernel'; import { HttpDispatcher } from './http-dispatcher.js'; From 1b1d909b47c5043595ec5b32273a651bc439f287 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 10:00:32 +0000 Subject: [PATCH 06/16] feat(approvals): members read their approval requests; the read gate answers waiting-on-me with the service's fold member_default names sys_approval_request (read only); request-read-gate.ts narrows the rows as before. A conjunctive pending_approvers $contains of the caller's own id is answered with the pending-approver index over the caller's acting addresses, so email- and position-addressed slots are found. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- .../plugin-approvals/src/approval-service.ts | 10 + .../plugin-approvals/src/request-read-gate.ts | 80 +++++++ ...read-waiting-on-caller.integration.test.ts | 198 ++++++++++++++++++ .../src/objects/default-permission-sets.ts | 17 ++ 4 files changed, 305 insertions(+) create mode 100644 packages/plugins/plugin-approvals/src/request-read-waiting-on-caller.integration.test.ts diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index d1d8396e14b..1b0f2bdf131 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -2059,6 +2059,16 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } return this.visibleRequestIds(context, tenantOrg, anchor); }, + // [#32442] "Waiting on me" for the read gate: the pending-approver index + // over the caller's acting addresses — the fold `visibleRequestIds`' + // current-approver probe and `listRequests`' approver filter read. The + // index holds rows only while a request is pending. + waitingOnCallerIds: async (context) => { + const tenantOrg = (context as any)?.organizationId ?? context?.tenantId ?? null; + const who = await this.actingCaller(context); + if (!who) return []; + return (await this.approverRequestIds(actingAddresses(who), tenantOrg)) ?? []; + }, }); } diff --git a/packages/plugins/plugin-approvals/src/request-read-gate.ts b/packages/plugins/plugin-approvals/src/request-read-gate.ts index f7b29f84430..1c26251a0d0 100644 --- a/packages/plugins/plugin-approvals/src/request-read-gate.ts +++ b/packages/plugins/plugin-approvals/src/request-read-gate.ts @@ -77,6 +77,24 @@ * `visible` predicate fails closed on this door, and a record reader admitted * by the tier is served the row read-only on both doors. * + * ## "Waiting on me" (#32442, ruling 1B + 2B, record 6849636735) + * + * The console's My Pending list view, and an agent over MCP, ask for the + * requests waiting on the caller as `status = pending` AND `pending_approvers` + * contains `{current_user_id}` (the engine resolves the placeholder before this + * gate runs, so the gate sees the caller's own id). Read literally, that misses + * every slot the caller acts under without its user id: a `user` approver + * authored as an email stores the email, a position nobody held at open time + * stores `position:

` (`approver-address.ts`). So the gate answers that one + * conjunct, where it pins the CALLER'S OWN id, with the approvals service's own + * fold ({@link RequestVisibilitySource.waitingOnCallerIds}: the pending-approver + * index over the caller's acting addresses, the set `listRequests` and the + * decision methods read). ⛔ Still no rule here, and no second fold: the + * conjunct becomes a constraint on `id` built from the ids the service + * returned. Any other `pending_approvers` predicate (another user's id, a + * substring) is left exactly as written. The participant narrowing below is + * ANDed after it, as for every read. + * * ## The child tables (#22589) * * A request's two child tables declare the same `get` / `list` shape: @@ -153,6 +171,58 @@ export interface RequestVisibilitySource { row?: { object: string; id: string } | null; }, ): Promise | null>; + /** + * [#32442] The ids of the pending requests holding a slot the caller acts + * under — the approvals door's "waiting on me", its own fold + * (`approverRequestIds` over `actingAddresses`). Empty for a caller who acts + * under nothing. + */ + waitingOnCallerIds(context: ExecutionContext): Promise; +} + +/** The column whose `$contains` of the caller's own id asks "waiting on me". */ +export const WAITING_ON_CALLER_COLUMN = 'pending_approvers'; + +const isPlainRecord = (v: unknown): v is Record => + v !== null && typeof v === 'object' && !Array.isArray(v); + +/** + * [#32442] `where` with each conjunct that asks for the requests waiting on + * `userId` taken out: `pending_approvers: { $contains: userId }`, at the root or + * inside a root `$and` (a conjunctive position, read as `pinnedEquality` reads + * one). `matched` is false, and `where` comes back as it was, when there is + * none. A predicate under `$or` / `$not`, or naming another id, is not one. + */ +export function splitWaitingOnCaller(where: unknown, userId: string): { where: unknown; matched: boolean } { + let matched = false; + const asks = (value: unknown): boolean => + isPlainRecord(value) + && Object.keys(value).length === 1 + && typeof value.$contains === 'string' + && value.$contains.trim() === userId; + const walk = (condition: unknown): unknown => { + if (!isPlainRecord(condition)) return condition; + const out: Record = {}; + for (const [key, value] of Object.entries(condition)) { + if (key === WAITING_ON_CALLER_COLUMN && asks(value)) { + matched = true; + continue; + } + out[key] = key === '$and' && Array.isArray(value) + ? value.map(walk).filter((sub) => !(isPlainRecord(sub) && Object.keys(sub).length === 0)) + : value; + } + return out; + }; + if (!userId) return { where, matched: false }; + const rest = walk(where); + return matched ? { where: rest, matched } : { where, matched: false }; +} + +/** `where` AND `filter`, an empty `where` dropped. */ +function andWhere(where: unknown, filter: Readonly>): unknown { + const empty = !where || (isPlainRecord(where) && Object.keys(where).length === 0); + return empty ? filter : { $and: [where, filter] }; } /** @@ -220,6 +290,16 @@ function bindVisibilityGate( if (!REQUEST_READ_OPS.has(opCtx?.operation) || !ast || !context) return next(); let filter: Readonly> | null; try { + // [#32442] "Waiting on me", answered with the service's own fold, before + // the participant narrowing (which is ANDed below as for every read). + const userId = context?.userId != null ? String(context.userId) : ''; + if (column === 'id' && userId) { + const split = splitWaitingOnCaller(ast.where, userId); + if (split.matched) { + const waiting = await source.waitingOnCallerIds(context); + ast.where = andWhere(split.where, requestVisibilityFilter(new Set(waiting), null, 'id') ?? REQUEST_READ_DENY_ALL); + } + } const visible = await source.visibleRequestIdsFor(context, targetOf(ast.where)); filter = requestVisibilityFilter(visible, pinnedEquality(ast.where, column), column); } catch (err: any) { diff --git a/packages/plugins/plugin-approvals/src/request-read-waiting-on-caller.integration.test.ts b/packages/plugins/plugin-approvals/src/request-read-waiting-on-caller.integration.test.ts new file mode 100644 index 00000000000..37bf12fafd2 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/request-read-waiting-on-caller.integration.test.ts @@ -0,0 +1,198 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#32442 — maintainer ruling 6849636735, 2B] "Waiting on me" on the generic + * data door is the approvals door's own answer. + * + * The console's My Pending list view and an agent over MCP ask for + * `status = pending` AND `pending_approvers` contains `{current_user_id}`. Read + * literally, that misses a slot the caller acts under without its user id: a + * position nobody held when the step opened stores `position:

`, an email + * approver stores the email. The request read gate answers that conjunct, where + * it pins the caller's OWN id, with the service's fold (the pending-approver + * index over the caller's acting addresses), and narrows to the participant set + * after it as for every read. + * + * The rig is `request-read-gate.integration.test.ts`'s: a real ObjectQL engine + * over better-sqlite3, the real `ApprovalsServicePlugin.start()`, so the gate is + * the one the plugin binds, and the placeholder is resolved by the engine as in + * a deployment. No security plugin: every caller holds read on the object (the + * member baseline grant, ruling 1B, pinned in the dogfood suite). + * + * - an approver whose slot is their user id gets exactly that request; + * - a position holder gets the request whose slot is the unstaffed + * `position:

` literal — the pin a literal `$contains` fails; + * - by find, count and grouped count alike; + * - a member on no request gets nothing; + * - a `pending_approvers` predicate naming ANOTHER id, or under `$or`, is left + * as written (and still narrowed to the caller's participant set); + * - a decided request leaves the answer. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ApprovalService } from './approval-service.js'; +import { ApprovalsServicePlugin } from './approvals-plugin.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; +import { splitWaitingOnCaller } from './request-read-gate.js'; + +const REQUEST = 'sys_approval_request'; +const OBJECT = 'exam_sheet'; +const SYSTEM = { isSystem: true, positions: [], permissions: [] } as any; +const asUser = (userId: string, positions: string[] = []) => ({ userId, positions, permissions: [] }) as any; + +const SUBMITTER = 'u_submitter'; +const APPROVER = 'u_approver'; +/** Holds the position the second request's slot names; on no other request. */ +const LEAD = 'u_lead'; +const LEAD_POSITION = 'exam_lead'; +const OUTSIDER = 'u_outsider'; + +/** The My Pending filter, as the list view and the MCP tool text spell it. */ +const WAITING_ON_ME = { status: 'pending', pending_approvers: { $contains: '{current_user_id}' } }; + +const examSheet = { + name: OBJECT, + label: 'Exam Sheet', + fields: { + id: { name: 'id', label: 'Id', type: 'text' as const, primaryKey: true }, + title: { name: 'title', label: 'Title', type: 'text' as const }, + }, +}; + +let current: ObjectQL | undefined; +afterEach(async () => { + try { await current?.destroy(); } catch { /* noop */ } + current = undefined; +}); + +async function boot() { + const engine = new ObjectQL(); + current = engine; + engine.registerDriver(new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: ':memory:' }, + useNullAsDefault: true, + }), true); + await engine.init(); + for (const def of [examSheet, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation]) { + engine.registry.registerObject(def as any, 'approvals-waiting-on-caller-test', 'approvals-waiting-on-caller-test'); + } + await engine.syncSchemas(); + await installDefaultOrganization(engine); + for (const id of ['sheet_a', 'sheet_b']) { + await engine.insert(OBJECT, { id, title: id }, { context: SYSTEM } as any); + } + + const services: Record = { objectql: engine }; + const ctx: any = { + getService: (name: string) => { + if (!(name in services)) throw new Error(`[Kernel] Service '${name}' not found`); + return services[name]; + }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + hook: () => {}, + logger: { info: () => {}, debug: () => {}, error: () => {}, warn: () => {} }, + }; + await new ApprovalsServicePlugin({}).start(ctx); + const svc = services.approvals as ApprovalService; + + const open = async (recordId: string, runId: string) => (await svc.openNodeRequest({ + object: OBJECT, recordId, runId, nodeId: 'review', flowName: 'exam_review', + config: { approvers: [{ type: 'user', value: APPROVER }], behavior: 'first_response' } as any, + submitterId: SUBMITTER, record: { id: recordId, title: recordId }, + }, asUser(SUBMITTER)) as any).id as string; + const byUserId = await open('sheet_a', 'run_a'); + const byPosition = await open('sheet_b', 'run_b'); + + // The second step opened on a position nobody held: the slot is the + // `position:

` literal, on the request and in the pending-approver index, + // as the open path writes it (`approver-address.ts`). + const literal = `position:${LEAD_POSITION}`; + await engine.update(REQUEST, { id: byPosition, pending_approvers: literal }, { context: SYSTEM } as any); + const [indexRow] = await engine.find('sys_approval_approver', { where: { request_id: byPosition }, context: SYSTEM } as any) as any[]; + await engine.update('sys_approval_approver', { id: indexRow.id, approver: literal }, { context: SYSTEM } as any); + + return { engine, svc, ids: { byUserId, byPosition } }; +} + +const idsOf = (rows: unknown) => (rows as any[]).map((r) => String(r.id)).sort(); + +describe('[#32442] the request read gate answers "waiting on me" with the approvals fold', () => { + it('an approver whose slot is their user id gets exactly that request', async () => { + const rig = await boot(); + const rows = await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: asUser(APPROVER) } as any); + expect(idsOf(rows)).toEqual([rig.ids.byUserId]); + }); + + it('a position holder gets the request whose slot is the unstaffed position literal, by find, count and grouped count', async () => { + const rig = await boot(); + const lead = asUser(LEAD, [LEAD_POSITION]); + // The literal reading matches nothing: the column holds `position:exam_lead`, not the id. + const stored = await rig.engine.find(REQUEST, { where: { id: rig.ids.byPosition }, context: SYSTEM } as any) as any[]; + expect(stored[0].pending_approvers).toBe(`position:${LEAD_POSITION}`); + + expect(idsOf(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: lead } as any))).toEqual([rig.ids.byPosition]); + expect(await rig.engine.count(REQUEST, { where: WAITING_ON_ME, context: lead } as any)).toBe(1); + const groups = await rig.engine.aggregate(REQUEST, { + where: WAITING_ON_ME, groupBy: ['status'], aggregations: [{ function: 'count', alias: 'n' }], context: lead, + } as any) as any[]; + expect(groups.map((g) => [g.status, Number(g.n)])).toEqual([['pending', 1]]); + }); + + it('a member on no request gets nothing, and the submitter gets nothing waiting on them', async () => { + const rig = await boot(); + expect(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: asUser(OUTSIDER) } as any)).toEqual([]); + expect(await rig.engine.count(REQUEST, { where: WAITING_ON_ME, context: asUser(OUTSIDER) } as any)).toBe(0); + expect(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: asUser(SUBMITTER) } as any)).toEqual([]); + // Control: the submitter's untargeted read serves both requests they filed. + expect(idsOf(await rig.engine.find(REQUEST, { context: asUser(SUBMITTER) } as any))) + .toEqual([rig.ids.byUserId, rig.ids.byPosition].sort()); + }); + + it('a predicate naming another id is left as written, still narrowed to the caller\'s own requests', async () => { + const rig = await boot(); + // The submitter asks what waits on the approver: read literally, under the + // submitter's participant set: the one request whose column holds that id. + const rows = await rig.engine.find(REQUEST, { + where: { status: 'pending', pending_approvers: { $contains: APPROVER } }, context: asUser(SUBMITTER), + } as any); + expect(idsOf(rows)).toEqual([rig.ids.byUserId]); + // An outsider asking the same reads nothing: the participant narrowing still applies. + expect(await rig.engine.find(REQUEST, { + where: { pending_approvers: { $contains: APPROVER } }, context: asUser(OUTSIDER), + } as any)).toEqual([]); + }); + + it('a decided request leaves the answer', async () => { + const rig = await boot(); + await rig.svc.decideNode(rig.ids.byUserId, { decision: 'approve' } as any, asUser(APPROVER)); + expect(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: asUser(APPROVER) } as any)).toEqual([]); + }); +}); + +describe('[#32442] splitWaitingOnCaller reads only a conjunctive pin of the caller\'s own id', () => { + const me = 'u_me'; + it('takes the conjunct out at the root and inside a root $and', () => { + expect(splitWaitingOnCaller({ status: 'pending', pending_approvers: { $contains: me } }, me)) + .toEqual({ where: { status: 'pending' }, matched: true }); + expect(splitWaitingOnCaller({ $and: [{ status: 'pending' }, { pending_approvers: { $contains: me } }] }, me)) + .toEqual({ where: { $and: [{ status: 'pending' }] }, matched: true }); + }); + + it('leaves another id, another operator, and a pin under $or as written', () => { + for (const where of [ + { pending_approvers: { $contains: 'u_other' } }, + { pending_approvers: me }, + { pending_approvers: { $contains: me, $ne: 'x' } }, + { $or: [{ pending_approvers: { $contains: me } }, { status: 'pending' }] }, + ]) { + expect(splitWaitingOnCaller(where, me)).toEqual({ where, matched: false }); + } + }); +}); diff --git a/packages/plugins/plugin-security/src/objects/default-permission-sets.ts b/packages/plugins/plugin-security/src/objects/default-permission-sets.ts index c22b03cb810..108f5bd254e 100644 --- a/packages/plugins/plugin-security/src/objects/default-permission-sets.ts +++ b/packages/plugins/plugin-security/src/objects/default-permission-sets.ts @@ -853,6 +853,23 @@ const baseDefaultPermissionSets: PermissionSet[] = [ // the same two gates. sys_comment: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false }, sys_activity: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, + // [#32442 — maintainer ruling 6849636735, 1B] The approval requests a + // member takes part in, on the data door and the MCP read tools, as the + // approvals inbox already serves them. Before this line a member held no + // data-door read on the object, so an approver's agent was refused (`403`) + // the requests waiting on them. + // + // Same shape as the two lines above: this opens the OBJECT, and ⛔ no row + // policy is added. WHICH ROWS is plugin-approvals' request read gate + // (`request-read-gate.ts`), the approvals door's own answer: the submitter, + // a current approver, a past actor (plus the default-OFF record-reader + // tier); a member on no request reads none, by list, by id, by count. The + // payload snapshot stays narrowed to the subject fields the reader may + // read (`payload-redaction-middleware.ts`). READ only: the object serves + // `get` / `list` alone, and decisions go through its decide actions. + // `sys_approval_action` and `sys_approval_approver` are not named. An + // external member resolves `external_default` and gets no such line. + sys_approval_request: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }, }, // [#21237] The identity object's `Admin` group is admin-review data, not a // staff directory: `sys_user_org_members` below opens every org peer's row, From 5b91c3641bd3e05ebe5f9f3600abaedfbcf5726f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 10:05:55 +0000 Subject: [PATCH 07/16] test(dogfood): an approver's agent lists and decides the approvals waiting on them over MCP Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- .../approval-read-over-mcp.dogfood.test.ts | 416 ++++++++++++++++++ 1 file changed, 416 insertions(+) create mode 100644 packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts diff --git a/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts new file mode 100644 index 00000000000..8e82d068522 --- /dev/null +++ b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts @@ -0,0 +1,416 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// #32442 (ruling A; maintainer ruling 6849636735, 1B + 2B) — an approver's +// agent lists the approval requests waiting on them over MCP, with the +// existing record tools, and then decides one. +// +// Three things make that reachable, each pinned here through the live MCP +// transport: +// +// - `sys_approval_request` declares `enable.aiReadable: true` (#32865), so +// the MCP read tools admit it past the `sys_*` refusal; no write tool does; +// - `member_default` names it read-only (1B), so a signed-in member holds a +// data-door read on the object with no grant from the app. Which ROWS is +// still the approvals request read gate (`request-read-gate.ts`): the +// submitter, a current approver, a past actor; +// - that gate answers "waiting on me" — `pending_approvers` contains +// `{current_user_id}`, the console's My Pending filter — with the approvals +// service's own fold (2B), so a slate that addresses the approver by email +// is found, not only one holding their user id. +// +// Nothing in this file grants the request object: every member here holds the +// shipped baseline and an app set naming the app's own objects. +// +// Real `SecurityPlugin`, real flows, real approvals plugin, real MCP plugin. +// Two one-step flows: overtime waits on one approver addressed by EMAIL and, +// once approved, stamps the record; expense waits on a TEAM. The overtime +// object carries a capability-gated masked field only the submitter may read. +// +// ⭐ the approver's "pending for me" query returns exactly their requests — +// the email-addressed ones, not the team's — with the inbox row's display +// fields; the team member's returns exactly the team's; +// ⭐ the same query as the submitter returns nothing; +// ⭐ a member on no request reads nothing: by query, by id, by aggregate; +// ⭐ the snapshot field the approver may not read is not served to them; +// ⭐ the object is listed and described; no write tool opens it, and +// `sys_approval_action` stays refused; +// ⭐ the query tool's text names the "pending for me" filter shape; +// ⭐ end to end: the submitter files over MCP, the approver lists, approves +// with confirmation, and the record's flow resumes and stamps it. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { type VerifyStack } from '@objectstack/verify'; +import { bootStack } from '@objectstack/verify'; +import { ApprovalsServicePlugin } from '@objectstack/plugin-approvals'; +import { RecordChangeTriggerPlugin } from '@objectstack/trigger-record-change'; +import { MCPServerPlugin } from '@objectstack/mcp'; +import { defineStack, defineFlow } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; +import { PermissionSetSchema, type PermissionSet } from '@objectstack/spec/security'; +import { AI_ACTION_CONFIRMATION_MEMBER } from '@objectstack/spec/contracts'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; +import { catalogPermissionSet } from './catalog-permission-set.js'; + +const OVERTIME = 'aprmcp_overtime'; +const EXPENSE = 'aprmcp_expense'; +const REQUEST = 'sys_approval_request'; +const SYS = { context: { isSystem: true } } as const; +const rowsOf = (r: any): any[] => (Array.isArray(r) ? r : Array.isArray(r?.records) ? r.records : Array.isArray(r?.value) ? r.value : []); + +const SUBMITTER = 'aprmcp-submitter@verify.test'; +const APPROVER = 'aprmcp-approver@verify.test'; +const TEAMMATE = 'aprmcp-teammate@verify.test'; +const STRANGER = 'aprmcp-stranger@verify.test'; +/** The team the expense flow waits on, inserted with this id before any request opens. */ +const TEAM_ID = 'aprmcp_team_reviewers'; + +/** A capability-gated masked field: the submitter holds the capability, the approver does not. */ +const MASKED = 'aprmcp_cost_code'; +const CAPABILITY = 'aprmcp_read_cost_code'; +const STORED = 'SYNTH7731CODE'; + +/** The console's My Pending filter, spelled as an MCP `where`. */ +const PENDING_FOR_ME = { status: 'pending', pending_approvers: { $contains: '{current_user_id}' } }; + +const overtime = ObjectSchema.create({ + name: OVERTIME, + label: 'Overtime Request', + pluralLabel: 'Overtime Requests', + sharingModel: 'public_read_write', + fields: { + name: Field.text({ label: 'Name', required: true }), + outcome: Field.text({ label: 'Outcome' }), + [MASKED]: Field.text({ label: 'Cost Code', maskingRule: { keepHead: 1, keepTail: 1 }, requiredPermissions: [CAPABILITY] }), + }, +}); +const expense = ObjectSchema.create({ + name: EXPENSE, + label: 'Expense Claim', + pluralLabel: 'Expense Claims', + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); + +const overtimeFlow = defineFlow({ + name: `${OVERTIME}_flow`, + label: 'Overtime approval', + description: 'Fires on insert, waits on the approver by email, and stamps the record once approved.', + type: 'autolaunched', + status: 'active', + runAs: 'system', + nodes: [ + { id: 'start', type: 'start', label: 'On Create', config: { objectName: OVERTIME, triggerType: 'record-after-create' } }, + { + id: 'manager', + type: 'approval', + label: 'Manager review', + config: { approvers: [{ type: 'user', value: APPROVER }], behavior: 'first_response', lockRecord: false }, + }, + { + id: 'stamp', + type: 'update_record', + label: 'Stamp the outcome', + config: { + objectName: OVERTIME, + filter: { id: { dialect: 'cel', source: 'record.id' } }, + fields: { outcome: 'approved' }, + }, + }, + { id: 'approved', type: 'end', label: 'Approved' }, + { id: 'rejected', type: 'end', label: 'Rejected' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'manager' }, + { id: 'e2', source: 'manager', target: 'stamp', label: 'approve' }, + { id: 'e3', source: 'stamp', target: 'approved' }, + { id: 'e4', source: 'manager', target: 'rejected', label: 'reject' }, + ], +}); + +const expenseFlow = defineFlow({ + name: `${EXPENSE}_flow`, + label: 'Expense approval', + description: 'Fires on insert and waits on a team.', + type: 'autolaunched', + status: 'active', + nodes: [ + { id: 'start', type: 'start', label: 'On Create', config: { objectName: EXPENSE, triggerType: 'record-after-create' } }, + { + id: 'manager', + type: 'approval', + label: 'Team review', + config: { approvers: [{ type: 'team', value: TEAM_ID }], behavior: 'first_response', lockRecord: false }, + }, + { id: 'approved', type: 'end', label: 'Approved' }, + { id: 'rejected', type: 'end', label: 'Rejected' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'manager' }, + { id: 'e2', source: 'manager', target: 'approved', label: 'approve' }, + { id: 'e3', source: 'manager', target: 'rejected', label: 'reject' }, + ], +}); + +const stackConfig = defineStack({ + manifest: { + id: 'com.dogfood.approval-read-over-mcp', + namespace: 'aprmcp', + version: '0.0.0', + type: 'app', + name: 'Approval Read Over MCP Fixture', + description: 'Two one-step approval flows, listed and decided over MCP.', + }, + requires: ['automation', 'triggers'], + objects: [overtime, expense], + flows: [overtimeFlow, expenseFlow], +}); + +/** The app's own objects only: nothing here names `sys_approval_request`. */ +const appObjects = { + [OVERTIME]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false }, + [EXPENSE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: false }, +}; +const baselineSet: PermissionSet = PermissionSetSchema.parse({ + name: 'aprmcp_baseline', + label: 'Approval Read Over MCP Baseline — the app objects', + objects: appObjects, +}); +const submitterSet: PermissionSet = PermissionSetSchema.parse({ + name: 'aprmcp_submitter', + label: 'Approval Read Over MCP Submitter — the app objects and the cost-code capability', + objects: appObjects, + systemPermissions: [CAPABILITY], +}); + +type Caller = { bearer: string }; + +describe('an approver\'s agent lists the approvals waiting on them over MCP (#32442, read half)', () => { + let stack: VerifyStack; + let ql: any; + let submitter: string; + let approver: string; + let teammate: string; + let stranger: string; + let submitterId: string; + + const idOf = async (email: string): Promise => + String((await ql.findOne('sys_user', { where: { email }, context: SYS.context }))?.id ?? ''); + + /** One MCP JSON-RPC call over the live transport, as a bearer. */ + const rpc = async (as: Caller, method: string, params: Record) => { + const res = await stack.api('/mcp', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json, text/event-stream', + Authorization: `Bearer ${as.bearer}`, + }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }), + }); + expect(res.status).toBe(200); + const body: any = await res.json(); + expect(body.error, JSON.stringify(body.error)).toBeUndefined(); + return body.result; + }; + /** One `tools/call`, its first content block parsed. */ + const tool = async (as: Caller, name: string, args: Record) => { + const result = await rpc(as, 'tools/call', { name, arguments: args }); + const text = String(result?.content?.[0]?.text ?? ''); + let payload: any; + try { payload = JSON.parse(text); } catch { payload = { message: text }; } + return { isError: result?.isError === true, payload, text }; + }; + const pendingForMe = (as: Caller) => + tool(as, 'query_records', { objectName: REQUEST, where: PENDING_FOR_ME }); + const pendingIds = async (as: Caller) => { + const answer = await pendingForMe(as); + expect(answer.isError, answer.text).toBe(false); + return rowsOf(answer.payload).map((r) => String(r.id)).sort(); + }; + + const requestRow = async (requestId: string) => + rowsOf(await ql.find(REQUEST, { where: { id: requestId }, context: SYS.context }))[0]; + + /** The submitter files one record over MCP; its flow opens the pending step. */ + const fileOverMcp = async (object: string, data: Record): Promise<{ recordId: string; requestId: string }> => { + const created = await tool({ bearer: submitter }, 'create_record', { objectName: object, data }); + expect(created.isError, created.text).toBe(false); + const recordId = String(created.payload?.id ?? created.payload?.record?.id ?? ''); + expect(recordId).not.toBe(''); + const [opened] = rowsOf(await ql.find(REQUEST, { where: { object_name: object, record_id: recordId }, context: SYS.context })); + expect(opened, 'the flow opened the approval step').toBeTruthy(); + expect(opened.status).toBe('pending'); + return { recordId, requestId: String(opened.id) }; + }; + + let first: { recordId: string; requestId: string }; + let second: { recordId: string; requestId: string }; + let teamOne: { recordId: string; requestId: string }; + + beforeAll(async () => { + stack = await bootStack(stackConfig as unknown as Parameters[0], { + automation: true, + security: new SecurityPlugin({ + defaultPermissionSets: [...securityDefaultPermissionSets, baselineSet, submitterSet], + fallbackPermissionSet: baselineSet.name, + }), + extraPlugins: [new RecordChangeTriggerPlugin(), new ApprovalsServicePlugin(), new MCPServerPlugin()], + }); + ql = await stack.kernel.getServiceAsync('objectql'); + await stack.signIn(); + submitter = await stack.signUp(SUBMITTER); + approver = await stack.signUp(APPROVER); + teammate = await stack.signUp(TEAMMATE); + stranger = await stack.signUp(STRANGER); + const assignments: Array<[string, PermissionSet]> = [ + [SUBMITTER, submitterSet], [APPROVER, baselineSet], [TEAMMATE, baselineSet], [STRANGER, baselineSet], + ]; + for (const [email, set] of assignments) { + expect(await catalogPermissionSet(ql, set.name), `${set.name} is served by the catalog`).toBeTruthy(); + await ql.insert('sys_user_permission_set', { user_id: await idOf(email), permission_set: set.name }, SYS); + } + submitterId = await idOf(SUBMITTER); + + // The expense flow's team, in the members' organization, with one member. + const membership = await ql.findOne('sys_member', { where: { user_id: submitterId }, context: SYS.context }); + const orgId = String(membership?.organization_id ?? ''); + expect(orgId).not.toBe(''); + await ql.insert('sys_team', { id: TEAM_ID, name: 'Expense reviewers', organization_id: orgId }, SYS); + await ql.insert('sys_team_member', { team_id: TEAM_ID, user_id: await idOf(TEAMMATE) }, SYS); + + first = await fileOverMcp(OVERTIME, { name: 'saturday shift', [MASKED]: STORED }); + second = await fileOverMcp(OVERTIME, { name: 'sunday shift' }); + teamOne = await fileOverMcp(EXPENSE, { name: 'taxi' }); + }, 300_000); + + afterAll(async () => { + await stack?.stop?.(); + }); + + it('⭐ the approver\'s "pending for me" query returns exactly the requests waiting on them, with the inbox row\'s display fields', async () => { + // The overtime slate holds the approver's EMAIL: the literal column is not their id. + expect((await requestRow(first.requestId)).pending_approvers).toBe(APPROVER); + const answer = await pendingForMe({ bearer: approver }); + expect(answer.isError, answer.text).toBe(false); + const rows = rowsOf(answer.payload); + expect(rows.map((r) => String(r.id)).sort()).toEqual([first.requestId, second.requestId].sort()); + for (const row of rows) { + expect(row.status).toBe('pending'); + // What an agent tells its user without a second lookup: which flow, + // which step, who submitted, and which record. + expect(row.process_label).toBe('Overtime approval'); + expect(row.current_step_label).toBe('Manager review'); + expect(String(row.submitter_id?.id ?? row.submitter_id)).toBe(submitterId); + expect(row.object_name).toBe(OVERTIME); + expect([first.recordId, second.recordId]).toContain(String(row.record_id)); + } + }); + + it('⭐ a team member\'s "pending for me" returns exactly the team\'s request', async () => { + expect(await pendingIds({ bearer: teammate })).toEqual([teamOne.requestId]); + }); + + it('⭐ the same query as the submitter returns nothing, though the submitter reads their own requests', async () => { + expect(await pendingIds({ bearer: submitter })).toEqual([]); + // The participant read is wider: the submitter's untargeted read serves + // the requests they filed. "Pending for me" is the filter, not the gate. + const all = await tool({ bearer: submitter }, 'query_records', { objectName: REQUEST }); + expect(all.isError, all.text).toBe(false); + expect(rowsOf(all.payload).map((r) => String(r.id)).sort()) + .toEqual([first.requestId, second.requestId, teamOne.requestId].sort()); + }); + + it('⭐ a member on no request reads nothing: by query, by id, by aggregate', async () => { + const listed = await tool({ bearer: stranger }, 'query_records', { objectName: REQUEST }); + expect(listed.isError, listed.text).toBe(false); + expect(rowsOf(listed.payload)).toEqual([]); + expect(await pendingIds({ bearer: stranger })).toEqual([]); + const byId = await tool({ bearer: stranger }, 'get_record', { objectName: REQUEST, recordId: first.requestId }); + expect(byId.isError, byId.text).toBe(true); + expect(byId.text).not.toContain(first.recordId); + const counted = await tool({ bearer: stranger }, 'aggregate_records', { + objectName: REQUEST, + aggregations: [{ function: 'count', alias: 'n' }], + }); + expect(counted.isError, counted.text).toBe(false); + expect(JSON.stringify(counted.payload)).toContain('"n":0'); + }); + + it('⭐ the snapshot field the approver may not read is not served to them; the submitter, who may, is served it', async () => { + const forApprover = rowsOf((await pendingForMe({ bearer: approver })).payload).find((r) => String(r.id) === first.requestId); + expect(forApprover?.payload_json, 'the approver is served the snapshot').toBeTruthy(); + expect(String(forApprover.payload_json)).not.toContain(MASKED); + expect(String(forApprover.payload_json)).not.toContain(STORED); + // Control: the stored snapshot carries it, and the submitter is served it. + expect(String((await requestRow(first.requestId)).payload_json)).toContain(STORED); + const own = await tool({ bearer: submitter }, 'get_record', { objectName: REQUEST, recordId: first.requestId }); + expect(own.isError, own.text).toBe(false); + expect(own.text).toContain(STORED); + }); + + it('⭐ the object is listed and described for the approver; no write tool opens it, and sys_approval_action stays refused', async () => { + const listed = await tool({ bearer: approver }, 'list_objects', {}); + expect(listed.isError, listed.text).toBe(false); + const names = (listed.payload.objects as any[]).map((o) => o.name); + expect(names).toContain(REQUEST); + expect(names.filter((n) => /^sys_/i.test(n))).toEqual([REQUEST]); + + const described = await tool({ bearer: approver }, 'describe_object', { objectName: REQUEST }); + expect(described.isError, described.text).toBe(false); + expect(JSON.stringify(described.payload)).toContain('pending_approvers'); + + const counted = await tool({ bearer: approver }, 'aggregate_records', { + objectName: REQUEST, + where: PENDING_FOR_ME, + aggregations: [{ function: 'count', alias: 'n' }], + }); + expect(counted.isError, counted.text).toBe(false); + expect(JSON.stringify(counted.payload)).toContain('"n":2'); + + const writes: Array<[string, Record]> = [ + ['create_record', { objectName: REQUEST, data: { status: 'approved' } }], + ['update_record', { objectName: REQUEST, recordId: first.requestId, data: { status: 'approved' } }], + ['delete_record', { objectName: REQUEST, recordId: first.requestId }], + ]; + for (const [name, args] of writes) { + const refused = await tool({ bearer: approver }, name, args); + expect(refused.isError, `${name}: ${refused.text}`).toBe(true); + expect(refused.text).toContain('is a system object and is not exposed via MCP'); + } + expect((await requestRow(first.requestId)).status).toBe('pending'); + + const sibling = await tool({ bearer: approver }, 'query_records', { objectName: 'sys_approval_action' }); + expect(sibling.isError, sibling.text).toBe(true); + expect(sibling.text).toContain('is a system object and is not exposed via MCP'); + }); + + it('⭐ the query tool\'s text tells an agent the "pending for me" filter shape', async () => { + const listed = await rpc({ bearer: approver }, 'tools/list', {}); + const query = (listed.tools as any[]).find((t) => t.name === 'query_records'); + expect(query?.description).toContain(REQUEST); + expect(query?.description).toContain('{current_user_id}'); + expect(query?.description).toContain('pending_approvers'); + }); + + it('⭐ end to end: the approver lists what waits on them, approves one with confirmation, and the flow resumes', async () => { + const before = rowsOf((await pendingForMe({ bearer: approver })).payload); + const target = before.find((r) => String(r.record_id) === first.recordId); + expect(target, 'the approver sees the request in their pending list').toBeTruthy(); + + const decided = await tool({ bearer: approver }, 'run_action', { + actionName: 'approval_approve', + objectName: REQUEST, + recordId: String(target.id), + params: { comment: 'approved over MCP' }, + [AI_ACTION_CONFIRMATION_MEMBER]: true, + }); + expect(decided.isError, decided.text).toBe(false); + + expect((await requestRow(first.requestId)).status).toBe('approved'); + // The run resumed past the approval node down its approve edge, whose + // next node stamps the record. + const record = rowsOf(await ql.find(OVERTIME, { where: { id: first.recordId }, context: SYS.context }))[0]; + expect(record?.outcome, JSON.stringify(record)).toBe('approved'); + + expect(await pendingIds({ bearer: approver })).toEqual([second.requestId]); + }); +}); From c12b78365ce5be0798a49e0cde92b799477a7840 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 10:08:08 +0000 Subject: [PATCH 08/16] docs(mcp): members read their approval requests; waiting-on-me covers email and position slots Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- .changeset/mcp-read-tools-ai-readable-system-object.md | 5 ++++- content/docs/ai/connect-mcp.mdx | 7 +++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/.changeset/mcp-read-tools-ai-readable-system-object.md b/.changeset/mcp-read-tools-ai-readable-system-object.md index 62892fd45b3..6d5f284b930 100644 --- a/.changeset/mcp-read-tools-ai-readable-system-object.md +++ b/.changeset/mcp-read-tools-ai-readable-system-object.md @@ -2,9 +2,12 @@ '@objectstack/mcp': patch '@objectstack/runtime': patch '@objectstack/plugin-approvals': patch +'@objectstack/plugin-security': patch --- Clause-②: yes (widening) Metadata-protocol: none -The MCP read tools (`list_objects`, `describe_object`, `query_records`, `get_record`, `aggregate_records`) now admit a system object whose author declared `enable.aiReadable: true`, asked through a new optional bridge member `aiReadExposed` that both bridges answer with `isAiReadExposed`. Every gate after admission is unchanged (the caller's permissions, row-level security, the object's own read gates, field masking), and every write tool still refuses every `sys_*` object. `sys_approval_request` declares the key, so an approver's agent can read the requests a read grant on that object serves them; `query_records` names the "waiting on you" filter shape. +The MCP read tools (`list_objects`, `describe_object`, `query_records`, `get_record`, `aggregate_records`) now admit a system object whose author declared `enable.aiReadable: true`, asked through a new optional bridge member `aiReadExposed` that both bridges answer with `isAiReadExposed`. Every gate after admission is unchanged (the caller's permissions, row-level security, the object's own read gates, field masking), and every write tool still refuses every `sys_*` object. `sys_approval_request` declares the key; `query_records` names the "waiting on you" filter shape. + +The member baseline `member_default` now names `sys_approval_request` read-only, so every signed-in member holds a data-door read on it; which rows is still the approvals request read gate (the submitter, a current approver, a past actor), and no write opens. That gate now answers a conjunctive `pending_approvers` `$contains` of the caller's own id with the approvals service's acting-address fold, so the console's My Pending view and an agent's "waiting on me" query find a slot addressed by email or an unstaffed position, not only one holding the user id. A `pending_approvers` predicate naming another id, or under `$or`, is read as written. diff --git a/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index 394f904e4da..7a6a7395393 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -336,8 +336,11 @@ can reach is the **default exposure policy (v1)**: as you under every gate a read already runs (your permissions, row-level security, the object's own read rules, field masking); no write tool opens it, and the stored-metadata tables stay refused. `sys_approval_request` - declares it, so an agent can list the approvals waiting on you where your - permissions let you read that object. + declares it: every signed-in member reads the requests they take part in + (submitted, waiting on them, or acted on) and no others, so an agent can + list the approvals waiting on you with `pending_approvers` contains + `{current_user_id}` — answered for a slot that names you by email, position + or team too, not only by user id. - **Actions require the author's opt-in**: `ai: { exposed: true }` plus an `ai.description` of at least 40 characters, and the action must be callable without a UI. In the open framework that means three types — `script` From 7fd55e60c190a656024a336e92019ea930535bae Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 14:46:46 +0000 Subject: [PATCH 09/16] test(approvals): type the waiting-on-me rig's query options Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- ...read-waiting-on-caller.integration.test.ts | 33 ++++++++++--------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/request-read-waiting-on-caller.integration.test.ts b/packages/plugins/plugin-approvals/src/request-read-waiting-on-caller.integration.test.ts index 37bf12fafd2..137afb48d35 100644 --- a/packages/plugins/plugin-approvals/src/request-read-waiting-on-caller.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/request-read-waiting-on-caller.integration.test.ts @@ -40,6 +40,7 @@ import { SysApprovalApprover } from './sys-approval-approver.object.js'; import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; import { installDefaultOrganization } from './default-organization.testkit.js'; import { splitWaitingOnCaller } from './request-read-gate.js'; +import type { EngineQueryOptions } from '@objectstack/spec/data'; const REQUEST = 'sys_approval_request'; const OBJECT = 'exam_sheet'; @@ -86,7 +87,7 @@ async function boot() { await engine.syncSchemas(); await installDefaultOrganization(engine); for (const id of ['sheet_a', 'sheet_b']) { - await engine.insert(OBJECT, { id, title: id }, { context: SYSTEM } as any); + await engine.insert(OBJECT, { id, title: id }, { context: SYSTEM } satisfies EngineQueryOptions); } const services: Record = { objectql: engine }; @@ -114,9 +115,9 @@ async function boot() { // `position:

` literal, on the request and in the pending-approver index, // as the open path writes it (`approver-address.ts`). const literal = `position:${LEAD_POSITION}`; - await engine.update(REQUEST, { id: byPosition, pending_approvers: literal }, { context: SYSTEM } as any); - const [indexRow] = await engine.find('sys_approval_approver', { where: { request_id: byPosition }, context: SYSTEM } as any) as any[]; - await engine.update('sys_approval_approver', { id: indexRow.id, approver: literal }, { context: SYSTEM } as any); + await engine.update(REQUEST, { id: byPosition, pending_approvers: literal }, { context: SYSTEM } satisfies EngineQueryOptions); + const [indexRow] = await engine.find('sys_approval_approver', { where: { request_id: byPosition }, context: SYSTEM } satisfies EngineQueryOptions) as any[]; + await engine.update('sys_approval_approver', { id: indexRow.id, approver: literal }, { context: SYSTEM } satisfies EngineQueryOptions); return { engine, svc, ids: { byUserId, byPosition } }; } @@ -126,7 +127,7 @@ const idsOf = (rows: unknown) => (rows as any[]).map((r) => String(r.id)).sort() describe('[#32442] the request read gate answers "waiting on me" with the approvals fold', () => { it('an approver whose slot is their user id gets exactly that request', async () => { const rig = await boot(); - const rows = await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: asUser(APPROVER) } as any); + const rows = await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: asUser(APPROVER) } satisfies EngineQueryOptions); expect(idsOf(rows)).toEqual([rig.ids.byUserId]); }); @@ -134,24 +135,24 @@ describe('[#32442] the request read gate answers "waiting on me" with the approv const rig = await boot(); const lead = asUser(LEAD, [LEAD_POSITION]); // The literal reading matches nothing: the column holds `position:exam_lead`, not the id. - const stored = await rig.engine.find(REQUEST, { where: { id: rig.ids.byPosition }, context: SYSTEM } as any) as any[]; + const stored = await rig.engine.find(REQUEST, { where: { id: rig.ids.byPosition }, context: SYSTEM } satisfies EngineQueryOptions) as any[]; expect(stored[0].pending_approvers).toBe(`position:${LEAD_POSITION}`); - expect(idsOf(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: lead } as any))).toEqual([rig.ids.byPosition]); - expect(await rig.engine.count(REQUEST, { where: WAITING_ON_ME, context: lead } as any)).toBe(1); + expect(idsOf(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: lead } satisfies EngineQueryOptions))).toEqual([rig.ids.byPosition]); + expect(await rig.engine.count(REQUEST, { where: WAITING_ON_ME, context: lead } satisfies EngineQueryOptions)).toBe(1); const groups = await rig.engine.aggregate(REQUEST, { where: WAITING_ON_ME, groupBy: ['status'], aggregations: [{ function: 'count', alias: 'n' }], context: lead, - } as any) as any[]; + } satisfies EngineQueryOptions) as any[]; expect(groups.map((g) => [g.status, Number(g.n)])).toEqual([['pending', 1]]); }); it('a member on no request gets nothing, and the submitter gets nothing waiting on them', async () => { const rig = await boot(); - expect(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: asUser(OUTSIDER) } as any)).toEqual([]); - expect(await rig.engine.count(REQUEST, { where: WAITING_ON_ME, context: asUser(OUTSIDER) } as any)).toBe(0); - expect(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: asUser(SUBMITTER) } as any)).toEqual([]); + expect(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: asUser(OUTSIDER) } satisfies EngineQueryOptions)).toEqual([]); + expect(await rig.engine.count(REQUEST, { where: WAITING_ON_ME, context: asUser(OUTSIDER) } satisfies EngineQueryOptions)).toBe(0); + expect(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: asUser(SUBMITTER) } satisfies EngineQueryOptions)).toEqual([]); // Control: the submitter's untargeted read serves both requests they filed. - expect(idsOf(await rig.engine.find(REQUEST, { context: asUser(SUBMITTER) } as any))) + expect(idsOf(await rig.engine.find(REQUEST, { context: asUser(SUBMITTER) } satisfies EngineQueryOptions))) .toEqual([rig.ids.byUserId, rig.ids.byPosition].sort()); }); @@ -161,18 +162,18 @@ describe('[#32442] the request read gate answers "waiting on me" with the approv // submitter's participant set: the one request whose column holds that id. const rows = await rig.engine.find(REQUEST, { where: { status: 'pending', pending_approvers: { $contains: APPROVER } }, context: asUser(SUBMITTER), - } as any); + } satisfies EngineQueryOptions); expect(idsOf(rows)).toEqual([rig.ids.byUserId]); // An outsider asking the same reads nothing: the participant narrowing still applies. expect(await rig.engine.find(REQUEST, { where: { pending_approvers: { $contains: APPROVER } }, context: asUser(OUTSIDER), - } as any)).toEqual([]); + } satisfies EngineQueryOptions)).toEqual([]); }); it('a decided request leaves the answer', async () => { const rig = await boot(); await rig.svc.decideNode(rig.ids.byUserId, { decision: 'approve' } as any, asUser(APPROVER)); - expect(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: asUser(APPROVER) } as any)).toEqual([]); + expect(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: asUser(APPROVER) } satisfies EngineQueryOptions)).toEqual([]); }); }); From 31a83f8b66aeff1afcd08ce332e3056b43fca1d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 15:24:18 +0000 Subject: [PATCH 10/16] test: re-ground the suites whose premise the member baseline read moved Ruling 6849636735 (1B) gives every member a data-door read on the approval request table, with the participant gate deciding rows. Two suites leaned on members having no read at all: - the action door's denied-load forward: its control now withdraws that one baseline line, so the denied load it pins still happens and the forward still has to authorize on its own; - the request definitions served by the approvals delegate: the request definition now follows the member read to every member, its rows are the participant set (the approver reads their own, a stranger none), and the action log stays delegate-only and closed on the data door. The waiting-on-me rig's aggregate and count options take their own engine option types. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- ...read-waiting-on-caller.integration.test.ts | 8 +-- ...-request-schema-party-read.dogfood.test.ts | 52 +++++++++++++++---- ...on-door-api-forward-denied-subject.test.ts | 52 +++++++++++++++---- 3 files changed, 88 insertions(+), 24 deletions(-) diff --git a/packages/plugins/plugin-approvals/src/request-read-waiting-on-caller.integration.test.ts b/packages/plugins/plugin-approvals/src/request-read-waiting-on-caller.integration.test.ts index 137afb48d35..6d44c22abdc 100644 --- a/packages/plugins/plugin-approvals/src/request-read-waiting-on-caller.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/request-read-waiting-on-caller.integration.test.ts @@ -40,7 +40,7 @@ import { SysApprovalApprover } from './sys-approval-approver.object.js'; import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; import { installDefaultOrganization } from './default-organization.testkit.js'; import { splitWaitingOnCaller } from './request-read-gate.js'; -import type { EngineQueryOptions } from '@objectstack/spec/data'; +import type { EngineAggregateOptions, EngineCountOptions, EngineQueryOptions } from '@objectstack/spec/data'; const REQUEST = 'sys_approval_request'; const OBJECT = 'exam_sheet'; @@ -139,17 +139,17 @@ describe('[#32442] the request read gate answers "waiting on me" with the approv expect(stored[0].pending_approvers).toBe(`position:${LEAD_POSITION}`); expect(idsOf(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: lead } satisfies EngineQueryOptions))).toEqual([rig.ids.byPosition]); - expect(await rig.engine.count(REQUEST, { where: WAITING_ON_ME, context: lead } satisfies EngineQueryOptions)).toBe(1); + expect(await rig.engine.count(REQUEST, { where: WAITING_ON_ME, context: lead } satisfies EngineCountOptions)).toBe(1); const groups = await rig.engine.aggregate(REQUEST, { where: WAITING_ON_ME, groupBy: ['status'], aggregations: [{ function: 'count', alias: 'n' }], context: lead, - } satisfies EngineQueryOptions) as any[]; + } satisfies EngineAggregateOptions) as any[]; expect(groups.map((g) => [g.status, Number(g.n)])).toEqual([['pending', 1]]); }); it('a member on no request gets nothing, and the submitter gets nothing waiting on them', async () => { const rig = await boot(); expect(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: asUser(OUTSIDER) } satisfies EngineQueryOptions)).toEqual([]); - expect(await rig.engine.count(REQUEST, { where: WAITING_ON_ME, context: asUser(OUTSIDER) } satisfies EngineQueryOptions)).toBe(0); + expect(await rig.engine.count(REQUEST, { where: WAITING_ON_ME, context: asUser(OUTSIDER) } satisfies EngineCountOptions)).toBe(0); expect(await rig.engine.find(REQUEST, { where: WAITING_ON_ME, context: asUser(SUBMITTER) } satisfies EngineQueryOptions)).toEqual([]); // Control: the submitter's untargeted read serves both requests they filed. expect(idsOf(await rig.engine.find(REQUEST, { context: asUser(SUBMITTER) } satisfies EngineQueryOptions))) diff --git a/packages/qa/dogfood/test/approval-request-schema-party-read.dogfood.test.ts b/packages/qa/dogfood/test/approval-request-schema-party-read.dogfood.test.ts index 9aaaf8d4502..360e9ec0ccf 100644 --- a/packages/qa/dogfood/test/approval-request-schema-party-read.dogfood.test.ts +++ b/packages/qa/dogfood/test/approval-request-schema-party-read.dogfood.test.ts @@ -27,6 +27,17 @@ // // The ablation (the declaration removed, the approver answered 404 again) is // run once by hand and cited in the PR, not kept as a file. +// +// Since #32442 (maintainer ruling 6849636735, 1B) the shipped member baseline +// names `sys_approval_request` read-only, so the request's data side is no +// longer closed to members: the object read check now admits every member, and +// under ADR-0106 the request DEFINITION follows that read to every member, +// projected by their own field security. Its rows stay the approvals request +// read gate's participant set. `sys_approval_action` is unchanged: closed on +// the data side, its definition served only through the delegate. So the +// pins below read, for the request: every member is served the definition; a +// member party to no request reads no row of it; the approver reads their own +// request's row on the data door. import { describe, it, expect } from 'vitest'; import { bootStack } from '@objectstack/verify'; @@ -192,27 +203,48 @@ describe('a party to an approval request is served the request definitions (deci expect(approverFields).not.toContain(WITHHELD); expect(Object.keys((await meta(submitter, REQUEST)).body?.item?.fields ?? {})).toContain(WITHHELD); - // ⭐ 2 — a member party to no request learns nothing new. - for (const object of [...DECLARED, SIBLING]) { + // ⭐ 2 — a member party to no request learns nothing new through the + // delegate: 404 on the action log and the undeclared sibling. The + // request definition reaches them by the member baseline's read + // (#32442, ruling 6849636735, 1B), projected by their own field + // security, with no row of it (⭐ 4). + for (const object of [ACTION, SIBLING]) { const read = await meta(stranger, object); expect(read.status, `stranger ${object}: ${read.text}`).toBe(404); } + const strangerRequest = await meta(stranger, REQUEST); + expect(strangerRequest.status, `stranger ${REQUEST}: ${strangerRequest.text}`).toBe(200); + expect(strangerRequest.body?.item?.name).toBe(REQUEST); const strangerList = await listed(stranger); - for (const object of DECLARED) expect(strangerList).not.toContain(object); + expect(strangerList).not.toContain(ACTION); + expect(strangerList).toContain(REQUEST); // ⭐ 3 — no other object moved: the approver's list is the stranger's - // plus exactly the two declared objects, and the undeclared sibling - // stays absent by name too. - expect(await listed(approver)).toEqual([...strangerList, ...DECLARED].sort()); + // plus exactly the delegate-served action log, and the undeclared + // sibling stays absent by name too. + expect(await listed(approver)).toEqual([...strangerList, ACTION].sort()); expect((await meta(approver, SIBLING)).status).toBe(404); - // ⭐ 4 — the rows are still closed to the approver on the data door. - for (const path of [`/data/${REQUEST}`, `/data/${REQUEST}/${request.id}`, `/data/${ACTION}`]) { - const res = await stack.apiAs(approver, 'GET', path); + // ⭐ 4 — the action log's rows are still closed to the approver on the + // data door; the request's rows are the participant set: the approver + // reads their own request, the stranger reads none. + { + const res = await stack.apiAs(approver, 'GET', `/data/${ACTION}`); const text = await res.text(); - expect([403, 404], `approver ${path}: ${text}`).toContain(res.status); + expect([403, 404], `approver /data/${ACTION}: ${text}`).toContain(res.status); expect(text).not.toContain(String(request.id)); } + const own = await stack.apiAs(approver, 'GET', `/data/${REQUEST}/${request.id}`); + expect(own.status, await own.clone().text()).toBe(200); + const strangerRows = await stack.apiAs(stranger, 'GET', `/data/${REQUEST}`); + const strangerRowsText = await strangerRows.text(); + expect(strangerRows.status, strangerRowsText).toBe(200); + expect(strangerRowsText).not.toContain(String(request.id)); + // By id: not found (the refusal names only the id the stranger sent). + const strangerById = await stack.apiAs(stranger, 'GET', `/data/${REQUEST}/${request.id}`); + const strangerByIdText = await strangerById.text(); + expect(strangerById.status, strangerByIdText).toBe(404); + expect(strangerByIdText).not.toContain(String(request.record_id)); } finally { await stack.stop(); } diff --git a/packages/verify/src/action-door-api-forward-denied-subject.test.ts b/packages/verify/src/action-door-api-forward-denied-subject.test.ts index 7881c283c24..406596650c7 100644 --- a/packages/verify/src/action-door-api-forward-denied-subject.test.ts +++ b/packages/verify/src/action-door-api-forward-denied-subject.test.ts @@ -8,14 +8,21 @@ * * The request page's decision actions are same-origin `type: 'api'` actions * (`approval_approve` → `POST /api/v1/approvals/requests/{id}/approve`). The - * action door loads the subject row in the CALLER's data scope first, and a - * member has no data-door read on `sys_approval_request` by design: the + * action door loads the subject row in the CALLER's data scope first; the * decision routes authorize a pending approver themselves (ADR-0066 D4). The - * door used to answer that denied load with its own `404 RECORD_NOT_FOUND` - * ahead of the forward, so no non-admin decision from the page ever reached - * the routes that would have admitted it. A denied load now forwards an api - * action whose request needs nothing from the row, and the door answers what - * the target answers. + * door used to answer a denied load with its own `404 RECORD_NOT_FOUND` ahead + * of the forward, so no decision from a caller the data door refused ever + * reached the routes that would have admitted it. A denied load now forwards + * an api action whose request needs nothing from the row, and the door answers + * what the target answers. + * + * Since #32442 (maintainer ruling 6849636735, 1B) the shipped member baseline + * `member_default` names `sys_approval_request` read-only, so out of the box a + * pending approver's load is no longer denied. The forward must still + * authorize on its own wherever the data door refuses the row (a deployment + * whose baseline does not name the request table), so this suite boots with + * that one line withdrawn from `member_default` — and only that line — to keep + * the denied-load forward under test. * * What is pinned, each against what only the real stack produces: * - the control: the approver cannot read the request row through the data @@ -39,6 +46,12 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { defineStack, defineFlow } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; + +// Paid at collection: the harness's boot loads these lazily (check:test-source-alias). +import '@objectstack/service-datasource'; +import '@objectstack/service-automation'; + import { bootStack, type VerifyStack } from './harness.js'; import { warmUpBoot } from './boot-warm-up.testkit.js'; @@ -112,6 +125,21 @@ const fixtureStack = defineStack({ flows: [flow], }); +/** + * The shipped default sets with `member_default`'s read on the request table + * withdrawn (see the header): every other grant is the platform's own. + */ +const withoutMemberRequestRead = securityDefaultPermissionSets.map((set) => { + if (set.name !== 'member_default') return set; + const { sys_approval_request: withdrawn, ...objects } = set.objects ?? {}; + // Guard the premise: if the baseline stops naming the table, this + // withdrawal is a no-op and the header's reason has moved again. + if ((withdrawn as { allowRead?: boolean } | undefined)?.allowRead !== true) { + throw new Error('member_default no longer names sys_approval_request read-only (#32442, 1B): re-read this suite\'s premise'); + } + return { ...set, objects }; +}); + type Answer = { status: number; text: string; json: any }; let stack: VerifyStack; @@ -148,7 +176,10 @@ const approveRows = async (id: string): Promise => const pendingOf = (row: any): string[] => String(row?.pending_approvers ?? '').split(',').map((s) => s.trim()).filter(Boolean); beforeAll(async () => { - stack = await bootStack(fixtureStack as never, { automation: true }); + stack = await bootStack(fixtureStack as never, { + automation: true, + security: new SecurityPlugin({ defaultPermissionSets: withoutMemberRequestRead }), + }); ql = await stack.kernel.getServiceAsync('objectql'); admin = await stack.signIn(); // The first user is the seeded dev admin, so these sign-ups are plain members. @@ -168,8 +199,9 @@ describe('a pending approver decides through the action door — the forward aut const requestId = await openRequest('INV-control'); // The slate holds the addresses the flow named. expect(pendingOf(await requestRow(requestId))).toEqual([FIRST, SECOND]); - // A member holds no object grant on the request table, so the data door - // refuses the read outright. + // With the baseline's read withdrawn (see the header), a member holds no + // object grant on the request table, so the data door refuses the read + // outright: the load the action door makes below is a denied one. const read = await call(first, 'GET', `/data/sys_approval_request/${requestId}`); expect(read.status, read.text).toBe(403); expect(read.json?.code).toBe('PERMISSION_DENIED'); From 1239e111edd1767a9eca32efb2ed0363bbf29aed Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 15:28:14 +0000 Subject: [PATCH 11/16] fix(audit): narrow the approval request's activity rows (GHSA-2985-5f64-8wgh) Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- .../src/activity-field-redaction.ts | 35 +++++++++++++ .../src/activity-side-copy-redaction.test.ts | 52 +++++++++++++++++++ .../approval-read-over-mcp.dogfood.test.ts | 23 +++++++- 3 files changed, 108 insertions(+), 2 deletions(-) create mode 100644 packages/plugins/plugin-audit/src/activity-side-copy-redaction.test.ts diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.ts index 27bd6c07451..fa7131f2e6f 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.ts @@ -514,6 +514,29 @@ export async function computeWithheldUpdateFilter( return branches.length === 1 ? branches[0] : { $or: branches }; } +/** + * [#32442] Parent columns an activity row never serves in `metadata.old` / + * `metadata.new`, by parent object: each holds another record's field values, + * served on its own row through its owner's door. The value stays at rest. + */ +export const ACTIVITY_SIDE_COPY_COLUMNS: Readonly> = Object.freeze({ + sys_approval_request: Object.freeze(['payload_json']), +}); + +/** Drop the side-copy columns of `object` from one snapshot; whether any went. */ +function dropSideCopies(object: string, snapshot: Record): boolean { + const columns = ACTIVITY_SIDE_COPY_COLUMNS[object]; + if (!columns) return false; + let dropped = false; + for (const column of columns) { + if (column in snapshot) { + delete snapshot[column]; + dropped = true; + } + } + return dropped; +} + /** * Redact the value-bearing columns of the activity rows one read is about to * hand back, as `context`. Mutates the rows in place (they are the read's own @@ -550,6 +573,18 @@ export async function redactActivityRows( stripValueBearing(row); continue; } + // [#32442] Ahead of the served-fields answer, for every reader. + if (ACTIVITY_SIDE_COPY_COLUMNS[object] && 'metadata' in row) { + // Stored as a JSON string; an already-parsed object is narrowed in place. + const inPlace = isRecord(row.metadata); + const copied = inPlace ? (row.metadata as Record) : parseMetadata(row.metadata); + let dropped = false; + for (const side of ['old', 'new'] as const) { + const snapshot = copied?.[side]; + if (isRecord(snapshot) && dropSideCopies(object, snapshot)) dropped = true; + } + if (dropped && !inPlace) row.metadata = JSON.stringify(copied); + } const answer = await servedFor(object); if (answer === undefined) continue; const servedSet = new Set(answer.map(String)); diff --git a/packages/plugins/plugin-audit/src/activity-side-copy-redaction.test.ts b/packages/plugins/plugin-audit/src/activity-side-copy-redaction.test.ts new file mode 100644 index 00000000000..ce7ba20929e --- /dev/null +++ b/packages/plugins/plugin-audit/src/activity-side-copy-redaction.test.ts @@ -0,0 +1,52 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#32442] `ACTIVITY_SIDE_COPY_COLUMNS`: the listed parent columns are not + * served in an activity row's `metadata.old` / `metadata.new`, for any reader; + * every other key is narrowed as before, and other objects are untouched. + */ + +import { describe, it, expect } from 'vitest'; +import { redactActivityRows, ACTIVITY_SIDE_COPY_COLUMNS } from './activity-field-redaction.js'; + +const SNAPSHOT = JSON.stringify({ name: 'INV-1', cost_code: 'SYNTH-SIDE-COPY-41' }); +const reader = { userId: 'u_reader', positions: [], permissions: [] }; + +const row = (object: string, metadata: unknown) => ({ id: 'act_1', object_name: object, record_id: 'r1', metadata }); +const allServed = (fields: string[]) => ({ + getReadableFields: async () => fields, + getQueryableFields: async () => fields, +}); + +describe('[#32442] activity rows do not serve the listed parent columns', () => { + it('names exactly the request snapshot column', () => { + expect(ACTIVITY_SIDE_COPY_COLUMNS).toEqual({ sys_approval_request: ['payload_json'] }); + }); + + it('drops payload_json from both sides for a reader served every request field, keeping the rest', async () => { + const r = row('sys_approval_request', JSON.stringify({ + old: { status: 'pending', payload_json: SNAPSHOT }, + new: { status: 'approved', payload_json: SNAPSHOT }, + })); + await redactActivityRows([r], allServed(['status', 'payload_json']), reader); + const served = JSON.parse(r.metadata as string); + expect(served.old).toEqual({ status: 'pending' }); + expect(served.new).toEqual({ status: 'approved' }); + expect(JSON.stringify(r)).not.toContain('SYNTH-SIDE-COPY-41'); + }); + + it('drops it for a reader the security service answers no narrowing for, and from parsed metadata', async () => { + const asText = row('sys_approval_request', JSON.stringify({ old: null, new: { status: 'pending', payload_json: SNAPSHOT } })); + const asObject = row('sys_approval_request', { old: null, new: { status: 'pending', payload_json: SNAPSHOT } }); + await redactActivityRows([asText, asObject], undefined, reader); + expect(JSON.stringify(asText)).not.toContain('SYNTH-SIDE-COPY-41'); + expect(JSON.stringify(asObject)).not.toContain('SYNTH-SIDE-COPY-41'); + expect(JSON.parse(asText.metadata as string).new).toEqual({ status: 'pending' }); + }); + + it('leaves a same-named column on another object to the parent\'s served fields', async () => { + const r = row('crm_note', JSON.stringify({ old: null, new: { payload_json: 'kept' } })); + await redactActivityRows([r], allServed(['payload_json']), reader); + expect(JSON.parse(r.metadata as string).new).toEqual({ payload_json: 'kept' }); + }); +}); diff --git a/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts index 8e82d068522..36192dabdfd 100644 --- a/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts +++ b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts @@ -31,7 +31,8 @@ // fields; the team member's returns exactly the team's; // ⭐ the same query as the submitter returns nothing; // ⭐ a member on no request reads nothing: by query, by id, by aggregate; -// ⭐ the snapshot field the approver may not read is not served to them; +// ⭐ the snapshot field the approver may not read is not served to them, +// on the request row or in the activity rows its writes left; // ⭐ the object is listed and described; no write tool opens it, and // `sys_approval_action` stays refused; // ⭐ the query tool's text names the "pending for me" filter shape; @@ -44,6 +45,7 @@ import { bootStack } from '@objectstack/verify'; import { ApprovalsServicePlugin } from '@objectstack/plugin-approvals'; import { RecordChangeTriggerPlugin } from '@objectstack/trigger-record-change'; import { MCPServerPlugin } from '@objectstack/mcp'; +import { AuditPlugin } from '@objectstack/plugin-audit'; import { defineStack, defineFlow } from '@objectstack/spec'; import { ObjectSchema, Field } from '@objectstack/spec/data'; import { PermissionSetSchema, type PermissionSet } from '@objectstack/spec/security'; @@ -253,7 +255,7 @@ describe('an approver\'s agent lists the approvals waiting on them over MCP (#32 defaultPermissionSets: [...securityDefaultPermissionSets, baselineSet, submitterSet], fallbackPermissionSet: baselineSet.name, }), - extraPlugins: [new RecordChangeTriggerPlugin(), new ApprovalsServicePlugin(), new MCPServerPlugin()], + extraPlugins: [new RecordChangeTriggerPlugin(), new ApprovalsServicePlugin(), new MCPServerPlugin(), new AuditPlugin()], }); ql = await stack.kernel.getServiceAsync('objectql'); await stack.signIn(); @@ -347,6 +349,23 @@ describe('an approver\'s agent lists the approvals waiting on them over MCP (#32 expect(own.text).toContain(STORED); }); + it('⭐ the activity rows the request\'s writes left do not serve the approver the snapshot either', async () => { + // Control: the mirror stored the snapshot, masked field and all, in the + // request's activity rows. + const stored = rowsOf(await ql.find('sys_activity', { + where: { object_name: REQUEST, record_id: first.requestId }, context: SYS.context, + })); + expect(stored.length, 'the request\'s insert left an activity row').toBeGreaterThan(0); + expect(JSON.stringify(stored)).toContain(STORED); + // The approver reads those rows on the data door (their participant read + // of the parent admits them) and is not served the snapshot. + const res = await stack.api('/data/sys_activity', { headers: { Authorization: `Bearer ${approver}` } }); + const text = await res.text(); + expect(res.status, text).toBe(200); + expect(text, 'the approver reads the request\'s activity').toContain(first.requestId); + expect(text).not.toContain(STORED); + }); + it('⭐ the object is listed and described for the approver; no write tool opens it, and sys_approval_action stays refused', async () => { const listed = await tool({ bearer: approver }, 'list_objects', {}); expect(listed.isError, listed.text).toBe(false); From dbd75155f360cb9d63084151c76654da427a1873 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 15:32:41 +0000 Subject: [PATCH 12/16] fix(approvals): no discussion thread on a request; restate what the member read changed - sys_approval_request declares enable.feeds false: its thread is the timeline and its reply the approval_comment action; - the object's schema-read note, the no-middleware warning, the action door's denied-load note and the approvals docs say what ruling 6849636735 (1B) made true; - the HTTP bridge answers every aiReadExposed ask of one request from one merged read; - the query tool names the approvals filter as an example. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- ...cp-read-tools-ai-readable-system-object.md | 3 ++ content/docs/automation/approvals.mdx | 30 +++++++++++-------- packages/mcp/src/mcp-http-tools.ts | 2 +- .../plugin-approvals/src/approvals-plugin.ts | 3 +- .../src/sys-approval-request.object.test.ts | 5 ++++ .../src/sys-approval-request.object.ts | 24 ++++++++++----- .../approval-read-over-mcp.dogfood.test.ts | 9 +++--- packages/runtime/src/action-execution.ts | 8 +++-- packages/runtime/src/domains/mcp.ts | 14 ++++++++- .../src/mcp-system-object-ai-read.test.ts | 22 ++++++++++++-- 10 files changed, 87 insertions(+), 33 deletions(-) diff --git a/.changeset/mcp-read-tools-ai-readable-system-object.md b/.changeset/mcp-read-tools-ai-readable-system-object.md index 6d5f284b930..59483916e95 100644 --- a/.changeset/mcp-read-tools-ai-readable-system-object.md +++ b/.changeset/mcp-read-tools-ai-readable-system-object.md @@ -3,6 +3,7 @@ '@objectstack/runtime': patch '@objectstack/plugin-approvals': patch '@objectstack/plugin-security': patch +'@objectstack/plugin-audit': patch --- Clause-②: yes (widening) @@ -11,3 +12,5 @@ Metadata-protocol: none The MCP read tools (`list_objects`, `describe_object`, `query_records`, `get_record`, `aggregate_records`) now admit a system object whose author declared `enable.aiReadable: true`, asked through a new optional bridge member `aiReadExposed` that both bridges answer with `isAiReadExposed`. Every gate after admission is unchanged (the caller's permissions, row-level security, the object's own read gates, field masking), and every write tool still refuses every `sys_*` object. `sys_approval_request` declares the key; `query_records` names the "waiting on you" filter shape. The member baseline `member_default` now names `sys_approval_request` read-only, so every signed-in member holds a data-door read on it; which rows is still the approvals request read gate (the submitter, a current approver, a past actor), and no write opens. That gate now answers a conjunctive `pending_approvers` `$contains` of the caller's own id with the approvals service's acting-address fold, so the console's My Pending view and an agent's "waiting on me" query find a slot addressed by email or an unstaffed position, not only one holding the user id. A `pending_approvers` predicate naming another id, or under `$or`, is read as written. + +`sys_approval_request` now declares `enable.feeds: false`: a request's thread is its timeline, and its reply is the `approval_comment` action. `@objectstack/plugin-audit`: GHSA-2985-5f64-8wgh. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 685472fcae4..b12c83263e8 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -590,16 +590,22 @@ The same rule governs a decision's files: an attachment is exactly as readable as the decision it hangs off, never more (`sys_approval_action` delegates that question back to this service via `fileAccessDelegate`). -So do the two objects' definitions. The metadata API answers an object the -caller may not read as absent, and `sys_approval_request` and -`sys_approval_action` are closed to ordinary members on the data side, yet the -request page renders from both definitions. Both declare -`schemaReadDelegate: 'approvals'`, so `GET /api/v1/meta/object/sys_approval_request` -(and `…/sys_approval_action`, and the object list) serves them to a caller who -can see at least one request by the rule above, projected by that caller's -field-level security. A member who can see none is answered `404`, and a -member the data door refuses still reaches the rows only through -`/api/v1/approvals/*`. +Every signed-in member holds a read on `sys_approval_request` through the +member baseline (`member_default`), and the data door serves them exactly the +requests the rule above lets them see, with the same snapshot redaction. So +`GET /api/v1/data/sys_approval_request` (and an MCP agent's `query_records`) +lists a member's own requests, and a `pending_approvers` filter on +`{current_user_id}` finds the requests waiting on them, including a step +addressed to their email or position. No write opens on it. + +The two objects' definitions follow. The metadata API answers an object the +caller may not read as absent; with the baseline read, every member is served +the `sys_approval_request` definition, projected by their field-level +security. `sys_approval_action` stays closed to ordinary members on the data +side, and both objects declare `schemaReadDelegate: 'approvals'`, so +`GET /api/v1/meta/object/sys_approval_action` (and the object list) serves it +to a caller who can see at least one request by the rule above. A member who +can see none is answered `404` for it. @@ -857,8 +863,8 @@ progress, the approvers it is waiting on, the merged decision timeline and a rem button for the submitter. Every viewer who can read the record sees it, not only approvers. A request opens on its record page through the approvals routes rather than the data API, so an approver who is not an administrator sees the whole page, -decision actions included, although the data API stays closed to them on the -approval objects. +decision actions included, even where the data API does not serve them the +request row. Each action's visibility is gated by a **server-computed per-viewer block** the service attaches to every request it returns: diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index b30d24beaca..d12208d2dca 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -2501,7 +2501,7 @@ export function registerObjectTools( // [#32442] The console's My Pending list, filter for filter: the // participant read alone also serves requests the caller submitted // or already decided, so an agent must not guess "mine" from it. - 'The approvals waiting on you (where the app has approvals): objectName "sys_approval_request", where ' + + 'For example, where the app runs approvals, the ones waiting on you: objectName "sys_approval_request", where ' + '{"status":"pending","pending_approvers":{"$contains":"{current_user_id}"}}; decide one with run_action.', inputSchema: strictToolInput( { diff --git a/packages/plugins/plugin-approvals/src/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index 8dcfd8d729b..6b0a427c2fc 100644 --- a/packages/plugins/plugin-approvals/src/approvals-plugin.ts +++ b/packages/plugins/plugin-approvals/src/approvals-plugin.ts @@ -406,7 +406,8 @@ export class ApprovalsServicePlugin implements Plugin { ctx.logger.warn( 'ApprovalsServicePlugin: the ObjectQL engine has no middleware seam — reads of sys_approval_request, ' + 'sys_approval_action and sys_approval_approver through the generic data door are NOT narrowed to the ' - + 'approval requests the caller may see. Grant no read on those objects to non-administrators on this stack.', + + 'approval requests the caller may see. Grant no read on those objects to non-administrators on this stack, ' + + 'and withdraw the member baseline\'s read on sys_approval_request (member_default, #32442).', ); } diff --git a/packages/plugins/plugin-approvals/src/sys-approval-request.object.test.ts b/packages/plugins/plugin-approvals/src/sys-approval-request.object.test.ts index 28ccddd65b9..9d6d4d09e98 100644 --- a/packages/plugins/plugin-approvals/src/sys-approval-request.object.test.ts +++ b/packages/plugins/plugin-approvals/src/sys-approval-request.object.test.ts @@ -294,4 +294,9 @@ describe('[#32442, ruling A] the AI read declaration', () => { expect(SysApprovalRequest.enable?.apiMethods).toEqual(['get', 'list']); expect(isAiReadExposed(SysApprovalAction)).toBe(false); }); + + it('[#32442] declares no generic discussion thread: the reply is approval_comment', () => { + expect(SysApprovalRequest.enable?.feeds).toBe(false); + expect((SysApprovalRequest.actions ?? []).map((a: any) => a.name)).toContain('approval_comment'); + }); }); diff --git a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts index 4eb0c60b07f..428552d398e 100644 --- a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts +++ b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts @@ -45,14 +45,16 @@ export const SysApprovalRequest = ObjectSchema.create({ isSystem: true, managedBy: 'engine-owned', description: 'Live approval instance tracked per submission', - // [decision 6840464379] The rows reach a member only through the approvals - // door (`/api/v1/approvals/*`); the data side is closed to ordinary members on - // purpose. The metadata API answers an object the caller may not read as - // absent (ADR-0106, ruling record 6787890900), yet the request page that door - // links to needs this definition to render, so the approvals service answers - // who else is served it: the callers its door serves a request to - // (`ApprovalService.authorizeSchemaRead`). Field security still projects it, - // and the rows stay closed. + // [decision 6840464379, as amended by ruling 6849636735 (1B, #32442)] The + // member baseline (`member_default`) grants every member a read on this + // object, and the request read gate (`request-read-gate.ts`) narrows the rows + // to the requests the approvals door would serve that member. The metadata + // API answers an object the caller may not read as absent (ADR-0106, ruling + // record 6787890900); with the baseline read, every member is served this + // definition, projected by their field security. The delegate stays: it + // answers a caller whose permission sets do not carry that read (a deployment + // that withdraws it) with the callers its door serves a request to + // (`ApprovalService.authorizeSchemaRead`). schemaReadDelegate: 'approvals', // [ADR-0079, ADR-0085] The record title is the flow's label, `process_label`: // a STORED column, so every door that serves the row serves its title. The @@ -914,5 +916,11 @@ export const SysApprovalRequest = ObjectSchema.create({ // declare their own `ai.exposed`. `sys_approval_action` declares nothing: // an approver lists and decides without reading the decision trail. aiReadable: true, + // [#32442] No generic discussion thread: a request's thread is its + // timeline, and its reply is the `approval_comment` action (stored as a + // `sys_approval_action` row), as the request page declares. With the + // member read (1B), `feeds` left on would let every party read and post + // `sys_comment` rows on a request beside that trail. + feeds: false, }, }); diff --git a/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts index 36192dabdfd..af85e29e9ad 100644 --- a/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts +++ b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts @@ -32,7 +32,7 @@ // ⭐ the same query as the submitter returns nothing; // ⭐ a member on no request reads nothing: by query, by id, by aggregate; // ⭐ the snapshot field the approver may not read is not served to them, -// on the request row or in the activity rows its writes left; +// on the request row or in its activity rows; // ⭐ the object is listed and described; no write tool opens it, and // `sys_approval_action` stays refused; // ⭐ the query tool's text names the "pending for me" filter shape; @@ -349,16 +349,15 @@ describe('an approver\'s agent lists the approvals waiting on them over MCP (#32 expect(own.text).toContain(STORED); }); - it('⭐ the activity rows the request\'s writes left do not serve the approver the snapshot either', async () => { - // Control: the mirror stored the snapshot, masked field and all, in the - // request's activity rows. + it('⭐ the request\'s activity rows serve the approver no value they may not read', async () => { + // Control: the value is at rest. const stored = rowsOf(await ql.find('sys_activity', { where: { object_name: REQUEST, record_id: first.requestId }, context: SYS.context, })); expect(stored.length, 'the request\'s insert left an activity row').toBeGreaterThan(0); expect(JSON.stringify(stored)).toContain(STORED); // The approver reads those rows on the data door (their participant read - // of the parent admits them) and is not served the snapshot. + // of the parent admits them). const res = await stack.api('/data/sys_activity', { headers: { Authorization: `Bearer ${approver}` } }); const text = await res.text(); expect(res.status, text).toBe(200); diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index 592addb3257..23084cf86ac 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -4021,9 +4021,11 @@ export async function refuseUngrantedDeclarativeUpdate( * (ADR-0066 D4) — a request the caller could send to that target directly. * Refusing it here put the generic data door's verdict in front of a door * that answers the question itself, and wrongly: approval decisions are - * authorized by the approvals routes (a pending approver may decide), while a - * member has no data-door read on `sys_approval_request` by design. So a - * denied load no longer answers its own 404 ahead of the forward; the door + * authorized by the approvals routes (a pending approver may decide), while + * the data door may refuse the same caller the request row (a deployment whose + * member baseline does not name `sys_approval_request`; the shipped one does + * since #32442, ruling 6849636735). So a denied load no longer answers its own + * 404 ahead of the forward; the door * forwards and relays what the target answers. A load that names nothing and * a load that was filtered are the same answer to the target too, so this * opens no existence oracle the target does not already answer. diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index 27460ace073..c45e5045d39 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -750,6 +750,9 @@ export function buildMcpBridge( * judges against: from the listing {@link readMergedObjects} reads, or the * metadata service's by-name read on a host with none. */ + /** {@link readMergedObjects}, read once per bridge for the `aiReadExposed` asks. */ + let mergedForAiRead: Promise | undefined; + const readServedObject = async (name: string): Promise => { const merged = await readMergedObjects(); return merged !== undefined @@ -937,7 +940,16 @@ export function buildMcpBridge( * ran (permissions, RLS, the object's own read middleware, field * masking), so this admits the object and nothing else. */ - aiReadExposed: async (name: string): Promise => isAiReadExposed(await readServedObject(name)), + aiReadExposed: async (name: string): Promise => { + // `list_objects` asks once per listed `sys_*` object: one merged + // read serves every ask this bridge (one request) makes. + mergedForAiRead ??= readMergedObjects(); + const merged = await mergedForAiRead; + const def = merged !== undefined + ? merged.find((o: any) => o?.name === name) + : await ((await getMeta()) as any)?.getObject?.(name); + return isAiReadExposed(def); + }, describeObject: async (name: string) => { const def: any = await readObjectForCaller(name); if (!def) return null; diff --git a/packages/runtime/src/mcp-system-object-ai-read.test.ts b/packages/runtime/src/mcp-system-object-ai-read.test.ts index cb7ac40a1ec..15b5a21b66f 100644 --- a/packages/runtime/src/mcp-system-object-ai-read.test.ts +++ b/packages/runtime/src/mcp-system-object-ai-read.test.ts @@ -32,7 +32,7 @@ import { HttpDispatcher } from './http-dispatcher.js'; const [FAMILY] = [...STORED_METADATA_BODY_OBJECTS]; -function bridgeOver(objects: any[]) { +function bridgeOver(objects: any[], protocol: any = null) { const byName = (n: string) => objects.find((o) => o.name === n); const metadata: any = { load: vi.fn(async () => null), @@ -43,7 +43,8 @@ function bridgeOver(objects: any[]) { const ql: any = { getSchema: byName, registry: { getObject: byName, getItem: () => undefined } }; const kernel: any = { context: { - getService: (n: string) => (n === 'objectql' || n === 'data' ? ql : n === 'metadata' ? metadata : null), + getService: (n: string) => + (n === 'objectql' || n === 'data' ? ql : n === 'metadata' ? metadata : n === 'protocol' ? protocol : null), }, }; const ctx: any = { @@ -84,3 +85,20 @@ describe('[#32442] the HTTP MCP bridge attests enable.aiReadable with isAiReadEx expect(await bridge.aiReadExposed('sys_probe_missing')).toBe(false); }); }); + +describe('[#32442] the bridge reads the merged listing once for every aiReadExposed ask it answers', () => { + it('answers several names from one merged read', async () => { + const getMetaItems = vi.fn(async () => ({ + type: 'object', + items: [ + { name: 'sys_probe_request', fields: {}, enable: { aiReadable: true } }, + { name: 'sys_probe_silent', fields: {} }, + ], + })); + const bridge = bridgeOver([], { getMetaItems }); + expect(await bridge.aiReadExposed('sys_probe_request')).toBe(true); + expect(await bridge.aiReadExposed('sys_probe_silent')).toBe(false); + expect(await bridge.aiReadExposed('sys_probe_missing')).toBe(false); + expect(getMetaItems).toHaveBeenCalledTimes(1); + }); +}); From 8e4da801d2578d70f624ca6d8b4c2a63bb9615c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 16:29:57 +0000 Subject: [PATCH 13/16] fix(approvals): keep the tracker id out of the warning text Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- packages/plugins/plugin-approvals/src/approvals-plugin.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/plugins/plugin-approvals/src/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index 6b0a427c2fc..18c28579f47 100644 --- a/packages/plugins/plugin-approvals/src/approvals-plugin.ts +++ b/packages/plugins/plugin-approvals/src/approvals-plugin.ts @@ -407,7 +407,7 @@ export class ApprovalsServicePlugin implements Plugin { 'ApprovalsServicePlugin: the ObjectQL engine has no middleware seam — reads of sys_approval_request, ' + 'sys_approval_action and sys_approval_approver through the generic data door are NOT narrowed to the ' + 'approval requests the caller may see. Grant no read on those objects to non-administrators on this stack, ' - + 'and withdraw the member baseline\'s read on sys_approval_request (member_default, #32442).', + + 'and withdraw the member baseline\'s read on sys_approval_request (member_default).', ); } From 1322726cbe9ced874accf6eeaeb300c3277cb282 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 17:07:27 +0000 Subject: [PATCH 14/16] fix(audit): harden the activity and audit copies of approval requests (GHSA-2985-5f64-8wgh) The writer omits the listed columns from new copies, a rewrite module handles copies at rest (its command is a follow-up), and until then the read seams and the query guards cover them. Revert the request's feeds declaration. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- ...cp-read-tools-ai-readable-system-object.md | 2 +- .../src/sys-approval-request.object.test.ts | 5 - .../src/sys-approval-request.object.ts | 6 - .../src/activity-field-redaction.ts | 29 +-- .../src/activity-side-copy-redaction.test.ts | 8 +- .../src/audit-log-field-redaction.ts | 19 ++ .../plugins/plugin-audit/src/audit-writers.ts | 5 + packages/plugins/plugin-audit/src/index.ts | 18 ++ .../src/parent-field-query-guard.ts | 36 ++++ .../src/side-copy-columns.test.ts | 95 ++++++++++ .../plugin-audit/src/side-copy-columns.ts | 49 +++++ .../plugin-audit/src/side-copy-migration.ts | 175 ++++++++++++++++++ .../approval-read-over-mcp.dogfood.test.ts | 59 ++++-- 13 files changed, 456 insertions(+), 50 deletions(-) create mode 100644 packages/plugins/plugin-audit/src/side-copy-columns.test.ts create mode 100644 packages/plugins/plugin-audit/src/side-copy-columns.ts create mode 100644 packages/plugins/plugin-audit/src/side-copy-migration.ts diff --git a/.changeset/mcp-read-tools-ai-readable-system-object.md b/.changeset/mcp-read-tools-ai-readable-system-object.md index 59483916e95..a95a1ef10d1 100644 --- a/.changeset/mcp-read-tools-ai-readable-system-object.md +++ b/.changeset/mcp-read-tools-ai-readable-system-object.md @@ -13,4 +13,4 @@ The MCP read tools (`list_objects`, `describe_object`, `query_records`, `get_rec The member baseline `member_default` now names `sys_approval_request` read-only, so every signed-in member holds a data-door read on it; which rows is still the approvals request read gate (the submitter, a current approver, a past actor), and no write opens. That gate now answers a conjunctive `pending_approvers` `$contains` of the caller's own id with the approvals service's acting-address fold, so the console's My Pending view and an agent's "waiting on me" query find a slot addressed by email or an unstaffed position, not only one holding the user id. A `pending_approvers` predicate naming another id, or under `$or`, is read as written. -`sys_approval_request` now declares `enable.feeds: false`: a request's thread is its timeline, and its reply is the `approval_comment` action. `@objectstack/plugin-audit`: GHSA-2985-5f64-8wgh. +`@objectstack/plugin-audit`: the activity and audit copies of an approval request no longer carry its subject snapshot, with a rewrite for copies at rest (`migrateSideCopies`) (GHSA-2985-5f64-8wgh). diff --git a/packages/plugins/plugin-approvals/src/sys-approval-request.object.test.ts b/packages/plugins/plugin-approvals/src/sys-approval-request.object.test.ts index 9d6d4d09e98..28ccddd65b9 100644 --- a/packages/plugins/plugin-approvals/src/sys-approval-request.object.test.ts +++ b/packages/plugins/plugin-approvals/src/sys-approval-request.object.test.ts @@ -294,9 +294,4 @@ describe('[#32442, ruling A] the AI read declaration', () => { expect(SysApprovalRequest.enable?.apiMethods).toEqual(['get', 'list']); expect(isAiReadExposed(SysApprovalAction)).toBe(false); }); - - it('[#32442] declares no generic discussion thread: the reply is approval_comment', () => { - expect(SysApprovalRequest.enable?.feeds).toBe(false); - expect((SysApprovalRequest.actions ?? []).map((a: any) => a.name)).toContain('approval_comment'); - }); }); diff --git a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts index 428552d398e..a6b0d37e768 100644 --- a/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts +++ b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts @@ -916,11 +916,5 @@ export const SysApprovalRequest = ObjectSchema.create({ // declare their own `ai.exposed`. `sys_approval_action` declares nothing: // an approver lists and decides without reading the decision trail. aiReadable: true, - // [#32442] No generic discussion thread: a request's thread is its - // timeline, and its reply is the `approval_comment` action (stored as a - // `sys_approval_action` row), as the request page declares. With the - // member read (1B), `feeds` left on would let every party read and post - // `sys_comment` rows on a request beside that trail. - feeds: false, }, }); diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.ts index fa7131f2e6f..1af49b8b0c2 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.ts @@ -187,6 +187,7 @@ import { * public names are unchanged. */ export { resolveServedFields } from './served-fields.js'; +import { omitSideCopyFromCopy, sideCopyColumnsOf } from './side-copy-columns.js'; const ACTIVITY_OBJECT = 'sys_activity'; const SYSTEM_CTX = { isSystem: true } as const; @@ -514,28 +515,8 @@ export async function computeWithheldUpdateFilter( return branches.length === 1 ? branches[0] : { $or: branches }; } -/** - * [#32442] Parent columns an activity row never serves in `metadata.old` / - * `metadata.new`, by parent object: each holds another record's field values, - * served on its own row through its owner's door. The value stays at rest. - */ -export const ACTIVITY_SIDE_COPY_COLUMNS: Readonly> = Object.freeze({ - sys_approval_request: Object.freeze(['payload_json']), -}); - -/** Drop the side-copy columns of `object` from one snapshot; whether any went. */ -function dropSideCopies(object: string, snapshot: Record): boolean { - const columns = ACTIVITY_SIDE_COPY_COLUMNS[object]; - if (!columns) return false; - let dropped = false; - for (const column of columns) { - if (column in snapshot) { - delete snapshot[column]; - dropped = true; - } - } - return dropped; -} +/** [#32442] The listed columns (`side-copy-columns.ts`), re-exported for the activity pins. */ +export { SIDE_COPY_COLUMNS as ACTIVITY_SIDE_COPY_COLUMNS } from './side-copy-columns.js'; /** * Redact the value-bearing columns of the activity rows one read is about to @@ -574,14 +555,14 @@ export async function redactActivityRows( continue; } // [#32442] Ahead of the served-fields answer, for every reader. - if (ACTIVITY_SIDE_COPY_COLUMNS[object] && 'metadata' in row) { + if (sideCopyColumnsOf(object).length > 0 && 'metadata' in row) { // Stored as a JSON string; an already-parsed object is narrowed in place. const inPlace = isRecord(row.metadata); const copied = inPlace ? (row.metadata as Record) : parseMetadata(row.metadata); let dropped = false; for (const side of ['old', 'new'] as const) { const snapshot = copied?.[side]; - if (isRecord(snapshot) && dropSideCopies(object, snapshot)) dropped = true; + if (isRecord(snapshot) && omitSideCopyFromCopy(object, snapshot)) dropped = true; } if (dropped && !inPlace) row.metadata = JSON.stringify(copied); } diff --git a/packages/plugins/plugin-audit/src/activity-side-copy-redaction.test.ts b/packages/plugins/plugin-audit/src/activity-side-copy-redaction.test.ts index ce7ba20929e..98638d36121 100644 --- a/packages/plugins/plugin-audit/src/activity-side-copy-redaction.test.ts +++ b/packages/plugins/plugin-audit/src/activity-side-copy-redaction.test.ts @@ -20,7 +20,7 @@ const allServed = (fields: string[]) => ({ describe('[#32442] activity rows do not serve the listed parent columns', () => { it('names exactly the request snapshot column', () => { - expect(ACTIVITY_SIDE_COPY_COLUMNS).toEqual({ sys_approval_request: ['payload_json'] }); + expect([...ACTIVITY_SIDE_COPY_COLUMNS.entries()]).toEqual([['sys_approval_request', ['payload_json']]]); }); it('drops payload_json from both sides for a reader served every request field, keeping the rest', async () => { @@ -49,4 +49,10 @@ describe('[#32442] activity rows do not serve the listed parent columns', () => await redactActivityRows([r], allServed(['payload_json']), reader); expect(JSON.parse(r.metadata as string).new).toEqual({ payload_json: 'kept' }); }); + + it('reads an object_name that is an inherited property name as unlisted, without throwing', async () => { + const r = row('constructor', JSON.stringify({ old: null, new: { payload_json: 'kept' } })); + await redactActivityRows([r], allServed(['payload_json']), reader); + expect(JSON.parse(r.metadata as string).new).toEqual({ payload_json: 'kept' }); + }); }); diff --git a/packages/plugins/plugin-audit/src/audit-log-field-redaction.ts b/packages/plugins/plugin-audit/src/audit-log-field-redaction.ts index a55e36d3f39..8a2ea1ce945 100644 --- a/packages/plugins/plugin-audit/src/audit-log-field-redaction.ts +++ b/packages/plugins/plugin-audit/src/audit-log-field-redaction.ts @@ -88,6 +88,7 @@ * the activity stream's open predicate question, not this one's. */ +import { omitSideCopyFromCopy, sideCopyColumnsOf } from './side-copy-columns.js'; import { dropUnservedKeys, ensureJudgedColumnsProjected, @@ -189,6 +190,24 @@ export async function redactAuditLogRows( stripSnapshots(row); continue; } + // [#32442] Ahead of the served-fields answer, for every reader: the listed + // columns of a copy (`side-copy-columns.ts`). + if (sideCopyColumnsOf(object).length > 0) { + for (const col of SNAPSHOT_COLUMNS) { + const raw = row[col]; + if (raw === undefined || raw === null) continue; + const inPlace = isRecord(raw); + let snapshot: unknown = raw; + if (!inPlace) { + try { + snapshot = typeof raw === 'string' ? JSON.parse(raw) : undefined; + } catch { + snapshot = undefined; + } + } + if (isRecord(snapshot) && omitSideCopyFromCopy(object, snapshot) && !inPlace) row[col] = JSON.stringify(snapshot); + } + } const answer = await servedFor(object); if (answer === undefined) continue; const served = new Set(answer.map(String)); diff --git a/packages/plugins/plugin-audit/src/audit-writers.ts b/packages/plugins/plugin-audit/src/audit-writers.ts index 979ec3c9723..c8faf4a68e9 100644 --- a/packages/plugins/plugin-audit/src/audit-writers.ts +++ b/packages/plugins/plugin-audit/src/audit-writers.ts @@ -22,6 +22,7 @@ import { SECRET_MASK, collectInternalReadFields, collectMaskedReadFields } from import { maskMailLogBodyCopy } from './mail-log-body-mask.js'; // The key-material columns no copy of a row carries (`key-material-copy.ts`). import { keyMaterialColumnsOf, omitKeyMaterialFromCopy } from './key-material-copy.js'; +import { omitSideCopyFromCopy } from './side-copy-columns.js'; // [#7230] ADR-0079's record display-name contract, imported rather than // re-derived. `resolveDisplayField` IS the definition of "which field is this // object's human title" (`nameField` → deprecated `displayNameField` alias → @@ -1934,6 +1935,10 @@ export function installAuditWriters( // copy records which row changed and how, never the material. One helper, // the one the at-rest rewrite of older copies applies. omitKeyMaterialFromCopy(objectName, out); + // [#32442] A column holding another record's field values + // (`side-copy-columns.ts`) is OMITTED on every side, by the list the + // at-rest rewrite of older copies applies. + omitSideCopyFromCopy(objectName, out); // [#21120] A stored metadata BODY (`sys_metadata` / `sys_metadata_history`) // is not a top-level secret field, so the mask above never touches it. The // audit copy is a credential read exit exactly like `/meta`, so the body is diff --git a/packages/plugins/plugin-audit/src/index.ts b/packages/plugins/plugin-audit/src/index.ts index e5aeb28537c..b362d4f5430 100644 --- a/packages/plugins/plugin-audit/src/index.ts +++ b/packages/plugins/plugin-audit/src/index.ts @@ -174,6 +174,24 @@ export type { KeyMaterialMigrationOptions, KeyMaterialMigrationReport, } from './key-material-copy-migration.js'; +// [#32442] The columns no ledger copy carries because they hold another +// record's field values, the one helper the writer and the at-rest rewrite +// apply, and that rewrite's planners and runners. +export { SIDE_COPY_COLUMNS, SIDE_COPY_OBJECTS, sideCopyColumnsOf, omitSideCopyFromCopy } from './side-copy-columns.js'; +export { + migrateSideCopies, + migrateArchivedSideCopies, + planSideCopyAuditRowPatch, + planSideCopyActivityRowPatch, + SIDE_COPY_TABLES, +} from './side-copy-migration.js'; +export type { + SideCopyArchiveDriver, + SideCopyTable, + SideCopyMigrationEngine, + SideCopyMigrationOptions, + SideCopyMigrationReport, +} from './side-copy-migration.js'; // [ADR-0139 E6] The stored-row backfill of `sys_activity`'s two writer-stamped // read-rule columns, and the one planner it, the CRUD mirror and the // before-insert hook stamp by. The CLI command diff --git a/packages/plugins/plugin-audit/src/parent-field-query-guard.ts b/packages/plugins/plugin-audit/src/parent-field-query-guard.ts index 4094787cdbb..868725f2d5e 100644 --- a/packages/plugins/plugin-audit/src/parent-field-query-guard.ts +++ b/packages/plugins/plugin-audit/src/parent-field-query-guard.ts @@ -109,6 +109,7 @@ * read gate and the redaction. */ +import { SIDE_COPY_OBJECTS, sideCopyColumnsOf } from './side-copy-columns.js'; import { FieldReferenceSchema } from '@objectstack/spec/data'; import { ACTIVITY_STAMPED_COLUMNS } from './activity-changed-fields.js'; import { resolveServedFields, type FieldRedactionLogger, type FieldVisibilitySource } from './served-fields.js'; @@ -156,6 +157,39 @@ export const AUDIT_LOG_QUERY_GUARD: ParentFieldQueryGuard = Object.freeze({ remedy: remedy('A ledger snapshot column'), }); +/** + * [#32442] Per guarded object: the columns that hold a COPY of a parent row, + * the place a listed side-copy column (`side-copy-columns.ts`) sits in a row + * written before the writer omitted it. + */ +export const SIDE_COPY_CARRIER_COLUMNS: ReadonlyMap = new Map([ + ['sys_activity', Object.freeze(['metadata'])], + ['sys_audit_log', Object.freeze(['old_value', 'new_value'])], +]); + +/** + * [#32442] The carrier columns `named` holds when the query can reach a + * parent `side-copy-columns.ts` lists — the ONE parent it pins, or every + * parent when it pins none — or `null` when it names none or reaches none. + * Refused for every non-system reader, whatever their served fields, until + * the at-rest rewrite has removed the column from every copy. + */ +export function namedSideCopyCarriers( + guarded: string, + parent: string | null, + named: NamedValueBearingColumns, +): NamedValueBearingColumns | null { + const carriers = SIDE_COPY_CARRIER_COLUMNS.get(guarded) ?? []; + if (carriers.length === 0) return null; + const reaches = parent === null ? SIDE_COPY_OBJECTS.length > 0 : sideCopyColumnsOf(parent).length > 0; + if (!reaches) return null; + const carried = { + aggregate: named.aggregate.filter((c) => carriers.includes(c)), + predicate: named.predicate.filter((c) => carriers.includes(c)), + }; + return carried.aggregate.length > 0 || carried.predicate.length > 0 ? carried : null; +} + /** The value-bearing columns a query names, by the role it names them in. */ export interface NamedValueBearingColumns { /** Grouped by, or aggregated over (an aggregation's own field). */ @@ -386,6 +420,8 @@ function installParentFieldQueryGuard( const security = getSecurity(); if (!security) return next(); const parent = pinnedParentObject(ctx.ast.where, guard.object); + const carried = namedSideCopyCarriers(guard.object, parent, named); + if (carried) throw parentFieldQueryRefusal(guard, ctx.operation, carried); let refuse = true; try { if (parent !== null) { diff --git a/packages/plugins/plugin-audit/src/side-copy-columns.test.ts b/packages/plugins/plugin-audit/src/side-copy-columns.test.ts new file mode 100644 index 00000000000..63f7c3e481a --- /dev/null +++ b/packages/plugins/plugin-audit/src/side-copy-columns.test.ts @@ -0,0 +1,95 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#32442] `side-copy-columns.ts`: the listed columns are omitted from every + * ledger copy, by the writer and by the at-rest rewrite's two planners. + */ + +import { describe, it, expect } from 'vitest'; +import { SIDE_COPY_COLUMNS, SIDE_COPY_OBJECTS, omitSideCopyFromCopy, sideCopyColumnsOf } from './side-copy-columns.js'; +import { planSideCopyActivityRowPatch, planSideCopyAuditRowPatch } from './side-copy-migration.js'; +import { namedSideCopyCarriers } from './parent-field-query-guard.js'; +import { redactAuditLogRows } from './audit-log-field-redaction.js'; + +const REQUEST = 'sys_approval_request'; +const SNAPSHOT = JSON.stringify({ name: 'INV-1', cost_code: 'SYNTH-SIDE-COPY-58' }); + +describe('[#32442] the side-copy list', () => { + it('names exactly the request snapshot column, and reads an inherited name as unlisted', () => { + expect([...SIDE_COPY_COLUMNS.entries()]).toEqual([[REQUEST, ['payload_json']]]); + expect(SIDE_COPY_OBJECTS).toEqual([REQUEST]); + for (const name of ['constructor', '__proto__', 'toString', 'crm_note', 42, undefined]) { + expect(sideCopyColumnsOf(name)).toEqual([]); + } + }); + + it('omits the listed column in place, once', () => { + const copy: Record = { status: 'pending', payload_json: SNAPSHOT }; + expect(omitSideCopyFromCopy(REQUEST, copy)).toBe(true); + expect(copy).toEqual({ status: 'pending' }); + expect(omitSideCopyFromCopy(REQUEST, copy)).toBe(false); + const other: Record = { payload_json: 'kept' }; + expect(omitSideCopyFromCopy('crm_note', other)).toBe(false); + expect(other).toEqual({ payload_json: 'kept' }); + }); +}); + +describe('[#32442] the at-rest rewrite plans', () => { + it('rewrites both audit snapshots of a listed object and nothing else, idempotently', () => { + const row = { + object_name: REQUEST, + old_value: JSON.stringify({ status: 'pending', payload_json: SNAPSHOT }), + new_value: JSON.stringify({ status: 'approved', payload_json: SNAPSHOT }), + }; + const patch = planSideCopyAuditRowPatch(row)!; + expect(JSON.parse(patch.old_value as string)).toEqual({ status: 'pending' }); + expect(JSON.parse(patch.new_value as string)).toEqual({ status: 'approved' }); + expect(planSideCopyAuditRowPatch({ ...row, ...patch })).toBeNull(); + expect(planSideCopyAuditRowPatch({ ...row, object_name: 'crm_note' })).toBeNull(); + }); + + it('rewrites both halves of an activity pair, keeping every other key', () => { + const row = { + object_name: REQUEST, + metadata: JSON.stringify({ old: null, new: { status: 'pending', payload_json: SNAPSHOT }, kind: 'created' }), + }; + const patch = planSideCopyActivityRowPatch(row)!; + expect(JSON.parse(patch.metadata as string)).toEqual({ old: null, new: { status: 'pending' }, kind: 'created' }); + expect(planSideCopyActivityRowPatch({ ...row, ...patch })).toBeNull(); + }); +}); + +describe('[#32442] the query guards refuse a carrying column whose reach includes a listed parent', () => { + const named = (predicate: string[], aggregate: string[] = []) => ({ predicate, aggregate }); + + it('refuses metadata on the activity stream pinned to the request, or pinned to nothing', () => { + expect(namedSideCopyCarriers('sys_activity', REQUEST, named(['metadata']))).toEqual(named(['metadata'])); + expect(namedSideCopyCarriers('sys_activity', null, named([], ['metadata']))).toEqual(named([], ['metadata'])); + expect(namedSideCopyCarriers('sys_audit_log', REQUEST, named(['new_value', 'object_name']))) + .toEqual(named(['new_value'])); + }); + + it('admits another parent, and a column that carries no copy', () => { + expect(namedSideCopyCarriers('sys_activity', 'crm_note', named(['metadata']))).toBeNull(); + expect(namedSideCopyCarriers('sys_activity', REQUEST, named(['summary']))).toBeNull(); + expect(namedSideCopyCarriers('sys_comment', REQUEST, named(['metadata']))).toBeNull(); + }); +}); + +describe('[#32442] the ledger redaction drops the listed column from a copy at rest', () => { + it('for a reader served every request field, and for one with no security answer', async () => { + const all = { getReadableFields: async () => ['status', 'payload_json'], getQueryableFields: async () => ['status', 'payload_json'] }; + for (const security of [all, undefined]) { + const row: Record = { + action: 'update', + object_name: REQUEST, + old_value: JSON.stringify({ status: 'pending', payload_json: SNAPSHOT }), + new_value: JSON.stringify({ status: 'approved', payload_json: SNAPSHOT }), + }; + await redactAuditLogRows([row], security, { userId: 'u_reader' }); + expect(JSON.parse(row.old_value as string)).toEqual({ status: 'pending' }); + expect(JSON.parse(row.new_value as string)).toEqual({ status: 'approved' }); + } + }); +}); + diff --git a/packages/plugins/plugin-audit/src/side-copy-columns.ts b/packages/plugins/plugin-audit/src/side-copy-columns.ts new file mode 100644 index 00000000000..766cc443865 --- /dev/null +++ b/packages/plugins/plugin-audit/src/side-copy-columns.ts @@ -0,0 +1,49 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#32442, GHSA-2985-5f64-8wgh] Columns a ledger copy of a row never carries + * because their stored value is ANOTHER record's field values, served on its + * own row only through its owner's per-reader narrowing. A copy cannot be + * narrowed that way, so it holds none of them. + * + * One list, read by every place that holds a copy to it: + * + * - the audit writer (`ledgerView` in `audit-writers.ts`) omits the columns + * from every new `sys_audit_log` / `sys_activity` copy at write time; + * - the at-rest rewrite (`side-copy-migration.ts`) removes them from copies + * written before; + * - until that rewrite has run, the two serve-time redactions drop them + * (`activity-field-redaction.ts`, `audit-log-field-redaction.ts`) and the + * two query guards refuse a non-system query that names a carrying column + * when its reach includes a listed object (`parent-field-query-guard.ts`). + * + * The list follows `key-material-copy.ts`: closed, declared, by object name. + */ + +/** Per object: the columns no ledger copy of its rows carries. */ +export const SIDE_COPY_COLUMNS: ReadonlyMap = new Map([ + // The approvals request's subject snapshot (`plugin-approvals`). + ['sys_approval_request', Object.freeze(['payload_json'])], +]); + +/** The objects {@link SIDE_COPY_COLUMNS} lists. */ +export const SIDE_COPY_OBJECTS: readonly string[] = [...SIDE_COPY_COLUMNS.keys()]; + +/** The listed columns of `objectName` — empty for an object the list does not name. */ +export function sideCopyColumnsOf(objectName: unknown): readonly string[] { + return typeof objectName === 'string' ? SIDE_COPY_COLUMNS.get(objectName) ?? [] : []; +} + +/** + * Omit the listed columns from one copy of an `objectName` row, IN PLACE. + * Returns whether any column was removed, so the at-rest rewrite is idempotent. + */ +export function omitSideCopyFromCopy(objectName: unknown, copy: Record): boolean { + let changed = false; + for (const column of sideCopyColumnsOf(objectName)) { + if (!(column in copy)) continue; + delete copy[column]; + changed = true; + } + return changed; +} diff --git a/packages/plugins/plugin-audit/src/side-copy-migration.ts b/packages/plugins/plugin-audit/src/side-copy-migration.ts new file mode 100644 index 00000000000..9e9642ca8ae --- /dev/null +++ b/packages/plugins/plugin-audit/src/side-copy-migration.ts @@ -0,0 +1,175 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#32442, GHSA-2985-5f64-8wgh] One-off rewrite of the columns + * `side-copy-columns.ts` lists out of the ledger copies written before the + * writer omitted them (`ledgerView`), so a repaired copy and a new one read + * the same. It is the key-material rewrite with a different list + * (`key-material-copy-migration.ts`): the same shared runner and stores + * (`mail-log-body-migration.ts`, {@link runLedgerCopyRewrite}), so the + * rewrites never disagree about paging, the write's context, a sealed row + * (amended first, or refused) or what is a failure. Dry-run by default, + * idempotent, counts only. + * + * Until it has run, the serve-time redactions drop the columns and the query + * guards refuse a query that names a carrying column (`side-copy-columns.ts`). + */ + +import type { IDataDriver, IDataEngine } from '@objectstack/spec/contracts'; +import type { AuditRedactionSeal } from './audit-seal/amendment-writer.js'; +import { SIDE_COPY_OBJECTS, omitSideCopyFromCopy } from './side-copy-columns.js'; +import { + ledgerCopyStoreOverArchiveDriver, + ledgerCopyStoreOverEngine, + runLedgerCopyRewrite, + type LedgerCopyRewriteSpec, +} from './mail-log-body-migration.js'; +import type { MigrationLogger } from './stored-metadata-body-migration.js'; + +/** The two audit-family tables the writer copies a row into. */ +export const SIDE_COPY_TABLES = ['sys_audit_log', 'sys_activity'] as const; + +/** One of {@link SIDE_COPY_TABLES}. */ +export type SideCopyTable = (typeof SIDE_COPY_TABLES)[number]; + +/** Omit the listed columns from one parsed snapshot. A non-object, or a snapshot without them, comes back unchanged. */ +function omittedSnapshot(objectName: unknown, snapshot: unknown): { changed: boolean; value: unknown } { + if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) return { changed: false, value: snapshot }; + const copy = { ...(snapshot as Record) }; + return omitSideCopyFromCopy(objectName, copy) ? { changed: true, value: copy } : { changed: false, value: snapshot }; +} + +/** Parse → apply `step` → re-serialize one stored JSON string column. A non-string / unparseable value is left as-is. */ +function rewriteSerialized( + serialized: unknown, + step: (parsed: unknown) => { changed: boolean; value: unknown }, +): { changed: boolean; value: unknown } { + if (typeof serialized !== 'string' || serialized === '') return { changed: false, value: serialized }; + let parsed: unknown; + try { + parsed = JSON.parse(serialized); + } catch { + return { changed: false, value: serialized }; + } + const { changed, value } = step(parsed); + return changed ? { changed: true, value: JSON.stringify(value) } : { changed: false, value: serialized }; +} + +/** + * The patch for one `sys_audit_log` row — its `new_value` and `old_value` with + * the listed columns removed — or `null` when the row is about an object + * the list does not name or holds none of them. + */ +export function planSideCopyAuditRowPatch( + row: Record, +): { new_value?: unknown; old_value?: unknown } | null { + const patch: { new_value?: unknown; old_value?: unknown } = {}; + for (const column of ['new_value', 'old_value'] as const) { + const out = rewriteSerialized(row[column], (parsed) => omittedSnapshot(row.object_name, parsed)); + if (out.changed) patch[column] = out.value; + } + return Object.keys(patch).length > 0 ? patch : null; +} + +/** + * The patch for one `sys_activity` row — the serialized pair `{ old, new }` + * with each half's listed columns removed, every other key of the pair + * kept — or `null` when the row needs none. + */ +export function planSideCopyActivityRowPatch(row: Record): { metadata: unknown } | null { + const out = rewriteSerialized(row.metadata, (parsed) => { + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return { changed: false, value: parsed }; + const pair = parsed as Record; + const next: Record = { ...pair }; + let changed = false; + for (const half of ['old', 'new'] as const) { + if (!(half in pair)) continue; + const omitted = omittedSnapshot(row.object_name, pair[half]); + if (!omitted.changed) continue; + next[half] = omitted.value; + changed = true; + } + return { changed, value: changed ? next : parsed }; + }); + return out.changed ? { metadata: out.value } : null; +} + +/** The engine surface the runner needs — the real data-engine contract's members. */ +export type SideCopyMigrationEngine = Pick; + +/** The driver surface the archive run needs — the real data-driver contract's members. */ +export type SideCopyArchiveDriver = Pick; + +/** What the runner options accept, for either store. */ +export interface SideCopyMigrationOptions { + apply?: boolean; + pageSize?: number; + /** The copy tables to walk — both by default. */ + objects?: readonly SideCopyTable[]; + /** + * [ADR-0154 D7] What amending a sealed row takes. Every shipped caller + * passes it; without it a row is rewritten with no amendment, and a sealed + * one then reads `modified` in `os audit verify`. + */ + seal?: AuditRedactionSeal; +} + +/** What one migration run did (or would do in dry-run). Counts only. */ +export interface SideCopyMigrationReport { + apply: boolean; + /** Per copy table: copy rows read, rows rewritten (or that would be), and sealed rows refused. */ + readonly byObject: Record; + /** Copy rows read, total. */ + scanned: number; + /** Rows holding a listed column, total — rewritten under `apply`. */ + rewritten: number; + /** + * [ADR-0154 D7] Sealed rows left as they are because their redaction + * amendment cannot be written — not counted in `rewritten`. + */ + refused: number; + /** A failed read, or a row an `update` threw on (apply mode) — re-run to finish. */ + failures: number; +} + +/** The side-copy rewrite's list, planners and words; its CLI door is owed (`os migrate audit-side-copies`). */ +const SIDE_COPY_REWRITE: LedgerCopyRewriteSpec = { + objectNames: SIDE_COPY_OBJECTS, + planAudit: planSideCopyAuditRowPatch, + planActivity: planSideCopyActivityRowPatch, + migration: 'os migrate audit-side-copies', + tag: '[side-copy-migration]', + summary: (report, label) => + `[side-copy-migration] ${report.apply ? 'removed' : 'would remove'} listed columns from ${report.rewritten} of ` + + `${report.scanned} ${label} cop(ies)` + + (report.refused > 0 ? ` (${report.refused} sealed row(s) refused: no amendment could be written)` : '') + + (report.failures > 0 ? ` (${report.failures} failed — re-run to finish)` : ''), +}; + +/** + * Remove the listed columns from every `sys_audit_log` / `sys_activity` + * copy of a listed object's row that still holds them. Dry-run by default; + * `apply` writes, as the platform, keeping each row's stored `updated_at`. + * Idempotent. + */ +export async function migrateSideCopies( + engine: SideCopyMigrationEngine, + logger: MigrationLogger, + options: SideCopyMigrationOptions = {}, +): Promise { + return runLedgerCopyRewrite(ledgerCopyStoreOverEngine(engine), logger, options, 'audit/activity', SIDE_COPY_REWRITE); +} + +/** + * The same rewrite over an ARCHIVE datasource — the store `sys_audit_log`'s + * `lifecycle.archive.to` names — through that datasource's registered driver, + * as the Archiver reads and writes it. An archive table that was never created + * reads as no rows; any other refused read is a failure, as on the hot run. + */ +export async function migrateArchivedSideCopies( + driver: SideCopyArchiveDriver, + logger: MigrationLogger, + options: SideCopyMigrationOptions = {}, +): Promise { + return runLedgerCopyRewrite(ledgerCopyStoreOverArchiveDriver(driver), logger, options, 'archived audit', SIDE_COPY_REWRITE); +} diff --git a/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts index af85e29e9ad..b19e9366716 100644 --- a/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts +++ b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts @@ -32,7 +32,8 @@ // ⭐ the same query as the submitter returns nothing; // ⭐ a member on no request reads nothing: by query, by id, by aggregate; // ⭐ the snapshot field the approver may not read is not served to them, -// on the request row or in its activity rows; +// on the request row; the request's activity copies are written without +// the snapshot, and an older copy at rest reaches them on no read face; // ⭐ the object is listed and described; no write tool opens it, and // `sys_approval_action` stays refused; // ⭐ the query tool's text names the "pending for me" filter shape; @@ -349,20 +350,52 @@ describe('an approver\'s agent lists the approvals waiting on them over MCP (#32 expect(own.text).toContain(STORED); }); - it('⭐ the request\'s activity rows serve the approver no value they may not read', async () => { - // Control: the value is at rest. - const stored = rowsOf(await ql.find('sys_activity', { + it('⭐ the request\'s activity and audit copies are written without the subject snapshot', async () => { + const activity = rowsOf(await ql.find('sys_activity', { where: { object_name: REQUEST, record_id: first.requestId }, context: SYS.context, })); - expect(stored.length, 'the request\'s insert left an activity row').toBeGreaterThan(0); - expect(JSON.stringify(stored)).toContain(STORED); - // The approver reads those rows on the data door (their participant read - // of the parent admits them). - const res = await stack.api('/data/sys_activity', { headers: { Authorization: `Bearer ${approver}` } }); - const text = await res.text(); - expect(res.status, text).toBe(200); - expect(text, 'the approver reads the request\'s activity').toContain(first.requestId); - expect(text).not.toContain(STORED); + expect(activity.length, 'the request\'s insert left an activity row').toBeGreaterThan(0); + expect(JSON.stringify(activity)).not.toContain(STORED); + expect(JSON.stringify(activity)).not.toContain('payload_json'); + // Control: the request row itself keeps it. + expect(String((await requestRow(first.requestId)).payload_json)).toContain(STORED); + }); + + it('⭐ a copy written before, still at rest, reaches the approver on no read face', async () => { + // A copy in the shape written before the writer omitted the snapshot. + const [row] = rowsOf(await ql.find('sys_activity', { + where: { object_name: REQUEST, record_id: second.requestId }, context: SYS.context, + })); + expect(row, 'the second request left an activity row').toBeTruthy(); + const pair = JSON.parse(String(row.metadata)); + pair.new = { ...(pair.new ?? {}), payload_json: JSON.stringify({ name: 'sunday shift', [MASKED]: STORED }) }; + await ql.update('sys_activity', { id: row.id, metadata: JSON.stringify(pair) }, { context: { isSystem: true, preserveAudit: true } }); + expect(JSON.stringify(rowsOf(await ql.find('sys_activity', { where: { id: row.id }, context: SYS.context })))).toContain(STORED); + + const rest = async (method: string, path: string, body?: unknown) => { + const res = await stack.apiAs(approver, method, path, body); + return { status: res.status, text: await res.text() }; + }; + // The list face: the row is served, the snapshot is not. + const listed = await rest('GET', '/data/sys_activity'); + expect(listed.status, listed.text).toBe(200); + expect(listed.text).toContain(second.requestId); + expect(listed.text).not.toContain(STORED); + + const pinned = { object_name: REQUEST }; + const faces: Array<[string, Record]> = [ + ['grouped', { where: pinned, groupBy: ['metadata'], aggregations: [{ function: 'count', alias: 'n' }] }], + ['contains, a right guess', { where: { $and: [pinned, { metadata: { $contains: STORED } }] } }], + ['contains, a wrong guess', { where: { $and: [pinned, { metadata: { $contains: 'SYNTH0000MISS' } }] } }], + ['count', { where: { $and: [pinned, { metadata: { $contains: STORED } }] }, aggregations: [{ function: 'count', alias: 'n' }] }], + ['sorted', { where: pinned, orderBy: [{ field: 'metadata', order: 'asc' }] }], + ['no parent named', { where: { metadata: { $contains: STORED } } }], + ]; + for (const [face, query] of faces) { + const answer = await rest('POST', '/data/sys_activity/query', query); + expect(answer.status, `${face}: ${answer.text}`).toBe(403); + expect(answer.text, face).not.toContain(STORED); + } }); it('⭐ the object is listed and described for the approver; no write tool opens it, and sys_approval_action stays refused', async () => { From a12e7c9c9b7d830c6e26a91e777af818dea41159 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 17:53:42 +0000 Subject: [PATCH 15/16] fix(audit): judge a pinned query over an approval request's copies against every object Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- .../src/parent-field-query-guard.ts | 31 +++++++------------ .../src/side-copy-columns.test.ts | 22 ++++++------- .../plugin-audit/src/side-copy-columns.ts | 7 +++-- .../plugin-audit/src/side-copy-migration.ts | 6 ++-- 4 files changed, 30 insertions(+), 36 deletions(-) diff --git a/packages/plugins/plugin-audit/src/parent-field-query-guard.ts b/packages/plugins/plugin-audit/src/parent-field-query-guard.ts index 868725f2d5e..05a70fa6ec9 100644 --- a/packages/plugins/plugin-audit/src/parent-field-query-guard.ts +++ b/packages/plugins/plugin-audit/src/parent-field-query-guard.ts @@ -109,7 +109,7 @@ * read gate and the redaction. */ -import { SIDE_COPY_OBJECTS, sideCopyColumnsOf } from './side-copy-columns.js'; +import { sideCopyColumnsOf } from './side-copy-columns.js'; import { FieldReferenceSchema } from '@objectstack/spec/data'; import { ACTIVITY_STAMPED_COLUMNS } from './activity-changed-fields.js'; import { resolveServedFields, type FieldRedactionLogger, type FieldVisibilitySource } from './served-fields.js'; @@ -168,26 +168,21 @@ export const SIDE_COPY_CARRIER_COLUMNS: ReadonlyMap = ]); /** - * [#32442] The carrier columns `named` holds when the query can reach a - * parent `side-copy-columns.ts` lists — the ONE parent it pins, or every - * parent when it pins none — or `null` when it names none or reaches none. - * Refused for every non-system reader, whatever their served fields, until - * the at-rest rewrite has removed the column from every copy. + * [#32442] Whether a query pinned to `parent` names a carrier column of a + * parent `side-copy-columns.ts` lists. A copy of such a parent's row may hold + * field values of ANY object (the approvals request's subject snapshot), so + * the objects the query can reach are every registered object, and the guard + * asks the unpinned query's question ({@link readerWithholdsAnyDeclaredParentField}), + * not the pinned parent's. A query naming no parent already asks it. */ -export function namedSideCopyCarriers( +export function reachesSideCopy( guarded: string, parent: string | null, named: NamedValueBearingColumns, -): NamedValueBearingColumns | null { +): boolean { + if (parent === null || sideCopyColumnsOf(parent).length === 0) return false; const carriers = SIDE_COPY_CARRIER_COLUMNS.get(guarded) ?? []; - if (carriers.length === 0) return null; - const reaches = parent === null ? SIDE_COPY_OBJECTS.length > 0 : sideCopyColumnsOf(parent).length > 0; - if (!reaches) return null; - const carried = { - aggregate: named.aggregate.filter((c) => carriers.includes(c)), - predicate: named.predicate.filter((c) => carriers.includes(c)), - }; - return carried.aggregate.length > 0 || carried.predicate.length > 0 ? carried : null; + return [...named.aggregate, ...named.predicate].some((c) => carriers.includes(c)); } /** The value-bearing columns a query names, by the role it names them in. */ @@ -420,11 +415,9 @@ function installParentFieldQueryGuard( const security = getSecurity(); if (!security) return next(); const parent = pinnedParentObject(ctx.ast.where, guard.object); - const carried = namedSideCopyCarriers(guard.object, parent, named); - if (carried) throw parentFieldQueryRefusal(guard, ctx.operation, carried); let refuse = true; try { - if (parent !== null) { + if (parent !== null && !reachesSideCopy(guard.object, parent, named)) { refuse = await readerWithholdsParentField(security, parent, ctx.context, logger); } else { refuse = await readerWithholdsAnyDeclaredParentField(engine, security, ctx.context, logger); diff --git a/packages/plugins/plugin-audit/src/side-copy-columns.test.ts b/packages/plugins/plugin-audit/src/side-copy-columns.test.ts index 63f7c3e481a..6e1e3913a3b 100644 --- a/packages/plugins/plugin-audit/src/side-copy-columns.test.ts +++ b/packages/plugins/plugin-audit/src/side-copy-columns.test.ts @@ -8,7 +8,7 @@ import { describe, it, expect } from 'vitest'; import { SIDE_COPY_COLUMNS, SIDE_COPY_OBJECTS, omitSideCopyFromCopy, sideCopyColumnsOf } from './side-copy-columns.js'; import { planSideCopyActivityRowPatch, planSideCopyAuditRowPatch } from './side-copy-migration.js'; -import { namedSideCopyCarriers } from './parent-field-query-guard.js'; +import { reachesSideCopy } from './parent-field-query-guard.js'; import { redactAuditLogRows } from './audit-log-field-redaction.js'; const REQUEST = 'sys_approval_request'; @@ -59,20 +59,20 @@ describe('[#32442] the at-rest rewrite plans', () => { }); }); -describe('[#32442] the query guards refuse a carrying column whose reach includes a listed parent', () => { +describe('[#32442] a query pinned to a listed parent and naming a carrier column reaches every object', () => { const named = (predicate: string[], aggregate: string[] = []) => ({ predicate, aggregate }); - it('refuses metadata on the activity stream pinned to the request, or pinned to nothing', () => { - expect(namedSideCopyCarriers('sys_activity', REQUEST, named(['metadata']))).toEqual(named(['metadata'])); - expect(namedSideCopyCarriers('sys_activity', null, named([], ['metadata']))).toEqual(named([], ['metadata'])); - expect(namedSideCopyCarriers('sys_audit_log', REQUEST, named(['new_value', 'object_name']))) - .toEqual(named(['new_value'])); + it('on the activity stream and on the ledger', () => { + expect(reachesSideCopy('sys_activity', REQUEST, named(['metadata']))).toBe(true); + expect(reachesSideCopy('sys_activity', REQUEST, named([], ['metadata']))).toBe(true); + expect(reachesSideCopy('sys_audit_log', REQUEST, named(['new_value', 'object_name']))).toBe(true); }); - it('admits another parent, and a column that carries no copy', () => { - expect(namedSideCopyCarriers('sys_activity', 'crm_note', named(['metadata']))).toBeNull(); - expect(namedSideCopyCarriers('sys_activity', REQUEST, named(['summary']))).toBeNull(); - expect(namedSideCopyCarriers('sys_comment', REQUEST, named(['metadata']))).toBeNull(); + it('not for another parent, no parent (already asked of every object), or a column that carries no copy', () => { + expect(reachesSideCopy('sys_activity', 'crm_note', named(['metadata']))).toBe(false); + expect(reachesSideCopy('sys_activity', null, named(['metadata']))).toBe(false); + expect(reachesSideCopy('sys_activity', REQUEST, named(['summary']))).toBe(false); + expect(reachesSideCopy('sys_comment', REQUEST, named(['metadata']))).toBe(false); }); }); diff --git a/packages/plugins/plugin-audit/src/side-copy-columns.ts b/packages/plugins/plugin-audit/src/side-copy-columns.ts index 766cc443865..8f933e1be4b 100644 --- a/packages/plugins/plugin-audit/src/side-copy-columns.ts +++ b/packages/plugins/plugin-audit/src/side-copy-columns.ts @@ -13,9 +13,10 @@ * - the at-rest rewrite (`side-copy-migration.ts`) removes them from copies * written before; * - until that rewrite has run, the two serve-time redactions drop them - * (`activity-field-redaction.ts`, `audit-log-field-redaction.ts`) and the - * two query guards refuse a non-system query that names a carrying column - * when its reach includes a listed object (`parent-field-query-guard.ts`). + * (`activity-field-redaction.ts`, `audit-log-field-redaction.ts`), and the + * two query guards judge a query pinned to a listed object that names a + * carrying column as one that reaches every object + * (`parent-field-query-guard.ts`): a copy may hold any object's fields. * * The list follows `key-material-copy.ts`: closed, declared, by object name. */ diff --git a/packages/plugins/plugin-audit/src/side-copy-migration.ts b/packages/plugins/plugin-audit/src/side-copy-migration.ts index 9e9642ca8ae..4b8a8cf85ca 100644 --- a/packages/plugins/plugin-audit/src/side-copy-migration.ts +++ b/packages/plugins/plugin-audit/src/side-copy-migration.ts @@ -12,7 +12,7 @@ * idempotent, counts only. * * Until it has run, the serve-time redactions drop the columns and the query - * guards refuse a query that names a carrying column (`side-copy-columns.ts`). + * guards judge a query naming a carrying column against every object (`side-copy-columns.ts`). */ import type { IDataDriver, IDataEngine } from '@objectstack/spec/contracts'; @@ -132,12 +132,12 @@ export interface SideCopyMigrationReport { failures: number; } -/** The side-copy rewrite's list, planners and words; its CLI door is owed (`os migrate audit-side-copies`). */ +/** The side-copy rewrite's list, planners and words. Its command-line door is owed; until then a host drives the runners. */ const SIDE_COPY_REWRITE: LedgerCopyRewriteSpec = { objectNames: SIDE_COPY_OBJECTS, planAudit: planSideCopyAuditRowPatch, planActivity: planSideCopyActivityRowPatch, - migration: 'os migrate audit-side-copies', + migration: 'side-copy-migration', tag: '[side-copy-migration]', summary: (report, label) => `[side-copy-migration] ${report.apply ? 'removed' : 'would remove'} listed columns from ${report.rewritten} of ` + From 33368c3153c9a6f55be19fcdb877515a773631c1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 19:21:46 +0000 Subject: [PATCH 16/16] fix(audit): state the copy-column rule in the guard's words, and run both copy rewrites in tests The parent-field query guard's header, its refusal remedy and its fail-closed warning now name the case a pinned query is judged against every object. New tests drive migrateSideCopies and migrateArchivedSideCopies end to end: dry run, apply, idempotent re-run, the objects option, and an archive store. The activity redaction's re-export of the column list is dropped; its test imports the list directly. The changeset states who the query rule refuses. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_016WV4cwJx2CfBxrD3ojeDPr --- ...cp-read-tools-ai-readable-system-object.md | 4 +- .../src/activity-field-redaction.ts | 3 - .../src/activity-side-copy-redaction.test.ts | 7 +- .../src/parent-field-query-guard.ts | 20 +- .../src/side-copy-migration.test.ts | 206 ++++++++++++++++++ 5 files changed, 228 insertions(+), 12 deletions(-) create mode 100644 packages/plugins/plugin-audit/src/side-copy-migration.test.ts diff --git a/.changeset/mcp-read-tools-ai-readable-system-object.md b/.changeset/mcp-read-tools-ai-readable-system-object.md index a95a1ef10d1..c27bb066e7e 100644 --- a/.changeset/mcp-read-tools-ai-readable-system-object.md +++ b/.changeset/mcp-read-tools-ai-readable-system-object.md @@ -13,4 +13,6 @@ The MCP read tools (`list_objects`, `describe_object`, `query_records`, `get_rec The member baseline `member_default` now names `sys_approval_request` read-only, so every signed-in member holds a data-door read on it; which rows is still the approvals request read gate (the submitter, a current approver, a past actor), and no write opens. That gate now answers a conjunctive `pending_approvers` `$contains` of the caller's own id with the approvals service's acting-address fold, so the console's My Pending view and an agent's "waiting on me" query find a slot addressed by email or an unstaffed position, not only one holding the user id. A `pending_approvers` predicate naming another id, or under `$or`, is read as written. -`@objectstack/plugin-audit`: the activity and audit copies of an approval request no longer carry its subject snapshot, with a rewrite for copies at rest (`migrateSideCopies`) (GHSA-2985-5f64-8wgh). +`@objectstack/plugin-audit`: the activity and audit copies of an approval request are hardened (GHSA-2985-5f64-8wgh). New copies no longer carry the request's subject snapshot, and `migrateSideCopies` / `migrateArchivedSideCopies` rewrite the copies at rest. Both ledgers' read redactions drop it from an older copy whether or not the rewrite has run. + +**Who can query those copies narrows.** A non-system query on `sys_activity` or `sys_audit_log` that names `sys_approval_request` by equality on `object_name` and names a column holding the copy (`metadata`; `old_value`, `new_value`), as a free-text search does, is now judged against every registered object, as a query naming no object already is. A reader withheld any field of any object, an organization administrator included, is refused it (`403`) where they were answered before. The same query pinned to another object, or naming only other columns, is judged as before. This does not depend on the rewrite having run. diff --git a/packages/plugins/plugin-audit/src/activity-field-redaction.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.ts index 1af49b8b0c2..0b9146cf5b2 100644 --- a/packages/plugins/plugin-audit/src/activity-field-redaction.ts +++ b/packages/plugins/plugin-audit/src/activity-field-redaction.ts @@ -515,9 +515,6 @@ export async function computeWithheldUpdateFilter( return branches.length === 1 ? branches[0] : { $or: branches }; } -/** [#32442] The listed columns (`side-copy-columns.ts`), re-exported for the activity pins. */ -export { SIDE_COPY_COLUMNS as ACTIVITY_SIDE_COPY_COLUMNS } from './side-copy-columns.js'; - /** * Redact the value-bearing columns of the activity rows one read is about to * hand back, as `context`. Mutates the rows in place (they are the read's own diff --git a/packages/plugins/plugin-audit/src/activity-side-copy-redaction.test.ts b/packages/plugins/plugin-audit/src/activity-side-copy-redaction.test.ts index 98638d36121..0b39ce1a9d1 100644 --- a/packages/plugins/plugin-audit/src/activity-side-copy-redaction.test.ts +++ b/packages/plugins/plugin-audit/src/activity-side-copy-redaction.test.ts @@ -1,13 +1,14 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * [#32442] `ACTIVITY_SIDE_COPY_COLUMNS`: the listed parent columns are not + * [#32442] `SIDE_COPY_COLUMNS`: the listed parent columns are not * served in an activity row's `metadata.old` / `metadata.new`, for any reader; * every other key is narrowed as before, and other objects are untouched. */ import { describe, it, expect } from 'vitest'; -import { redactActivityRows, ACTIVITY_SIDE_COPY_COLUMNS } from './activity-field-redaction.js'; +import { redactActivityRows } from './activity-field-redaction.js'; +import { SIDE_COPY_COLUMNS } from './side-copy-columns.js'; const SNAPSHOT = JSON.stringify({ name: 'INV-1', cost_code: 'SYNTH-SIDE-COPY-41' }); const reader = { userId: 'u_reader', positions: [], permissions: [] }; @@ -20,7 +21,7 @@ const allServed = (fields: string[]) => ({ describe('[#32442] activity rows do not serve the listed parent columns', () => { it('names exactly the request snapshot column', () => { - expect([...ACTIVITY_SIDE_COPY_COLUMNS.entries()]).toEqual([['sys_approval_request', ['payload_json']]]); + expect([...SIDE_COPY_COLUMNS.entries()]).toEqual([['sys_approval_request', ['payload_json']]]); }); it('drops payload_json from both sides for a reader served every request field, keeping the rest', async () => { diff --git a/packages/plugins/plugin-audit/src/parent-field-query-guard.ts b/packages/plugins/plugin-audit/src/parent-field-query-guard.ts index 05a70fa6ec9..7d9f238e8ad 100644 --- a/packages/plugins/plugin-audit/src/parent-field-query-guard.ts +++ b/packages/plugins/plugin-audit/src/parent-field-query-guard.ts @@ -7,7 +7,9 @@ * search, group or aggregate by one of their value-bearing columns only when * it is served every field of the objects the query can reach: the ONE parent * object the query names, or, when it names none, every registered object. - * Any other such query is refused, in the engine's own refusal shape. + * A query that names a parent whose copies `side-copy-columns.ts` lists, by a + * column holding such a copy, reaches every registered object too. Any other + * such query is refused, in the engine's own refusal shape. * * ## The defect this closes * @@ -61,7 +63,13 @@ * * - A query that names ONE parent object — an equality on `object_name` at the * root of its `where`, directly or inside a root `$and` — reaches no other - * parent, and is judged against that object alone. + * parent, and is judged against that object alone, with one exception: + * - A query that names one parent `side-copy-columns.ts` lists AND names a + * column holding a copy of its row ({@link SIDE_COPY_CARRIER_COLUMNS}) is + * judged as one that names none ({@link reachesSideCopy}). Such a copy can + * carry field values of other objects, so pinning the parent does not + * bound what the column holds. Naming any other column, or another parent, + * keeps the pinned rule. * - A query that names none is judged against the DECLARED set: every object * registered in the engine ({@link declaredParentObjects}), read from * metadata, never from rows, so it answers the same whatever the query and @@ -134,7 +142,8 @@ export interface ParentFieldQueryGuard { const remedy = (what: string) => ` ${what} carries field values of the record its row is about, so a query may filter, sort, search, group ` + 'or aggregate by it only for a caller served every field of the objects it can reach: one parent object ' + - 'named by equality on object_name, or every object when it names none.'; + 'named by equality on object_name, or every object when it names none or when the named object\'s ' + + 'copies in this column can carry other objects\' values.'; /** * The activity stream: the columns the field redaction narrows (see its header @@ -415,9 +424,10 @@ function installParentFieldQueryGuard( const security = getSecurity(); if (!security) return next(); const parent = pinnedParentObject(ctx.ast.where, guard.object); + const askEveryObject = parent === null || reachesSideCopy(guard.object, parent, named); let refuse = true; try { - if (parent !== null && !reachesSideCopy(guard.object, parent, named)) { + if (!askEveryObject && parent !== null) { refuse = await readerWithholdsParentField(security, parent, ctx.context, logger); } else { refuse = await readerWithholdsAnyDeclaredParentField(engine, security, ctx.context, logger); @@ -425,7 +435,7 @@ function installParentFieldQueryGuard( } catch (err) { logger.warn( `[audit] ${guard.object} query guard: could not tell whether the caller is served every field of ` + - `${parent !== null ? `'${parent}'` : 'every registered object'} — refusing the query (fail closed): ` + + `${askEveryObject ? 'every registered object' : `'${parent}'`} — refusing the query (fail closed): ` + `${(err as Error)?.message ?? err}`, ); refuse = true; diff --git a/packages/plugins/plugin-audit/src/side-copy-migration.test.ts b/packages/plugins/plugin-audit/src/side-copy-migration.test.ts new file mode 100644 index 00000000000..e80942dd117 --- /dev/null +++ b/packages/plugins/plugin-audit/src/side-copy-migration.test.ts @@ -0,0 +1,206 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The at-rest rewrite of the columns `side-copy-columns.ts` lists, run end to + * end: the paged runner against a fake engine, then the archive run through a + * real SQL driver. The rows are shaped as the writer stored them before it + * omitted the column: a create, an update and a delete, on all four copy sides + * (`new_value`, `old_value`, and the two halves of `sys_activity.metadata`). + * The planners themselves are pinned in `side-copy-columns.test.ts`. + * + * ⛔ The value here is a sentinel, and no title or message names one. + */ + +import { isDeepStrictEqual } from 'node:util'; +import { describe, expect, it, vi } from 'vitest'; +// [engine-double-contract] A fake engine's update must refuse exactly what +// ObjectQL refuses, as in `key-material-copy-migration.test.ts`. +import { assertEngineUpdateDispatch } from '@objectstack/metadata-core'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; +import { SysAuditLog } from './objects/sys-audit-log.object.js'; +import { + migrateArchivedSideCopies, + migrateSideCopies, + type SideCopyMigrationEngine, +} from './side-copy-migration.js'; + +type Row = Record; + +const LISTED = 'sys_approval_request'; +const HELD = 'side-copy-sentinel'; + +/** A listed row as the writer copied it whole, before it omitted the column. */ +const requestRow = (id: string, status: string, held = true): Row => ({ + id, + process_name: 'expense', + status, + ...(held ? { payload_json: JSON.stringify({ note: HELD }) } : {}), +}); + +const auditRows = (): Row[] => [ + { id: 'al_1', object_name: LISTED, action: 'create', record_id: 'r_1', updated_at: '2026-11-01T00:00:00.000Z', old_value: null, new_value: JSON.stringify(requestRow('r_1', 'pending')) }, + { id: 'al_2', object_name: LISTED, action: 'update', record_id: 'r_1', old_value: JSON.stringify(requestRow('r_1', 'pending')), new_value: JSON.stringify(requestRow('r_1', 'approved')) }, + { id: 'al_3', object_name: LISTED, action: 'delete', record_id: 'r_1', old_value: JSON.stringify(requestRow('r_1', 'approved')), new_value: null }, + // A listed update that never carried the column: never touched. + { id: 'al_4', object_name: LISTED, action: 'update', record_id: 'r_2', old_value: JSON.stringify({ status: 'pending' }), new_value: JSON.stringify({ status: 'rejected' }) }, + // Not a listed object: never touched, whatever its columns are called. + { id: 'al_5', object_name: 'crm_note', action: 'create', record_id: 'n_1', old_value: null, new_value: JSON.stringify({ id: 'n_1', payload_json: HELD }) }, +]; + +const TEXT_SOURCES = { summary: ['process_name'] }; + +const activityRows = (): Row[] => [ + { id: 'ac_1', object_name: LISTED, record_id: 'r_1', summary: 'Created', metadata: JSON.stringify({ old: null, new: requestRow('r_1', 'pending'), _textSources: TEXT_SOURCES }) }, + { id: 'ac_2', object_name: LISTED, record_id: 'r_2', summary: 'Updated', metadata: JSON.stringify({ old: { status: 'pending' }, new: { status: 'rejected' } }) }, + { id: 'ac_3', object_name: 'crm_note', record_id: 'n_1', summary: 'Created', metadata: JSON.stringify({ old: null, new: { payload_json: HELD } }) }, +]; + +/** Rows of the listed object that still hold the sentinel. */ +const heldCopies = (rows: Row[]): number => + rows.filter((r) => r.object_name === LISTED && JSON.stringify(r).includes(HELD)).length; + +/** The Filter Protocol subset the runner's page query speaks; anything else is refused. */ +function matchesWhere(r: Row, w: Record): boolean { + return Object.entries(w).every(([key, cond]) => { + if (key === '$and') return (cond as Record[]).every((c) => matchesWhere(r, c)); + if (key.startsWith('$')) throw new Error(`fake engine: combinator ${key} is not implemented`); + if (cond && typeof cond === 'object') { + const ops = Object.keys(cond); + if (ops.length !== 1 || !['$in', '$gt'].includes(ops[0]!)) { + throw new Error(`fake engine: operator ${ops.join(',')} is not implemented`); + } + if ('$in' in cond) return (cond.$in as unknown[]).includes(r[key]); + return String(r[key]) > String(cond.$gt); + } + return r[key] === cond; + }); +} + +describe('migrateSideCopies (driven, paged)', () => { + function fakeEngine(tables: Record) { + const writes: Array<{ object: string; data: Row; context: unknown }> = []; + const engine: SideCopyMigrationEngine = { + async find(object, query) { + const q = (query ?? {}) as { where?: any; limit?: number }; + const rows = (tables[object] ?? []) + .filter((r) => matchesWhere(r, q.where ?? {})) + .sort((a, b) => String(a.id).localeCompare(String(b.id))); + const page = typeof q.limit === 'number' ? rows.slice(0, q.limit) : rows; + return page.map((r) => ({ ...r })); + }, + async update(object, data, options) { + assertEngineUpdateDispatch(data, options === undefined ? undefined : { ...options }); + writes.push({ object, data: data as Row, context: (options as { context?: unknown } | undefined)?.context }); + const { id, ...rest } = data as Row; + const row = (tables[object] ?? []).find((r) => r.id === id); + if (row) Object.assign(row, rest); + return { id, ...rest }; + }, + }; + return { engine, writes }; + } + const logger = () => ({ info: vi.fn(), warn: vi.fn() }); + + it('a dry run counts the listed copies holding the column and writes nothing', async () => { + const tables = { sys_audit_log: auditRows(), sys_activity: activityRows() }; + const before = JSON.stringify(tables); + const { engine, writes } = fakeEngine(tables); + const report = await migrateSideCopies(engine, logger()); + expect(report).toEqual({ + apply: false, + byObject: { sys_audit_log: { scanned: 4, rewritten: 3, refused: 0 }, sys_activity: { scanned: 2, rewritten: 1, refused: 0 } }, + scanned: 6, + rewritten: 4, + refused: 0, + failures: 0, + }); + expect(writes).toHaveLength(0); + expect(JSON.stringify(tables)).toBe(before); + }); + + it('apply leaves no listed copy holding the column, moves no other key, column or row, and a re-run is a no-op', async () => { + const tables = { sys_audit_log: auditRows(), sys_activity: activityRows() }; + expect(heldCopies([...tables.sys_audit_log, ...tables.sys_activity])).toBe(4); + const { engine, writes } = fakeEngine(tables); + const log = logger(); + const report = await migrateSideCopies(engine, log, { apply: true, pageSize: 2 }); + expect(report.rewritten).toBe(4); + expect(report.failures).toBe(0); + expect(heldCopies([...tables.sys_audit_log, ...tables.sys_activity])).toBe(0); + + const originals = new Map([...auditRows(), ...activityRows()].map((r) => [r.id, r])); + for (const row of [...tables.sys_audit_log, ...tables.sys_activity]) { + const original = originals.get(row.id)!; + for (const key of Object.keys(original)) { + if (['new_value', 'old_value', 'metadata'].includes(key)) continue; + expect(row[key], `${String(row.id)}.${key}`).toBe(original[key]); + } + } + const { payload_json: _omitted, ...kept } = requestRow('r_1', 'pending'); + expect(JSON.parse(String(tables.sys_audit_log[0]!.new_value))).toEqual(kept); + const pair = JSON.parse(String(tables.sys_activity[0]!.metadata)); + expect(pair.new).toEqual(kept); + expect(pair._textSources).toEqual(TEXT_SOURCES); + expect(tables.sys_audit_log[3]).toEqual(auditRows()[3]); + expect(tables.sys_audit_log[4]).toEqual(auditRows()[4]); + expect(tables.sys_activity[2]).toEqual(activityRows()[2]); + expect(writes[0]!.data.updated_at).toBe('2026-11-01T00:00:00.000Z'); + expect(writes.every((w) => isDeepStrictEqual(w.context, { isSystem: true, preserveAudit: true }))).toBe(true); + const lines = [...log.info.mock.calls, ...log.warn.mock.calls].flat().join('\n'); + expect(lines).not.toContain(HELD); + + const after = JSON.stringify(tables); + const again = await migrateSideCopies(engine, logger(), { apply: true, pageSize: 2 }); + expect(again.rewritten).toBe(0); + expect(again.scanned).toBe(6); + expect(JSON.stringify(tables)).toBe(after); + }); + + it('walks only the tables `objects` names', async () => { + const tables = { sys_audit_log: auditRows(), sys_activity: activityRows() }; + const { engine } = fakeEngine(tables); + const report = await migrateSideCopies(engine, logger(), { apply: true, objects: ['sys_activity'] }); + expect(report.rewritten).toBe(1); + expect(tables.sys_audit_log).toEqual(auditRows()); + }); +}); + +describe('migrateArchivedSideCopies (an archive datasource, through its driver)', () => { + async function archiveStore(rows: Row[]): Promise { + const cold = new SqliteWasmDriver({ filename: ':memory:' }); + await cold.connect(); + await cold.syncSchema('sys_audit_log', SysAuditLog); + for (const row of rows) await cold.upsert('sys_audit_log', row, ['id']); + return cold; + } + const allRows = async (cold: SqliteWasmDriver): Promise => + (await cold.find('sys_audit_log', { orderBy: [{ field: 'id', order: 'asc' }] })).map((r) => ({ ...r })); + const logger = () => ({ info: vi.fn(), warn: vi.fn() }); + + it('apply leaves no archived listed copy holding the column, moves nothing else, and a re-run changes no byte', async () => { + const cold = await archiveStore(auditRows()); + const before = new Map((await allRows(cold)).map((r) => [r.id, r])); + expect(heldCopies([...before.values()])).toBe(3); + const report = await migrateArchivedSideCopies(cold, logger(), { apply: true, pageSize: 2, objects: ['sys_audit_log'] }); + expect(report.rewritten).toBe(3); + expect(report.failures).toBe(0); + + const after = await allRows(cold); + expect(heldCopies(after)).toBe(0); + for (const row of after) { + const original = before.get(row.id)!; + for (const key of Object.keys(original)) { + if (key === 'new_value' || key === 'old_value') continue; + expect(row[key], `${String(row.id)}.${key}`).toEqual(original[key]); + } + } + const created = JSON.parse(String(after.find((r) => r.id === 'al_1')!.new_value)); + expect(created).not.toHaveProperty('payload_json'); + expect(created.status).toBe('pending'); + expect(after.find((r) => r.id === 'al_5')).toEqual(before.get('al_5')); + + const again = await migrateArchivedSideCopies(cold, logger(), { apply: true, objects: ['sys_audit_log'] }); + expect(again.rewritten).toBe(0); + expect(isDeepStrictEqual(await allRows(cold), after)).toBe(true); + }); +});