Skip to content

Commit 1af67b2

Browse files
fix(mcp): the refusal-reasons relay withholds only the security gate's own refusal (#37537)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4Uu3zQ2AqeghSGpv6Q7VEPDyQ)_ Fixes #37512 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:智能体通过 MCP 遇到应用自己按“无权限”声明的多原因拒绝时,现在也能完整拿到每条原因再转告用户;平台安全检查本身的拒绝仍然什么都不多给。 - 为什么做:这是上一轮“多原因拒绝完整转告智能体”审核留下的跟进项;同一个调用者走 REST 接口早已拿到这些原因,MCP 却少给了。 - 出错会怎样:只影响应用声明为“无权限”的多原因拒绝,智能体多看到一段原因文字;安全检查的内部授权信息在任何路径上都不读取,可以直接撤回。 - 要你做什么:无。 ## What changes `packages/mcp/src/mcp-http-tools.ts` only, plus the tests and one changeset. - **S1, the guard's reach (narrowed to the gate's own refusal).** `withRefusalReasonsRelay` now withholds the relay block on a served `PERMISSION_DENIED` with no `declaredCode`: the security gate's own refusal. A listed refusal an app's catalogue declared at `403` under its own code is served as `PERMISSION_DENIED` with that code in `declaredCode` (the doors' demotion of an unregistered code) and now gets the block. `errorResultFromThrown`'s `PERMISSION_DENIED` arm now passes through the same function, so `run_action` / `resume_run` reach it too; that arm still serves no `details` (the #23529 / #7450 withholding is unchanged). The relay reads only `refusals` and `userMessage`, never `details`, so the gate's `positions` / `permissionSets` reach it on no path. - **Parity, measured, not argued.** For the same 403 app-code throw, both REST doors' own readers serve the same caller every relayed line as `details.refusals`: `mapDataError` (what the `/data` routes answer with) and `actionsDoorAnswerOf` (what `/actions` answers with, its `userMessage` uncut, closing line included). The dispatcher's withholding arm keys on `isPermissionDeniedError`, which reads `false` for that throw (scratch probe against `plugin-security`'s source: app-at-403 `false`, gate-shaped `true`). So MCP serves nothing REST does not serve the same caller. MCP stays stricter than REST in two places, both left alone: the gate's own literal `PERMISSION_DENIED` carrying a list (REST `/data` would attach it), and `details` on `run_action` for the demoted 403. - **S2, the 5xx arm.** Pinned (a listed throw at 503 on `run_action` and `resume_run`, the only renderers that reach the relay on a fault; on the record tools a declared 5xx never reaches the envelope path). The jsdoc reason is corrected: the doors do still serve `userMessage` on a declared 5xx; the block is withheld because a refusal catalogue declares only a 4xx (`declaredRefusalEntrySchema`), so a listed throw at a 5xx is no catalogue refusal. - **S3, `delete_records` per-row refusals: declared needless, with a pin.** Measured: the per-row group's `reason` is NOT cut. The catalogue throws a coded `SandboxError` whose caller sentence (`innerMessage`) is the same text as `userMessage` (`hook-refusal-catalogue.ts`, both set to `answer.message`), and `rowRefusalOf` reads a coded throw's own sentence, never the door's 500-character cut. So each group already names every line whole, in order, closing line last. No relay block is added, so the grouping shape is untouched; `rowRefusalOf`'s jsdoc says why, and a pin holds a list over 500 characters. - **N3.** `REFUSAL_REASONS_RELAY_LEAD` now reads `Tell the user every line below, whole and in this order, in place of userMessage:` (true on both doors; `/actions` never cuts). ## Tests `packages/mcp/src/mcp-refusal-reasons.test.ts` (the card's harness file; new top-level `describe` blocks), 17 new cases, all through the real HTTP `/mcp` transport: - S1: on each of the five write/action tools, a listed 403 app-code refusal answers two blocks, `content[0]` is `{ code: PERMISSION_DENIED, declaredCode, status: 403 }` with no `details`, `content[1]` is the relay. Parity case: `mapDataError` and `actionsDoorAnswerOf` on the same throw serve `details.refusals` equal to the lines. Control: a gate-shaped throw (`PermissionDeniedError`, literal code, `details.positions` / `permissionSets`) answers one block on every tool, no `declaredCode`, and none of its details' text. - S2: a listed throw at 503 on `run_action` and `resume_run` answers one block, status 503, no `details`. - N1: `query_records`, `aggregate_records`, `get_record`, `get_record_context` and the `delete_records` outer catch each answer the relay, `content[0]` equal to the same throw without a list; `query_records` with an unknown field keeps `notRecorded` / `ifNotRecorded` beside the envelope and the relay after it. - N2: a `FLOW_FAILED` throw that is also listed answers three blocks in order: envelope, flow sentence, relay. - S3: `delete_records` over two rows refused by a six-line list (over 500 characters): one group, `reason` equal to the whole text, its lines the listed lines then the closing line; one content block. - The double gained an `asCatalogue` option (caller sentence = `userMessage`, the catalogue's real shape); the #37416 cases keep their old double unchanged. <details><summary>Package suite, typecheck, ablations (head 4682eb8)</summary> - `pnpm --filter @objectstack/mcp typecheck && pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2`, under the verify lock: `VERDICT command-exit 0`; Test Files 86 passed (86), Tests 1557 passed (1557) (1540 on main + 17); `check:test-typecheck: OK`. - Ablation S1 (`node scripts/ablation-replace.mjs`, anchor `PERMISSION_DENIED && served.declaredCode === undefined)` to the bare code check; blob 0754dee to 5fe5f300): 5 failed / 26 passed, the five per-tool 403 cases. Restored: blob equals HEAD, `git diff HEAD` empty. (A first attempt with a replacement that already occurred in the file was refused by the tool before any run: counted 5 to 5; re-run with a distinct marker.) - Ablation S2 (the `isServerFault` guard deleted; blob to fa47a2ee): 2 failed / 29 passed, the two 503 cases. Restored, `git diff HEAD` empty. - Ablation S1 on `/actions` (the `PERMISSION_DENIED` arm back to `codedErrorResult(envelope)`; blob to 4f91d8a8): 2 failed / 29 passed, the `run_action` / `resume_run` 403 cases. Restored, `git diff HEAD` empty. - The tests import `src/` relatively, so no rebuild was needed for the ablations. </details> ## Acceptance notes - Premise corrections, measured: S2's "a catalogue entry may declare a 5xx status" does not hold at authoring (`declaredRefusalEntrySchema` takes 400 to 499; the hook and action schema tests refuse 500 / 503); the arm is defence for a hand-built listed throw. S3's "keeps the cut sentence" does not hold for the catalogue's throw (see What changes); it held only for the #37416 test double, whose caller sentence is the bare code. - Not changed: `run_action` / `resume_run` still serve no `details` on any `PERMISSION_DENIED`, including the demoted 403, while REST `/actions` serves its `details.refusals`. The relay block now carries those lines, so nothing an agent needs is missing; widening `details` there is outside this card. - L2: the diff narrows a permission-keyed withholding guard, so `Security-touching` reads yes for the reviewer; no exposure found (the relay reads no `details`). ## Verification <details><summary>Derived gates (67), on 4682eb8</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` (3 paths vs merge base 54ea3c8): 67 derived; 66 exit 0. One NOT MEASURED: `pnpm check:dual-build-cjs-loads` exit 3 (PREREQUISITE NOT MET: needs the whole workspace built; CI Build Core runs it). - `--ran` reconciliation with exit codes recorded: 67 accounted, 66 run, 1 NOT-MEASURED (derived from the recorded exit 3), 0 UNRUN. - `node scripts/pm/overlap-check.mjs`: clean against origin/main and #37436. </details> CI check-runs are the authority for every family. Two-minute check: `pnpm --filter @objectstack/mcp exec vitest run --maxWorkers=2 src/mcp-refusal-reasons.test.ts`. Expect 31 passed. Read first: `withRefusalReasonsRelay` (the narrowed guard and its jsdoc), the `PERMISSION_DENIED` arm of `errorResultFromThrown`, and the parity case in the test file. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgVUz5oS8fMgmncxU96 <!-- signed: repo:objectstack#2 · os-sales · session_01L6bhgVUz5oS8fMgmncxU96 --> Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5dbcc02 commit 1af67b2

3 files changed

Lines changed: 251 additions & 16 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/mcp': patch
3+
---
4+
5+
Clause-②: no
6+
Metadata-protocol: none
7+
8+
MCP tools: a refusal an app declares at 403 now names its reasons to the agent.
9+
10+
A refusal with several declared reasons, thrown under the app's own code at `status: 403`, is served as
11+
`PERMISSION_DENIED` with the app's code in `declaredCode`, as every door demotes an unregistered code. The
12+
second text block that names every reason, whole and in order, was withheld for it, because the tools withheld
13+
the block on any `PERMISSION_DENIED`. They now withhold it only on the security gate's own refusal (a
14+
`PERMISSION_DENIED` with no `declaredCode`). Both REST doors already serve the same caller those lines as
15+
`details.refusals`. The gate's refusal is unchanged: no block, and none of its `details`.
16+
17+
The block's lead now reads "Tell the user every line below, whole and in this order, in place of userMessage:".
18+
It used to say the door "may have cut" the `userMessage`, which `run_action` and `resume_run` never cut.
19+
`delete_records` is unchanged: each refused group's `reason` already names every listed line whole, the
20+
closing line last.

