diff --git a/.changeset/33524-master-edit-refusal-user-message.md b/.changeset/33524-master-edit-refusal-user-message.md new file mode 100644 index 00000000000..877722b0811 --- /dev/null +++ b/.changeset/33524-master-edit-refusal-user-message.md @@ -0,0 +1,15 @@ +--- +'@objectstack/spec': patch +'@objectstack/plugin-security': patch +--- + +fix(plugin-security, spec): the master-detail write refusal tells its user which master record needs their access, in their language + +Clause-②: no +Metadata-protocol: none + +A write of a `controlled_by_parent` detail (create, edit, delete and the other write verbs) refused because the caller lacks edit access on its master record (or read access, on a detail that declares `writeRequiresMasterRead`) now carries a `userMessage`. It names the master object's label: the deployment's translation in the caller's language, else the declared label. The caller's language is the request locale, else the workspace default, else English. The console shows a refusal's `userMessage` in place of its generic "You don't have permission to save this record.", so a user creating a billing milestone under a contract they can read but not edit now reads that the missing access is on the contract. + +The sentences are new keys in the operation-message catalog (en, zh-CN, ja-JP, es-ES): `errors.master_record_edit_denied` and `errors.master_record_read_denied`, with `{{master}}`, and their `_opaque` forms, which name no master. The opaque forms answer a writer who cannot read the master reference (the refusal names no master to them) and a master object with no label. A deployment overrides any of the four with a `translation` item under that key. + +The HTTP status, `code`, `message` and `details` of the refusal are unchanged; only `userMessage` is added. The owner-rule refusal of a row whose optional master is empty is unchanged and carries no `userMessage`. diff --git a/packages/plugins/plugin-security/src/controlled-by-parent-master-edit-user-message.test.ts b/packages/plugins/plugin-security/src/controlled-by-parent-master-edit-user-message.test.ts new file mode 100644 index 00000000000..775bc30820a --- /dev/null +++ b/packages/plugins/plugin-security/src/controlled-by-parent-master-edit-user-message.test.ts @@ -0,0 +1,264 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0055 §3] A write of a `controlled_by_parent` detail refused for want of + * access on its MASTER record carries the end user's half as `userMessage`: + * the operation-message catalog's `master_record_edit_denied` (or + * `master_record_read_denied`, on a detail that asks read), naming the master + * object's LABEL in the caller's language — the request locale, else the + * workspace default — beside a `code`, status and `message` that do not move. + * + * The console replaces a `403 PERMISSION_DENIED` that carries no `userMessage` + * with its generic "You don't have permission to save this record.", so before + * this a user creating a detail under a master they read but cannot edit never + * learned that the missing access was on the master. + * + * Two forms name nothing (`_opaque`): a writer who cannot read the master + * reference (the refusal's own sentence names no master to them), and a + * master object with no label (an API name never reaches a user). The CONTROL + * is the gate's other refusal, the owner rule of a row whose optional master + * is empty: its sentence is its own and it carries no `userMessage`. + * + * Measured with the real security layer on a real `ObjectQL` over a real + * `SqlDriver`, through the engine's own writes. The console half is pinned in + * `ui/packages/plugin-form/src/ModalForm.markedRefusal-33524.test.tsx`. + */ + +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysUser } from '@objectstack/platform-objects/identity'; +import { PermissionSetSchema, type PermissionSet } from '@objectstack/spec/security'; +import { BUILTIN_OPERATION_MESSAGES, objectLabelKey, renderOperationMessage } from '@objectstack/spec/system'; +import { mapDataError } from '@objectstack/types'; +import { SecurityPlugin } from './security-plugin.js'; +import { wireEngineSecuritySource } from './engine-security-source.testkit.js'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const SYS = { context: { isSystem: true, userId: 'usr_system', tenantId: DEFAULT_ORGANIZATION_ID } } as never; +const WRITER = 'usr_writer'; +const OTHER = 'usr_other'; + +const CRUD = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; +const READ_ONLY = { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false }; +const GRANTS = { + '*': CRUD, + // Masters the writer reads and does not edit: the object-permission leg. + mue_contract: READ_ONLY, + mue_vault: READ_ONLY, + // A master the writer does not read: the read question of an opted-in detail. + mue_ledger: { allowRead: false, allowCreate: false, allowEdit: false, allowDelete: false }, + // Every contact readable, none of them the writer's, no Modify All: the owner rule refuses. + mue_contact: { ...CRUD, viewAllRecords: true }, +}; +const READABLE_SET: PermissionSet = PermissionSetSchema.parse({ name: 'mue_readable', label: 'Readable', objects: GRANTS }); +/** The same set with the milestone's master reference hidden from its holder. */ +const HIDDEN_SET: PermissionSet = PermissionSetSchema.parse({ + name: 'mue_hidden', label: 'Hidden', objects: GRANTS, + fields: { 'mue_milestone.contract': { readable: false, editable: true } }, +}); +const SETS = [READABLE_SET, HIDDEN_SET]; + +const callerOf = (set: PermissionSet, locale?: string, workspaceLocale?: string) => ({ + userId: WRITER, positions: [], permissions: [set.name], posture: 'MEMBER', tenantId: DEFAULT_ORGANIZATION_ID, + ...(locale ? { locale } : {}), + ...(workspaceLocale ? { workspaceLocale } : {}), +}); + +/** The deployment's translations: the contract's label in zh-CN only. */ +const TRANSLATIONS: Record> = { + 'zh-CN': { [objectLabelKey('mue_contract')]: '合同' }, +}; + +const text = (name: string) => ({ name, type: 'text' }); +const MASTER_READ_OPT_IN = { sharing: { controlledByParent: { writeRequiresMasterRead: true } } }; +const OBJECTS = [ + SysUser, + { name: 'mue_contract', label: 'Contract', sharingModel: 'public_read_write', fields: { name: text('name') } }, + // A master whose label is its API name: no label to name. + { name: 'mue_vault', label: 'mue_vault', sharingModel: 'public_read_write', fields: { name: text('name') } }, + { name: 'mue_ledger', label: 'Ledger', sharingModel: 'public_read_write', fields: { name: text('name') } }, + { + name: 'mue_milestone', label: 'Billing Milestone', sharingModel: 'controlled_by_parent', + fields: { name: text('name'), contract: { name: 'contract', type: 'master_detail', reference: 'mue_contract', required: true } }, + }, + { + name: 'mue_note', label: 'Note', sharingModel: 'controlled_by_parent', + fields: { name: text('name'), vault: { name: 'vault', type: 'master_detail', reference: 'mue_vault', required: true } }, + }, + { + name: 'mue_entry', label: 'Entry', sharingModel: 'controlled_by_parent', ...MASTER_READ_OPT_IN, + fields: { name: text('name'), ledger: { name: 'ledger', type: 'master_detail', reference: 'mue_ledger', required: true } }, + }, + { + name: 'mue_contact', label: 'Contact', sharingModel: 'controlled_by_parent', + fields: { name: text('name'), contract: { name: 'contract', type: 'master_detail', reference: 'mue_contract', required: false } }, + }, +]; + +let engine: ObjectQL; + +beforeAll(async () => { + engine = new ObjectQL(); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as never, + true, + ); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.qa.master-edit-user-message', + name: 'A master-detail write refusal names the master to its user', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: OBJECTS, + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine as never); + + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + (type === 'permission' ? SETS.find((s) => s.name === name) : engine.getSchema(name)) ?? null, + list: async () => SETS, + }, + sharing: { canEdit: async () => true }, + i18n: { t: (key: string, loc: string) => TRANSLATIONS[loc]?.[key] ?? key }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + hook: () => undefined, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'mue_readable' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + wireEngineSecuritySource(engine, () => plugin); + vi.spyOn((engine as unknown as { logger: { warn: () => void } }).logger, 'warn').mockImplementation(() => undefined); + + await engine.insert('sys_user', [WRITER, OTHER].map((id) => ({ id, name: id, email: `${id}@mue.test` })), SYS); + await engine.insert('mue_contract', [{ id: 'ctr_1', name: 'contract' }], SYS); + await engine.insert('mue_vault', [{ id: 'vault_1', name: 'vault' }], SYS); + await engine.insert('mue_ledger', [{ id: 'ledger_1', name: 'ledger' }], SYS); + await engine.insert('mue_milestone', [{ id: 'ms_1', name: 'milestone', contract: 'ctr_1' }], SYS); + await engine.insert('mue_note', [{ id: 'note_1', name: 'note', vault: 'vault_1' }], SYS); + await engine.insert('mue_contact', [{ id: 'ct_orphan', name: 'contact', contract: null, owner_id: OTHER }], SYS); +}); + +afterAll(async () => { + try { await engine?.destroy(); } catch { /* noop */ } +}); + +/** The refusal a write threw; a failure when it was admitted. */ +async function refusal(write: Promise): Promise { + try { + await write; + } catch (e) { + return e; + } + throw new Error('expected the write to be refused'); +} +const insert = (object: string, data: Record, caller: unknown) => + refusal(engine.insert(object, data, { context: { ...(caller as object) } } as never)); +const update = (object: string, id: string, data: Record, caller: unknown) => + refusal(engine.update(object, data, { where: { id }, context: { ...(caller as object) } } as never)); +const remove = (object: string, id: string, caller: unknown) => + refusal(engine.delete(object, { where: { id }, context: { ...(caller as object) } } as never)); + +const edit = (locale: string, master: string) => + renderOperationMessage({ messageKey: 'master_record_edit_denied', params: { master } }, { locale }); + +/** The envelope the refusal kept: code, status, the diagnostic's opening. */ +function expectGateEnvelope(e: any, operation: string, object: string, question = 'edit') { + expect(e.code).toBe('PERMISSION_DENIED'); + expect(e.statusCode ?? e.status).toBe(403); + expect(String(e.message)).toMatch( + new RegExp(`^\\[Security\\] Access denied: ${operation} on '${object}' requires ${question} access to its master record \\(`), + ); +} + +describe('master-detail write refusal: the userMessage names the master', () => { + it('create, en: names the master label', async () => { + const e = await insert('mue_milestone', { name: 'new', contract: 'ctr_1' }, callerOf(READABLE_SET, 'en')); + expectGateEnvelope(e, 'insert', 'mue_milestone'); + expect(e.userMessage).toBe(edit('en', 'Contract')); + expect(e.userMessage).toContain('Contract'); + }); + + it('create, zh-CN: names the translated label in the zh-CN sentence', async () => { + const e = await insert('mue_milestone', { name: 'new', contract: 'ctr_1' }, callerOf(READABLE_SET, 'zh-CN')); + expectGateEnvelope(e, 'insert', 'mue_milestone'); + expect(e.userMessage).toBe('您需要拥有这条记录所属合同的编辑权限,如需访问请联系该合同的负责人或管理员。'); + }); + + it('edit, en and zh-CN: the same sentence for an update of a stored detail', async () => { + const en = await update('mue_milestone', 'ms_1', { name: 'renamed' }, callerOf(READABLE_SET, 'en')); + expectGateEnvelope(en, 'update', 'mue_milestone'); + expect(en.userMessage).toBe(edit('en', 'Contract')); + const zh = await update('mue_milestone', 'ms_1', { name: 'renamed' }, callerOf(READABLE_SET, 'zh-CN')); + expectGateEnvelope(zh, 'update', 'mue_milestone'); + expect(zh.userMessage).toBe(edit('zh-CN', '合同')); + }); + + it('delete: the lifecycle verb reaches the same refusal and the same sentence', async () => { + const e = await remove('mue_milestone', 'ms_1', callerOf(READABLE_SET, 'en')); + expectGateEnvelope(e, 'delete', 'mue_milestone'); + expect(e.userMessage).toBe(edit('en', 'Contract')); + }); + + it('a request language with no text falls back to the workspace default', async () => { + const e = await insert('mue_milestone', { name: 'new', contract: 'ctr_1' }, callerOf(READABLE_SET, 'de-DE', 'zh-CN')); + expect(e.userMessage).toBe(edit('zh-CN', '合同')); + }); + + it('no translation in the resolved language: the declared label, in that language\'s sentence', async () => { + const e = await insert('mue_milestone', { name: 'new', contract: 'ctr_1' }, callerOf(READABLE_SET, 'ja-JP')); + expect(e.userMessage).toBe(edit('ja-JP', 'Contract')); + }); + + it('the read question: a detail that asks read on its master says read', async () => { + const e = await insert('mue_entry', { name: 'new', ledger: 'ledger_1' }, callerOf(READABLE_SET, 'en')); + expectGateEnvelope(e, 'insert', 'mue_entry', 'read'); + expect(e.userMessage).toBe(renderOperationMessage( + { messageKey: 'master_record_read_denied', params: { master: 'Ledger' } }, { locale: 'en' }, + )); + }); + + it('a writer who cannot read the master reference is named no master', async () => { + const e = await insert('mue_milestone', { name: 'new', contract: 'ctr_1' }, callerOf(HIDDEN_SET, 'zh-CN')); + expectGateEnvelope(e, 'insert', 'mue_milestone'); + expect(e.userMessage).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].master_record_edit_denied_opaque); + expect(e.userMessage).not.toContain('合同'); + expect(String(e.message)).not.toContain('mue_contract'); + }); + + it('a master with no label is named by none, never by its API name', async () => { + const e = await insert('mue_note', { name: 'new', vault: 'vault_1' }, callerOf(READABLE_SET, 'en')); + expectGateEnvelope(e, 'insert', 'mue_note'); + expect(e.userMessage).toBe(BUILTIN_OPERATION_MESSAGES.en.master_record_edit_denied_opaque); + }); + + it('CONTROL: the owner rule of a row with no master keeps its own sentence and carries no userMessage', async () => { + const e = await update('mue_contact', 'ct_orphan', { name: 'renamed' }, callerOf(READABLE_SET, 'en')); + expect(e.code).toBe('PERMISSION_DENIED'); + expect(e.statusCode ?? e.status).toBe(403); + expect(String(e.message)).toMatch(/is permitted only to the record's owner or a holder of Modify All/); + expect('userMessage' in e).toBe(false); + }); + + it('the REST data door relays it: code and status unchanged, userMessage on the body', async () => { + const answer = mapDataError( + await insert('mue_milestone', { name: 'new', contract: 'ctr_1' }, callerOf(READABLE_SET, 'zh-CN')), + 'mue_milestone', + ); + expect(answer.status).toBe(403); + expect(answer.body.code).toBe('PERMISSION_DENIED'); + expect(answer.body.userMessage).toBe(edit('zh-CN', '合同')); + }); +}); diff --git a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts index 0a3f81e4963..f4bb68c5609 100644 --- a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts +++ b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts @@ -97,6 +97,7 @@ import { markFilterSubtreeProvenance } from '@objectstack/spec/data'; import { BUILTIN_OPERATION_MESSAGES, objectFieldLabelKey, + objectLabelKey, operationMessageTranslationKey, renderOperationMessage, resolveBundleLocale, @@ -130,6 +131,7 @@ import { } from './unresolved-posture.js'; import { assertReadableQueryFields } from './predicate-guard.js'; import { PermissionDeniedError, MaskedValueWriteError } from './errors.js'; +import { masterGateRefusalUserCopyOf, type MasterQuestion } from './security-plugin-cbp-write-gate.js'; import { QUEUE_FIELD, CLAIM_REFUSAL, @@ -274,8 +276,8 @@ function denialLocaleOf( /** * The catalog keys this middleware renders. The first three are the `message` * of the gates #7414 / #7451 localized; the rest are the `userMessage` of the - * owner-anchor, queue and field-write refusals ({@link withUserMessage}); the - * last two are the list rules `field_edit_denied`'s `{{fields}}` is spelled by + * owner-anchor, queue, field-write and master-detail write refusals + * ({@link withUserMessage}); the last two are the list rules `field_edit_denied`'s `{{fields}}` is spelled by * ({@link labelList}). */ type UserFacingDenialKey = @@ -289,6 +291,10 @@ type UserFacingDenialKey = | 'record_queue_assign_denied' | 'field_edit_denied' | 'field_edit_denied_opaque' + | 'master_record_edit_denied' + | 'master_record_edit_denied_opaque' + | 'master_record_read_denied' + | 'master_record_read_denied_opaque' | 'field_label_quoted' | 'field_label_list_separator'; @@ -386,6 +392,54 @@ function fieldEditDenialMessage( return userFacingDenialMessage(ctx, 'field_edit_denied', locale, { fields: labelList(ctx, labels, locale) }); } +/** + * [ADR-0055 §3] The master-detail write gate's `userMessage`: the user saving a + * `controlled_by_parent` record lacks edit (or read) access on its MASTER + * record, so the sentence names the master object's LABEL — the deployment's + * translation in the language the sentence resolves to, else the declared + * label — and sends the user to that record's owner + * (`master_record_edit_denied` / `master_record_read_denied`). + * + * The `_opaque` form names nothing, for two callers: one the gate names no + * master to (it cannot read the master reference, `copy.master` absent), and + * a master with no label, because an API name never reaches a user (#7414). + */ +function masterGateDenialMessage( + ctx: PluginContext, + ql: IObjectQLEngine, + copy: { question: MasterQuestion; master: string | undefined }, + locales: DenialLocales, +): string { + const named: UserFacingDenialKey = copy.question === 'read' ? 'master_record_read_denied' : 'master_record_edit_denied'; + const opaque: UserFacingDenialKey = + copy.question === 'read' ? 'master_record_read_denied_opaque' : 'master_record_edit_denied_opaque'; + const master = copy.master; + if (master === undefined) return userFacingDenialMessage(ctx, opaque, locales); + const translate = denialTranslator(ctx); + const loc = denialLocaleOf(named, locales, translate) ?? 'en'; + let label: string | undefined; + if (translate) { + const key = objectLabelKey(master); + try { + const translated = translate(key, loc); + if (typeof translated === 'string' && translated.trim().length > 0 && translated !== key) label = translated.trim(); + } catch { + // A misbehaving i18n service must not turn a 403 into a 500. + } + } + if (label === undefined) { + let declared: unknown; + try { + declared = typeof ql?.getSchema === 'function' ? (ql.getSchema(master) as { label?: unknown } | undefined)?.label : undefined; + } catch { + declared = undefined; + } + if (typeof declared === 'string' && declared.trim().length > 0) label = declared.trim(); + } + if (label === undefined || label === master) return userFacingDenialMessage(ctx, opaque, [loc]); + return userFacingDenialMessage(ctx, named, [loc], { master: label }); +} + /** * The labels as one phrase in the caller's locale: each quoted by the * catalog's `field_label_quoted` and joined by its `field_label_list_separator` @@ -1473,23 +1527,34 @@ export function registerAuthzMiddleware( !!opCtx.context?.userId && this.ql ) { - await this.assertControlledByParentWrite( - permissionSets, - opCtx.object, - opCtx.operation, - opCtx, - opCtx.context, - ); - // [ADR-0090 D10] The delegator must ALSO have edit access to the master - // — a detail write on behalf of a user requires that user's master-edit. - if (delegatorSets) { + // [ADR-0055 §3] A refusal of the gate's keeps its `code`, status and + // `message`, and gains the end user's half ({@link masterGateDenialMessage}): + // the console shows a 403's `userMessage` in place of its generic line. + try { await this.assertControlledByParentWrite( - delegatorSets, + permissionSets, opCtx.object, opCtx.operation, opCtx, - delegatorContext, + opCtx.context, ); + // [ADR-0090 D10] The delegator must ALSO have edit access to the master + // — a detail write on behalf of a user requires that user's master-edit. + if (delegatorSets) { + await this.assertControlledByParentWrite( + delegatorSets, + opCtx.object, + opCtx.operation, + opCtx, + delegatorContext, + ); + } + } catch (e) { + const copy = masterGateRefusalUserCopyOf(e); + if (copy) { + withUserMessage(e as PermissionDeniedError, masterGateDenialMessage(ctx, ql, copy, denialLocalesOf(opCtx.context))); + } + throw e; } } diff --git a/packages/plugins/plugin-security/src/security-plugin-cbp-write-gate.ts b/packages/plugins/plugin-security/src/security-plugin-cbp-write-gate.ts index de20609c13c..e2178931bbe 100644 --- a/packages/plugins/plugin-security/src/security-plugin-cbp-write-gate.ts +++ b/packages/plugins/plugin-security/src/security-plugin-cbp-write-gate.ts @@ -147,6 +147,36 @@ export type MasterQuestion = 'edit' | 'read'; */ const MASTER_DENIAL_QUESTION = new WeakMap(); +/** + * [ADR-0055 §3] The master a gate refusal may NAME to the end user, keyed by + * the refusal itself, beside {@link MASTER_EDIT_DENIAL_LEG} and for the same + * reason: nothing is added to the error's own properties here. Written where a + * master-edit refusal is built (`masterEditDenied`, the master the caller's + * object names) and where it is reworded for a caller who cannot read the + * master reference (`undefined`: that caller is named no master). A refusal + * without an entry is not a master-access refusal — the owner rule of a row + * that names no master ({@link assertControlledByParentWrite}'s + * `nullMasterOwnerDenied`) has its own sentence and carries no user copy. + */ +const MASTER_DENIAL_NAMED_MASTER = new WeakMap(); + +/** + * The end user's half of a master-gate refusal, read off the refusal: the + * question it answered and the master object it may name (`undefined` = name + * none). `undefined` when `e` is not a master-access refusal of this gate. + * The authorization middleware renders it into the refusal's `userMessage` + * from the operation-message catalog (`master_record_edit_denied` and its + * siblings); `code`, status and `message` are the gate's, unchanged. + */ +export function masterGateRefusalUserCopyOf( + e: unknown, +): { question: MasterQuestion; master: string | undefined } | undefined { + if (!(e instanceof PermissionDeniedError)) return undefined; + const named = MASTER_DENIAL_NAMED_MASTER.get(e); + if (!named) return undefined; + return { question: MASTER_DENIAL_QUESTION.get(e) ?? 'edit', master: named.master }; +} + /** * The gate's refusal builder, as the chain walk and the legs receive it: the * leg, the reason, the master row it names, and the question that was asked @@ -423,6 +453,7 @@ export async function assertControlledByParentWrite( ); MASTER_EDIT_DENIAL_LEG.set(withheld, leg); if (question !== 'edit') MASTER_DENIAL_QUESTION.set(withheld, question); + MASTER_DENIAL_NAMED_MASTER.set(withheld, { master: undefined }); throw withheld; } } @@ -467,6 +498,8 @@ async function judgeControlledByParentWrite( ); MASTER_EDIT_DENIAL_LEG.set(denial, leg); if (question !== 'edit') MASTER_DENIAL_QUESTION.set(denial, question); + // Built only after `rel` below resolved: every caller of this builder runs past it. + MASTER_DENIAL_NAMED_MASTER.set(denial, { master: rel?.master }); return denial; }; const denyMasterEdit = (leg: ControlledByParentWriteDenialLeg, reason: string, recordId?: unknown): never => { diff --git a/packages/spec/src/system/operation-message.test.ts b/packages/spec/src/system/operation-message.test.ts index 10126e95fad..049625165b0 100644 --- a/packages/spec/src/system/operation-message.test.ts +++ b/packages/spec/src/system/operation-message.test.ts @@ -549,3 +549,60 @@ describe('operation message catalog — the duplicate refusal', () => { } }); }); + +/** + * The master-detail write gate's refusal (ADR-0055 §3): the user's half of a + * `controlled_by_parent` write refused for want of edit (or read) access on + * the master record. The named forms carry the master's label; the opaque + * forms, for a writer who cannot read the master reference or a master with no + * label, carry none. The emitter is pinned in + * `packages/plugins/plugin-security/src/controlled-by-parent-master-edit-user-message.test.ts`. + */ +describe('operation message catalog — the master-detail write refusal', () => { + const NAMED = ['master_record_edit_denied', 'master_record_read_denied'] as const; + const OPAQUE = ['master_record_edit_denied_opaque', 'master_record_read_denied_opaque'] as const; + const GRANT_VOCABULARY = /controlled_by_parent|master_detail|allowEdit|modifyAllRecords|_id\b|\[Security\]|Access denied/; + + it('every locale defines all four: the named forms take {{master}} only, the opaque forms no placeholder', () => { + const locales = Object.keys(BUILTIN_OPERATION_MESSAGES); + expect(locales.length).toBeGreaterThanOrEqual(4); + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const key of NAMED) { + expect(catalog[key], `${locale} defines ${key}`).toBeTypeOf('string'); + expect(new Set(catalog[key].match(/\{\{\w+\}\}/g)), `${locale}.${key}`).toEqual(new Set(['{{master}}'])); + expect(catalog[key], `${locale}.${key}`).not.toMatch(GRANT_VOCABULARY); + } + for (const key of OPAQUE) { + expect(catalog[key], `${locale} defines ${key}`).toBeTypeOf('string'); + expect(catalog[key], `${locale}.${key} placeholder-free`).not.toMatch(/[{}]/); + expect(catalog[key], `${locale}.${key}`).not.toMatch(GRANT_VOCABULARY); + } + } + }); + + it('edit and read are two sentences, and neither is a sibling restated, in any locale', () => { + const SIBLINGS = ['permission_denied', 'record_access_denied', 'record_write_denied'] as const; + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + expect(catalog.master_record_edit_denied, locale).not.toBe(catalog.master_record_read_denied); + expect(catalog.master_record_edit_denied_opaque, locale).not.toBe(catalog.master_record_read_denied_opaque); + for (const key of [...NAMED, ...OPAQUE]) { + for (const sibling of SIBLINGS) expect(catalog[key], `${locale}.${key} vs ${sibling}`).not.toBe(catalog[sibling]); + } + } + }); + + it('names the master label in the caller locale', () => { + expect(renderOperationMessage({ messageKey: 'master_record_edit_denied', params: { master: 'Contract' } }, { locale: 'en' })) + .toBe('You need edit access to the Contract this record belongs to. Contact the person who owns that Contract, or your administrator, if you need access.'); + expect(renderOperationMessage({ messageKey: 'master_record_edit_denied', params: { master: '合同' } }, { locale: 'zh-CN' })) + .toBe('您需要拥有这条记录所属合同的编辑权限,如需访问请联系该合同的负责人或管理员。'); + }); + + it('a deployment translation override wins, under the shared `errors.` address', () => { + for (const key of [...NAMED, ...OPAQUE]) { + expect(operationMessageTranslationKey(key)).toBe(`errors.${key}`); + const translate = (k: string) => (k === `errors.${key}` ? '部署自定义文案。' : k); + expect(renderOperationMessage({ messageKey: key }, { locale: 'zh-CN', translate })).toBe('部署自定义文案。'); + } + }); +}); diff --git a/packages/spec/src/system/operation-message.ts b/packages/spec/src/system/operation-message.ts index ee68ac270dc..b89ca9f78a7 100644 --- a/packages/spec/src/system/operation-message.ts +++ b/packages/spec/src/system/operation-message.ts @@ -15,7 +15,8 @@ * conversion is #12260's half) and plugin-approvals' non-submitter recall * refusal (`approval_recall_not_submitter`; emitter conversion is #11993's * half) — and the unique-constraint refusal (`409 UNIQUE_VIOLATION` on the - * wire, the engine's `DuplicateRecordError`). The catalog is the seat for the rest of the family as they are + * wire, the engine's `DuplicateRecordError`) — and the `userMessage` of the + * master-detail write gate's `403 PERMISSION_DENIED` (ADR-0055 §3). The catalog is the seat for the rest of the family as they are * localized — a second mechanism for the second producer is exactly what this * module exists to prevent. * @@ -37,6 +38,7 @@ * | `record_owner_remove_denied` | they tried to leave this record with no owner | ask an administrator | * | `record_queue_change_denied` | they tried to change which queue an existing record is in (put it in one, take it out, or move it to another) without the right to | ask an administrator | * | `record_queue_assign_denied` | they tried to create a record in a queue they do not belong to | leave the queue blank or choose one they belong to, or ask an administrator | + * | `master_record_edit_denied` / `master_record_read_denied` (and their `_opaque` forms) | they wrote a `controlled_by_parent` record (a detail) without the edit access (or, where the detail asks it, the read access) its master record requires | ask the master record's owner, or an administrator | * | `field_edit_denied` / `field_edit_denied_opaque` | they changed a field their permissions do not let them edit | undo that change, or ask an administrator | * * `record_write_denied` (commit aa5994e17) is NOT `record_access_denied` restated: the @@ -55,6 +57,16 @@ * record — the #3424 override), so the sentence sends the user to the * submitter or an administrator instead of dead-ending them. * + * `master_record_edit_denied` / `master_record_read_denied` are the + * master-detail write gate's refusals (ADR-0055 §3, plugin-security): the + * record the user is saving takes its access from a master record, and the + * access they lack is on THAT record, so the sentence names the master's + * object LABEL (`{{master}}`) and sends them to its owner. The `_opaque` forms + * name no master: the gate uses them for a writer who cannot read the + * master reference (the refusal's diagnostic names no master to them either) + * and for a master object with no label, since an API name never reaches a + * user. Which check refused, and which master row, stay on the diagnostic. + * * The distinction the copy does NOT make is the internal one: a caller blocked * by a missing CRUD bit and a caller blocked by a missing `requiredPermissions` * capability are in the SAME situation (their grants do not cover the action; @@ -282,6 +294,14 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'You do not have permission to change which queue this record is in. Contact your administrator if it needs to be moved.', record_queue_assign_denied: 'You do not have permission to create a record in that queue. Leave the queue blank or choose a queue you belong to, or contact your administrator.', + master_record_edit_denied: + 'You need edit access to the {{master}} this record belongs to. Contact the person who owns that {{master}}, or your administrator, if you need access.', + master_record_edit_denied_opaque: + 'You need edit access to the parent record this record belongs to. Contact your administrator if you need access.', + master_record_read_denied: + 'You need read access to the {{master}} this record belongs to. Contact the person who owns that {{master}}, or your administrator, if you need access.', + master_record_read_denied_opaque: + 'You need read access to the parent record this record belongs to. Contact your administrator if you need access.', field_edit_denied: 'You do not have permission to edit {{fields}}. Undo those changes and try again, or contact your administrator if you need access.', field_edit_denied_opaque: @@ -311,6 +331,10 @@ export const BUILTIN_OPERATION_MESSAGES: Record> record_owner_remove_denied: '您无权清除这条记录的负责人,如需更换负责人请联系管理员。', record_queue_change_denied: '您无权更改这条记录所在的队列,如需调整请联系管理员。', record_queue_assign_denied: '您无权在该队列中创建记录,请将队列留空或选择您所属的队列,或联系管理员。', + master_record_edit_denied: '您需要拥有这条记录所属{{master}}的编辑权限,如需访问请联系该{{master}}的负责人或管理员。', + master_record_edit_denied_opaque: '您需要拥有这条记录所属上级记录的编辑权限,如需访问请联系管理员。', + master_record_read_denied: '您需要拥有这条记录所属{{master}}的查看权限,如需访问请联系该{{master}}的负责人或管理员。', + master_record_read_denied_opaque: '您需要拥有这条记录所属上级记录的查看权限,如需访问请联系管理员。', field_edit_denied: '您无权编辑{{fields}},请撤销这些修改后重试,或联系管理员。', field_edit_denied_opaque: '您无权编辑所修改的部分字段,请撤销这些修改后重试,或联系管理员。', field_label_quoted: '「{{label}}」', @@ -347,6 +371,14 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'このレコードのキューを変更する権限がありません。移動が必要な場合は管理者にお問い合わせください。', record_queue_assign_denied: '指定したキューにレコードを作成する権限がありません。キューを空欄にするか自分が所属するキューを選択するか、管理者にお問い合わせください。', + master_record_edit_denied: + 'このレコードが属する{{master}}の編集権限が必要です。アクセスが必要な場合は、その{{master}}の担当者または管理者にお問い合わせください。', + master_record_edit_denied_opaque: + 'このレコードが属する親レコードの編集権限が必要です。アクセスが必要な場合は管理者にお問い合わせください。', + master_record_read_denied: + 'このレコードが属する{{master}}の参照権限が必要です。アクセスが必要な場合は、その{{master}}の担当者または管理者にお問い合わせください。', + master_record_read_denied_opaque: + 'このレコードが属する親レコードの参照権限が必要です。アクセスが必要な場合は管理者にお問い合わせください。', field_edit_denied: '{{fields}}を編集する権限がありません。その変更を取り消して再試行するか、管理者にお問い合わせください。', field_edit_denied_opaque: @@ -386,6 +418,14 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'No tiene permiso para cambiar la cola en la que está este registro. Póngase en contacto con su administrador si es necesario moverlo.', record_queue_assign_denied: 'No tiene permiso para crear un registro en esa cola. Deje la cola vacía o elija una cola a la que pertenezca, o póngase en contacto con su administrador.', + master_record_edit_denied: + 'Necesita acceso de edición al registro de {{master}} al que pertenece este registro. Póngase en contacto con la persona responsable de ese registro de {{master}} o con su administrador si necesita acceso.', + master_record_edit_denied_opaque: + 'Necesita acceso de edición al registro principal al que pertenece este registro. Póngase en contacto con su administrador si necesita acceso.', + master_record_read_denied: + 'Necesita acceso de lectura al registro de {{master}} al que pertenece este registro. Póngase en contacto con la persona responsable de ese registro de {{master}} o con su administrador si necesita acceso.', + master_record_read_denied_opaque: + 'Necesita acceso de lectura al registro principal al que pertenece este registro. Póngase en contacto con su administrador si necesita acceso.', field_edit_denied: 'No tiene permiso para editar {{fields}}. Deshaga esos cambios e inténtelo de nuevo, o póngase en contacto con su administrador si necesita acceso.', field_edit_denied_opaque: