Skip to content

Commit d08d2ae

Browse files
fix(plugin-approvals): a locked record's refusal names it only by a field the writer may read (#38555)
Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:审批锁定期间编辑记录被拒时,提示只会用编辑者能读到的字段称呼这条记录;若该字段是内部字段或凭据字段,提示改为只写对象名称,其余不变。 - 为什么做:加固审批插件的记录锁提示,让拒绝提示与其它读取路径一样,不出现任何人都读不到的字段。 - 出错会怎样:最坏情况是某条普通记录的拒绝提示少了记录标题、只剩对象名称,编辑仍照常被拒;改动可直接撤回。 - 要你做什么:无 ## What changes A locked record's refusal names it only by a field the writer may read. - While an approval holds a record, the `RECORD_LOCKED` refusal names the record by its display field only when that field is one a caller can be served at all. A display field declared `internal: true`, or of a credential type (`secret`, `password`), never titles the refusal, whether it is the object's explicit `nameField` or the derived one. - When the field-visibility source cannot answer, the refusal names no title. - The refusal keeps its code (`RECORD_LOCKED`), its status (409) and its sentence. Without a title it names the object's label ("This Vault Entry is locked while an approval is in progress, ..."). An ordinary display field still names the record as before, with or without a field-visibility source wired. - Changeset: `@objectstack/plugin-approvals` patch. Read first, by risk: 1. `packages/plugins/plugin-approvals/src/lifecycle-hooks.ts`: the new `isWithheldTitleField` and its one call in `recordTitleOf`, plus the `failClosedOnThrow` argument at the per-row refusal. 2. `packages/plugins/plugin-approvals/src/payload-redaction.ts`: the opt-in `failClosedOnThrow` branch. Callers that do not pass it are unchanged. 3. `packages/plugins/plugin-approvals/src/record-lock-refusal-writer-fls.integration.test.ts`: the new top-level `describe`. ## Tests The new pins sit in the existing harness file as a top-level `describe`. They run against a real `ObjectQL`, a real sqlite driver and the real lock hooks: - an internal display field named by the object: by-id update and predicate update; - an internal display field the object derives; - a credential-typed display field; - a line under a locked master, on update and on delete; - a field-visibility source that cannot answer; - with no source wired, a withheld display field still gives no title; - controls: an ordinary display field still names the record, with a source wired and with none. Red on base, green on head: <details><summary>Readings</summary> - Base (pins only, commit da50bf0): 6 failed, 8 passed (14). - Head 33765d4: 14/14 passed. With the neighbouring lock suites (`record-lock-user-facing-message`, `detail-row-lock`): 3 files, 54/54. - Ablation, each guard reverted on disk through `scripts/ablation-replace.mjs`, then restored (blob equals HEAD, `git diff HEAD` empty): - withheld-field guard removed: 5 failed, 9 passed. These are the five withheld-field pins; the throw pin stays green. - fail-closed argument flipped to `false`: 1 failed, 13 passed. That one is the throw pin. - A first attempt at the second ablation ran nothing: the tool refused it because the replacement text already occurred in the file. It was re-run with a distinct replacement. - `pnpm --filter @objectstack/plugin-approvals test`: 131/131 files, 1997/1997 tests. - `pnpm --filter @objectstack/plugin-approvals typecheck`: exit 0. That covers tsc, the scripts project and `check:test-typecheck` OK. </details> ## Acceptance notes - The line-under-master refusal (detail-row lock) already named only the master's label on base. Its new pin is green on base and guards it. Deleting the locked record itself is not refused, by design, so it has no refusal to pin. - `origin/main` moved 7 commits past the base. None of them touches `packages/plugins/plugin-approvals`, `packages/core/src` or `packages/spec/src/data`, so the branch was not merged. ## Verification <details><summary>Gates</summary> - `node scripts/pm/dispatch-gates.mjs --commands` (head 33765d4) derived 71 families. Local results: 69 exit 0. 2 exit 3 (PREREQUISITE NOT MET, a whole-repo build is absent), so they are NOT MEASURED locally and CI carries them: `pnpm check:dual-build-cjs-loads`, `pnpm check:i18n`. - `--ran` reconciliation: 71 accounted, 69 run, 2 NOT-MEASURED, 0 UNRUN. - Dogfood battery on head 33765d4 (`pnpm --filter @objectstack/dogfood test`, after building its closure): the lock VERDICT reads command-exit 0. Test Files: 495 passed, 3 skipped (498). Tests: 4183 passed, 68 skipped (4251). No failures. The lock was held 3602 s on a shared box, closure build included, and it flagged holder-side starvation for that length. </details> Two-minute check: ``` pnpm --filter @objectstack/plugin-approvals exec vitest run --maxWorkers=2 src/record-lock-refusal-writer-fls.integration.test.ts ``` Expect 14 passed. Revert the fix files to `origin/main` and expect 6 failed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_017xRBcW9L8Noz9BxEwjwiov --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent cd19179 commit d08d2ae

