diff --git a/.changeset/32656-refusal-user-text-locale.md b/.changeset/32656-refusal-user-text-locale.md new file mode 100644 index 00000000000..edb359d2a5e --- /dev/null +++ b/.changeset/32656-refusal-user-text-locale.md @@ -0,0 +1,14 @@ +--- +'@objectstack/plugin-security': patch +'@objectstack/metadata-protocol': patch +--- + +fix(plugin-security): permission refusals speak the caller's language, falling back to the workspace default + +Clause-②: no +Metadata-protocol: none + +Ruling C on #32440, second half of #32656: a refusal's user-facing sentence is composed in the request's language, else the workspace's default language, else English. Codes, statuses and the diagnostic `message` are unchanged. + +- **Packaged permission-set lock.** Saving a permission set an installed package provides, and the fail-closed refusal when the system cannot tell, used to answer their `userMessage` in English only. They now answer in the caller's language (English, Simplified and Traditional Chinese, Japanese, Korean, Spanish, French, German, Brazilian Portuguese, Russian and Arabic). The metadata write door hands each type's authoring gate the caller's two languages (`MetadataAuthoringGateContext.userTextLocales`); a caller that states none gets English, as before. +- **Permission denials.** The record, field, owner and queue denials of the security middleware were rendered in the request's language only, so a request in a language the platform has no text in fell to English even when the workspace default had text. They now fall back to the workspace default first. A deployment's `errors.` translation override counts as text for its language. diff --git a/packages/metadata-protocol/src/mutation-listeners.test.ts b/packages/metadata-protocol/src/mutation-listeners.test.ts index 3e6d3c1dac7..61922f09d0a 100644 --- a/packages/metadata-protocol/src/mutation-listeners.test.ts +++ b/packages/metadata-protocol/src/mutation-listeners.test.ts @@ -13,6 +13,8 @@ import { describe, it, expect, vi } from 'vitest'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Paid at collection, not inside a clocked case (check-test-source-alias). +import '@objectstack/lint'; import type { MetadataMutationEvent } from './protocol.js'; function makeProtocol() { @@ -149,6 +151,16 @@ describe('ObjectStackProtocolImplementation.registerAuthoringGate (#3050)', () = }); }); + it('[#32656] hands the gate the caller\'s user-text locales, empty entries dropped; none stated, no key', async () => { + const p = makeProtocol(); + const seen: any[] = []; + p.registerAuthoringGate('object', (ctx) => { seen.push(ctx); }); + await (p as any).runAuthoringGate(save({ userTextLocales: ['zh-CN', undefined, '', 'de'] })); + await (p as any).runAuthoringGate(save()); + expect(seen[0].userTextLocales).toEqual(['zh-CN', 'de']); + expect('userTextLocales' in seen[1]).toBe(false); + }); + it('normalizes plural registrations to the singular type', async () => { const p = makeProtocol(); const gate = vi.fn(); diff --git a/packages/metadata-protocol/src/protocol-authoring-channel.ts b/packages/metadata-protocol/src/protocol-authoring-channel.ts index b1c4a0b1363..aa49bcfe063 100644 --- a/packages/metadata-protocol/src/protocol-authoring-channel.ts +++ b/packages/metadata-protocol/src/protocol-authoring-channel.ts @@ -36,6 +36,13 @@ export interface MetadataAuthoringGateContext { isArtifactBacked: boolean; /** The packaged (code-layer) baseline body when {@link isArtifactBacked}; the declaration an overlay customizes. */ declaredBody?: unknown; + /** + * [#32656] The locales a gate's refusal `userMessage` is composed in, in + * ladder order (the request's, then the workspace default), as the write + * door stated them (`SaveMetaItemRequestSchema.userTextLocales`). Absent + * when the door stated none: the gate composes `en`. + */ + userTextLocales?: readonly string[]; } export type MetadataAuthoringGate = (ctx: MetadataAuthoringGateContext) => void | Promise; diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 4f440d5617d..04823e11c3c 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -185,6 +185,7 @@ export async function runAuthoringGate( this: Pick, evt: { type: string; name: string; state: 'draft' | 'active'; body: unknown; + userTextLocales?: readonly (string | undefined)[]; }): Promise { const singular = PLURAL_TO_SINGULAR[evt.type] ?? evt.type; const gate = this.authoringGates.get(singular); @@ -203,6 +204,9 @@ export async function runAuthoringGate( body: evt.body, isArtifactBacked: artifactBacked, ...(declaredBody !== undefined ? { declaredBody } : {}), + ...(evt.userTextLocales !== undefined + ? { userTextLocales: evt.userTextLocales.filter((l): l is string => typeof l === 'string' && l.length > 0) } + : {}), }); } diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 02bff5a7fb8..84b15d11517 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -1791,6 +1791,7 @@ export class ProtocolSaveFacet { name: request.name, state: mode === 'draft' ? 'draft' : 'active', body: request.item, + ...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}), }); } diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index e46a2e7eda5..58a4b279be5 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1753,6 +1753,7 @@ export class ObjectStackProtocolImplementation implements */ private runAuthoringGate(evt: { type: string; name: string; state: 'draft' | 'active'; body: unknown; + userTextLocales?: readonly (string | undefined)[]; }): Promise { // [#25467 cut 8] The body moved to `protocol-authoring-gate.ts` (see `AuthoringGateHost`). const readAuthoringGates = () => this.authoringGates; diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts index dd06cde20df..a1147ba8e87 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts @@ -78,6 +78,8 @@ export interface PermissionSetLockGateContext { type: string; name: string; body: unknown; + /** [#32656] The caller's language ladder, stated by the write door (`MetadataAuthoringGateContext`). */ + userTextLocales?: readonly string[]; } /** @@ -111,7 +113,7 @@ export function registerPackagedPermissionSetLockGate(protocol: any, ql: any): b // A metadata-door save that targets a package-declared name is an // override of the shipped base whether or not an overlay row exists yet, // so the remedy the refusal teaches is the clone path. - assertPermissionSetNotPackageDeclared(ctx.name, ql, 'update', probe); + assertPermissionSetNotPackageDeclared(ctx.name, ql, 'update', probe, ctx.userTextLocales); }); return true; } diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts index f7fcf3a8864..b9ed6192ea4 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts @@ -259,6 +259,46 @@ describe('the lock refusal carries its guidance as `userMessage` on the wire env expect(String(rejection.message)).toContain('registry unavailable'); }); + // [#32656] Ruling C on #32440: the producer composes the sentence in the + // request's language, else the workspace default, else `en`. The write door + // states the two locales on the gate's context (`userTextLocales`). + it('[#32656] the refusal speaks the caller\'s language: request locale, then the workspace default, then en', async () => { + const gate = lockGate(makeQl([shippedArtifact()])); + const refuse = (userTextLocales?: string[]) => gate({ + type: 'permission', name: SET_NAME, body: packagedSet(), ...(userTextLocales ? { userTextLocales } : {}), + } as any).then(() => null, (e: any) => e); + + const zh = await refuse(['zh-CN', 'en']); + expect(zh).toBeInstanceOf(PackagedPermissionSetLockedError); + expect(zh.userMessage).toContain('此权限集由已安装的软件包提供'); + expectEndUserCopy(zh.userMessage, SET_NAME, PACKAGE_ID); + const ja = await refuse(['ja-JP', 'zh-CN']); + expect(ja.userMessage, 'the request language wins when it has text').toContain('この権限セット'); + const workspace = await refuse(['tlh', 'zh-TW']); + expect(workspace.userMessage, 'an unsupported request language falls back to the workspace default').toContain('此權限集'); + const floor = await refuse(['tlh', 'tlh']); + const unstated = await refuse(); + expect(floor.userMessage).toBe(unstated.userMessage); + expect(String(unstated.userMessage)).toMatch(/clone it instead/i); + // Only the user's half moves: code, status and the diagnostic are the same in every language. + for (const r of [zh, ja, workspace, floor]) { + expect(r.code).toBe('NOT_OVERRIDABLE'); + expect(r.status).toBe(403); + expect(r.message).toBe(unstated.message); + } + }); + + it('[#32656] the provenance-unknown refusal follows the same ladder', async () => { + const ql = makeQl([]); + ql.registry = { listItems: () => { throw new Error('registry unavailable'); } }; + const gate = lockGate(ql, async () => { throw new Error('metadata store unavailable'); }); + const rejection = await gate({ type: 'permission', name: 'unknown_provenance', body: {}, userTextLocales: ['de-DE'] } as any) + .then(() => null, (e: any) => e); + expect(rejection).toBeInstanceOf(PackagedPermissionSetProvenanceUnknownError); + expect(rejection.userMessage).toContain('kann gerade nicht gespeichert werden'); + expectEndUserCopy(rejection.userMessage, 'unknown_provenance', 'registry unavailable', 'metadata store unavailable'); + }); + it('a SchemaRegistry that answers with a NON-LIST is the same ambiguity: the save is refused, not read as "nothing declared"', async () => { const ql = makeQl([]); ql.registry = { listItems: () => undefined as any }; diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock.ts index 207369a6f75..bf6780d0388 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock.ts @@ -86,6 +86,7 @@ */ import { isTenantAuthored } from '@objectstack/metadata-core'; +import { resolveBundleLocale } from '@objectstack/spec/system'; /** * ⛔ This module imports NOTHING from the rest of the plugin, and that is @@ -290,18 +291,96 @@ export function classifyPackagedPermissionSet( * carries no host state either: a sandboxed body that catches this error * receives static text. * - * English, like every platform refusal: there is no localization path for a - * thrown `userMessage`, and these texts do not invent one. + * [#32656] In the caller's language (ruling C on #32440): the producer + * composes the sentence in the request locale, else the workspace default, + * else `en` ({@link packagedSetUserMessage}). The write door states the two + * locales (`MetadataAuthoringGateContext.userTextLocales`); a caller that + * states none gets `en`, the text this refusal always carried. */ -const LOCKED_USER_MESSAGE = - `This permission set is provided by an installed package and can't be edited here. Clone it instead ` - + `with the Clone action, then edit the clone. The clone is your organization's own permission set, ` - + `and package upgrades keep reaching the original.`; +type PackagedSetUserText = Readonly>; -const PROVENANCE_UNKNOWN_USER_MESSAGE = - `This permission set can't be saved right now, because the system couldn't confirm whether an installed ` - + `package provides it. Try again in a moment. To customize a permission set that a package provides, ` - + `clone it with the Clone action and edit the clone.`; +const LOCKED_USER_TEXT: PackagedSetUserText = { + en: `This permission set is provided by an installed package and can't be edited here. Clone it instead ` + + `with the Clone action, then edit the clone. The clone is your organization's own permission set, ` + + `and package upgrades keep reaching the original.`, + 'zh-Hans': '此权限集由已安装的软件包提供,不能在这里编辑。请使用“克隆”操作克隆它,然后编辑克隆出的权限集。' + + '克隆出的权限集归贵组织所有,软件包升级仍会照常更新原权限集。', + 'zh-Hant': '此權限集由已安裝的套件提供,無法在這裡編輯。請使用「複製」動作複製它,然後編輯複製出的權限集。' + + '複製出的權限集歸貴組織所有,套件升級仍會照常更新原權限集。', + ja: 'この権限セットはインストール済みのパッケージが提供しているため、ここでは編集できません。' + + '「複製」アクションで複製し、複製したほうを編集してください。複製した権限セットは組織独自のものになり、' + + 'パッケージのアップグレードは引き続き元の権限セットに適用されます。', + ko: '이 권한 집합은 설치된 패키지가 제공하므로 여기에서 편집할 수 없습니다. 복제 작업으로 복제한 다음 복제본을 ' + + '편집하세요. 복제본은 조직 고유의 권한 집합이 되며, 패키지 업그레이드는 계속 원본에 적용됩니다.', + es: 'Este conjunto de permisos lo proporciona un paquete instalado y no se puede editar aquí. Clónelo con la ' + + 'acción Clonar y edite el clon. El clon es un conjunto de permisos propio de su organización, y las ' + + 'actualizaciones del paquete siguen llegando al original.', + fr: 'Cet ensemble d’autorisations est fourni par un package installé et ne peut pas être modifié ici. ' + + 'Clonez-le avec l’action Cloner, puis modifiez le clone. Le clone appartient à votre organisation, et les ' + + 'mises à jour du package continuent de s’appliquer à l’original.', + de: 'Dieser Berechtigungssatz wird von einem installierten Paket bereitgestellt und kann hier nicht bearbeitet ' + + 'werden. Klonen Sie ihn mit der Aktion „Klonen“ und bearbeiten Sie den Klon. Der Klon gehört Ihrer ' + + 'Organisation, und Paket-Upgrades erreichen weiterhin das Original.', + 'pt-BR': 'Este conjunto de permissões é fornecido por um pacote instalado e não pode ser editado aqui. Clone-o ' + + 'com a ação Clonar e edite o clone. O clone é um conjunto de permissões da sua organização, e as ' + + 'atualizações do pacote continuam chegando ao original.', + ru: 'Этот набор разрешений предоставлен установленным пакетом, и его нельзя изменить здесь. Клонируйте его ' + + 'действием «Клонировать» и измените клон. Клон принадлежит вашей организации, а обновления пакета ' + + 'по-прежнему применяются к оригиналу.', + ar: 'مجموعة الأذونات هذه يوفرها حزمة مثبتة ولا يمكن تعديلها هنا. انسخها باستخدام إجراء النسخ، ثم عدّل النسخة. ' + + 'النسخة مجموعة أذونات خاصة بمؤسستك، وتستمر ترقيات الحزمة في الوصول إلى المجموعة الأصلية.', +}; + +const PROVENANCE_UNKNOWN_USER_TEXT: PackagedSetUserText = { + en: `This permission set can't be saved right now, because the system couldn't confirm whether an installed ` + + `package provides it. Try again in a moment. To customize a permission set that a package provides, ` + + `clone it with the Clone action and edit the clone.`, + 'zh-Hans': '此权限集暂时无法保存,因为系统无法确认它是否由已安装的软件包提供。请稍后重试。' + + '如需自定义由软件包提供的权限集,请使用“克隆”操作克隆它,然后编辑克隆出的权限集。', + 'zh-Hant': '此權限集暫時無法儲存,因為系統無法確認它是否由已安裝的套件提供。請稍後再試。' + + '如需自訂由套件提供的權限集,請使用「複製」動作複製它,然後編輯複製出的權限集。', + ja: 'この権限セットは現在保存できません。インストール済みのパッケージが提供しているかどうかを確認できなかったためです。' + + 'しばらくしてからもう一度お試しください。パッケージが提供する権限セットをカスタマイズするには、' + + '「複製」アクションで複製し、複製したほうを編集してください。', + ko: '설치된 패키지가 이 권한 집합을 제공하는지 확인할 수 없어 지금은 저장할 수 없습니다. 잠시 후 다시 시도하세요. ' + + '패키지가 제공하는 권한 집합을 사용자 지정하려면 복제 작업으로 복제한 다음 복제본을 편집하세요.', + es: 'Este conjunto de permisos no se puede guardar ahora, porque el sistema no pudo confirmar si lo proporciona ' + + 'un paquete instalado. Vuelva a intentarlo en un momento. Para personalizar un conjunto de permisos que ' + + 'proporciona un paquete, clónelo con la acción Clonar y edite el clon.', + fr: 'Cet ensemble d’autorisations ne peut pas être enregistré pour le moment, car le système n’a pas pu ' + + 'confirmer s’il est fourni par un package installé. Réessayez dans un instant. Pour personnaliser un ' + + 'ensemble d’autorisations fourni par un package, clonez-le avec l’action Cloner et modifiez le clone.', + de: 'Dieser Berechtigungssatz kann gerade nicht gespeichert werden, weil das System nicht bestätigen konnte, ' + + 'ob ein installiertes Paket ihn bereitstellt. Versuchen Sie es gleich noch einmal. Um einen ' + + 'Berechtigungssatz anzupassen, den ein Paket bereitstellt, klonen Sie ihn mit der Aktion „Klonen“ und ' + + 'bearbeiten Sie den Klon.', + 'pt-BR': 'Este conjunto de permissões não pode ser salvo agora, porque o sistema não conseguiu confirmar se um ' + + 'pacote instalado o fornece. Tente novamente em instantes. Para personalizar um conjunto de permissões ' + + 'fornecido por um pacote, clone-o com a ação Clonar e edite o clone.', + ru: 'Этот набор разрешений сейчас нельзя сохранить: системе не удалось проверить, предоставлен ли он ' + + 'установленным пакетом. Повторите попытку чуть позже. Чтобы настроить набор разрешений из пакета, ' + + 'клонируйте его действием «Клонировать» и измените клон.', + ar: 'لا يمكن حفظ مجموعة الأذونات هذه الآن، لأن النظام لم يتمكن من التأكد مما إذا كانت حزمة مثبتة توفرها. ' + + 'حاول مرة أخرى بعد قليل. لتخصيص مجموعة أذونات توفرها حزمة، انسخها باستخدام إجراء النسخ ثم عدّل النسخة.', +}; + +/** + * The sentence of `text` in the first locale of `locales` it has, each code + * matched by the platform's one locale ladder ({@link resolveBundleLocale}: + * exact, case-insensitive, the platform table language, one subtag shorter); + * `en` when none matches or none is stated. + */ +function packagedSetUserMessage( + text: PackagedSetUserText, + locales: readonly (string | null | undefined)[] | undefined, +): string { + for (const locale of locales ?? []) { + if (typeof locale !== 'string' || locale.length === 0) continue; + const matched = resolveBundleLocale(text, locale); + if (matched !== undefined) return text[matched]!; + } + return text.en!; +} /** * The refusal a write door throws for a package-declared set. @@ -347,7 +426,13 @@ export class PackagedPermissionSetLockedError extends Error { * [ADR-0150 D2, #31698] `packageId`: the package that declares the set, or * every one that does, each named — never the first found alone. */ - constructor(name: string, packageId: string | readonly string[], _operation: 'insert' | 'update') { + constructor( + name: string, + packageId: string | readonly string[], + _operation: 'insert' | 'update', + /** [#32656] The caller's language ladder: request locale, then workspace default. */ + userTextLocales?: readonly (string | null | undefined)[], + ) { const declarers = (typeof packageId === 'string' ? [packageId] : packageId).map((id) => `'${id}'`); const by = declarers.length > 1 ? `packages ${declarers.slice(0, -1).join(', ')} and ${declarers[declarers.length - 1]}` : `package ${declarers[0]}`; super( @@ -359,7 +444,7 @@ export class PackagedPermissionSetLockedError extends Error { + `flowing to '${name}' untouched.`, ); this.name = 'PackagedPermissionSetLockedError'; - this.userMessage = LOCKED_USER_MESSAGE; + this.userMessage = packagedSetUserMessage(LOCKED_USER_TEXT, userTextLocales); } } @@ -375,7 +460,7 @@ export class PackagedPermissionSetProvenanceUnknownError extends Error { readonly statusCode = 403; /** The guidance addressed to the end user; `message` stays the diagnostic. */ readonly userMessage: string; - constructor(name: string, reason: string) { + constructor(name: string, reason: string, userTextLocales?: readonly (string | null | undefined)[]) { super( `[Security] Permission set '${name}' cannot be saved right now: this system could not determine ` + `whether the set is declared by an installed package (${reason}). The save is refused rather than ` @@ -383,7 +468,7 @@ export class PackagedPermissionSetProvenanceUnknownError extends Error { + `once the metadata layer is readable; if you meant to customize a packaged set, clone it instead.`, ); this.name = 'PackagedPermissionSetProvenanceUnknownError'; - this.userMessage = PROVENANCE_UNKNOWN_USER_MESSAGE; + this.userMessage = packagedSetUserMessage(PROVENANCE_UNKNOWN_USER_TEXT, userTextLocales); } } @@ -398,13 +483,14 @@ export function assertPermissionSetNotPackageDeclared( ql: any, operation: 'insert' | 'update', layered?: LayeredProbe, + userTextLocales?: readonly (string | null | undefined)[], ): PackagedSetVerdict { const verdict = classifyPackagedPermissionSet(name, ql, layered); if (verdict.status === 'packaged') { - throw new PackagedPermissionSetLockedError(name, verdict.packageIds, operation); + throw new PackagedPermissionSetLockedError(name, verdict.packageIds, operation, userTextLocales); } if (verdict.status === 'unknown') { - throw new PackagedPermissionSetProvenanceUnknownError(name, verdict.reason); + throw new PackagedPermissionSetProvenanceUnknownError(name, verdict.reason, userTextLocales); } return verdict; } diff --git a/packages/plugins/plugin-security/src/permission-denied-user-copy.test.ts b/packages/plugins/plugin-security/src/permission-denied-user-copy.test.ts index 41db69c8b4c..0bcfe4542bc 100644 --- a/packages/plugins/plugin-security/src/permission-denied-user-copy.test.ts +++ b/packages/plugins/plugin-security/src/permission-denied-user-copy.test.ts @@ -176,6 +176,7 @@ interface Denial { async function denyDelete( locale: string | undefined, i18n?: FileI18nAdapter, + workspaceLocale?: string, ): Promise { const engine = makeEngine(); const metadata = { @@ -221,6 +222,7 @@ async function denyDelete( positions: ['org_member'], permissions: ['app_reader'], ...(locale ? { locale } : {}), + ...(workspaceLocale ? { workspaceLocale } : {}), }, }; try { @@ -271,6 +273,18 @@ describe('#7414 — the 403 an end user reads', () => { } }); + // [#32656] Ruling C on #32440: the request's language, else the workspace + // default, else `en`. `locale` folds the two (the request wins), so the + // workspace default rides the context on its own as `workspaceLocale`. + it('[#32656] a request language with no text falls back to the workspace default, then to en', async () => { + const workspace = await denyDelete('de-DE', undefined, 'zh-CN'); + expect(workspace.message).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].permission_denied); + const request = await denyDelete('ja-JP', undefined, 'zh-CN'); + expect(request.message, 'the request language wins when it has text').toBe(BUILTIN_OPERATION_MESSAGES['ja-JP'].permission_denied); + const floor = await denyDelete('de-DE', undefined, 'de-DE'); + expect(floor.message).toBe(BUILTIN_OPERATION_MESSAGES.en.permission_denied); + }); + it('names no object, no operation and no position — in every locale it can render', async () => { const locales = Object.keys(BUILTIN_OPERATION_MESSAGES); expect(locales.length).toBeGreaterThanOrEqual(4); 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 440ec9c3d06..0a3f81e4963 100644 --- a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts +++ b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts @@ -94,7 +94,13 @@ import { markFilterSubtreeProvenance } from '@objectstack/spec/data'; // [#7414] The SHARED operation-message catalog #7307 built for the data path's // operation-level refusals. Second consumer, same mechanism — a second remedy // for one defect class is what that module exists to prevent. -import { objectFieldLabelKey, renderOperationMessage } from '@objectstack/spec/system'; +import { + BUILTIN_OPERATION_MESSAGES, + objectFieldLabelKey, + operationMessageTranslationKey, + renderOperationMessage, + resolveBundleLocale, +} from '@objectstack/spec/system'; // [#19989] The engine's own update-dispatch predicate, asked rather than // re-derived: step 3.6 needs to know which row the ENGINE will write. import { resolveEngineUpdateDispatch, type EngineUpdateDispatchData } from '@objectstack/metadata-core'; @@ -218,10 +224,51 @@ export interface WriteImageCheckSeam { function userFacingDenialMessage( ctx: PluginContext, messageKey: UserFacingDenialKey, - locale: string | undefined, + locales: DenialLocales, params?: Record, ): string { - return renderOperationMessage({ messageKey, params }, { locale, translate: denialTranslator(ctx) }); + const translate = denialTranslator(ctx); + return renderOperationMessage({ messageKey, params }, { locale: denialLocaleOf(messageKey, locales, translate), translate }); +} + +/** + * [#32656] The caller's language ladder for a refusal's user sentence: the + * request's locale, then the workspace default (ruling C on #32440), read off + * the operation's execution context. `locale` alone folds the two (the request + * locale wins the fold), so a request in a language the platform has no text + * in used to fall straight to `en` past a workspace default it does have. + */ +type DenialLocales = readonly (string | undefined)[]; + +function denialLocalesOf(context: { locale?: string; workspaceLocale?: string } | undefined): DenialLocales { + return [context?.locale, context?.workspaceLocale]; +} + +/** + * The first locale of the ladder this sentence has text in: a deployment's + * `errors.` override for it, else the built-in catalog (matched by the + * platform's one locale ladder). `undefined` when none has it, which + * {@link renderOperationMessage} renders in `en`. + */ +function denialLocaleOf( + messageKey: UserFacingDenialKey, + locales: DenialLocales, + translate: ReturnType, +): string | undefined { + const key = operationMessageTranslationKey(messageKey); + for (const locale of locales) { + if (typeof locale !== 'string' || locale.length === 0) continue; + if (translate) { + try { + const override = translate(key, locale); + if (typeof override === 'string' && override.length > 0 && override !== key) return locale; + } catch { + // A misbehaving i18n service must not turn a 403 into a 500. + } + } + if (resolveBundleLocale(BUILTIN_OPERATION_MESSAGES, locale) !== undefined) return locale; + } + return undefined; } /** @@ -310,10 +357,12 @@ function fieldEditDenialMessage( forbidden: readonly string[], schema: { fields?: Record } | null | undefined, readable: Record, - locale: string | undefined, + locales: DenialLocales, ): string { const translate = denialTranslator(ctx); - const loc = locale ?? 'en'; + // Labels are translated in the language the sentence itself resolves to. + const loc = denialLocaleOf('field_edit_denied', locales, translate) ?? 'en'; + const locale = [loc]; const labels: string[] = []; for (const field of forbidden) { if (readable[field]?.readable === false) return userFacingDenialMessage(ctx, 'field_edit_denied_opaque', locale); @@ -344,7 +393,7 @@ function fieldEditDenialMessage( * they fill, so they resolve by the catalog's own locale ladder and a * deployment's `errors.` override applies to them as to the sentence. */ -function labelList(ctx: PluginContext, labels: readonly string[], locale: string | undefined): string { +function labelList(ctx: PluginContext, labels: readonly string[], locale: DenialLocales): string { const separator = userFacingDenialMessage(ctx, 'field_label_list_separator', locale); return labels.map((label) => userFacingDenialMessage(ctx, 'field_label_quoted', locale, { label })).join(separator); } @@ -911,7 +960,7 @@ export function registerAuthzMiddleware( userId: opCtx.context?.userId ?? 'unknown', }); throw new PermissionDeniedError( - userFacingDenialMessage(ctx, 'permission_denied', opCtx.context?.locale), + userFacingDenialMessage(ctx, 'permission_denied', denialLocalesOf(opCtx.context)), { operation: opCtx.operation, object: opCtx.object, @@ -1051,7 +1100,7 @@ export function registerAuthzMiddleware( userId: opCtx.context?.userId ?? 'unknown', }); throw new PermissionDeniedError( - userFacingDenialMessage(ctx, 'permission_denied', opCtx.context?.locale), + userFacingDenialMessage(ctx, 'permission_denied', denialLocalesOf(opCtx.context)), { operation: opCtx.operation, object: opCtx.object, positions, permissionSets: explicitPermissionSets }, developerMessage, ); @@ -1376,7 +1425,7 @@ export function registerAuthzMiddleware( userId: opCtx.context?.userId ?? 'unknown', }); throw new PermissionDeniedError( - userFacingDenialMessage(ctx, 'record_access_denied', opCtx.context?.locale), + userFacingDenialMessage(ctx, 'record_access_denied', denialLocalesOf(opCtx.context)), { operation: opCtx.operation, object: opCtx.object, @@ -1510,7 +1559,7 @@ export function registerAuthzMiddleware( forbidden, typeof ql?.getSchema === 'function' ? ql.getSchema(opCtx.object) as any : undefined, this.computeQueryGuardFieldPerms(opCtx.object, secMeta, permissionSets, delegatorSets), - opCtx.context?.locale, + denialLocalesOf(opCtx.context), ), ); } @@ -1706,7 +1755,7 @@ export function registerAuthzMiddleware( `${action} requires the transfer grant (allowTransfer or modifyAllRecords)`, refusalDetails, ), - userFacingDenialMessage(ctx, userKey, opCtx.context?.locale), + userFacingDenialMessage(ctx, userKey, denialLocalesOf(opCtx.context)), ); }; // [ADR-0142 D4] A claim or a release the step did not admit names the @@ -1718,7 +1767,7 @@ export function registerAuthzMiddleware( 'other change of ownership requires the transfer grant (allowTransfer or modifyAllRecords)', refusalDetails, ), - userFacingDenialMessage(ctx, userKey, opCtx.context?.locale), + userFacingDenialMessage(ctx, userKey, denialLocalesOf(opCtx.context)), ); }; const denyQueueWrite = (condition: string, userKey: UserFacingDenialKey): never => { @@ -1728,7 +1777,7 @@ export function registerAuthzMiddleware( '(allowTransfer or modifyAllRecords)', refusalDetails, ), - userFacingDenialMessage(ctx, userKey, opCtx.context?.locale), + userFacingDenialMessage(ctx, userKey, denialLocalesOf(opCtx.context)), ); }; // [ADR-0138 D1] The guest branch (see the step's header). Its refusal @@ -2078,7 +2127,7 @@ export function registerAuthzMiddleware( userId: opCtx.context?.userId ?? 'unknown', }); throw new PermissionDeniedError( - userFacingDenialMessage(ctx, 'record_change_not_allowed', opCtx.context?.locale), + userFacingDenialMessage(ctx, 'record_change_not_allowed', denialLocalesOf(opCtx.context)), { operation: opCtx.operation, object: opCtx.object, positions, permissionSets: explicitPermissionSets }, developerMessage, ); @@ -2228,7 +2277,7 @@ export function registerAuthzMiddleware( userId: opCtx.context?.userId ?? 'unknown', }); throw new PermissionDeniedError( - userFacingDenialMessage(ctx, 'record_change_not_allowed', opCtx.context?.locale), + userFacingDenialMessage(ctx, 'record_change_not_allowed', denialLocalesOf(opCtx.context)), { operation: opCtx.operation, object: opCtx.object, positions, permissionSets: explicitPermissionSets }, developerMessage, ); @@ -2659,7 +2708,7 @@ export function registerAuthzMiddleware( userId: opCtx.context?.userId ?? 'unknown', }); throw new PermissionDeniedError( - userFacingDenialMessage(ctx, 'record_change_not_allowed', opCtx.context?.locale), + userFacingDenialMessage(ctx, 'record_change_not_allowed', denialLocalesOf(opCtx.context)), { operation: opCtx.operation, object: opCtx.object, positions, permissionSets: explicitPermissionSets }, developerMessage, ); diff --git a/packages/runtime/src/domains/meta-save-user-text-locale.test.ts b/packages/runtime/src/domains/meta-save-user-text-locale.test.ts index f9c2c9b6d66..b60f9c716b5 100644 --- a/packages/runtime/src/domains/meta-save-user-text-locale.test.ts +++ b/packages/runtime/src/domains/meta-save-user-text-locale.test.ts @@ -89,18 +89,24 @@ async function bootStore() { const protocol = new ObjectStackProtocolImplementation(engine as any); // What each save handed the protocol, read where the protocol receives it. const stated: unknown[] = []; + // …and what the type's authoring gate was handed (plugin-security's + // packaged permission-set lock registers here; its refusal's + // `userMessage` is composed from these). + const gated: unknown[] = []; + protocol.registerAuthoringGate('permission', (ctx) => { gated.push(ctx.userTextLocales); }); const save = protocol.saveMetaItem.bind(protocol); (protocol as any).saveMetaItem = (request: any) => { stated.push(request.userTextLocales); return save(request); }; - return { protocol, stated }; + return { protocol, stated, gated }; } interface Saved { status: number; body: any } interface Door { save(who: Caller, name: string): Promise; stated: unknown[]; + gated: unknown[]; } function makeRes() { @@ -116,12 +122,13 @@ function makeRes() { } async function bootDispatcher(): Promise { - const { protocol, stated } = await bootStore(); + const { protocol, stated, gated } = await bootStore(); const get = (n: string) => (n === 'protocol' ? protocol : null); const kernel: any = { context: { getService: get }, getService: get, getServiceAsync: async (n: string) => get(n) }; const dispatcher = new HttpDispatcher(kernel); return { stated, + gated, save: async (who, name) => { (dispatcher as any).timedResolveExecutionContext = async () => clone(who); const body = permissionSet(name); @@ -138,7 +145,7 @@ async function bootDispatcher(): Promise { } async function bootRestServer(): Promise { - const { protocol, stated } = await bootStore(); + const { protocol, stated, gated } = await bootStore(); const noop = () => {}; const server = { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; const rest: any = new RestServer(server as any, protocol as any, { api: { requireAuth: false } } as any); @@ -147,6 +154,7 @@ async function bootRestServer(): Promise { if (!route) throw new Error(`PUT ${META}/:type/:name is not registered`); return { stated, + gated, save: async (who, name) => { rest.resolveExecCtx = async () => clone(who); const res = makeRes(); @@ -180,6 +188,13 @@ for (const [doorName, boot] of DOORS) { expect(door.stated).toEqual([['zh-CN', 'de'], []]); }, 60_000); + it('the type\'s authoring gate receives the same locales, for its refusal\'s userMessage', async () => { + const door = await boot(); + await door.save(caller('zh-CN', 'de'), 'finance_user'); + await door.save(caller(), 'finance_user'); + expect(door.gated).toEqual([['zh-CN', 'de'], []]); + }, 60_000); + it('a zh-CN request reads the advisory in Simplified Chinese; rule, message and hint are unchanged', async () => { const door = await boot(); const zh = advisoryOf(await door.save(caller('zh-CN', 'en'), 'finance_user'));