‎packages/mcp/src/mcp-http-tools.ts‎

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1374,7 +1374,11 @@ function errorResultFromThrown(err: unknown, request: string, objectName?: strin
13741374
...(answer.declaredCode !== undefined ? { declaredCode: answer.declaredCode } : {}),
13751375
...(answer.userMessage !== undefined ? { userMessage: answer.userMessage } : {}),
13761376
};
1377-
if (answer.code === StandardErrorCode.enum.PERMISSION_DENIED) return codedErrorResult(envelope);
1377+
// [#37512] Its `details` stay withheld; a listed refusal an app declared at
1378+
// 403 still names its lines ({@link withRefusalReasonsRelay} says which).
1379+
if (answer.code === StandardErrorCode.enum.PERMISSION_DENIED) {
1380+
return withRefusalReasonsRelay(codedErrorResult(envelope), err, envelope);
1381+
}
13781382
// A fault (5xx) carries nothing but the door's sanitised answer: a thrown
13791383
// `details` rides only on a refusal, as `/actions` serves no producer
13801384
// context on a fault.
@@ -1397,7 +1401,7 @@ function errorResultFromThrown(err: unknown, request: string, objectName?: strin
13971401
* for the pin; not on the package entry.
13981402
*/
13991403
export const REFUSAL_REASONS_RELAY_LEAD =
1400-
'Tell the user every line below, whole and in this order, rather than a userMessage the door may have cut:\n';
1404+
'Tell the user every line below, whole and in this order, in place of userMessage:\n';
14011405

14021406
/**
14031407
* [#37416] A refusal thrown as a declared `reasons` list (#36877, ruling
@@ -1432,18 +1436,31 @@ export const REFUSAL_REASONS_RELAY_LEAD =
14321436
*
14331437
* ## When it is withheld
14341438
*
1435-
* - A `PERMISSION_DENIED` answer gets no block, as it gets no `details` (the
1436-
* ruling on #7450, {@link errorResultFromThrown}).
1437-
* - An answer that serves no `userMessage`, or a fault (5xx), gets none: the
1438-
* door decided that the marked sentence does not reach this caller, and the
1439-
* lines are that sentence.
1439+
* - [#37512] The security gate's own refusal gets no block: a served
1440+
* `PERMISSION_DENIED` with no `declaredCode` (the ruling on #7450,
1441+
* {@link errorResultFromThrown}). A refusal an app's catalogue declared at
1442+
* `403` under its own code is served as `PERMISSION_DENIED` too, the doors'
1443+
* demotion of an unregistered code, with that code in `declaredCode`; it
1444+
* gets the block. It is not the gate's refusal, and both REST doors serve
1445+
* its lines whole to the same caller as `details.refusals` (`mapDataError`,
1446+
* `thrownAnswerOf`). The relay never reads `details`, so the gate's
1447+
* `positions` and `permissionSets` reach it on no path, and the `details`
1448+
* withholding in {@link errorResultFromThrown} is unchanged.
1449+
* - An answer that serves no `userMessage` gets none: there is no sentence for
1450+
* the lines to stand in for.
1451+
* - A fault (5xx) gets none. The block's lines are a refusal's reasons, and a
1452+
* refusal catalogue declares only a 4xx (`declaredRefusalEntrySchema`,
1453+
* `@objectstack/spec`), so a listed throw at a 5xx is no catalogue refusal.
1454+
* The doors still serve its `userMessage` (and `/data` its
1455+
* `details.refusals`); this tool serves the `userMessage` in the envelope,
1456+
* and serves a fault no `details`.
14401457
*/
14411458
function withRefusalReasonsRelay<R extends { content: Array<{ type: 'text'; text: string }> }>(
14421459
result: R,
14431460
err: unknown,
1444-
served: { code?: string; status?: number; userMessage?: string },
1461+
served: { code?: string; status?: number; declaredCode?: string; userMessage?: string },
14451462
): R {
1446-
if (served.code === StandardErrorCode.enum.PERMISSION_DENIED) return result;
1463+
if (served.code === StandardErrorCode.enum.PERMISSION_DENIED && served.declaredCode === undefined) return result;
14471464
if (served.userMessage === undefined) return result;
14481465
if (served.status !== undefined && isServerFault(served.status)) return result;
14491466
const text = refusalReasonsRelayText(err);
@@ -2392,6 +2409,13 @@ interface DeleteEachOutcome {
23922409
*
23932410
* Measured on a booted stack: REST `DELETE` answers the sandboxed refusal
23942411
* `400 HOOK_ABORTED` and the code hook's bare throw `500 INTERNAL_ERROR`.
2412+
*
2413+
* [#37512] A refusal thrown as a declared `reasons` list needs no relay block
2414+
* here ({@link withRefusalReasonsRelay}). It is coded, so its `reason` is the
2415+
* thrown value's own sentence, never the door's 500-character cut: the
2416+
* runtime's refusal catalogue sets that sentence to the same text as
2417+
* `userMessage`, every listed line whole and in order, its closing line last.
2418+
* So the group already names each line as ruling 7178348458 term 3 asks.
23952419
*/
23962420
function rowRefusalOf(err: unknown, objectName: string): Omit<DeleteRefusalGroup, 'count' | 'recordIds'> | undefined {
23972421
const door = dataDoorAnswerOf(err, objectName);

‎packages/mcp/src/mcp-refusal-reasons.test.ts‎

Lines changed: 198 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,37 @@
3232
* #7450); a list the shared recogniser does not read gets none; a
3333
* `userMessage` that does not begin with the lines gets no invented closing
3434
* line.
35+
*
36+
* [#37512] The follow-ups:
37+
*
38+
* - The withholding's reach: the security gate's own refusal (a served
39+
* `PERMISSION_DENIED` with no `declaredCode`) gets no relay and serves none
40+
* of its `details`; a listed refusal an app declared at 403, which the doors
41+
* demote to `PERMISSION_DENIED` beside `declaredCode`, gets it. The parity
42+
* case reads both REST doors' own answer to that throw (`mapDataError`,
43+
* `actionsDoorAnswerOf`): each serves the same lines as `details.refusals`.
44+
* - A listed throw at a 5xx gets no relay (`run_action`, `resume_run`, the
45+
* only tools whose renderer reaches the relay on a fault).
46+
* - The record read tools and `delete_records`' outer catch, the not-recorded
47+
* members beside a relay, and a `FLOW_FAILED` throw that is also listed.
48+
* - `delete_records`' per-row groups name a listed refusal whole in `reason`
49+
* (the catalogue's caller sentence IS its `userMessage`, `asCatalogue`), so
50+
* they carry no relay block.
3551
*/
3652

3753
import { describe, it, expect } from 'vitest';
3854

55+
import { GET_RECORD_CONTEXT_TOOL_NAME } from '@objectstack/spec/ai';
56+
import { createRecordContextTools } from '@objectstack/service-record-context';
57+
import { actionsDoorAnswerOf, mapDataError } from '@objectstack/types';
58+
3959
import { MCPServerRuntime } from './mcp-server-runtime.js';
40-
import { REFUSAL_REASONS_RELAY_LEAD, type McpActionBridge, type McpDataBridge } from './mcp-http-tools.js';
60+
import {
61+
FLOW_FAILURE_RELAY_LEAD,
62+
REFUSAL_REASONS_RELAY_LEAD,
63+
type McpActionBridge,
64+
type McpDataBridge,
65+
} from './mcp-http-tools.js';
4166

4267
type Bridge = McpDataBridge & McpActionBridge;
4368

@@ -72,18 +97,30 @@ const TWO: Listed = {
7297
*/
7398
function listedRefusal(
7499
listed: Listed,
75-
opts: { withList?: boolean; code?: string; status?: number; userMessage?: string; refusals?: unknown } = {},
100+
opts: {
101+
withList?: boolean;
102+
code?: string;
103+
status?: number;
104+
userMessage?: string;
105+
refusals?: unknown;
106+
/** The caller sentence; the catalogue sets it to `userMessage` (`asCatalogue`). */
107+
innerMessage?: string;
108+
asCatalogue?: boolean;
109+
name?: string;
110+
details?: unknown;
111+
} = {},
76112
): () => Error {
77113
return () => {
78114
const userMessage = opts.userMessage ?? [...listed.lines.map((line) => line.message), listed.closing].join('\n');
79115
const err = Object.assign(new Error(`hook 'expense_submit_guard' threw: Error: ${CODE}`), {
80-
innerMessage: CODE,
116+
innerMessage: opts.innerMessage ?? (opts.asCatalogue ? userMessage : CODE),
81117
code: opts.code ?? CODE,
82118
status: opts.status ?? 400,
83119
userMessage,
120+
...(opts.details !== undefined ? { details: opts.details } : {}),
84121
...(opts.withList === false ? {} : { refusals: opts.refusals ?? listed.lines.map((line) => ({ ...line })) }),
85122
});
86-
err.name = 'SandboxError';
123+
err.name = opts.name ?? 'SandboxError';
87124
return err;
88125
};
89126
}
@@ -109,7 +146,7 @@ function refusingBridge(thrown: () => Error): Bridge {
109146
let nextId = 1;
110147

111148
/** One `tools/call` over the real HTTP transport; answers the parsed tool result. */
112-
async function callOverHttp(bridge: Bridge, name: string, args: Record<string, unknown>) {
149+
async function callOverHttp(bridge: Bridge, name: string, args: Record<string, unknown>, isError = true) {
113150
const body = { jsonrpc: '2.0', id: nextId++, method: 'tools/call', params: { name, arguments: args } };
114151
const runtime = new MCPServerRuntime({ name: 'pin', version: '0.0.0' });
115152
const res = await runtime.handleHttpRequest(
@@ -123,8 +160,8 @@ async function callOverHttp(bridge: Bridge, name: string, args: Record<string, u
123160
expect(res.status, `${name}: the HTTP transport itself answered ${res.status}`).toBe(200);
124161
const json = JSON.parse(await res.text()) as { result?: any; error?: unknown };
125162
expect(json.error, `${name}: JSON-RPC error ${JSON.stringify(json.error)}`).toBeUndefined();
126-
expect(json.result.isError, `${name}: not a tool error`).toBe(true);
127-
return json.result as { isError: true; content: Array<{ type: string; text: string }> };
163+
expect(json.result.isError === true, `${name}: isError`).toBe(isError);
164+
return json.result as { isError?: true; content: Array<{ type: string; text: string }> };
128165
}
129166

130167
/** The tools whose catch renders the door's `userMessage`, and which door that is. */
@@ -214,3 +251,157 @@ describe('MCP tools: a refusal with several declared reasons names every line, w
214251
expect(content[1].text).toBe(`${REFUSAL_REASONS_RELAY_LEAD}${LINE_ON_REPORT}\n${LINE_APPROVED}`);
215252
});
216253
});
254+
255+
/** The record read tools and `delete_records`' selection read: the refusal is thrown by the read. */
256+
function readRefusingBridge(thrown: () => Error): Bridge {
257+
return {
258+
...refusingBridge(thrown),
259+
async query() { throw thrown(); },
260+
async get() { throw thrown(); },
261+
async aggregate() { throw thrown(); },
262+
async getRecordContext() { throw thrown(); },
263+
recordContextToolDefinitions: () => createRecordContextTools().definitions,
264+
};
265+
}
266+
267+
/** The tools whose refusal the read throws, each rendered through the `/data` door's answer. */
268+
const READ_DOORS = [
269+
{ tool: 'query_records', args: { objectName: OBJECT } },
270+
{ tool: 'aggregate_records', args: { objectName: OBJECT, aggregations: [{ function: 'count', alias: 'n' }] } },
271+
{ tool: 'get_record', args: { objectName: OBJECT, recordId: RECORD_ID } },
272+
{ tool: GET_RECORD_CONTEXT_TOOL_NAME, args: { objectName: OBJECT, recordId: RECORD_ID } },
273+
// The selection read is the outer catch's coded throw.
274+
{ tool: 'delete_records', args: { objectName: OBJECT, recordIds: [RECORD_ID], confirm: true } },
275+
] as const;
276+
277+
describe('[#37512] the relay\'s reach: the security gate\'s own refusal is withheld, an app\'s 403 is not', () => {
278+
const appAt403 = listedRefusal(TWO, { status: 403, asCatalogue: true });
279+
280+
for (const door of DOORS) {
281+
it(`${door.tool} (${door.door}): a listed refusal an app declared at 403 names its lines; no details are served`, async () => {
282+
const { content } = await callOverHttp(refusingBridge(appAt403), door.tool, door.args);
283+
expect(content).toHaveLength(2);
284+
const envelope = JSON.parse(content[0].text);
285+
expect(envelope.error).toMatchObject({ code: 'PERMISSION_DENIED', declaredCode: CODE, status: 403 });
286+
expect(envelope.error.details).toBeUndefined();
287+
expect(content[1]).toEqual({ type: 'text', text: relayOf(TWO) });
288+
});
289+
}
290+
291+
it('parity: both REST doors serve the same caller every relayed line for that throw', () => {
292+
const data = mapDataError(appAt403(), OBJECT);
293+
expect(data.status).toBe(403);
294+
expect(data.body).toMatchObject({ code: 'PERMISSION_DENIED', declaredCode: CODE });
295+
expect((data.body.details as { refusals?: unknown }).refusals).toEqual(TWO.lines);
296+
297+
const actions = actionsDoorAnswerOf(appAt403(), OBJECT);
298+
expect(actions).toMatchObject({ status: 403, code: 'PERMISSION_DENIED', declaredCode: CODE });
299+
expect(actions.details?.refusals).toEqual(TWO.lines);
300+
// `/actions` serves userMessage uncut, so the closing line is served there too.
301+
const served = actions.userMessage!.split('\n');
302+
expect(served[served.length - 1]).toBe(CLOSING);
303+
304+
// Every line the relay names is one of those: nothing beyond what REST serves.
305+
const relayed = relayOf(TWO).slice(REFUSAL_REASONS_RELAY_LEAD.length).split('\n');
306+
expect(relayed).toEqual([...TWO.lines.map((line) => line.message), CLOSING]);
307+
});
308+
309+
it('control: the gate\'s own PERMISSION_DENIED (no declaredCode) gets no relay and serves none of its details', async () => {
310+
const gate = listedRefusal(TWO, {
311+
code: 'PERMISSION_DENIED',
312+
status: 403,
313+
name: 'PermissionDeniedError',
314+
details: { positions: ['pin37512_position'], permissionSets: ['pin37512_set'] },
315+
});
316+
for (const door of DOORS) {
317+
const { content } = await callOverHttp(refusingBridge(gate), door.tool, door.args);
318+
expect(content, door.tool).toHaveLength(1);
319+
const error = JSON.parse(content[0].text).error;
320+
expect(error.code, door.tool).toBe('PERMISSION_DENIED');
321+
expect(error.declaredCode, door.tool).toBeUndefined();
322+
expect(content[0].text, door.tool).not.toContain('pin37512_');
323+
}
324+
});
325+
});
326+
327+
describe('[#37512] a listed throw at a 5xx is a fault: no relay block', () => {
328+
for (const door of DOORS.filter((d) => d.door === '/actions')) {
329+
it(`${door.tool}: a listed throw at 503 answers the envelope alone`, async () => {
330+
const { content } = await callOverHttp(
331+
refusingBridge(listedRefusal(TWO, { status: 503, asCatalogue: true })), door.tool, door.args,
332+
);
333+
expect(content).toHaveLength(1);
334+
const error = JSON.parse(content[0].text).error;
335+
expect(error.status).toBe(503);
336+
expect(error.details).toBeUndefined();
337+
});
338+
}
339+
});
340+
341+
describe('[#37512] the record read tools and delete_records\' outer catch relay a listed refusal', () => {
342+
for (const door of READ_DOORS) {
343+
it(`${door.tool}: every line rides as a second text block; the envelope is unchanged`, async () => {
344+
const listed = await callOverHttp(readRefusingBridge(listedRefusal(TWO)), door.tool, door.args);
345+
const unlisted = await callOverHttp(readRefusingBridge(listedRefusal(TWO, { withList: false })), door.tool, door.args);
346+
expect(unlisted.content).toHaveLength(1);
347+
expect(listed.content).toHaveLength(2);
348+
expect(listed.content[0]).toEqual(unlisted.content[0]);
349+
expect(JSON.parse(listed.content[0].text).error).toMatchObject({ status: 400, declaredCode: CODE });
350+
expect(listed.content[1]).toEqual({ type: 'text', text: relayOf(TWO) });
351+
});
352+
}
353+
354+
it('query_records: the not-recorded members stay beside the envelope, and the relay still follows it', async () => {
355+
const { content } = await callOverHttp(
356+
readRefusingBridge(listedRefusal(TWO)), 'query_records', { objectName: OBJECT, fields: ['pin37512_missing'] },
357+
);
358+
expect(content).toHaveLength(2);
359+
const envelope = JSON.parse(content[0].text);
360+
expect(envelope.notRecorded).toEqual({ object: OBJECT, fields: ['pin37512_missing'] });
361+
expect(typeof envelope.ifNotRecorded).toBe('string');
362+
expect(content[1]).toEqual({ type: 'text', text: relayOf(TWO) });
363+
});
364+
});
365+
366+
describe('[#37512] a FLOW_FAILED throw that is also listed answers three blocks', () => {
367+
it('run_action: the envelope, then the flow sentence, then every listed line', async () => {
368+
const thrown = listedRefusal(TWO, {
369+
code: 'FLOW_FAILED',
370+
status: 400,
371+
asCatalogue: true,
372+
details: { errorMessage: 'pin37512 The approval flow refused the report.' },
373+
});
374+
const { content } = await callOverHttp(refusingBridge(thrown), 'run_action', DOORS[0].args);
375+
expect(content).toHaveLength(3);
376+
expect(JSON.parse(content[0].text).error.code).toBe('FLOW_FAILED');
377+
expect(content[1]).toEqual({ type: 'text', text: `${FLOW_FAILURE_RELAY_LEAD}pin37512 The approval flow refused the report.` });
378+
expect(content[2]).toEqual({ type: 'text', text: relayOf(TWO) });
379+
});
380+
});
381+
382+
describe('[#37512] delete_records: a row\'s listed refusal is named whole in its group, with no relay block', () => {
383+
it('a list longer than the door\'s 500-character cut: the group reason is every line whole, the closing line last', async () => {
384+
const lines = Array.from({ length: 6 }, (_, i) => ({
385+
reason: 'on_report',
386+
message: `pin37512 Expense line ${i + 1} (${'x'.repeat(90)}) is already on another report.`,
387+
}));
388+
const whole = [...lines.map((line) => line.message), CLOSING].join('\n');
389+
expect(whole.length).toBeGreaterThan(500);
390+
const bridge: Bridge = {
391+
...refusingBridge(listedRefusal({ lines, closing: CLOSING }, { asCatalogue: true })),
392+
async query() { return { object: OBJECT, records: [{ id: 'er_1' }, { id: 'er_2' }], total: 2 }; },
393+
};
394+
395+
const { content } = await callOverHttp(
396+
bridge, 'delete_records', { objectName: OBJECT, recordIds: ['er_1', 'er_2'], confirm: true }, false,
397+
);
398+
399+
expect(content).toHaveLength(1);
400+
const outcome = JSON.parse(content[0].text);
401+
expect(outcome).toMatchObject({ deleted: 0, refused: 2 });
402+
expect(outcome.refusals).toHaveLength(1);
403+
expect(outcome.refusals[0]).toMatchObject({ code: CODE, status: 400, count: 2, recordIds: ['er_1', 'er_2'] });
404+
expect(outcome.refusals[0].reason).toBe(whole);
405+
expect(outcome.refusals[0].reason.split('\n')).toEqual([...lines.map((line) => line.message), CLOSING]);
406+
});
407+
});

0 commit comments

Comments
 (0)