4 files changed

Lines changed: 239 additions & 5 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/plugin-approvals': patch
3+
---
4+
5+
fix(plugin-approvals): a locked record's refusal names it only by a field the writer may read
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The `RECORD_LOCKED` refusal raised while an approval holds a record names that record by its display field only when the field is one a caller can be served: a display field declared `internal: true`, or of a credential type (`secret`, `password`), never titles it. When the field-visibility source cannot answer, the refusal names no title. In both cases the refusal keeps its code (`RECORD_LOCKED`), its status (409) and its sentence, naming the object's label: "This Opportunity is locked while an approval is in progress, …". An ordinary display field still names the record as before.

‎packages/plugins/plugin-approvals/src/lifecycle-hooks.ts‎

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -125,12 +125,27 @@
125125
* nothing. With no field-visibility authority wired, the title passes through
126126
* as before, exactly as the payload snapshot does.
127127
*
128+
* Two answers sit beside that one, both fail-closed:
129+
*
130+
* - a display field no caller is served on any read path — one declared
131+
* `internal: true`, or of a credential type — never titles the refusal,
132+
* whatever the served-fields answer says and whether or not one is wired.
133+
* These are the two sets the engine's read path withholds
134+
* (`collectInternalReadFields` and `collectCredentialFields` in
135+
* `@objectstack/objectql`), asked here through the same predicates
136+
* (`collectInternalWriteResponseFields`, `@objectstack/core`, restating the
137+
* first; `isCredentialFieldType`, `@objectstack/spec/data`, deciding the
138+
* second), see {@link recordTitleOf};
139+
* - a served-fields source that THROWS gives no title (`failClosedOnThrow`),
140+
* where the payload snapshot falls open: the refusal still answers, only
141+
* without a title nobody vetted.
142+
*
128143
* Registered under `packageId: 'plugin-approvals:lock'` so it can be cleanly
129144
* unbound on plugin stop.
130145
*/
131146

132-
import { withoutOperationPrivateKeys } from '@objectstack/core';
133-
import { resolveDisplayField, type EngineQueryOptions } from '@objectstack/spec/data';
147+
import { collectInternalWriteResponseFields, withoutOperationPrivateKeys } from '@objectstack/core';
148+
import { isCredentialFieldType, resolveDisplayField, type EngineQueryOptions } from '@objectstack/spec/data';
134149
import { renderOperationMessage, type ValidationMessageTranslator } from '@objectstack/spec/system';
135150
import { redactSnapshot, resolveReadableSnapshotFields, type FieldVisibilitySource } from './payload-redaction.js';
136151
import { negotiatedReaderLocale, readerLabelsFor, type ReaderLabelI18n } from './reader-locale-labels.js';
@@ -236,6 +251,18 @@ function lockedError(message: string, userMessage?: string): never {
236251
throw err;
237252
}
238253

