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..c27bb066e7e --- /dev/null +++ b/.changeset/mcp-read-tools-ai-readable-system-object.md @@ -0,0 +1,18 @@ +--- +'@objectstack/mcp': patch +'@objectstack/runtime': patch +'@objectstack/plugin-approvals': patch +'@objectstack/plugin-security': patch +'@objectstack/plugin-audit': 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; `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. + +`@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/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index 169f85a4c79..e33e56150dc 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -362,7 +362,17 @@ 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: 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` 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/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 diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 777a202873a..2308c0d9327 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. + '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( { 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..48f2726940b --- /dev/null +++ b/packages/mcp/src/mcp-system-object-ai-read.test.ts @@ -0,0 +1,190 @@ +// 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) is pinned in `packages/runtime/src/mcp-system-object-ai-read.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/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', 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/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/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index 8dcfd8d729b..18c28579f47 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).', ); } 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..6d44c22abdc --- /dev/null +++ b/packages/plugins/plugin-approvals/src/request-read-waiting-on-caller.integration.test.ts @@ -0,0 +1,199 @@ +// 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'; +import type { EngineAggregateOptions, EngineCountOptions, EngineQueryOptions } from '@objectstack/spec/data'; + +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 } satisfies EngineQueryOptions); + } + + 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 } 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 } }; +} + +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) } satisfies EngineQueryOptions); + 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 } 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 } satisfies EngineQueryOptions))).toEqual([rig.ids.byPosition]); + 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 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 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))) + .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), + } 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), + } 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) } satisfies EngineQueryOptions)).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-approvals/src/sys-approval-request.object.test.ts b/packages/plugins/plugin-approvals/src/sys-approval-request.object.test.ts index 2f1d05146e9..36ba8f835db 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); @@ -301,3 +303,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/plugins/plugin-approvals/src/sys-approval-request.object.ts b/packages/plugins/plugin-approvals/src/sys-approval-request.object.ts index 9f220a34669..8bfece4bbe7 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 @@ -928,5 +930,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/plugins/plugin-audit/src/activity-field-redaction.ts b/packages/plugins/plugin-audit/src/activity-field-redaction.ts index 27bd6c07451..0b9146cf5b2 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; @@ -550,6 +551,18 @@ export async function redactActivityRows( stripValueBearing(row); continue; } + // [#32442] Ahead of the served-fields answer, for every reader. + 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) && omitSideCopyFromCopy(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..0b39ce1a9d1 --- /dev/null +++ b/packages/plugins/plugin-audit/src/activity-side-copy-redaction.test.ts @@ -0,0 +1,59 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#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 } 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: [] }; + +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([...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 () => { + 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' }); + }); + + 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..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 @@ -109,6 +117,7 @@ * read gate and the redaction. */ +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'; @@ -133,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 @@ -156,6 +166,34 @@ 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] 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 reachesSideCopy( + guarded: string, + parent: string | null, + named: NamedValueBearingColumns, +): boolean { + if (parent === null || sideCopyColumnsOf(parent).length === 0) return false; + const carriers = SIDE_COPY_CARRIER_COLUMNS.get(guarded) ?? []; + return [...named.aggregate, ...named.predicate].some((c) => carriers.includes(c)); +} + /** 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,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) { + if (!askEveryObject && parent !== null) { refuse = await readerWithholdsParentField(security, parent, ctx.context, logger); } else { refuse = await readerWithholdsAnyDeclaredParentField(engine, security, ctx.context, logger); @@ -396,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-columns.test.ts b/packages/plugins/plugin-audit/src/side-copy-columns.test.ts new file mode 100644 index 00000000000..6e1e3913a3b --- /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 { reachesSideCopy } 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] a query pinned to a listed parent and naming a carrier column reaches every object', () => { + const named = (predicate: string[], aggregate: string[] = []) => ({ predicate, aggregate }); + + 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('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); + }); +}); + +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..8f933e1be4b --- /dev/null +++ b/packages/plugins/plugin-audit/src/side-copy-columns.ts @@ -0,0 +1,50 @@ +// 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 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. + */ + +/** 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.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); + }); +}); 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..4b8a8cf85ca --- /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 judge a query naming a carrying column against every object (`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 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: 'side-copy-migration', + 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/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, 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..b19e9366716 --- /dev/null +++ b/packages/qa/dogfood/test/approval-read-over-mcp.dogfood.test.ts @@ -0,0 +1,467 @@ +// 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, +// 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; +// ⭐ 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 { 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'; +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(), new AuditPlugin()], + }); + 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 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(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 () => { + 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]); + }); +}); 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/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index b079234e1e2..f1afabd558a 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 0ab4d2977d6..aefdede835b 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, @@ -752,6 +754,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 @@ -929,6 +934,26 @@ 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 => { + // `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 new file mode 100644 index 00000000000..15b5a21b66f --- /dev/null +++ b/packages/runtime/src/mcp-system-object-ai-read.test.ts @@ -0,0 +1,104 @@ +// 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'; + +// 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'; + +const [FAMILY] = [...STORED_METADATA_BODY_OBJECTS]; + +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), + 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 : n === 'protocol' ? protocol : 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); + }); +}); + +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); + }); +}); 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');