diff --git a/.changeset/approval-payload-read-time-redaction.md b/.changeset/approval-payload-read-time-redaction.md new file mode 100644 index 00000000000..fef5dd81d03 --- /dev/null +++ b/.changeset/approval-payload-read-time-redaction.md @@ -0,0 +1,64 @@ +--- +"@objectstack/plugin-approvals": patch +--- + +Apply the subject object's field-level read controls to the approval payload +snapshot at serve time (#10749), so an approver no longer receives fields the +app author declared they may not read. + +`sys_approval_request.payload_json` stores the submitted record's raw row, +captured from the flow's `$record` variable — which the automation layer hands +over with the record's own FLS never applying. The column is a `textarea` on +`sys_approval_request`, so to every read door it is an opaque string: the +field-visibility machinery governs *columns of objects* and cannot see inside a +JSON column. Every field-level read control declared on the SUBJECT object — +`requiredPermissions` (ADR-0066 D3), a permission set marking a field +non-readable, a `maskingRule` — was therefore unenforceable on the approval +path, for every app. + +Per the maintainer's ruling (2026-08-22, Option B) the full snapshot **stays at +rest**: the approval record remains audit evidence of what was actually +submitted, which write-time trimming would have given away. Redaction happens at +**serve** time, keyed on the reading caller, so the same row answers an admin +with the whole snapshot and a restricted approver with only the fields they may +read. The readable set is not recomputed — it comes from the security service's +`getReadableFields`, documented as the same field mask the read middleware +applies, so this seam cannot drift from data-plane FLS. + +Two doors are covered, because `payload_json` has two independent readers and a +seam covering one manufactures the belief that the path is masked: + +- the **service door** (`getRequest` / `listRequests`, behind + `GET /api/v1/approvals/requests[/:id]`), which serves the parsed `payload`. + Redaction runs BEFORE display enrichment, so `payload_display` and + `payload_labels` — both built by walking the snapshot's own keys — cannot ship + a restricted field's name, its authored label, or the title of the record it + points at; +- the **generic data door**: the object declares + `enable.apiMethods: ['get','list']`, so a plain `find`/`findOne` returns the + raw string without the service ever running. Covered by object-scoped engine + middleware, which reaches the whole family sharing that producer (REST data + routes, ObjectQL, CSV/XLSX export, MCP). Middleware rather than an `afterFind` + hook on purpose: a hook receives `buildSession`'s output, which carries no + `onBehalfOf`, so a hook-based seam would drop the ADR-0090 D10 delegator + intersection and answer a delegated read more permissively than the service. + +**Behaviour change, argued rather than assumed.** A non-admin caller that was +reading restricted keys out of the snapshot now receives fewer keys, and that is +a real change for such a consumer. It is shipped as a fix rather than a breaking +change because those fields were never that caller's to read: the approval path +was a bypass of a declaration the platform enforces everywhere else, and the +served type is `payload?: unknown` — never a promised field set. This follows the +`__search` companion strip (#7642), which shipped the same way on the same +reasoning. Object-level access is deliberately untouched: an approver commonly +holds no read grant on the object under approval at all, and +`getReadableFields` answers a caller with no field-permission entries with the +full set, so every approval drawer shipping today keeps rendering. + +`hidden: true` is deliberately NOT acted on. It is a UI contract ("Hidden from +default UI") which, in the spec's own words, "has never governed serialization" +— measurably: no read path in the repo strips a value on it. Enforcing it here +alone would make the approval path stricter than a direct read of the same row +(closing no leak, since the approver can simply read the record) while breaking +drawers that render a `hidden` business column. That is a `packages/spec` +semantics question and is left open. diff --git a/packages/plugins/plugin-approvals/src/approval-payload-redaction.test.ts b/packages/plugins/plugin-approvals/src/approval-payload-redaction.test.ts new file mode 100644 index 00000000000..85121a40fd8 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-payload-redaction.test.ts @@ -0,0 +1,357 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Read-time redaction of the approval payload snapshot (#10749). + * + * ## What is being pinned, and why each direction is load-bearing + * + * The maintainer ruled Option B on 2026-08-22: the full snapshot stays AT REST + * in `sys_approval_request.payload_json` (so the approval record still proves + * what was actually submitted), and redaction happens at SERVE time, keyed on + * the reading caller. Three of the four directions below exist because a + * plausible wrong implementation scores green without them: + * + * 1. **leak closed** — a non-admin approver does not receive the + * FLS-restricted keys. Asserted BY NAME, not by shape: a shape assertion + * ("payload has 4 keys") passes against a redactor that removed the wrong + * four. + * 2. **audit preserved** — the stored column still holds the whole row. A + * write-time TRIM would pass a leak-only suite while silently taking + * Option A, the option the maintainer declined. This is asserted against + * the table, separately from anything served. + * 3. **still-served** — the approver still receives the business fields the + * drawer renders. A seam that redacted everything would also score green + * on a leak-only suite, and would break every approval drawer shipping + * today. + * 4. **admin unchanged** — a caller who may read every field still gets the + * whole snapshot. This is what makes the change read-time MASKING rather + * than trimming; without it (2) and (3) can both hold while the feature is + * really a trim with an exception list. + * + * ## Both doors, each with its own assertion + * + * `payload_json` has two independent read doors, and one pin does not stand for + * the other: + * + * - **the service door** — `ApprovalService.getRequest` / `listRequests`, + * behind `GET /api/v1/approvals/requests[/:id]`, which serve the PARSED + * `payload` (plus `payload_display` / `payload_labels` derived from its + * keys); + * - **the generic data door** — the object declares + * `enable.apiMethods: ['get','list']`, so a plain `find`/`findOne` on + * `sys_approval_request` returns the RAW `payload_json` string without the + * service ever running. Registering at the engine covers the whole family + * that shares that producer (REST data routes, ObjectQL, CSV/XLSX export, + * MCP). + * + * The derived-map pin (`payload_labels`) is not decoration either: those maps + * are built by walking the snapshot's own keys, so a seam that redacted AFTER + * enrichment would still ship a restricted field's NAME and authored LABEL. + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { ApprovalService } from './approval-service.js'; +import { redactSnapshot } from './payload-redaction.js'; +import { + bindSnapshotRedactionMiddleware, + redactRowsInPlace, + APPROVAL_REQUEST_OBJECT, +} from './payload-redaction-middleware.js'; + +const OBJECT = 'expense_report'; +const RECORD = 'exp_1'; +const REQUEST = 'req_1'; +const TENANT = 't1'; +const APPROVER = 'finance_user'; +/** + * A second approver on the SAME request who holds read on every field. Modelled + * as a participant on purpose: `getRequest` enforces #3590 participation before + * any of this runs, so a non-participant "admin" would answer `null` and the + * pin below would be measuring visibility, not field masking. + */ +const ADMIN = 'finance_admin'; + +/** The full submitted row, as the flow's `$record` handed it over. */ +const FULL_ROW = { + id: RECORD, + title: 'Q1 travel', + amount: 1200, + submitted_by: 'employee_7', + // Field-level restricted on the SUBJECT object — the leak this closes. + salary: 98000, + ssn: '123-45-6789', + internal_notes: 'flagged for audit', +}; + +/** What a restricted approver may read on `expense_report`. */ +const APPROVER_READABLE = ['id', 'title', 'amount', 'submitted_by']; +/** The keys an approver must NOT receive — asserted by name throughout. */ +const RESTRICTED = ['salary', 'ssn', 'internal_notes']; + +interface FakeRow { [k: string]: any } + +/** + * Engine double. The `sys_approval_*` tables are open because the service reads + * them with `SYSTEM_CTX` on purpose; this file's subject is what happens to the + * SNAPSHOT on the way out, not who may load the request. + */ +function makeEngine() { + const tables: Record = {}; + const ensure = (n: string) => (tables[n] ??= []); + function matches(row: FakeRow, filter: any): boolean { + if (!filter || typeof filter !== 'object') return true; + for (const [k, v] of Object.entries(filter)) { + if (k === '$or') { if (!(v as any[]).some(s => matches(row, s))) return false; continue; } + if (k === '$and') { if (!(v as any[]).every(s => matches(row, s))) return false; continue; } + const rv = row[k]; + if (v != null && typeof v === 'object' && '$in' in (v as any)) { + if (!(v as any).$in.includes(rv)) return false; continue; + } + if (rv !== v) return false; + } + return true; + } + return { + _tables: tables, + async find(object: string, options?: any) { + const rows = ensure(object).filter(r => matches(r, options?.filter ?? options?.where)); + return rows.slice(options?.offset ?? 0, (options?.offset ?? 0) + (options?.limit ?? 1000)); + }, + async insert(object: string, data: any) { ensure(object).push({ ...data }); return { ...data }; }, + // ⛔ No `update` / `delete` here ON PURPOSE. This file's subject is the READ + // path (`getRequest` / `listRequests` / a generic `find`), which never + // reaches a write verb — so declaring the two verbs would add an engine + // double to `check:engine-double-contract`'s pinned ledger for coverage + // nothing here exercises. If a future test in this file drives a write, add + // them back routed through `assertEngineUpdateDispatch` / + // `assertEngineDeleteDispatch` (never a hand-mirrored copy of the check) + // and run the gate's `--write` in the same edit. + }; +} + +/** + * Field-visibility double standing in for `plugin-security`'s + * `getReadableFields`. It reproduces the three answers that method actually + * gives, because this seam branches on all three: a field list, `undefined` + * (schema unresolvable — NOT a denial, #3807) and `[]` (the plugin's own + * fail-closed tier). + */ +function makeVisibility(answers: Record, opts?: { throwFor?: string }) { + const calls: Array<{ object: string; context: any }> = []; + return { + _calls: calls, + async getReadableFields(object: string, context?: any): Promise { + calls.push({ object, context }); + if (opts?.throwFor === object) throw new Error('metadata unavailable'); + // Mirrors the real method's `isSystem` bypass: system reads see everything. + if (context?.isSystem) return Object.keys(FULL_ROW); + return answers[object]; + }, + }; +} + +const asUser = (userId: string) => + ({ userId, tenantId: TENANT, positions: [], permissions: [] }) as any; + +function seed(engine: ReturnType) { + engine._tables[OBJECT] = [{ ...FULL_ROW, organization_id: TENANT }]; + engine._tables['sys_approval_request'] = [{ + id: REQUEST, + organization_id: TENANT, + process_name: 'flow:expense_review', + object_name: OBJECT, + record_id: RECORD, + submitter_id: 'employee_7', + status: 'pending', + current_step: 'finance', + pending_approvers: [APPROVER, ADMIN].join(','), + payload_json: JSON.stringify(FULL_ROW), + created_at: '2026-08-01T00:00:00Z', + }]; + engine._tables['sys_approval_approver'] = [ + { id: 'idx_1', request_id: REQUEST, approver: APPROVER, organization_id: TENANT }, + { id: 'idx_2', request_id: REQUEST, approver: ADMIN, organization_id: TENANT }, + ]; + engine._tables['sys_approval_action'] = []; +} + +/** The snapshot still in the column — the audit-preservation probe. */ +function storedSnapshot(engine: ReturnType): Record { + return JSON.parse(String(engine._tables['sys_approval_request'][0].payload_json)); +} + +describe('#10749 payload snapshot redaction — the service door', () => { + let engine: ReturnType; + let service: ApprovalService; + + beforeEach(() => { + engine = makeEngine(); + seed(engine); + service = new ApprovalService({ engine: engine as any }); + }); + + it('(1) leak closed + (3) still-served: a restricted approver loses the restricted keys BY NAME and keeps the business ones', async () => { + service.attachFieldVisibility(makeVisibility({ [OBJECT]: APPROVER_READABLE })); + + const row = await service.getRequest(REQUEST, asUser(APPROVER)); + const payload = row!.payload as Record; + + // (1) leak closed — by name, not by shape. + for (const key of RESTRICTED) { + expect(payload, `restricted key '${key}' must not be served`).not.toHaveProperty(key); + } + // (3) still-served — the drawer still renders. + expect(payload).toMatchObject({ + id: RECORD, title: 'Q1 travel', amount: 1200, submitted_by: 'employee_7', + }); + }); + + it('(2) audit preserved: the stored column still holds the WHOLE row after a restricted read', async () => { + service.attachFieldVisibility(makeVisibility({ [OBJECT]: APPROVER_READABLE })); + + await service.getRequest(REQUEST, asUser(APPROVER)); + + // A write-time trim would have taken Option A and would fail here while + // passing every leak-only assertion above. + expect(storedSnapshot(engine)).toEqual(FULL_ROW); + for (const key of RESTRICTED) { + expect(storedSnapshot(engine)).toHaveProperty(key); + } + }); + + it('(4) admin unchanged: a caller who may read every field still receives the whole snapshot', async () => { + service.attachFieldVisibility(makeVisibility({ [OBJECT]: Object.keys(FULL_ROW) })); + + const row = await service.getRequest(REQUEST, asUser(ADMIN)); + + expect(row!.payload).toEqual(FULL_ROW); + for (const key of RESTRICTED) expect(row!.payload).toHaveProperty(key); + }); + + it('derived maps are clean: `payload_labels` never carries a restricted key (redaction runs BEFORE enrichment)', async () => { + service.attachFieldVisibility(makeVisibility({ [OBJECT]: APPROVER_READABLE })); + + const row = await service.getRequest(REQUEST, asUser(APPROVER)) as any; + + for (const key of RESTRICTED) { + expect(Object.keys(row.payload_labels ?? {})).not.toContain(key); + expect(Object.keys(row.payload_display ?? {})).not.toContain(key); + } + }); + + it('the list door narrows too — one door\'s pin does not stand for another\'s', async () => { + service.attachFieldVisibility(makeVisibility({ [OBJECT]: APPROVER_READABLE })); + + const rows = await service.listRequests({ approverId: APPROVER }, asUser(APPROVER)); + + expect(rows).toHaveLength(1); + const payload = rows[0].payload as Record; + for (const key of RESTRICTED) expect(payload).not.toHaveProperty(key); + expect(payload).toHaveProperty('amount', 1200); + }); + + it('redaction is keyed on the READING caller, and asks about the SUBJECT object', async () => { + const vis = makeVisibility({ [OBJECT]: APPROVER_READABLE }); + service.attachFieldVisibility(vis); + + await service.getRequest(REQUEST, asUser(APPROVER)); + + expect(vis._calls).toHaveLength(1); + expect(vis._calls[0].object).toBe(OBJECT); + expect(vis._calls[0].context?.userId).toBe(APPROVER); + // ⛔ Not SYSTEM_CTX: the service loads the ROW as system, but the + // visibility question must be asked as the caller, or every read unmasks. + expect(vis._calls[0].context?.isSystem).toBeFalsy(); + }); + + it('no security service wired ⇒ served exactly as before (no new way for a drawer to render empty)', async () => { + const row = await service.getRequest(REQUEST, asUser(APPROVER)); + expect(row!.payload).toEqual(FULL_ROW); + }); + + it('`undefined` readable set is NOT a denial (#3807) — the snapshot passes through whole', async () => { + service.attachFieldVisibility(makeVisibility({ [OBJECT]: undefined })); + const row = await service.getRequest(REQUEST, asUser(APPROVER)); + expect(row!.payload).toEqual(FULL_ROW); + }); + + it('`[]` IS a denial — the security plugin\'s own fail-closed tier is honoured', async () => { + service.attachFieldVisibility(makeVisibility({ [OBJECT]: [] })); + const row = await service.getRequest(REQUEST, asUser(APPROVER)); + expect(row!.payload).toEqual({}); + // and still nothing was trimmed at rest. + expect(storedSnapshot(engine)).toEqual(FULL_ROW); + }); + + it('a THROW from the visibility authority serves unredacted rather than blanking every drawer', async () => { + service.attachFieldVisibility(makeVisibility({ [OBJECT]: APPROVER_READABLE }, { throwFor: OBJECT })); + const row = await service.getRequest(REQUEST, asUser(APPROVER)); + expect(row!.payload).toEqual(FULL_ROW); + }); +}); + +describe('#10749 payload snapshot redaction — the generic data door', () => { + it('a generic read is narrowed: the RAW `payload_json` string loses the restricted keys and keeps the business ones', async () => { + const rows = [{ + id: REQUEST, object_name: OBJECT, payload_json: JSON.stringify(FULL_ROW), + }]; + await redactRowsInPlace(rows, makeVisibility({ [OBJECT]: APPROVER_READABLE }), asUser(APPROVER)); + + const served = JSON.parse(rows[0].payload_json); + for (const key of RESTRICTED) expect(served).not.toHaveProperty(key); + expect(served).toMatchObject({ id: RECORD, title: 'Q1 travel', amount: 1200 }); + }); + + it('an admin generic read still returns the whole snapshot', async () => { + const rows = [{ id: REQUEST, object_name: OBJECT, payload_json: JSON.stringify(FULL_ROW) }]; + await redactRowsInPlace(rows, makeVisibility({ [OBJECT]: Object.keys(FULL_ROW) }), asUser(ADMIN)); + expect(JSON.parse(rows[0].payload_json)).toEqual(FULL_ROW); + }); + + it('is registered against `sys_approval_request` only, and skips writes and system reads', async () => { + const registered: Array<{ fn: any; options: any }> = []; + const engine = { registerMiddleware: (fn: any, options: any) => registered.push({ fn, options }) }; + bindSnapshotRedactionMiddleware(engine, () => makeVisibility({ [OBJECT]: APPROVER_READABLE })); + + expect(registered).toHaveLength(1); + expect(registered[0].options).toEqual({ object: APPROVAL_REQUEST_OBJECT }); + + const mw = registered[0].fn; + const rowsFor = () => [{ id: REQUEST, object_name: OBJECT, payload_json: JSON.stringify(FULL_ROW) }]; + + // A read as a restricted caller narrows. + const read: any = { operation: 'find', context: asUser(APPROVER), result: rowsFor() }; + await mw(read, async () => {}); + expect(JSON.parse(read.result[0].payload_json)).not.toHaveProperty('ssn'); + + // A SYSTEM read is the audit/replay channel — untouched. + const sys: any = { operation: 'find', context: { isSystem: true }, result: rowsFor() }; + await mw(sys, async () => {}); + expect(JSON.parse(sys.result[0].payload_json)).toEqual(FULL_ROW); + + // A write is not a serve door — untouched. + const write: any = { operation: 'update', context: asUser(APPROVER), result: rowsFor() }; + await mw(write, async () => {}); + expect(JSON.parse(write.result[0].payload_json)).toEqual(FULL_ROW); + }); +}); + +describe('#10749 redactSnapshot — the shape contract', () => { + it('drops exactly the keys outside the readable set, and reports them', () => { + const out = redactSnapshot(FULL_ROW, APPROVER_READABLE); + expect(out.redactedKeys).toEqual(['internal_notes', 'salary', 'ssn']); + expect(Object.keys(out.payload as object).sort()).toEqual([...APPROVER_READABLE].sort()); + }); + + it('passes a non-object snapshot through — field visibility governs COLUMNS', () => { + for (const v of ['a string', 42, null, ['a', 'b']]) { + expect(redactSnapshot(v, APPROVER_READABLE).payload).toEqual(v); + } + }); + + it('returns the SAME reference when nothing was removed (no needless rewrite)', () => { + const out = redactSnapshot(FULL_ROW, Object.keys(FULL_ROW)); + expect(out.payload).toBe(FULL_ROW); + expect(out.redactedKeys).toEqual([]); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 20083b9a4ab..dd38fe823ae 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -49,6 +49,11 @@ import { type ApproverOrgScopeDeps, type ApproverOrgScopeEngine, } from './approver-org-scope.js'; +import { + redactSnapshot, + resolveReadableSnapshotFields, + type FieldVisibilitySource, +} from './payload-redaction.js'; /** * Node-era approval runtime (ADR-0019). @@ -560,6 +565,14 @@ export interface ApprovalServiceOptions { * guard stands down. */ tenancyPosture?: () => string | undefined; + /** + * [#10749] Field-visibility authority used to redact the payload snapshot at + * serve time. Usually attached after construction via + * {@link ApprovalService.attachFieldVisibility}, because the security plugin + * may register after this one. Absent ⇒ snapshots are served unredacted, + * exactly as before this seam landed. + */ + fieldVisibility?: FieldVisibilitySource; /** * [#8652] Objects on which a user holding READ access to the target business * record may also see that record's approval requests and action history — @@ -578,6 +591,7 @@ export class ApprovalService implements IApprovalService { private messaging?: ApprovalMessagingSurface; private publicBaseUrl: string; private tenancyPosture?: () => string | undefined; + private fieldVisibility?: FieldVisibilitySource; /** * [#8652] The enabled object set for the record-reader visibility tier. * EMPTY means the tier is off — the default, and the shape every existing @@ -593,6 +607,7 @@ export class ApprovalService implements IApprovalService { this.messaging = opts.messaging; this.publicBaseUrl = (opts.publicBaseUrl ?? '').replace(/\/$/, ''); this.tenancyPosture = opts.tenancyPosture; + this.fieldVisibility = opts.fieldVisibility; this.recordReaderVisibleObjects = new Set( (Array.isArray(opts.recordReaderVisibleObjects) ? opts.recordReaderVisibleObjects : []) .map((n) => String(n ?? '').trim()) @@ -605,6 +620,53 @@ export class ApprovalService implements IApprovalService { this.tenancyPosture = provider; } + /** + * [#10749] Attach (or replace) the field-visibility authority the payload + * redaction seam reads. Late-bound: plugin load order does not guarantee the + * security service exists when this one is constructed. + */ + attachFieldVisibility(source: FieldVisibilitySource | undefined): void { + this.fieldVisibility = source; + } + + /** + * [#10749] Redact each row's payload snapshot down to the fields the READING + * caller may see on that row's subject object. + * + * Runs BEFORE {@link ApprovalService.enrichRows}, and that ordering is + * load-bearing rather than incidental: `enrichRows` derives `payload_display` + * (lookup foreign keys inside the snapshot resolved to referenced record + * titles) and `payload_labels` (a label per snapshot key) by WALKING THE + * SNAPSHOT'S OWN KEYS. Redact first and both derived maps are clean for free; + * redact after and a restricted field's name, its authored label and the + * title of the record it points at all still ship — the value would be gone + * and the disclosure would not. + * + * Rows are grouped by subject object so one `getReadableFields` call covers a + * whole page of same-object requests. + */ + private async redactPayloads(rows: ApprovalRequestRow[], context: ExecutionContext): Promise { + const withPayload = rows.filter((r: any) => r?.payload != null); + if (withPayload.length === 0) return; + const byObject = new Map(); + for (const r of withPayload) { + const key = String((r as any).object_name ?? ''); + let list = byObject.get(key); + if (!list) { list = []; byObject.set(key, list); } + list.push(r); + } + for (const [object, group] of byObject) { + const readable = await resolveReadableSnapshotFields( + this.fieldVisibility, object, context, this.logger, + ); + if (readable === undefined) continue; + for (const r of group as any[]) { + const { payload } = redactSnapshot(r.payload, readable); + r.payload = payload; + } + } + } + /** Deps bundle for the ADR-0105 D9 org-scope helpers. */ private get orgScopeDeps(): ApproverOrgScopeDeps { return { @@ -4382,6 +4444,8 @@ export class ApprovalService implements IApprovalService { const rows = await this.engine.find('sys_approval_request', findOpts); const list = Array.isArray(rows) ? rows.map(rowFromRequest) : []; + // [#10749] Redact before enrichment — see `redactPayloads`. + await this.redactPayloads(list, context); await this.enrichRows(list); this.attachViewers(list, context); return list; @@ -4473,6 +4537,8 @@ export class ApprovalService implements IApprovalService { if (visible && !visible.has(String(rows[0].id))) return null; } const row = rowFromRequest(rows[0]); + // [#10749] Redact before enrichment — see `redactPayloads`. + await this.redactPayloads([row], context); await this.enrichRows([row]); await this.attachFlowSteps(row); await this.attachDecisionProgress(row, rows[0]); diff --git a/packages/plugins/plugin-approvals/src/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index 033d81be6ed..04f5c0e390d 100644 --- a/packages/plugins/plugin-approvals/src/approvals-plugin.ts +++ b/packages/plugins/plugin-approvals/src/approvals-plugin.ts @@ -21,6 +21,8 @@ import { type ApprovalMessagingSurface, } from './approval-service.js'; import { bindApprovalLockHook, bindDelegationWriteGuard, unbindAllHooks } from './lifecycle-hooks.js'; +import { bindSnapshotRedactionMiddleware } from './payload-redaction-middleware.js'; +import type { FieldVisibilitySource } from './payload-redaction.js'; import { registerApprovalNode, type ApprovalAutomationSurface } from './approval-node.js'; export interface ApprovalsPluginOptions { @@ -199,6 +201,30 @@ export class ApprovalsServicePlugin implements Plugin { }, }); + // [#10749] Field-visibility authority for payload-snapshot redaction. + // Resolved LAZILY on every read, for the same reason `tenancyPosture` is: + // the security plugin may register after this one, and a resolver captured + // at start would pin `undefined` for the life of the process — which here + // means "never redact", i.e. the leak this seam closes, silently reopened + // by load order. `getService` THROWS on an empty slot, so an absent + // security plugin degrades to serving snapshots exactly as before. + const fieldVisibility = (): FieldVisibilitySource | undefined => { + try { + const sec = ctx.getService('security'); + return sec && typeof sec.getReadableFields === 'function' ? sec : undefined; + } catch { + return undefined; + } + }; + this.service.attachFieldVisibility({ + getReadableFields: (object: string, context?: unknown) => { + const sec = fieldVisibility(); + return sec + ? sec.getReadableFields(object, context) + : Promise.resolve(undefined); + }, + }); + // Record lock: block edits to a record while it has a pending request. // Delegation write-guard: a self-service OOO delegation may only name the // acting user as delegator (#1322 follow-up). Both bind under the same @@ -208,6 +234,11 @@ export class ApprovalsServicePlugin implements Plugin { unbindAllHooks(engine); bindApprovalLockHook(engine, ctx.logger); bindDelegationWriteGuard(engine, ctx.logger); + // [#10749] Generic-door snapshot redaction. Registered here so the + // service door and the generic data door narrow together — see + // `payload-redaction-middleware.ts` on why one door covered alone is + // worse than none. + bindSnapshotRedactionMiddleware(engine as any, fieldVisibility, ctx.logger); } catch (err: any) { ctx.logger.warn?.('[approvals] failed to bind approval hooks', { error: err?.message }); } diff --git a/packages/plugins/plugin-approvals/src/payload-redaction-middleware.ts b/packages/plugins/plugin-approvals/src/payload-redaction-middleware.ts new file mode 100644 index 00000000000..66e957c6e83 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/payload-redaction-middleware.ts @@ -0,0 +1,124 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +import { + redactSnapshot, + resolveReadableSnapshotFields, + type FieldVisibilitySource, +} from './payload-redaction.js'; + +/** + * [#10749] Read-time snapshot redaction on the GENERIC data door. + * + * ## Why a second seam exists at all + * + * `ApprovalService.getRequest` / `listRequests` are not the only way to read + * `sys_approval_request`. The object declares `enable.apiMethods: ['get', + * 'list']`, so a caller reaches the very same row — and the very same + * `payload_json` string — straight through the generic data path, which never + * touches the service and therefore never touches the service's redaction. + * + * That generic path is not one door but a family of them, all sharing a single + * PRODUCER: `find` / `findOne` on the engine. Registering here, at the engine, + * covers the whole family at once — the REST data routes, ObjectQL callers, the + * CSV/XLSX export route (a read-derived projection), the MCP data tool and the + * AI-context interceptor. Fixing them one consumer at a time is how most of + * them would stay open, and a seam that covers the service door while leaving + * this one manufactures the belief that the path is masked. + * + * ## Why middleware rather than an `afterFind` hook + * + * A hook receives `hookContext.session`, which `Engine.buildSession` builds + * WITHOUT `onBehalfOf`. `getReadableFields` intersects the delegator's field + * mask on an on-behalf-of read (ADR-0090 D10, fail-closed on a dangling + * delegator), so a hook-based seam would silently drop that intersection and + * answer a delegated read more permissively than the service door does. + * Middleware carries `opCtx.context` — the real `ExecutionContext` — so both + * doors narrow identically. + * + * ## The at-rest guarantee + * + * This rewrites `payload_json` only on the RESULT ROWS handed back from a read, + * after the driver has answered. Storage is untouched: the full snapshot stays + * in the column as the approval record's audit evidence of what was actually + * submitted, which is the half of the maintainer's ruling that write-time + * trimming would have given away. + */ + +/** The engine surface this seam needs. */ +export interface MiddlewareEngine { + registerMiddleware( + fn: (opCtx: any, next: () => Promise) => Promise | void, + options?: { object?: string }, + ): void; +} + +export const APPROVAL_REQUEST_OBJECT = 'sys_approval_request'; + +/** Parse a stored snapshot string; non-JSON is left alone. */ +function parseSnapshot(raw: unknown): { ok: boolean; value: unknown } { + if (typeof raw !== 'string' || raw.trim() === '') return { ok: false, value: undefined }; + try { + return { ok: true, value: JSON.parse(raw) }; + } catch { + return { ok: false, value: undefined }; + } +} + +/** + * Redact `payload_json` on rows a generic read is about to hand back. + * + * Exported for direct testing: the middleware body is this function plus the + * registration, so a test can pin the narrowing without standing up an engine. + */ +export async function redactRowsInPlace( + rows: unknown, + security: FieldVisibilitySource | undefined, + context: unknown, + logger?: { warn?: (msg: string, meta?: Record) => void }, +): Promise { + const list = Array.isArray(rows) ? rows : rows ? [rows] : []; + if (list.length === 0) return; + // One readable-field resolution per subject object, not per row. + const cache = new Map(); + for (const row of list as any[]) { + if (!row || typeof row !== 'object') continue; + const raw = row.payload_json; + const parsed = parseSnapshot(raw); + if (!parsed.ok) continue; + const object = String(row.object_name ?? '').trim(); + if (!object) continue; + if (!cache.has(object)) { + cache.set(object, await resolveReadableSnapshotFields(security, object, context, logger)); + } + const readable = cache.get(object); + if (readable === undefined) continue; + const { payload, redactedKeys } = redactSnapshot(parsed.value, readable); + if (redactedKeys.length === 0) continue; + row.payload_json = JSON.stringify(payload); + } +} + +/** + * Register the generic-door seam. `getSecurity` is resolved lazily on each + * read because the security plugin may register after this one. + */ +export function bindSnapshotRedactionMiddleware( + engine: MiddlewareEngine, + getSecurity: () => FieldVisibilitySource | undefined, + logger?: { warn?: (msg: string, meta?: Record) => void }, +): void { + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + await next(); + if (opCtx?.operation !== 'find' && opCtx?.operation !== 'findOne') return; + // A system read is the audit/replay channel — it gets the whole snapshot, + // mirroring the `isSystem` skip every other field-visibility gate takes. + if ((opCtx?.context as any)?.isSystem) return; + try { + await redactRowsInPlace(opCtx.result, getSecurity(), opCtx.context, logger); + } catch (err: any) { + logger?.warn?.('[approvals] snapshot redaction middleware failed', { + error: err?.message ?? String(err), + }); + } + }, { object: APPROVAL_REQUEST_OBJECT }); +} diff --git a/packages/plugins/plugin-approvals/src/payload-redaction.ts b/packages/plugins/plugin-approvals/src/payload-redaction.ts new file mode 100644 index 00000000000..c7cb0dfa9c8 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/payload-redaction.ts @@ -0,0 +1,143 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Read-time redaction of the approval payload snapshot (#10749). + * + * ## The defect this closes + * + * `sys_approval_request.payload_json` stores the submitted record's raw row, + * captured from the flow's `$record` variable — which the automation layer + * hands over with **the record's own FLS never applying**. The column is a + * `textarea` on `sys_approval_request`, so to every read door it is an opaque + * string: the field-visibility machinery governs *columns of objects* and + * cannot see inside a JSON column. Every field-level read control an app + * author declared on the SUBJECT object — `requiredPermissions` (ADR-0066 D3), + * a permission set marking a field non-readable, a `maskingRule` — is + * therefore unenforceable on the approval path, for every app. + * + * ## The shape of the fix (maintainer ruling 2026-08-22, Option B) + * + * The full snapshot **stays at rest**: the approval record remains audit + * evidence of what was actually submitted. Redaction is applied at SERVE time, + * keyed on the reading caller, so the same row answers an admin with the whole + * snapshot and a restricted approver with only the fields they may read. + * + * The readable set is not recomputed here. It comes from the security + * service's `getReadableFields(object, context)` — documented as the same + * field mask the read middleware applies, so this seam cannot drift from + * data-plane FLS, and the CSV/XLSX export path already derives its columns + * from it. + * + * ## What this deliberately does NOT do + * + * - **It does not gate on OBJECT-level access.** An approver routinely has no + * read grant on the object under approval at all — that is the normal shape + * of an approval, and the snapshot is how they see what they are approving. + * `getReadableFields` answers with the full field set for a caller who has + * no field-permission entries for the object, which is exactly the behaviour + * this seam wants: FIELD-level declarations are enforced, object-level + * access is untouched, and every approval drawer shipping today keeps + * rendering. + * - **It does not act on `hidden: true`.** `hidden` is a UI contract ("Hidden + * from default UI") and, in the spec's own words, "has never governed + * serialization" — measurably: no read path in the repo strips a value on + * it. Making it govern serialization here alone would make the approval path + * stricter than a direct read of the very same row (so it would close no + * leak — the approver can just read the record), while breaking every drawer + * that renders a `hidden` business column. That is a `packages/spec` + * semantics question, and it is left open rather than decided here. + */ + +/** The slice of the security service this seam consumes. */ +export interface FieldVisibilitySource { + /** + * Fields of `object` this context may read — the same mask the ObjectQL read + * middleware applies. `undefined` when the object schema cannot be resolved; + * `[]` is the security plugin's own fail-closed tier (unresolvable posture, + * dangling on-behalf-of delegator). + */ + getReadableFields(object: string, context?: unknown): Promise; +} + +/** Outcome of one redaction pass, for logging and for tests to assert on. */ +export interface RedactionOutcome { + /** The snapshot to serve. Identical reference when nothing was removed. */ + payload: unknown; + /** Keys removed, sorted. Empty when the snapshot passed through whole. */ + redactedKeys: string[]; +} + +/** + * Drop every key of `payload` that is not in `readable`. + * + * ⛔ `readable === undefined` is NOT a denial (#3807). It is the security + * plugin's "schema not resolvable" answer, and its documented contract is that + * the caller falls back to its own projection — so the snapshot passes through + * unchanged. Redacting on it would empty the drawer whenever object metadata + * is briefly unavailable, which is an availability regression rather than a + * security gain: the same caller can read the subject record directly through + * a door that is likewise not narrowing during that window. + * + * `readable === []` IS a denial — it is what `getReadableFields` returns for an + * unresolvable security posture or a dangling delegator, both of which the + * platform already fails closed on (`canExport`, the export column projection). + * Honouring it here keeps this seam consistent with those. + * + * A non-object snapshot (a JSON scalar, an array, `null`) has no keys to + * govern and passes through: the field-visibility contract is about columns. + */ +export function redactSnapshot(payload: unknown, readable: string[] | undefined): RedactionOutcome { + if (readable === undefined) return { payload, redactedKeys: [] }; + if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) { + return { payload, redactedKeys: [] }; + } + const allowed = new Set(readable.map((f) => String(f))); + const source = payload as Record; + const redactedKeys: string[] = []; + const kept: Record = {}; + for (const key of Object.keys(source)) { + if (allowed.has(key)) kept[key] = source[key]; + else redactedKeys.push(key); + } + if (redactedKeys.length === 0) return { payload, redactedKeys: [] }; + return { payload: kept, redactedKeys: redactedKeys.sort() }; +} + +/** + * Resolve the caller-readable field set for `object`, or `undefined` when this + * seam must not narrow. + * + * `undefined` is returned — and the snapshot therefore served whole — in three + * cases, each a deliberate fail-OPEN that preserves today's behaviour rather + * than introducing a new way for an approval to render empty: + * + * 1. no security service is wired (a bare engine boot, most unit fixtures); + * 2. no object name is known for the request; + * 3. `getReadableFields` THREW. + * + * Case 3 is the one worth naming out loud: the platform's stated posture for + * consumers that turn this into an access decision is to fail closed, and this + * seam does honour the fail-closed tier the security plugin itself computes + * (`[]`). What it declines to do is treat a transient THROW as a denial, since + * that would blank the snapshot on every approval drawer in the deployment for + * the duration of a metadata hiccup. The trade is logged loudly so a persistent + * outage is observable instead of silently non-narrowing. + */ +export async function resolveReadableSnapshotFields( + security: FieldVisibilitySource | undefined, + objectName: string | undefined, + context: unknown, + logger?: { warn?: (msg: string, meta?: Record) => void }, +): Promise { + if (!security || typeof security.getReadableFields !== 'function') return undefined; + const object = String(objectName ?? '').trim(); + if (!object) return undefined; + try { + return await security.getReadableFields(object, context); + } catch (err: any) { + logger?.warn?.('[approvals] payload redaction could not resolve readable fields — serving the snapshot unredacted', { + object, error: err?.message ?? String(err), + }); + return undefined; + } +}