254+
/**
255+
* Is `field` of `schema` one no caller is served on any read path — declared
256+
* `internal: true`, or of a credential type? Such a field never titles the
257+
* refusal (see the module docstring). A schema without the field declares
258+
* neither, so it answers `false`.
259+
*/
260+
function isWithheldTitleField(schema: unknown, field: string): boolean {
261+
if (collectInternalWriteResponseFields(schema).includes(field)) return true;
262+
const def = (schema as { fields?: Record<string, { type?: unknown } | undefined> } | undefined)?.fields?.[field];
263+
return !!def && isCredentialFieldType(def.type);
264+
}
265+
239266
/**
240267
* The record's human title, or `undefined` — ⛔ NEVER its id (#18153).
241268
*
@@ -255,6 +282,10 @@ function lockedError(message: string, userMessage?: string): never {
255282
* - a title whose VALUE is the record id is refused too, so "no id in the
256283
* toast" holds structurally rather than by trusting the pointer.
257284
*
285+
* A third guard keeps the title to a field a caller can be served at all: a
286+
* display field declared `internal: true` or of a credential type gives no
287+
* title ({@link isWithheldTitleField}).
288+
*
258289
* An empty or whitespace-only title is absence, not a title.
259290
*/
260291
function recordTitleOf(
@@ -265,6 +296,7 @@ function recordTitleOf(
265296
if (!schema || !record || typeof record !== 'object') return undefined;
266297
const field = resolveDisplayField(schema as any);
267298
if (!field || field === 'id' || field === '_id') return undefined;
299+
if (isWithheldTitleField(schema, field)) return undefined;
268300
const raw = record[field];
269301
if (raw === null || raw === undefined || typeof raw === 'object') return undefined;
270302
const title = String(raw).trim();
@@ -827,9 +859,12 @@ export function bindApprovalLockHook(
827859
// answer the approval inbox narrows its titles and snapshots by (readable,
828860
// and not masked for this caller), asked with the writer's own envelope.
829861
// A display field the writer may not be served gives no title, and the
830-
// sentence degrades to the label — ⛔ never to the id.
862+
// sentence degrades to the label — ⛔ never to the id. A source that
863+
// cannot answer (it throws) serves no field here: no title nobody vetted.
831864
const served = record
832-
? await resolveReadableSnapshotFields(fieldVisibility?.(), object, writerEnvelope(ctx), logger)
865+
? await resolveReadableSnapshotFields(
866+
fieldVisibility?.(), object, writerEnvelope(ctx), logger, { failClosedOnThrow: true },
867+
)
833868
: undefined;
834869
const asServed = record && served !== undefined
835870
? redactSnapshot(record, served).payload as Record<string, unknown>

‎packages/plugins/plugin-approvals/src/payload-redaction.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,12 +182,20 @@ export function redactSnapshot(payload: unknown, readable: string[] | undefined)
182182
* mask hides. With the security plugin wired, the member is always present and
183183
* answers a list whenever the read projection does, so this branch is reached
184184
* only by a source that predates the member; it is logged for that reason.
185+
*
186+
* `options.failClosedOnThrow` turns case 3's THROW into `[]` (no field served)
187+
* for a caller whose served value is not a snapshot the same reader can open
188+
* elsewhere but a one-off disclosure — the record lock's refusal title. There
189+
* the availability trade above buys nothing: the refusal still answers, only
190+
* without a title nobody vetted. `undefined` from the source (schema
191+
* unresolvable) is unaffected.
185192
*/
186193
export async function resolveReadableSnapshotFields(
187194
security: FieldVisibilitySource | undefined,
188195
objectName: string | undefined,
189196
context: unknown,
190197
logger?: { warn?: (msg: string, meta?: Record<string, any>) => void },
198+
options?: { failClosedOnThrow?: boolean },
191199
): Promise<string[] | undefined> {
192200
if (!security || typeof security.getReadableFields !== 'function') return undefined;
193201
const object = String(objectName ?? '').trim();
@@ -196,6 +204,12 @@ export async function resolveReadableSnapshotFields(
196204
try {
197205
readable = await security.getReadableFields(object, context);
198206
} catch (err: any) {
207+
if (options?.failClosedOnThrow) {
208+
logger?.warn?.('[approvals] could not resolve readable fields — serving no field (fail closed)', {
209+
object, error: err?.message ?? String(err),
210+
});
211+
return [];
212+
}
199213
logger?.warn?.('[approvals] payload redaction could not resolve readable fields — serving the snapshot unredacted', {
200214
object, error: err?.message ?? String(err),
201215
});

‎packages/plugins/plugin-approvals/src/record-lock-refusal-writer-fls.integration.test.ts‎

Lines changed: 176 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
4040
import { ObjectQL } from '@objectstack/objectql';
4141
import { SqlDriver } from '@objectstack/driver-sql';
42-
import { bindApprovalLockHook } from './lifecycle-hooks.js';
42+
import { bindApprovalLockHook, bindDetailRowLockHook } from './lifecycle-hooks.js';
4343
import type { FieldVisibilitySource } from './payload-redaction.js';
4444
import { installDefaultOrganization } from './default-organization.testkit.js';
4545

@@ -192,3 +192,178 @@ describe('[#23618] the RECORD_LOCKED refusal names the record from what its writ
192192
expect(vis.calls).toEqual([{ object: 'opportunity', userId: RESTRICTED, permissions: [`grant_${RESTRICTED}`] }]);
193193
});
194194
});
195+
196+
/**
197+
* A locked record's refusal names it only by a field the writer may read.
198+
*
199+
* A column declared `internal: true`, or of a credential type, is one no
200+
* caller reads on any read path, so it never titles the refusal. When the
201+
* served-fields source cannot answer, the refusal names no title. A writer
202+
* refused a title still gets the same code, status and sentence, naming the
203+
* object's label.
204+
*
205+
* The stand-in source serves the writer every declared field (full
206+
* field-level access).
207+
*/
208+
describe('a locked record\'s refusal names it only by a field the writer may read', () => {
209+
const STORED = 'stored-value-7f3a';
210+
const ORDINARY_TITLE = 'Ordinary title';
211+
212+
const fieldsOf = (extra: Record<string, unknown>) => ({
213+
id: { name: 'id', type: 'text' as const, primaryKey: true },
214+
...extra,
215+
amount: { name: 'amount', type: 'number' as const },
216+
});
217+
218+
/** An explicit title pointer at an `internal: true` text column. */
219+
const INTERNAL_NAMED = {
220+
name: 'vault_entry', label: 'Vault Entry', nameField: 'code',
221+
fields: fieldsOf({ code: { name: 'code', type: 'text' as const, internal: true } }),
222+
};
223+
/** No pointer: the derivation lands on a name-ish column, which is `internal: true`. */
224+
const INTERNAL_DERIVED = {
225+
name: 'vault_token', label: 'Vault Token',
226+
fields: fieldsOf({ holder_name: { name: 'holder_name', type: 'text' as const, internal: true } }),
227+
};
228+
/** An explicit title pointer at a credential-typed column. */
229+
const CREDENTIAL_NAMED = {
230+
name: 'service_login', label: 'Service Login', nameField: 'passcode',
231+
fields: fieldsOf({ passcode: { name: 'passcode', type: 'password' as const } }),
232+
};
233+
/** The control: an ordinary display field. */
234+
const ORDINARY = {
235+
name: 'plain_deal', label: 'Plain Deal', nameField: 'name',
236+
fields: fieldsOf({ name: { name: 'name', type: 'text' as const } }),
237+
};
238+
/** A line under a locked master whose display field is `internal: true`. */
239+
const LINE = {
240+
name: 'vault_entry_line', label: 'Vault Entry Line',
241+
fields: {
242+
id: { name: 'id', type: 'text' as const, primaryKey: true },
243+
qty: { name: 'qty', type: 'number' as const },
244+
vault_entry: { name: 'vault_entry', type: 'master_detail' as const, reference: 'vault_entry' },
245+
},
246+
};
247+
248+
const OBJECTS = [INTERNAL_NAMED, INTERNAL_DERIVED, CREDENTIAL_NAMED, ORDINARY, LINE, APPROVAL_REQUEST];
249+
250+
type Mode = 'full' | 'throws' | 'none';
251+
let mode: Mode;
252+
let engine: ObjectQL;
253+
const locked: Record<string, string> = {};
254+
let lineId: string;
255+
256+
/** Full field-level access for the writer, as the security service answers it. */
257+
const source = (): FieldVisibilitySource | undefined => {
258+
if (mode === 'none') return undefined;
259+
const every = (object: string) => Object.keys((OBJECTS.find((o) => o.name === object) as any)?.fields ?? {});
260+
return {
261+
async getReadableFields(object: string, context?: any) {
262+
if (mode === 'throws' && !context?.isSystem) throw new Error('field-visibility source unavailable');
263+
return every(object);
264+
},
265+
async getQueryableFields(object: string) {
266+
return every(object);
267+
},
268+
};
269+
};
270+
271+
afterEach(async () => {
272+
try { await engine?.destroy(); } catch { /* noop */ }
273+
});
274+
275+
beforeEach(async () => {
276+
mode = 'full';
277+
engine = new ObjectQL();
278+
engine.registerDriver(new SqlDriver({
279+
client: 'better-sqlite3',
280+
connection: { filename: ':memory:' },
281+
useNullAsDefault: true,
282+
}), true);
283+
await engine.init();
284+
for (const o of OBJECTS) engine.registry.registerObject(o as any, 'com.objectstack.test.lock-title-withheld');
285+
await engine.syncSchemas();
286+
await installDefaultOrganization(engine);
287+
288+
const seeds: Array<[string, Record<string, unknown>]> = [
289+
['vault_entry', { code: STORED, amount: 1 }],
290+
['vault_token', { holder_name: STORED, amount: 1 }],
291+
['service_login', { passcode: STORED, amount: 1 }],
292+
['plain_deal', { name: ORDINARY_TITLE, amount: 1 }],
293+
];
294+
for (const [object, row] of seeds) {
295+
locked[object] = String((await engine.insert(object, row, { context: SYSTEM } as any)).id);
296+
await engine.insert('sys_approval_request', {
297+
object_name: object, record_id: locked[object], status: 'pending', flow_run_id: `run_${object}`,
298+
node_config_json: JSON.stringify({ lockRecord: true }),
299+
}, { context: SYSTEM } as any);
300+
}
301+
lineId = String((await engine.insert('vault_entry_line', { qty: 1, vault_entry: locked.vault_entry }, { context: SYSTEM } as any)).id);
302+
303+
bindApprovalLockHook(engine as any, { warn: () => {}, info: () => {} }, source);
304+
bindDetailRowLockHook(engine as any, { warn: () => {}, info: () => {} });
305+
});
306+
307+
async function refused(write: () => Promise<unknown>): Promise<any> {
308+
let thrown: any = null;
309+
try { await write(); } catch (e) { thrown = e; }
310+
expect(thrown, 'the write was not refused').not.toBeNull();
311+
expect(thrown.code).toBe('RECORD_LOCKED');
312+
expect(thrown.statusCode).toBe(409);
313+
return thrown;
314+
}
315+
316+
const update = (object: string, options: Record<string, unknown> = { where: { id: locked[object] } }) =>
317+
refused(() => engine.update(object, { amount: 2 }, { ...options, context: asUser(WRITER) } as any));
318+
319+
const expectUntitled = (thrown: any, label: string) => {
320+
const sentence = `This ${label} ${LOCKED_SENTENCE}`;
321+
expect(thrown.message).toBe(`RECORD_LOCKED: ${sentence}`);
322+
expect(thrown.userMessage).toBe(sentence);
323+
expect(`${thrown.message} ${thrown.userMessage}`).not.toContain(STORED);
324+
};
325+
326+
it('an internal display field named by the object gives no title — by-id update', async () => {
327+
expectUntitled(await update('vault_entry'), 'Vault Entry');
328+
});
329+
330+
it('…nor on a predicate update, where the refusal is raised per matched row', async () => {
331+
expectUntitled(await update('vault_entry', { where: { amount: 1 }, multi: true }), 'Vault Entry');
332+
});
333+
334+
it('an internal display field the object derives gives no title', async () => {
335+
expectUntitled(await update('vault_token'), 'Vault Token');
336+
});
337+
338+
it('a credential-typed display field gives no title', async () => {
339+
expectUntitled(await update('service_login'), 'Service Login');
340+
});
341+
342+
it('a line under a locked master is refused without the master\'s withheld title — update and delete', async () => {
343+
const opts = { where: { id: lineId }, context: asUser(WRITER) } as any;
344+
expectUntitled(await refused(() => engine.update('vault_entry_line', { qty: 3 }, opts)), 'Vault Entry');
345+
expectUntitled(await refused(() => engine.delete('vault_entry_line', opts)), 'Vault Entry');
346+
});
347+
348+
it('a served-fields source that cannot answer gives no title', async () => {
349+
mode = 'throws';
350+
expectUntitled(await update('plain_deal'), 'Plain Deal');
351+
});
352+
353+
it('control: an ordinary display field still names the record', async () => {
354+
const thrown = await update('plain_deal');
355+
expect(thrown.message).toBe(`RECORD_LOCKED: Plain Deal '${ORDINARY_TITLE}' ${LOCKED_SENTENCE}`);
356+
});
357+
358+
it('control: with no served-fields source wired, an ordinary display field still names the record', async () => {
359+
mode = 'none';
360+
const thrown = await update('plain_deal');
361+
expect(thrown.message).toBe(`RECORD_LOCKED: Plain Deal '${ORDINARY_TITLE}' ${LOCKED_SENTENCE}`);
362+
});
363+
364+
it('with no served-fields source wired, a withheld display field still gives no title', async () => {
365+
mode = 'none';
366+
expectUntitled(await update('vault_entry'), 'Vault Entry');
367+
expectUntitled(await update('service_login'), 'Service Login');
368+
});
369+
});

0 commit comments

Comments
 (0)