diff --git a/.changeset/28657-api-action-forward-denied-subject.md b/.changeset/28657-api-action-forward-denied-subject.md new file mode 100644 index 00000000000..8ecb0f68614 --- /dev/null +++ b/.changeset/28657-api-action-forward-denied-subject.md @@ -0,0 +1,16 @@ +--- +'@objectstack/runtime': patch +--- + +fix(runtime): a non-admin approver's decision from the request page reaches the approvals routes instead of answering 404 (#28657) + +Clause-②: yes (widening: on `POST /api/v1/actions/:object/:action` and MCP `run_action`, a same-origin `type: 'api'` action whose subject row the caller's own scope does not deliver, and whose request needs no field of that row, is forwarded and answers its target's answer where it answered `404 RECORD_NOT_FOUND`) +Metadata-protocol: none + +The request page's decision actions (`approval_approve`, `approval_reject`, `approval_comment`, `approval_request_info`, and the submitter's `approval_remind` / `approval_recall`) are same-origin `type: 'api'` actions that forward to the approvals routes (`/api/v1/approvals/requests/{id}/approve` and the rest). The action door loaded the `sys_approval_request` row in the caller's data scope first, and a member has no data-door read on that object by design, so every decision a non-admin sent from the page answered `404 RECORD_NOT_FOUND` before the approvals route, which admits a pending approver itself, was ever asked. + +- **Now.** When the caller-scope load does not deliver the row, a same-origin api action is forwarded anyway, and the door answers what the target answers: a pending approver's Approve answers 200 and the request moves; a member who is not on the slate gets the approvals route's own refusal. The target authorizes the caller with the caller's own credentials (ADR-0066 D4), the same request the caller could send it directly, so nothing new is disclosed. +- **⛔ No row data the caller could not read reaches the request.** On a denied load the request is built from the `recordId`, the params and the caller only. A declaration whose request needs a field of the row (a `{field}` path token other than `{id}`, or a `recordIdParam` read from a `recordIdField` other than `id`) keeps the `404 RECORD_NOT_FOUND`, and nothing is forwarded. +- **Unchanged.** The declarative update, `type: 'flow'` and script/body actions still refuse a denied load with `404 RECORD_NOT_FOUND` before anything trusted is built. The member data grant on `sys_approval_request` is not widened. +- **Both doors, one rule.** The REST `/actions` door and the MCP `run_action` bridge call one shared function at the same point (`refuseDeniedSubjectLoadBeforeDispatch`, with `apiForwardSubjectRecord` building the request's row). +- **The target's sentence is relayed.** A target that answers `{ code, error: '' }`, as the approvals decision routes do, now has that sentence relayed as the refusal's message (for example, which decision outputs are required to approve), where the door answered "its target answered HTTP 400". diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index ad1870a54d3..c122d823309 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -1980,8 +1980,15 @@ export function apiActionRefusalMembers(answer: ApiActionForwardAnswer): Record< */ export function apiActionForwardRefusal(action: any, answer: ApiActionForwardAnswer): Error { const body = answer.body; + // [#28657] Three places a target writes its sentence: the ADR-0112 + // envelope's `error.message`, a bare `message` (better-auth), and a bare + // STRING `error` beside a top-level `code` — the approvals decision routes' + // `{ code, error }`, whose prescription (which decision outputs are + // required to approve, why this actor may not decide) was replaced by the + // fallback below before this read it. const message: string = (body && typeof body === 'object' && typeof body.error?.message === 'string' && body.error.message) || + (body && typeof body === 'object' && typeof body.error === 'string' && body.error) || (body && typeof body === 'object' && typeof body.message === 'string' && body.message) || `Action '${action?.name ?? 'unknown'}' — its target answered HTTP ${answer.status}`; const code: string = @@ -3356,6 +3363,102 @@ export function refuseDeniedSubjectLoad( throw recordNotFoundError(objectName, recordId ?? ''); } +/** + * Contract point 3 as the two action doors' dispatch reads it, for every + * branch: {@link refuseDeniedSubjectLoad}, except for a same-origin + * `type: 'api'` forward that needs nothing from the row. + * + * ## Why the api forward is different + * + * The 404 exists so that nothing TRUSTED is built for a caller who has not + * shown read access to the subject row: the RLS/FLS-bypassing `ctx.engine` / + * `ctx.api` of a script body, a persisted flow run, a declarative write. An + * api forward builds none of those. It hands its declared `target` the + * caller's OWN credentials, and the target authorizes the caller itself + * (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 + * 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. + * + * ## ⛔ No row data the caller could not read reaches the request + * + * On a denied load the request is built from the `recordId`, the params and + * the caller only ({@link apiForwardSubjectRecord}). A declaration whose + * request needs a field OF the row ({@link apiActionRequestReadsSubjectRow}) + * cannot be built from those, so it keeps today's 404 `RECORD_NOT_FOUND`. + * + * Every other branch — the declarative update, the flow dispatch, the + * script/body dispatch — keeps the refusal unchanged. Both doors call this + * ONE function at the same point (the REST `/actions` door and the MCP + * `run_action` bridge), so the rule cannot hold at one and not the other. + */ +export function refuseDeniedSubjectLoadBeforeDispatch( + action: any, + objectName: string, + recordId: string | undefined, + subject: ActionSubjectRecordLoad, +): void { + if (subject.recordLoadDenied && forwardsOnDeniedSubjectLoad(action)) return; + refuseDeniedSubjectLoad(objectName, recordId, subject); +} + +/** + * Does a denied subject load still forward this action? Exactly a same-origin + * `type: 'api'` action (the doors refuse an off-origin one earlier) whose + * request can be built without the row. A declarative update is never one, + * whatever its `type` says: `operation` before `type`. + */ +export function forwardsOnDeniedSubjectLoad(action: any): boolean { + return !isDeclarativeUpdateAction(action) + && action?.type === 'api' + && isSameOriginApiTarget(action?.target) + && !apiActionRequestReadsSubjectRow(action); +} + +/** + * Does this api action's request need a field OF the subject row — beyond the + * `id` the caller already named? Two places in the declaration read the row + * ({@link buildApiActionRequest}): a `{field}` path token in `target`, and a + * `recordIdParam` seeded from a `recordIdField`. `{id}` and a `recordIdField` + * of `id` (the default) are the routed `recordId` itself, so they do not. + * + * Read off the declaration, before any substitution: a token that only looks + * like a field (a `${name}` with no scope the substitution leaves in place) + * counts as one, which errs toward the 404, never toward a forward. + */ +export function apiActionRequestReadsSubjectRow(action: any): boolean { + const target: string = typeof action?.target === 'string' ? action.target : ''; + for (const match of target.matchAll(/\{([a-z_][a-z0-9_]*)\}/gi)) { + if (match[1] !== 'id') return true; + } + const recordIdParam = typeof action?.recordIdParam === 'string' && action.recordIdParam ? action.recordIdParam : undefined; + if (recordIdParam) { + const field: string = typeof action?.recordIdField === 'string' && action.recordIdField ? action.recordIdField : 'id'; + if (field !== 'id') return true; + } + return false; +} + +/** + * The subject row an api forward's request is built from. A row the caller's + * own scope delivered, as it was; on a denied load, `{ id: recordId }` and + * nothing else — built from the id the caller named, ⛔ never from whatever + * the load left behind, so no field of a row the caller could not read can + * reach the request. + */ +export function apiForwardSubjectRecord( + recordId: string | undefined, + subject: ActionSubjectRecordLoad, +): Record { + if (!subject.recordLoadDenied) return subject.record; + return recordId ? { id: recordId } : {}; +} + /** * [#15079] The prior/next value pair a successful declarative update hands back * when the action declares `undoable: true` — the anchor that key never had. @@ -3867,7 +3970,11 @@ async function dispatchAdmittedBusinessAction(deps: ActionExecutionDeps, // persisted automation run exists and no trusted body has been entered // when the refusal lands. `ok: true` on a row the caller cannot read is // the defect; refusing after the run was created would only describe it. - refuseDeniedSubjectLoad(objectName, recordId, subject); + // + // [#28657] Except ahead of an api forward that needs nothing from the row + // (`refuseDeniedSubjectLoadBeforeDispatch`): the target authorizes the + // caller itself. The REST `/actions` door calls the same function. + refuseDeniedSubjectLoadBeforeDispatch(action, objectName, recordId, subject); // ── api forward (#27506) ── a same-origin `type: 'api'` action is // forwarded in-process to its declared `target` with the caller's own @@ -3889,7 +3996,7 @@ async function dispatchAdmittedBusinessAction(deps: ActionExecutionDeps, code: standardErrorCodeForHttpStatus(503), status: 503, }); } - const built = buildApiActionRequest(action, { recordId, record, params, ec }); + const built = buildApiActionRequest(action, { recordId, record: apiForwardSubjectRecord(recordId, subject), params, ec }); if ('message' in built) { throw Object.assign(new Error(built.message), { code: standardErrorCodeForHttpStatus(built.status), status: built.status }); } diff --git a/packages/runtime/src/domains/actions.ts b/packages/runtime/src/domains/actions.ts index 23767580554..a762e11688a 100644 --- a/packages/runtime/src/domains/actions.ts +++ b/packages/runtime/src/domains/actions.ts @@ -879,7 +879,13 @@ async function dispatchAdmittedRestAction( // audit line and the RLS/FLS-bypassing `ctx.engine` / `ctx.api` are // built below, and none of them may exist for a caller who has not // demonstrated read access to the subject row. - actionExec.refuseDeniedSubjectLoad(objectName, recordId, subject); + // + // [#28657] Except ahead of an api forward that needs nothing from the + // row: it builds none of that, and its target authorizes the caller + // itself (ADR-0066 D4), so a denied load forwards and the target's + // answer is this door's — see `refuseDeniedSubjectLoadBeforeDispatch`. + // The MCP `run_action` bridge calls the same function at the same point. + actionExec.refuseDeniedSubjectLoadBeforeDispatch(actionDef, objectName, recordId, subject); // ── api forward (#27506, ruling 6499781492) ── a same-origin // `type: 'api'` action is forwarded IN-PROCESS to its declared @@ -903,7 +909,11 @@ async function dispatchAdmittedRestAction( if (!inject) { return { handled: true, response: deps.error(actionExec.apiActionForwardUnavailableError(actionDef), 503) }; } - const built = actionExec.buildApiActionRequest(actionDef, { recordId, record, params: reqParams, ec }); + // [#28657] On a denied load the request is built from the + // `recordId` alone — ⛔ never from a row the caller could not read. + const built = actionExec.buildApiActionRequest(actionDef, { + recordId, record: actionExec.apiForwardSubjectRecord(recordId, subject), params: reqParams, ec, + }); if ('message' in built) { return { handled: true, response: deps.error(built.message, built.status) }; } diff --git a/packages/runtime/src/domains/api-action-forward.test.ts b/packages/runtime/src/domains/api-action-forward.test.ts index 9e30954c114..5f309e576b6 100644 --- a/packages/runtime/src/domains/api-action-forward.test.ts +++ b/packages/runtime/src/domains/api-action-forward.test.ts @@ -31,6 +31,9 @@ import { HttpDispatcher } from '../http-dispatcher.js'; import type { HttpProtocolContext } from '../http-dispatcher.js'; import { invokeBusinessAction, + apiActionRequestReadsSubjectRow, + apiForwardSubjectRecord, + forwardsOnDeniedSubjectLoad, apiActionResultOf, buildApiActionRequest, isHeadlessInvokableAction, @@ -81,6 +84,21 @@ const APPROVE_LEAD = { ai: { exposed: true, description: 'Approve the lead.' }, }; +/** + * [#28657] An api action whose request needs a field OF the subject row: a + * `{field}` path token other than `{id}`. + */ +const NOTE_OWNER = { + name: 'note_owner', label: 'Note Owner', objectName: OBJECT, type: 'api', method: 'POST', + target: '/api/v1/data/crm_note/{email}', ai: { exposed: true, description: 'Note the owner.' }, +}; +/** [#28657] The other one: a `recordIdParam` seeded from a `recordIdField` other than `id`. */ +const FLAG_BY_EMAIL = { + name: 'flag_by_email', label: 'Flag', objectName: OBJECT, type: 'api', method: 'POST', + target: '/api/v1/data/crm_flag', recordIdParam: 'email', recordIdField: 'email', + ai: { exposed: true, description: 'Flag the lead by email.' }, +}; + type Injected = { url: string; init: RequestInit }; function boot(opts: { @@ -104,7 +122,7 @@ function boot(opts: { }); const server = { getRawApp: () => ({ request }) }; const executeAction = vi.fn(async () => ({ ran: 'script' })); - const objectDef = { name: OBJECT, actions: [BAN_LEAD, REMOTE_PING, DELETE_LEAD, RECALC_LEAD, APPROVE_LEAD] }; + const objectDef = { name: OBJECT, actions: [BAN_LEAD, REMOTE_PING, DELETE_LEAD, RECALC_LEAD, APPROVE_LEAD, NOTE_OWNER, FLAG_BY_EMAIL] }; const ql: any = { executeAction, getSchema: (name: string) => (name === OBJECT ? objectDef : undefined), @@ -1162,3 +1180,165 @@ describe('[ADR-0090 D10 rule 5, #28367] the two flipped cells: an OAuth agent is expect(sent[FORWARD_CREDENTIAL_HEADER]).toBeUndefined(); }); }); + +// [#28657] A same-origin api action's target authorizes the caller itself +// (ADR-0066 D4), so a subject row the caller's own scope did not deliver no +// longer answers the door's own 404 ahead of the forward: the door forwards +// and answers what the target answers. The real-stack half — a non-admin +// pending approver's decision from the request page, on the real approvals +// routes — is `packages/verify/src/action-door-api-forward-denied-subject.test.ts`. +// The branches that keep the 404 on a denied load (flow, script/body, and the +// declarative update) stay pinned in `../action-door-record-load-denied.test.ts` +// and `../http-dispatcher.actions-type-dispatch.test.ts`. +describe('[#28657] a denied subject load forwards an api action whose request needs nothing from the row', () => { + /** An id the fake data layer delivers no row for: the caller-scope load is denied. */ + const HIDDEN = 'areq_hidden'; + const runViaMcp = async (h: ReturnType, name: string, input: any = {}) => { + const deps: any = { + resolveService: async (_ctx: unknown, service: string) => + service === 'metadata' ? h.metadata + : service === 'automation' ? null + : service === 'http.server' ? { getRawApp: () => ({ request: h.request }) } + : h.ql, + getObjectQL: async () => h.ql, + }; + return invokeBusinessAction(deps, CTX() as any, name, input, { + driver: h.ql, + ec: { userId: 'u_agent', tenantId: 'org_1', systemPermissions: [] }, + getMeta: () => h.metadata, + // The caller's scope delivers nothing for HIDDEN: the data layer's 404. + callData: async (_a: string, p: any) => { + if (p?.id === HIDDEN) throw Object.assign(new Error('not found'), { status: 404, code: 'RECORD_NOT_FOUND' }); + return { object: p?.object, id: p?.id, record: { id: p?.id, email: 'target@example.test' } }; + }, + }); + }; + + it('REST: the approve shape on a row the caller cannot read is forwarded, and the target\'s 200 is the answer', async () => { + const { dispatcher, injected } = boot({ answer: { body: { success: true, data: { request: { id: HIDDEN } } } } }); + + const res = await dispatcher.handleActions( + `/${OBJECT}/${APPROVE_LEAD.name}`, 'POST', { recordId: HIDDEN, params: { comment: 'ok' } }, CTX(), + ); + + expect(statusOf(res), JSON.stringify(res?.response?.body)).toBe(200); + expect(injected).toHaveLength(1); + expect(injected[0].url).toBe(`http://app.example.test/api/v1/approvals/requests/${HIDDEN}/approve`); + expect(JSON.parse(String(injected[0].init.body))).toEqual({ comment: 'ok' }); + expect(headersOf(injected[0].init).authorization).toBe('Bearer tok_member'); + expect(res?.response?.body?.data).toEqual({ request: { id: HIDDEN } }); + }); + + it('REST: the target\'s refusal is the answer — its status, its code, and its `{ code, error }` sentence', async () => { + // The approvals decision routes answer `{ code, error: '' }`. + const sentence = "actor 'u_member' is not a pending approver"; + const { dispatcher, injected } = boot({ answer: { status: 403, body: { code: 'FORBIDDEN', error: sentence } } }); + + const res = await dispatcher.handleActions(`/${OBJECT}/${APPROVE_LEAD.name}`, 'POST', { recordId: HIDDEN }, CTX()); + + expect(injected).toHaveLength(1); + expect(statusOf(res)).toBe(403); + expect(codeOf(res)).toBe('FORBIDDEN'); + expect(messageOf(res)).toBe(sentence); + }); + + it('REST: a `recordIdParam` read from `id` is seeded from the routed id alone', async () => { + const { dispatcher, injected } = boot(); + + const res = await dispatcher.handleActions(`/${OBJECT}/${RECALC_LEAD.name}`, 'POST', { recordId: HIDDEN }, CTX()); + + expect(statusOf(res), JSON.stringify(res?.response?.body)).toBe(200); + expect(JSON.parse(String(injected[0].init.body))).toEqual({ recordId: HIDDEN }); + }); + + it('REST: an api action whose request needs a field OF the row keeps the 404 RECORD_NOT_FOUND, and nothing is forwarded', async () => { + for (const action of [NOTE_OWNER, FLAG_BY_EMAIL]) { + const { dispatcher, request } = boot(); + + const res = await dispatcher.handleActions(`/${OBJECT}/${action.name}`, 'POST', { recordId: HIDDEN }, CTX()); + + expect(statusOf(res), action.name).toBe(404); + expect(codeOf(res), action.name).toBe('RECORD_NOT_FOUND'); + expect(request, action.name).not.toHaveBeenCalled(); + } + }); + + it('REST, the firing control: the same two actions on a row the caller CAN read are forwarded with the row\'s field', async () => { + const note = boot(); + expect(statusOf(await note.dispatcher.handleActions(`/${OBJECT}/${NOTE_OWNER.name}`, 'POST', { recordId: 'u_target' }, CTX()))).toBe(200); + expect(note.injected[0].url).toBe('http://app.example.test/api/v1/data/crm_note/target%40example.test'); + + const flag = boot(); + expect(statusOf(await flag.dispatcher.handleActions(`/${OBJECT}/${FLAG_BY_EMAIL.name}`, 'POST', { recordId: 'u_target' }, CTX()))).toBe(200); + expect(JSON.parse(String(flag.injected[0].init.body))).toEqual({ email: 'target@example.test' }); + }); + + it('REST: a target\'s 400 prescription in `{ code, error }` is relayed, not replaced by "its target answered HTTP 400"', async () => { + const sentence = 'decision output(s) `amount` are required to approve this step'; + const { dispatcher } = boot({ answer: { status: 400, body: { code: 'VALIDATION_FAILED', error: sentence } } }); + + const res = await dispatcher.handleActions(`/${OBJECT}/${APPROVE_LEAD.name}`, 'POST', { recordId: 'u_target' }, CTX()); + + expect(statusOf(res)).toBe(400); + expect(codeOf(res)).toBe('VALIDATION_FAILED'); + expect(messageOf(res)).toBe(sentence); + }); + + it('MCP `run_action`: the same approve shape on a row the caller cannot read is forwarded and succeeds', async () => { + const h = boot({ answer: { body: { success: true, data: { request: { id: HIDDEN } } } } }); + + const result: any = await runViaMcp(h, APPROVE_LEAD.name, { recordId: HIDDEN, params: { comment: 'ok' } }); + + expect(result.ok).toBe(true); + expect(result.result).toEqual({ request: { id: HIDDEN } }); + expect(h.injected[0].url).toBe(`http://app.example.test/api/v1/approvals/requests/${HIDDEN}/approve`); + expect(JSON.parse(String(h.injected[0].init.body))).toEqual({ comment: 'ok' }); + }); + + it('MCP `run_action`: a request that needs a field OF the row is thrown the 404 RECORD_NOT_FOUND, and nothing is forwarded', async () => { + for (const action of [NOTE_OWNER, FLAG_BY_EMAIL]) { + const h = boot(); + + const thrown = await runViaMcp(h, action.name, { recordId: HIDDEN }).catch((e) => e); + + expect((thrown as any).status ?? (thrown as any).statusCode, action.name).toBe(404); + expect((thrown as any).code, action.name).toBe('RECORD_NOT_FOUND'); + expect(h.request, action.name).not.toHaveBeenCalled(); + } + }); + + it('MCP `run_action`: the target\'s `{ code, error }` sentence rides the throw', async () => { + const sentence = 'decision output(s) `amount` are required to approve this step'; + const h = boot({ answer: { status: 400, body: { code: 'VALIDATION_FAILED', error: sentence } } }); + + const thrown = await runViaMcp(h, APPROVE_LEAD.name, { recordId: HIDDEN }).catch((e) => e); + + expect((thrown as any).status).toBe(400); + expect((thrown as any).code).toBe('VALIDATION_FAILED'); + expect(String(thrown.message)).toBe(sentence); + }); + + it('the shared helpers: which declarations read the row, and the row a denied load builds from', () => { + expect(apiActionRequestReadsSubjectRow(APPROVE_LEAD)).toBe(false); + expect(apiActionRequestReadsSubjectRow(RECALC_LEAD)).toBe(false); + expect(apiActionRequestReadsSubjectRow(BAN_LEAD)).toBe(false); + expect(apiActionRequestReadsSubjectRow(DELETE_LEAD)).toBe(false); + expect(apiActionRequestReadsSubjectRow(NOTE_OWNER)).toBe(true); + expect(apiActionRequestReadsSubjectRow(FLAG_BY_EMAIL)).toBe(true); + expect(apiActionRequestReadsSubjectRow({ ...APPROVE_LEAD, target: '/api/v1/x/{id}/{status}' })).toBe(true); + + expect(forwardsOnDeniedSubjectLoad(APPROVE_LEAD)).toBe(true); + expect(forwardsOnDeniedSubjectLoad(NOTE_OWNER)).toBe(false); + expect(forwardsOnDeniedSubjectLoad(REMOTE_PING)).toBe(false); + expect(forwardsOnDeniedSubjectLoad({ name: 'run_it', type: 'flow', target: 'some_flow' })).toBe(false); + expect(forwardsOnDeniedSubjectLoad({ name: 'go', type: 'script' })).toBe(false); + // `operation` before `type`: a declarative update is never forwarded. + expect(forwardsOnDeniedSubjectLoad({ ...APPROVE_LEAD, operation: 'update', patch: { done: true } })).toBe(false); + + // ⛔ Whatever a denied load left behind, the request sees the routed id only. + const leftover = { record: { id: HIDDEN, email: 'secret@example.test' }, recordLoadDenied: true }; + expect(apiForwardSubjectRecord(HIDDEN, leftover)).toEqual({ id: HIDDEN }); + const delivered = { record: { id: 'u_target', email: 'target@example.test' }, recordLoadDenied: false }; + expect(apiForwardSubjectRecord('u_target', delivered)).toBe(delivered.record); + }); +}); 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 new file mode 100644 index 00000000000..6bfe0a75b8a --- /dev/null +++ b/packages/verify/src/action-door-api-forward-denied-subject.test.ts @@ -0,0 +1,222 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A pending approver decides from the request page: the approval actions + * through `POST /api/v1/actions/sys_approval_request/:action`, on a booted + * stack — the real dispatcher, the real approvals service and its real + * decision routes, the real in-process forward. No fetch is doubled. + * + * 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 + * 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. + * + * What is pinned, each against what only the real stack produces: + * - the control: the approver cannot read the request row through the data + * door, so every answer below is the forward's, not a widened grant's; + * - the approver's Approve through the action door answers 200, and the + * request MOVES: one of two approvals recorded, the approver off + * `pending_approvers`, an `approve` row in the request's actions; + * - a member who is NOT on the slate meets the approvals door's own refusal + * (the same status and code the decision route answers them directly), + * never a 200, never the row; + * - the decision route's refusal sentence is relayed, not replaced by + * "its target answered HTTP N". + * + * ⚠️ This suite resolves `@objectstack/runtime` and + * `@objectstack/plugin-approvals` through their BUILT `dist/`. Rebuild + * runtime before trusting a run of this file — and especially an ablated one. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; + +import { defineStack, defineFlow } from '@objectstack/spec'; +import { ObjectSchema, Field } from '@objectstack/spec/data'; + +import { bootStack, type VerifyStack } from './harness.js'; +import { warmUpBoot } from './boot-warm-up.testkit.js'; + +// Booting the full in-process stack runs well past vitest's 5s default. +const BOOT_TIMEOUT = 120_000; + +// The boot's first load, paid during collection rather than in the +// `beforeAll` below (see `boot-warm-up.testkit.ts`): the same options and the +// same `requires` as this file's own boot. +await warmUpBoot({ automation: true }, { requires: ['automation', 'triggers', 'approvals'] }); + +const OBJECT = 'afd_invoice'; +const SYS = { isSystem: true } as const; + +/** The step's slate, both by email: `unanimous`, so one approval is 1 of 2. */ +const FIRST = 'afd-first@verify.test'; +const SECOND = 'afd-second@verify.test'; +/** On no slate. */ +const STRANGER = 'afd-stranger@verify.test'; + +const Invoice = ObjectSchema.create({ + name: OBJECT, + label: 'Invoice', + pluralLabel: 'Invoices', + sharingModel: 'private', + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); + +const flow = defineFlow({ + name: `${OBJECT}_signoff`, + label: 'Invoice Dual Sign-off', + description: 'Fires on insert and waits on both approvers, unanimously.', + type: 'autolaunched', + status: 'active', + nodes: [ + { id: 'start', type: 'start', label: 'On Create', config: { objectName: OBJECT, triggerType: 'record-after-create' } }, + { + id: 'signoff', + type: 'approval', + label: 'Sign-off', + config: { + approvers: [{ type: 'user', value: FIRST }, { type: 'user', value: SECOND }], + behavior: 'unanimous', + lockRecord: false, + }, + }, + { id: 'approved', type: 'end', label: 'Approved' }, + { id: 'rejected', type: 'end', label: 'Rejected' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'signoff' }, + { id: 'e2', source: 'signoff', target: 'approved', label: 'approve' }, + { id: 'e3', source: 'signoff', target: 'rejected', label: 'reject' }, + ], +}); + +const fixtureStack = defineStack({ + manifest: { + id: 'com.objectstack.verify.action-door-api-forward-denied-subject', + namespace: 'afd', + version: '0.0.0', + type: 'app', + name: 'Action Door Api Forward Denied Subject Fixture', + description: 'One private object and a two-approver unanimous sign-off flow on it.', + }, + // ADR-0097: the `record-after-create` start node needs the trigger + // capability; `approvals` mounts the approvals service and its decision + // routes, the providers `objectstack serve` mounts for these tokens. + requires: ['automation', 'triggers', 'approvals'], + objects: [Invoice], + flows: [flow], +}); + +type Answer = { status: number; text: string; json: any }; + +let stack: VerifyStack; +let admin: string; +let first: string; +let firstId: string; +let stranger: string; +let ql: any; + +const call = async (token: string, method: string, path: string, body?: unknown): Promise => { + const res = await stack.apiAs(token, method, path, body); + const text = await res.text(); + let json: any; + try { json = JSON.parse(text); } catch { json = undefined; } + return { status: res.status, text, json }; +}; + +/** Open one request: the admin creates an invoice, the flow opens the step. */ +const openRequest = async (name: string): Promise => { + const created = await call(admin, 'POST', `/data/${OBJECT}`, { name }); + expect(created.status, created.text).toBe(201); + const recordId = String(created.json?.id ?? created.json?.record?.id ?? ''); + const rows = await ql.find('sys_approval_request', { + where: { object_name: OBJECT, record_id: recordId, status: 'pending' }, context: SYS, + }); + expect(rows, `the flow opened a request for ${name}`).toHaveLength(1); + return String(rows[0].id); +}; + +const requestRow = async (id: string): Promise => + ql.findOne('sys_approval_request', { where: { id }, context: SYS }); +const approveRows = async (id: string): Promise => + ql.find('sys_approval_action', { where: { request_id: id, action: 'approve' }, context: SYS }); +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 }); + 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. + first = await stack.signUp(FIRST); + await stack.signUp(SECOND); + stranger = await stack.signUp(STRANGER); + firstId = String((await ql.findOne('sys_user', { where: { email: FIRST }, context: SYS }))?.id ?? ''); + expect(firstId).not.toBe(''); +}, BOOT_TIMEOUT); + +afterAll(async () => { + await stack?.stop().catch(() => undefined); +}); + +describe('a pending approver decides through the action door — the forward authorizes, not the data door', () => { + it('the control: the approver cannot read the request row through the data door', async () => { + 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. + 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'); + }); + + it('Approve answers 200 and the request moves: 1 of 2, the approver off the slate, an approve row', async () => { + const requestId = await openRequest('INV-1'); + expect(await approveRows(requestId)).toEqual([]); + expect(pendingOf(await requestRow(requestId))).toEqual([FIRST, SECOND]); + + const answer = await call(first, 'POST', '/actions/sys_approval_request/approval_approve', { + recordId: requestId, params: { comment: 'Looks right.' }, + }); + + expect(answer.status, answer.text).toBe(200); + const row = await requestRow(requestId); + expect(row.status).toBe('pending'); + expect(pendingOf(row)).toEqual([SECOND]); + const approvals = await approveRows(requestId); + expect(approvals).toHaveLength(1); + expect(approvals[0].actor_id).toBe(firstId); + expect(approvals[0].comment).toBe('Looks right.'); + // The decision route's own read-back, as the approver reads it. + const served = await call(first, 'GET', `/approvals/requests/${requestId}`); + expect(served.status, served.text).toBe(200); + const progress = (served.json?.data ?? served.json)?.decision_progress; + expect(progress).toMatchObject({ behavior: 'unanimous', got: 1, need: 2 }); + }); + + it('a member on no slate gets the decision route\'s own refusal through the door — never a 200, never the row', async () => { + const requestId = await openRequest('INV-2'); + + const direct = await call(stranger, 'POST', `/approvals/requests/${requestId}/approve`, {}); + const viaDoor = await call(stranger, 'POST', '/actions/sys_approval_request/approval_approve', { + recordId: requestId, params: {}, + }); + + expect(direct.status, direct.text).toBeGreaterThanOrEqual(400); + expect(viaDoor.status, viaDoor.text).toBe(direct.status); + expect(viaDoor.json?.success).toBe(false); + expect(viaDoor.json?.error?.code).toBe(direct.json?.code); + // The route's own sentence, relayed — not "its target answered HTTP N". + expect(viaDoor.json?.error?.message).toBe(direct.json?.error); + expect(viaDoor.text).not.toContain('its target answered HTTP'); + expect(viaDoor.text).not.toContain('INV-2'); + // Nothing moved. + expect(await approveRows(requestId)).toEqual([]); + expect(pendingOf(await requestRow(requestId))).toEqual([FIRST, SECOND]); + }); +});