From 36edb6afbd94ff3c540d3c60098019f00a13665a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 19:42:21 +0000 Subject: [PATCH 01/15] fix(objectql,metadata-protocol,console): a view column on a field a disabled package withholds no longer fails the list (#34901) The served object read names the fields a disabled package withholds (`_withheldFields`, a read decoration stripped on write), the view save door judges a view write against the storage fold (`includeDisabledExtensions`), and the console list readers leave a withheld name out of every request, hide its column by derivation and keep it in the persisted sort. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .../src/protocol-authoring-gate.ts | 49 ++++- .../src/protocol-meta-item-face.ts | 43 ++++ .../src/protocol-meta-list-reads.ts | 15 +- .../src/protocol.read-decorations.test.ts | 45 ++++ ...protocol-withheld-extension-fields.test.ts | 202 ++++++++++++++++++ ...gistry-disabled-package-extensions.test.ts | 76 +++++++ .../src/registry-object-registration.ts | 42 +++- packages/objectql/src/registry-top-level.ts | 10 + packages/objectql/src/registry.ts | 17 ++ .../src/kernel/metadata-read-decorations.ts | 7 +- ui/packages/core/src/index.ts | 1 + ui/packages/core/src/utils/withheld-fields.ts | 97 +++++++++ ui/packages/i18n/src/locales/ar.ts | 1 + ui/packages/i18n/src/locales/de.ts | 1 + ui/packages/i18n/src/locales/en.ts | 1 + ui/packages/i18n/src/locales/es.ts | 1 + ui/packages/i18n/src/locales/fr.ts | 1 + ui/packages/i18n/src/locales/ja.ts | 1 + ui/packages/i18n/src/locales/ko.ts | 1 + ui/packages/i18n/src/locales/pt-BR.ts | 1 + ui/packages/i18n/src/locales/ru.ts | 1 + ui/packages/i18n/src/locales/zh-Hans.ts | 1 + ui/packages/i18n/src/locales/zh-Hant.ts | 1 + .../src/objectGridGenerateColumns.tsx | 11 +- .../src/objectGridGroupingDecisions.ts | 32 ++- .../plugin-grid/src/objectGridRowLoad.ts | 29 ++- ui/packages/plugin-list/src/ListView.tsx | 138 ++++++++++-- 27 files changed, 781 insertions(+), 44 deletions(-) create mode 100644 packages/objectql/src/protocol-withheld-extension-fields.test.ts create mode 100644 ui/packages/core/src/utils/withheld-fields.ts diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index c05bab828be..5d6ef7cd64e 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -328,6 +328,50 @@ export async function assertRuntimeAuthoringRules( return verdict.advisories; } +/** + * [#34901] The objects a `view` write is judged against: each object a + * disabled package extends, folded with that package's `extend` contribution + * IN (`includeDisabledExtensions`, the fold the storage layer keeps), and + * every other object exactly as served. + * + * A disable withholds the fields its extensions add from the served object, + * while the owner's views keep naming them on purpose: re-enabling the package + * serves the column again with no write. Judged against the served objects, + * every save of such a view (a rename, a pin, a Studio edit) was refused as + * `list-view-field-unknown` / `sort-field-unknown` for as long as the package + * stayed off. Judged against this fold, a withheld name is the real, stored + * field it is, and a name no contributor declares is still unknown. + * + * Applied to the merged universe (registered and stored halves alike), so a + * stored overlay of an extended object is folded the same way. ⛔ View writes + * ONLY: a flow, a formula or a validation rule written while the package is + * off would read a field the served object does not carry. + */ +export function withDisabledExtensionsFolded(registry: unknown, objects: unknown[]): unknown[] { + const r = registry as { + getWithheldExtensionFields?: (name: string) => Record; + foldObjectExtendersOnto?: (name: string, base: unknown, options?: { includeDisabledExtensions?: true }) => unknown; + } | null | undefined; + if (typeof r?.getWithheldExtensionFields !== 'function' || typeof r.foldObjectExtendersOnto !== 'function') return objects; + let changed = false; + const folded = objects.map((object) => { + const name = (object as { name?: unknown } | null)?.name; + if (typeof name !== 'string' || Object.keys(r.getWithheldExtensionFields!(name)).length === 0) return object; + try { + const storage = r.foldObjectExtendersOnto!(name, object, { includeDisabledExtensions: true }); + if (storage === object || storage === null || typeof storage !== 'object') return object; + changed = true; + const packageId = (object as { _packageId?: unknown })._packageId; + return packageId === undefined ? storage : { ...(storage as Record), _packageId: packageId }; + } catch { + // The fold is a read over in-memory contributors; a failure leaves + // the served object, the judgement this write had before. + return object; + } + }); + return changed ? folded : objects; +} + /** * [#26707] The judgement {@link assertRuntimeAuthoringRules} enforces, handed * back instead of thrown: the gate's {@link RuntimeAuthoringVerdict}, its @@ -627,7 +671,10 @@ export async function judgeRuntimeAuthoringRules( name: evt.name, state: evt.state, body: evt.body, - objects, + // [#34901] A `view` write judges its field names against the STORAGE + // fold ({@link withDisabledExtensionsFolded}); every other type keeps + // the served objects. + objects: singular === 'view' ? withDisabledExtensionsFolded(this.engine?.registry, objects) : objects, permissions, books, datasets, diff --git a/packages/metadata-protocol/src/protocol-meta-item-face.ts b/packages/metadata-protocol/src/protocol-meta-item-face.ts index 3fd2c22513c..88118a285d0 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-face.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-face.ts @@ -775,6 +775,42 @@ async function rowHeldBaseJudgment( return { base, atMember: atMemberPackages, pairAmongHolders: [...atMemberPackages].some(isPairOfAHolder) }; } +/** + * [#34901] `item`, a SERVED object body, with the `_withheldFields` read + * decoration: each field a disabled package's `extend` contribution adds and + * the served fold therefore withholds, with that package + * (`SchemaRegistry.getWithheldExtensionFields`), less any name the body itself + * declares. `item` itself when nothing is withheld, or when the registry + * cannot answer. + * + * Why it is served: an owner's view keeps naming such a field on purpose (the + * column returns when the package is re-enabled, with no write), while the + * data door refuses the name as unknown on every query axis. The console reads + * this map to leave exactly those names out of a request — a name nothing + * declares is still sent, and still refused, so a typo stays loud. + * + * A read decoration (`METADATA_READ_DECORATIONS`, `@objectstack/spec`): derived + * on every read, stripped on every write and before any re-parse, never + * authorable. Stamped on the served faces only (this by-name read and the + * served list); never on the layered/editor read, the execution face, a + * pending draft's authoring read or a registry fold. + */ +export function withWithheldFieldsDecoration(registry: unknown, item: unknown, name?: string): unknown { + if (item === null || typeof item !== 'object' || Array.isArray(item)) return item; + const body = item as Record; + const objectName = typeof name === 'string' && name !== '' ? name : body.name; + const r = registry as { getWithheldExtensionFields?: (name: string) => Record } | null | undefined; + if (typeof objectName !== 'string' || typeof r?.getWithheldExtensionFields !== 'function') return item; + const withheld = r.getWithheldExtensionFields(objectName); + const declared = body.fields !== null && typeof body.fields === 'object' && !Array.isArray(body.fields) + ? body.fields as Record + : undefined; + const entries = Object.entries(withheld) + .filter(([field]) => !(declared && Object.prototype.hasOwnProperty.call(declared, field))); + if (entries.length === 0) return item; + return { ...body, _withheldFields: Object.fromEntries(entries.map(([field, at]) => [field, { packageId: at.packageId }])) }; +} + /** The body of `ObjectStackProtocolImplementation#readMetaItemFace`; the method's docblock there is its contract. */ export async function readMetaItemFace( this: Pick & ServedRowHost, @@ -875,6 +911,13 @@ export async function readMetaItemFace( ? activeRows.rows : undefined)); if (withheldHolder === undefined && (request.type === 'object' || request.type === 'package' || (!withheldAction && !isItemOfDisabledPackage(this.engine?.registry, answer?.item)))) { + // [#34901] The served object read names the fields a disabled + // package withholds ({@link withWithheldFieldsDecoration}); the + // execution face and a pending draft's authoring read never do. + if (request.type === 'object' && face === 'served' && request.state !== 'draft' && answer?.item != null) { + const item = withWithheldFieldsDecoration(this.engine?.registry, answer.item, request.name); + return item === answer.item ? answer : { ...answer, item }; + } return answer; } if (request.state === 'draft') throw noPendingDraftError(request.type, request.name); diff --git a/packages/metadata-protocol/src/protocol-meta-list-reads.ts b/packages/metadata-protocol/src/protocol-meta-list-reads.ts index 8be8dda9805..086e0b043f8 100644 --- a/packages/metadata-protocol/src/protocol-meta-list-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-list-reads.ts @@ -49,7 +49,7 @@ import { storedEntryRow } from './protocol-stored-overlay-types.js'; import { viewIdentityPatch } from './protocol-view-normalization.js'; import { isServedOverrideRowOf, type ServedOverrideRow } from './served-override.js'; import { installedManifestsOfEngine } from './installed-manifests.js'; -import { packagelessRowWithheld } from './protocol-meta-item-face.js'; +import { packagelessRowWithheld, withWithheldFieldsDecoration } from './protocol-meta-item-face.js'; import { declinesPackageLessRowAt, disabledExactAddressHolder, @@ -1098,7 +1098,18 @@ export async function readFlattenedMetaItems(host: Pick decorateListedItem(request.type, it)) : governed, + // + // [#34901] …and, on the EFFECTIVE served list of objects only, the + // fields a disabled package withholds ({@link withWithheldFieldsDecoration}); + // never the per-package layer (a package's export) or the execution face. + items: audience === 'served' + ? governed.map((it) => { + const listed = decorateListedItem(request.type, it); + return request.type === 'object' && layer === 'effective' + ? withWithheldFieldsDecoration(host.engine?.registry, listed) + : listed; + }) + : governed, // [#23316] Served only: the engine's verdict on each listed flow — // see {@link flowRegistrationsOf}. The execution face is the // engine's own read, so it carries none. diff --git a/packages/metadata-protocol/src/protocol.read-decorations.test.ts b/packages/metadata-protocol/src/protocol.read-decorations.test.ts index 56d125a6136..dfb49573715 100644 --- a/packages/metadata-protocol/src/protocol.read-decorations.test.ts +++ b/packages/metadata-protocol/src/protocol.read-decorations.test.ts @@ -286,6 +286,51 @@ const flowBody = (name: string) => ({ * These run against the REAL `getMetaItems`, so they fail if the read path ever * grows a decoration that consumers don't know to remove. */ +/** + * [#34901] `_withheldFields`, the served object's note of the fields a + * disabled package withholds from it, is a read decoration like `_diagnostics`: + * stamped on the served face only, and never stored by the Studio round-trip. + * The stub registry answers the withheld-field reader the way `SchemaRegistry` + * does while the extending package is off. + */ +describe('[#34901] the served object carries `_withheldFields`; a GET → edit → PUT never stores it', () => { + const WITHHELD = { crm_project: { packageId: 'com.example.projects' } }; + const withWithheldReader = (engine: any) => { + engine.registry.getWithheldExtensionFields = (name: string) => (name === 'crm_invoice' ? WITHHELD : {}); + return engine; + }; + + it('stripReadDecorations removes it', () => { + expect(stripReadDecorations({ name: 'x', _withheldFields: WITHHELD })).toEqual({ name: 'x' }); + }); + + it('the served read stamps it, the layered (editor) read does not, and the PUT stores none of it', async () => { + const { engine, rows } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(withWithheldReader(engine)); + await protocol.saveMetaItem({ type: 'object', name: 'crm_invoice', item: objectBody('crm_invoice') }); + const firstStored = storedBody(rows, 'crm_invoice'); + + const served: any = (await protocol.getMetaItem({ type: 'object', name: 'crm_invoice' })).item; + expect(served._withheldFields, 'precondition: the served read carries the marker').toEqual(WITHHELD); + + const layered: any = await (protocol as any).getMetaItemLayered({ type: 'object', name: 'crm_invoice' }); + expect(JSON.stringify(layered ?? null)).not.toContain('_withheldFields'); + + await protocol.saveMetaItem({ type: 'object', name: 'crm_invoice', item: { ...served, label: 'Invoice (edited)' } }); + const stored = storedBody(rows, 'crm_invoice'); + expect('_withheldFields' in stored).toBe(false); + expect({ ...stored, label: firstStored.label }).toEqual(firstStored); + }); + + it('control: nothing withheld ⇒ no marker on the served read', async () => { + const { engine } = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(withWithheldReader(engine)); + await protocol.saveMetaItem({ type: 'object', name: 'crm_other', item: objectBody('crm_other') }); + const served: any = (await protocol.getMetaItem({ type: 'object', name: 'crm_other' })).item; + expect('_withheldFields' in served).toBe(false); + }); +}); + describe('a served document survives its own (closed) schema — cloud#971', () => { /** Serve `flowBody(name)` back through the real read path. */ async function serveFlow(name: string): Promise> { diff --git a/packages/objectql/src/protocol-withheld-extension-fields.test.ts b/packages/objectql/src/protocol-withheld-extension-fields.test.ts new file mode 100644 index 00000000000..2e0a3a40e1f --- /dev/null +++ b/packages/objectql/src/protocol-withheld-extension-fields.test.ts @@ -0,0 +1,202 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34901] A view over a field a DISABLED package contributes, through the + * real protocol over the real `ObjectQL` engine and an in-memory driver. + * + * Package P extends Q's object with `crm_project`; Q's list view names it as a + * column and as its sort. Disabling P withholds the field from the served + * object (and the data door refuses it on every axis), while Q's view keeps + * naming it. Pinned here: + * + * - the served object read says which names are withheld (`_withheldFields`), + * the execution face and the layered read do not, and re-enabling P clears + * it with no write; + * - the view save door judges a view write against the storage fold, so the + * view saves into Q's customization pair while P is off, and a typo'd + * column is still refused; + * - that fold is for view writes only: an object write whose embedded list + * view names the withheld field is still judged against the served object. + * + * Test-path resolution: the protocol is `@objectstack/metadata-protocol`'s + * `dist/`, so a change there is read here after that package is rebuilt. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import type { ServiceObject } from '@objectstack/spec/data'; +import { ObjectStackProtocolImplementation, resetEnvWritableMetadataTypes } from '@objectstack/metadata-protocol'; +import { SysMetadataAuditObject, SysMetadataCommitObject, SysMetadataHistoryObject } from '@objectstack/metadata-core'; +import { ObjectQL } from './engine.js'; + +const sysMetadataObject: ServiceObject = { + name: 'sys_metadata', label: 'System Metadata', + fields: { + id: { name: 'id', label: 'ID', type: 'text' as const }, + type: { name: 'type', label: 'Type', type: 'text' as const, required: true }, + name: { name: 'name', label: 'Name', type: 'text' as const, required: true }, + organization_id: { name: 'organization_id', label: 'Org', type: 'text' as const }, + package_id: { name: 'package_id', label: 'Package', type: 'text' as const }, + bundle_member: { name: 'bundle_member', label: 'Bundle Member', type: 'text' as const, maxLength: 100 }, + metadata: { name: 'metadata', label: 'Body', type: 'textarea' as const }, + draft_changes: { name: 'draft_changes', label: 'Draft Changes', type: 'textarea' as const }, + checksum: { name: 'checksum', label: 'Checksum', type: 'text' as const, maxLength: 71 }, + state: { name: 'state', label: 'State', type: 'text' as const }, + version: { name: 'version', label: 'Version', type: 'number' as const }, + created_at: { name: 'created_at', label: 'Created', type: 'datetime' as const }, + updated_at: { name: 'updated_at', label: 'Updated', type: 'datetime' as const }, + }, +}; + +function makeMemoryDriver() { + const stores = new Map>>(); + const storeFor = (o: string) => { let s = stores.get(o); if (!s) { s = new Map(); stores.set(o, s); } return s; }; + let nextId = 0; + const matchesWhere = (row: Record, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + for (const [k, v] of Object.entries(where)) { + if (k === '$and' && Array.isArray(v)) { if (!v.every((w: any) => matchesWhere(row, w))) return false; continue; } + if (k === '$or' && Array.isArray(v)) { if (!v.some((w: any) => matchesWhere(row, w))) return false; continue; } + if (k.startsWith('$')) continue; + const rowVal = row[k]; + if (v && typeof v === 'object' && Array.isArray((v as any).$in)) { if (!(v as any).$in.includes(rowVal === undefined ? null : rowVal)) return false; continue; } + const expected = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v; + if ((rowVal === undefined ? null : rowVal) !== (expected === undefined ? null : expected)) return false; + } + return true; + }; + const driver: any = { + name: 'memory', version: '0.0.0', supports: {} as any, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async find(o: string, ast: any) { const rows = Array.from(storeFor(o).values()).filter((r) => matchesWhere(r, ast?.where)); return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; }, + async findOne(o: string, ast: any) { for (const r of storeFor(o).values()) if (matchesWhere(r, ast?.where)) return r; return null; }, + async create(o: string, data: Record) { nextId += 1; const id = (data.id as string) ?? `r_${nextId}`; const row = { ...data, id }; storeFor(o).set(id, row); return row; }, + async update(o: string, id: string, data: Record) { const s = storeFor(o); const cur = s.get(id); if (!cur) throw new Error(`not found ${o}/${id}`); const u = { ...cur, ...data, id }; s.set(id, u); return u; }, + async upsert(o: string, data: Record) { const id = data.id as string | undefined; if (id && storeFor(o).has(id)) return this.update(o, id, data); return this.create(o, data); }, + async delete(o: string, id: string) { return storeFor(o).delete(id); }, + async count(o: string, ast: any) { return (await this.find(o, ast)).length; }, + async bulkCreate(o: string, rows: Record[]) { return Promise.all(rows.map((r) => this.create(o, r))); }, + async bulkUpdate() { return []; }, async bulkDelete() {}, + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + }; + return { driver }; +} + +const Q = 'com.example.expenses'; +const P = 'com.example.projects'; +const O = 'crm_expense'; +const VIEW = 'crm_expense.all'; +const PAIR = `${Q}.custom`; + +async function boot() { + const engine = new ObjectQL(); + engine.registerDriver(makeMemoryDriver().driver, true); + await engine.init(); + engine.registry.registerObject(sysMetadataObject, 'test-package'); + for (const o of [SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) engine.registry.registerObject(o as any, 'test-package'); + engine.registerApp({ + id: Q, name: 'expenses', version: '1.0.0', namespace: 'crm', type: 'app', + objects: [{ name: O, label: 'Expense', fields: { name: { name: 'name', label: 'Name', type: 'text' }, amount: { name: 'amount', label: 'Amount', type: 'number' } } }], + views: [{ object: O, listViews: { all: { label: 'All expenses', type: 'grid', data: { provider: 'object', object: O }, columns: [{ field: 'name' }, { field: 'amount' }, { field: 'crm_project' }], sort: [{ field: 'crm_project', order: 'asc' }] } } }], + } as any); + engine.registerApp({ + id: P, name: 'projects', version: '1.0.0', namespace: 'crm', type: 'app', dependencies: { [Q]: '^1.0.0' }, + objectExtensions: [{ extend: O, fields: { crm_project: { name: 'crm_project', label: 'Project', type: 'text' } } }], + } as any); + const protocol = new ObjectStackProtocolImplementation(engine, () => new Map()); + await (protocol as any).installPackage({ manifest: { id: PAIR, name: 'expenses-custom', version: '0.1.0', type: 'app', namespace: 'crm_custom', dependencies: { [Q]: '^1' } } }); + return { engine, registry: engine.registry as any, protocol: protocol as any }; +} + +const savedWritable = process.env.OS_METADATA_WRITABLE; +beforeEach(() => { delete process.env.OS_METADATA_WRITABLE; ObjectStackProtocolImplementation.resetEnvWritableCache(); resetEnvWritableMetadataTypes(); }); +afterEach(() => { + if (savedWritable === undefined) delete process.env.OS_METADATA_WRITABLE; else process.env.OS_METADATA_WRITABLE = savedWritable; + ObjectStackProtocolImplementation.resetEnvWritableCache(); resetEnvWritableMetadataTypes(); +}); + +/** The served view as the console's read-merge-write holds it, ready to PUT into Q's pair. */ +async function servedViewBody(protocol: any, edit: (config: any) => any = (c) => c) { + const item = (await protocol.getMetaItem({ type: 'view', name: VIEW })).item; + const { _packageId, _provenance, ...body } = item; + return { ...body, config: edit(body.config), overrides: { package: Q, basedOn: '1.0.0' } }; +} + +async function outcome(fn: () => Promise) { + try { + await fn(); + return { ok: true as const }; + } catch (e: any) { + const issues = e?.issues ?? e?.details?.issues ?? e?.errors; + return { + ok: false as const, + code: e?.code, + status: e?.status, + rules: Array.isArray(issues) ? issues.map((i: any) => i?.rule ?? i?.code) : [], + message: String(e?.message ?? ''), + }; + } +} + +describe('[#34901] a view over a field a disabled package contributes', () => { + it('the served object read names the withheld field and its package; the execution face does not; re-enable clears it', async () => { + const { registry, protocol } = await boot(); + const on = (await protocol.getMetaItem({ type: 'object', name: O })).item; + expect('_withheldFields' in on, 'nothing disabled ⇒ no marker').toBe(false); + + registry.disablePackage(P); + const off = (await protocol.getMetaItem({ type: 'object', name: O })).item; + expect(off._withheldFields).toEqual({ crm_project: { packageId: P } }); + expect(Object.keys(off.fields)).not.toContain('crm_project'); + const listed = ((await protocol.getMetaItems({ type: 'object' })).items as any[]).find((o) => o?.name === O); + expect(listed?._withheldFields, 'the list read carries it too').toEqual({ crm_project: { packageId: P } }); + const execution = (await protocol.getMetaItemForExecution({ type: 'object', name: O }))?.item; + expect(execution, 'precondition: the execution face answers').toBeTruthy(); + expect('_withheldFields' in execution, 'the execution face is not decorated').toBe(false); + + registry.enablePackage(P); + const back = (await protocol.getMetaItem({ type: 'object', name: O })).item; + expect('_withheldFields' in back).toBe(false); + expect(Object.keys(back.fields)).toContain('crm_project'); + }); + + it('the view saves into the pair while P is off, keeping the withheld column and sort, served as saved once P is back', async () => { + const { registry, protocol } = await boot(); + registry.disablePackage(P); + const body = await servedViewBody(protocol, (c) => ({ ...c, columns: c.columns.map((col: any) => (col.field === 'name' ? { ...col, width: 240 } : col)) })); + const saved = await outcome(() => protocol.saveMetaItem({ type: 'view', name: VIEW, item: body, packageId: PAIR })); + expect(saved).toEqual({ ok: true }); + + registry.enablePackage(P); + const served = (await protocol.getMetaItem({ type: 'view', name: VIEW })).item; + expect(served.config.columns.map((c: any) => c.field)).toEqual(['name', 'amount', 'crm_project']); + expect(served.config.columns[0].width).toBe(240); + expect(served.config.sort).toEqual([{ field: 'crm_project', order: 'asc' }]); + }); + + it('a typo\'d column is still refused while P is off', async () => { + const { registry, protocol } = await boot(); + registry.disablePackage(P); + const body = await servedViewBody(protocol, (c) => ({ ...c, columns: [...c.columns, { field: 'crm_projcet' }] })); + const saved = await outcome(() => protocol.saveMetaItem({ type: 'view', name: VIEW, item: body, packageId: PAIR })); + expect(saved).toMatchObject({ ok: false, status: 422 }); + // One issue, on the typo's own position: the withheld column beside it is not refused. + expect((saved as any).rules).toEqual(['list-view-field-unknown']); + expect((saved as any).message).toContain('config.columns[3].field'); + }); + + it('the fold is for view writes only: a page sorting by the withheld field is still refused while P is off', async () => { + const { registry, protocol } = await boot(); + const page = (field: string) => ({ + name: 'crm_custom_expenses', label: 'Expenses', type: 'list', object: O, + interfaceConfig: { source: O, sort: [{ field, order: 'asc' }] }, + }); + const save = (field: string) => outcome(() => protocol.saveMetaItem({ type: 'page', name: 'crm_custom_expenses', item: page(field), packageId: PAIR })); + expect(await save('crm_project'), 'precondition: with P on the page saves').toEqual({ ok: true }); + + registry.disablePackage(P); + const refused = await save('crm_project'); + expect(refused).toMatchObject({ ok: false, status: 422 }); + expect((refused as any).rules).toEqual(['page-field-unknown']); + expect(await save('name'), 'control: a served field saves').toEqual({ ok: true }); + }); +}); diff --git a/packages/objectql/src/registry-disabled-package-extensions.test.ts b/packages/objectql/src/registry-disabled-package-extensions.test.ts index afd18a02985..e07a17738b2 100644 --- a/packages/objectql/src/registry-disabled-package-extensions.test.ts +++ b/packages/objectql/src/registry-disabled-package-extensions.test.ts @@ -217,3 +217,79 @@ describe('[#30756] the asEnabled fold', () => { expect(fieldsOf(served({ asEnabled: OTHER_PKG }))).toEqual(['name', 'qa_score']); }); }); + +/** + * [#34901] The two reads the withheld-field marker and the view save door are + * built on: `getWithheldExtensionFields` names what a disable withholds from + * the served object (and which package withholds it), and the fold option + * `includeDisabledExtensions` folds EVERY disabled package's extension in, + * the storage view of the object, without moving any state. + */ +describe('[#34901] the withheld-field reader and includeDisabledExtensions', () => { + const APP_PKG = 'com.qa.wh.app'; + const MODULE_PKG = 'com.qa.wh.projects'; + const OTHER_PKG = 'com.qa.wh.scoring'; + const OBJECT = 'qw_expense'; + const manifest = (id: string, type: string) => + ({ id, name: id, version: '1.0.0', type, namespace: 'qw', ...(type === 'module' ? { dependencies: { [APP_PKG]: '^1.0.0' } } : {}) }) as any; + + let registry: SchemaRegistry; + beforeEach(() => { + registry = new SchemaRegistry({ multiTenant: false }); + (registry as any).logLevel = 'silent'; + registry.installPackage(manifest(APP_PKG, 'app'), 'code'); + registry.installPackage(manifest(MODULE_PKG, 'module'), 'code'); + registry.installPackage(manifest(OTHER_PKG, 'module'), 'code'); + registry.registerObject({ + name: OBJECT, label: 'Expense', fields: { name: { name: 'name', type: 'text', label: 'Name' } }, + } as any, APP_PKG, 'qw', 'own'); + registry.registerObject({ + name: OBJECT, + fields: { + qw_project: { name: 'qw_project', type: 'text', label: 'Project' }, + qw_shared: { name: 'qw_shared', type: 'text', label: 'Shared' }, + }, + } as any, MODULE_PKG, 'qw', 'extend'); + registry.registerObject({ + name: OBJECT, + fields: { + qw_score: { name: 'qw_score', type: 'number', label: 'Score' }, + qw_shared: { name: 'qw_shared', type: 'text', label: 'Shared' }, + }, + } as any, OTHER_PKG, 'qw', 'extend'); + }); + const fieldsOf = (body: any): string[] => Object.keys(body?.fields ?? {}).filter((f) => f.startsWith('qw_') || f === 'name').sort(); + + it('names each withheld field with the disabled package that adds it, and nothing a kept contributor also declares', () => { + expect(registry.getWithheldExtensionFields(OBJECT), 'nothing disabled ⇒ nothing withheld').toEqual({}); + registry.disablePackage(MODULE_PKG); + expect(registry.getWithheldExtensionFields(OBJECT)).toEqual({ qw_project: { packageId: MODULE_PKG } }); + expect(fieldsOf(registry.getObject(OBJECT)), 'the reader agrees with the served fold').toEqual(['name', 'qw_score', 'qw_shared']); + registry.disablePackage(OTHER_PKG); + expect(registry.getWithheldExtensionFields(OBJECT)).toEqual({ + qw_project: { packageId: MODULE_PKG }, + qw_shared: { packageId: MODULE_PKG }, + qw_score: { packageId: OTHER_PKG }, + }); + expect(registry.getWithheldExtensionFields('qw_unknown'), 'an unknown object withholds nothing').toEqual({}); + }); + + it('re-enabling the package clears the reader with no other write', () => { + registry.disablePackage(MODULE_PKG); + expect(Object.keys(registry.getWithheldExtensionFields(OBJECT))).toEqual(['qw_project']); + registry.enablePackage(MODULE_PKG); + expect(registry.getWithheldExtensionFields(OBJECT)).toEqual({}); + expect(fieldsOf(registry.getObject(OBJECT))).toEqual(['name', 'qw_project', 'qw_score', 'qw_shared']); + }); + + it('includeDisabledExtensions folds every disabled extension in, and leaves the served fold and the disable state alone', () => { + registry.disablePackage(MODULE_PKG); + registry.disablePackage(OTHER_PKG); + const owner = { name: OBJECT, label: 'Expense', fields: { name: { name: 'name', type: 'text', label: 'Name' } } }; + const storage = registry.foldObjectExtendersOnto(OBJECT, owner, { includeDisabledExtensions: true }); + expect(fieldsOf(storage)).toEqual(['name', 'qw_project', 'qw_score', 'qw_shared']); + expect(fieldsOf(registry.foldObjectExtendersOnto(OBJECT, owner)), 'control: unset, the served fold').toEqual(['name']); + expect(fieldsOf(registry.getObject(OBJECT))).toEqual(['name']); + expect(registry.isPackageDisabled(MODULE_PKG) && registry.isPackageDisabled(OTHER_PKG)).toBe(true); + }); +}); diff --git a/packages/objectql/src/registry-object-registration.ts b/packages/objectql/src/registry-object-registration.ts index 3da9d6a4ad1..e96f26fcfb6 100644 --- a/packages/objectql/src/registry-object-registration.ts +++ b/packages/objectql/src/registry-object-registration.ts @@ -769,6 +769,32 @@ export class ObjectRegistrationFacet { return { kept, withheldFields, withheldRules, withheldIndexes }; } + /** + * [#34901] The body of `SchemaRegistry#getWithheldExtensionFields`; the + * method's docblock there is its contract. Read off + * {@link withholdDisabledExtensions}, the one reading of what a disable + * withholds, so this answer and the served fold cannot disagree. + */ + static getWithheldExtensionFields(this: Pick, name: string): Record { + const fqn = this.resolveObjectKey(name); + const contributors = fqn === undefined ? undefined : this.objectContributors.get(fqn); + if (!contributors || contributors.length === 0) return {}; + const withheld = this.withholdDisabledExtensions(contributors); + if (!withheld || withheld.withheldFields.size === 0) return {}; + const out: Record = {}; + // In fold order, so a field two disabled packages both add names the + // first; any of them re-enabled serves it again. + for (const c of contributors) { + if (c.ownership !== 'extend' || withheld.kept.includes(c) || typeof c.packageId !== 'string') continue; + for (const field of fieldNamesOf(c.definition)) { + if (withheld.withheldFields.has(field) && !Object.prototype.hasOwnProperty.call(out, field)) { + out[field] = { packageId: c.packageId }; + } + } + } + return out; + } + /** * [#29903, #29872, ADR-0146 D8 item 3] An object as {@link resolveObject} * resolves it, but with the `extend` contributions `options` names left out @@ -792,16 +818,19 @@ export class ObjectRegistrationFacet { const asEnabled = options?.asEnabled !== undefined && this.isPackageDisabled(options.asEnabled) ? options.asEnabled : undefined; - const contributors = leavesExtensionsOut(options) || asEnabled !== undefined ? this.objectContributors.get(fqn) : undefined; + // [#34901] …and `includeDisabledExtensions` folds EVERY disabled package in. + const includeDisabled = options?.includeDisabledExtensions === true; + const contributors = leavesExtensionsOut(options) || asEnabled !== undefined || includeDisabled ? this.objectContributors.get(fqn) : undefined; if (!contributors || !contributors.some((c) => isLeftOutExtension(c, options!) - || (asEnabled !== undefined && c.ownership === 'extend' && c.packageId === asEnabled))) return this.resolveObject(fqn); + || (asEnabled !== undefined && c.ownership === 'extend' && c.packageId === asEnabled) + || (includeDisabled && c.ownership === 'extend' && this.isPackageDisabled(c.packageId)))) return this.resolveObject(fqn); const kept = contributors.filter((c) => !isLeftOutExtension(c, options!)); const ownerContrib = kept.find(c => c.ownership === 'own'); if (!ownerContrib) return undefined; const base = kept.find(c => c.ownership === 'overlay') ?? ownerContrib; // …and a disabled package's, as on every served fold ({@link withholdDisabledExtensions}), - // except the one `asEnabled` names. - const withheld = this.withholdDisabledExtensions(kept, asEnabled); + // except the one `asEnabled` names — and none at all under `includeDisabledExtensions`. + const withheld = includeDisabled ? undefined : this.withholdDisabledExtensions(kept, asEnabled); return withheld ? this.foldExtendersOntoDefinition(withheld.kept, withoutWithheldMembers(base.definition, withheld)) : this.foldExtenders(kept, base); @@ -1473,8 +1502,9 @@ export class ObjectRegistrationFacet { const registered = this.objectContributors.get(fqn); const listed = leavesExtensionsOut(options) ? registered?.filter((c) => !isLeftOutExtension(c, options)) : registered; // A disabled package's `extend` contributions are withheld, and taken off - // a base that already carries them, as on {@link resolveObject}. - const withheld = listed ? this.withholdDisabledExtensions(listed) : undefined; + // a base that already carries them, as on {@link resolveObject} — unless + // [#34901] `includeDisabledExtensions` asks for the storage fold. + const withheld = listed && options?.includeDisabledExtensions !== true ? this.withholdDisabledExtensions(listed) : undefined; const contributors = withheld?.kept ?? listed; const served = withheld ? withoutWithheldMembers(base as unknown as ServiceObject, withheld) : base as unknown as ServiceObject; if (!contributors || !contributors.some((c) => c.ownership === 'extend')) { diff --git a/packages/objectql/src/registry-top-level.ts b/packages/objectql/src/registry-top-level.ts index 5b7a47ccfe4..0091ee0e594 100644 --- a/packages/objectql/src/registry-top-level.ts +++ b/packages/objectql/src/registry-top-level.ts @@ -719,11 +719,21 @@ type ServedObjectLayer = 'served' | 'code'; * Every other disabled package's stay withheld. The enable door's pre-check * reads it, as the disable door's reads `withoutExtensionsOf`; for a package * that is not disabled it changes nothing. + * + * [#34901] `includeDisabledExtensions` is `asEnabled` for EVERY disabled + * package at once: no `extend` contribution is withheld, so the fold is the + * one the storage layer keeps ({@link SchemaRegistry.getStorageObject}). The + * runtime authoring gate reads it on a `view` write ONLY, so a column or sort + * naming a field a disabled package adds is judged a real, stored field rather + * than an unknown one: the view the owner ships keeps naming it, and + * re-enabling the package serves it again with no write. A name no + * contributor declares is unknown either way. */ export interface ObjectExtensionFoldOptions { withoutExtensionsOf?: string; onlyExtensionsOf?: string; asEnabled?: string; + includeDisabledExtensions?: true; } /** Whether `options` leaves any contribution out (otherwise the fold is the ordinary one). */ diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 41fba891e8d..2e870dda3c7 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -2934,6 +2934,23 @@ export class SchemaRegistry { return ObjectRegistrationFacet.resolveStorageObject.call(objectRegistrationHost.of(this), fqn); } + /** + * [#34901] The fields a disabled package's `extend` contribution adds to + * `name` and the served fold therefore withholds, each with the package + * that adds it: `{ crm_project: { packageId: 'com.acme.projects' } }`. + * Empty when nothing is withheld (no disabled extender, or every field it + * adds is also declared by the owner or a served extension). + * + * The served object read stamps this as its `_withheldFields` read + * decoration, so a console can tell a name a switched-off package withholds + * from a name nothing declares, and leave it out of every query while the + * data door keeps refusing both. Accepts a short name or an FQN, as + * {@link getObject} does. + */ + getWithheldExtensionFields(name: string): Record { + return ObjectRegistrationFacet.getWithheldExtensionFields.call(objectRegistrationHost.of(this), name); + } + private withholdDisabledExtensions(contributors: readonly ObjectContributor[], asEnabled?: string): WithheldExtensions | undefined { // [#33949 codemod] The body moved to `registry-object-registration.ts`, its docblock with it (see `ObjectRegistrationHost`). return ObjectRegistrationFacet.withholdDisabledExtensions.call(objectRegistrationHost.of(this), contributors, asEnabled); diff --git a/packages/spec/src/kernel/metadata-read-decorations.ts b/packages/spec/src/kernel/metadata-read-decorations.ts index 77d94232b17..2f0a0d25163 100644 --- a/packages/spec/src/kernel/metadata-read-decorations.ts +++ b/packages/spec/src/kernel/metadata-read-decorations.ts @@ -37,6 +37,11 @@ * derived from the document, so neither belongs inside it. * - `_draft` — the preview badge added by draft reads. Draft-ness lives in the * row's `state` column and the `mode` parameter, never in the body. + * - `_withheldFields` — on a served `object` read, the fields a disabled + * package's extension adds and the served fold withholds, each with that + * package (`{ FIELD: { packageId } }`). Derived from which packages are + * disabled at read time, so a copy saved into a body would be a stale + * verdict the next enable or disable contradicts. * * Deliberately NOT members, though they share the underscore spelling: the * ADR-0010 protection envelope (`_lock`, `_lockReason`, `_lockSource`, @@ -45,7 +50,7 @@ * legitimately carries and merges, and the closed metadata schemas allowlist * them precisely so a served document keeps its provenance on re-parse. */ -export const METADATA_READ_DECORATIONS = ['_diagnostics', '_draft'] as const; +export const METADATA_READ_DECORATIONS = ['_diagnostics', '_draft', '_withheldFields'] as const; /** Union of the keys in {@link METADATA_READ_DECORATIONS}. */ export type MetadataReadDecoration = (typeof METADATA_READ_DECORATIONS)[number]; diff --git a/ui/packages/core/src/index.ts b/ui/packages/core/src/index.ts index 8ea048534d1..2da3be788ce 100644 --- a/ui/packages/core/src/index.ts +++ b/ui/packages/core/src/index.ts @@ -378,6 +378,7 @@ export * from './utils/parent-scope.js'; // The other half of a view's field appetite: the fields its PREDICATES read, // which the column-derived `$select` never asked the server for. export * from './utils/predicate-fields.js'; +export * from './utils/withheld-fields.js'; // The THIRD source of a view's field appetite: the fields it GROUPS BY. The // spec's `grouping` block is a sibling of `columns`, not a subset, so a grid // may group by a field it never shows (objectui#7179). diff --git a/ui/packages/core/src/utils/withheld-fields.ts b/ui/packages/core/src/utils/withheld-fields.ts new file mode 100644 index 00000000000..d43368406e7 --- /dev/null +++ b/ui/packages/core/src/utils/withheld-fields.ts @@ -0,0 +1,97 @@ +/** + * ObjectUI — fields a disabled package withholds + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#34901 — the fields a DISABLED package contributes to an object it + * extends. + * + * A package can add fields to another package's object (`objectExtensions`). + * While that package is disabled the platform leaves those fields out of the + * served object, and the data door judges every `$select`, `$filter`, + * `$orderby`, `$searchFields` and `groupBy` name against the served object: a + * name it does not know is refused with `400 INVALID_FIELD`, and with it the + * whole list. The owner's views are not rewritten by a disable, so a view + * column on such a field used to fail the list for everyone. + * + * The served object read now says which names are withheld, under the + * top-level read decoration `_withheldFields` (`{ [field]: { packageId } }`, + * `METADATA_READ_DECORATIONS` in `@objectstack/spec`). It is stamped on the + * served face only, stripped by the save door, and absent when nothing is + * withheld. The list readers leave a withheld name out of every request and + * hide its column by derivation, never by writing the view or the user's list + * preferences, so re-enabling the package brings the column, the sort and the + * grouping back with no write at all. + * + * Deliberately a separate map and not a stub in `fields`: every other field + * reader (forms, pickers, the filter builder, the FLS check, + * {@link isProjectableField}) keeps treating the name as undeclared, which is + * what it is while the package is off. + */ +export const WITHHELD_FIELDS_KEY = '_withheldFields'; + +/** One shared empty set, so a dependency list never sees a new identity when nothing is withheld. */ +export const NO_WITHHELD_FIELDS: ReadonlySet = new Set(); + +/** + * The field map a definition's withheld names were read beside. Lets a reader + * that holds only the field map (`ObjectGrid`'s grouping decisions take + * `objectSchema.fields`, not the definition) ask the same question; filled by + * {@link readWithheldFieldNames}, which every list reader calls on the + * definition it fetched before handing the definition on. + */ +const withheldByFieldMap = new WeakMap>(); + +/** + * The names `objectDef` marks as withheld by a disabled package. A name the + * definition also declares in `fields` is not withheld (the platform only + * marks names the served body leaves out, and a declared field is servable). + * Empty for anything without the marker. + */ +export function readWithheldFieldNames(objectDef: unknown): ReadonlySet { + if (!objectDef || typeof objectDef !== 'object') return NO_WITHHELD_FIELDS; + const def = objectDef as Record; + const fields = def.fields; + const marked = def[WITHHELD_FIELDS_KEY]; + let names: ReadonlySet = NO_WITHHELD_FIELDS; + if (marked && typeof marked === 'object' && !Array.isArray(marked)) { + const declared = declaredFieldNames(fields); + const found = new Set(); + for (const name of Object.keys(marked as Record)) { + if (name.length > 0 && !declared.has(name)) found.add(name); + } + if (found.size > 0) names = found; + } + if (fields && typeof fields === 'object') withheldByFieldMap.set(fields as object, names); + return names; +} + +/** + * The withheld names read beside this field map by {@link readWithheldFieldNames}. + * Empty when that definition carried none, or was never read. + */ +export function withheldFieldNamesOfFieldMap(fields: unknown): ReadonlySet { + if (!fields || typeof fields !== 'object') return NO_WITHHELD_FIELDS; + return withheldByFieldMap.get(fields as object) ?? NO_WITHHELD_FIELDS; +} + +/** Whether a field reference (`project`, or a dotted `project.name`) starts at a withheld field. */ +export function refersToWithheldField(ref: unknown, withheld: ReadonlySet): ref is string { + return typeof ref === 'string' && withheld.size > 0 && withheld.has(ref.split('.')[0]); +} + +function declaredFieldNames(fields: unknown): ReadonlySet { + if (Array.isArray(fields)) { + return new Set( + fields + .map((f) => (f as { name?: unknown } | null)?.name) + .filter((n): n is string => typeof n === 'string'), + ); + } + if (fields && typeof fields === 'object') return new Set(Object.keys(fields as Record)); + return NO_WITHHELD_FIELDS; +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 597a4082c1b..040e098ac74 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1045,6 +1045,7 @@ const ar = { groupingUnstoredNotice: "لا يمكن تجميع هذه القائمة حسب {{fields}}: تُحسب القيمة عند العرض ولا تُخزَّن. تُعرض القائمة دون هذا التجميع.", groupingUnstoredRemove: "إزالة من التجميع", draftOnlyQueryDropped: "لم تتم التصفية أو الفرز حسب {{fields}}: هذا الحقل موجود في المسودة فقط حتى النشر.", + withheldFieldsLeftOut: "لا يتم العرض أو التصفية أو الفرز أو التجميع حسب {{fields}}: الحزمة التي تضيف هذا الحقل معطلة. سيعود عند تفعيل الحزمة.", inlineEditShort: "تحرير مضمّن", inlineEditLabel: "حرّر السجلات مباشرة (انقر خلية للتحرير)", }, diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index f901683b38f..8bd934f8b2a 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -936,6 +936,7 @@ const de = { groupingUnstoredNotice: "Diese Liste kann nicht nach {{fields}} gruppiert werden: Der Wert wird bei der Anzeige berechnet und nicht gespeichert. Die Liste wird ohne diese Gruppierung angezeigt.", groupingUnstoredRemove: "Aus Gruppierung entfernen", draftOnlyQueryDropped: "Nicht nach {{fields}} gefiltert oder sortiert: Das Feld existiert bis zur Veröffentlichung nur im Entwurf.", + withheldFieldsLeftOut: "Nicht angezeigt, gefiltert, sortiert oder gruppiert nach {{fields}}: Das Paket, das das Feld hinzufügt, ist deaktiviert. Es kehrt zurück, sobald das Paket aktiviert wird.", inlineEditShort: "Inline bearbeiten", inlineEditLabel: "Datensätze inline bearbeiten (Zelle anklicken zum Bearbeiten)", }, diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 36f12c9b330..8f5cdfda0e7 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1225,6 +1225,7 @@ const en = { groupingUnstoredNotice: 'This list cannot be grouped by {{fields}}: its value is calculated when shown, not stored. The list is shown without that grouping.', groupingUnstoredRemove: 'Remove from grouping', draftOnlyQueryDropped: 'Not filtered or sorted by {{fields}}: it exists only in the draft until you publish.', + withheldFieldsLeftOut: 'Not shown, filtered, sorted or grouped by {{fields}}: the package that adds it is disabled. It comes back when the package is enabled.', inlineEditShort: 'Edit inline', inlineEditLabel: 'Edit records inline (click a cell to edit)', }, diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index fb840e1f413..02e79dc017c 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -966,6 +966,7 @@ const es = { groupingUnstoredNotice: "Esta lista no se puede agrupar por {{fields}}: su valor se calcula al mostrarse y no se almacena. La lista se muestra sin esa agrupación.", groupingUnstoredRemove: "Quitar de la agrupación", draftOnlyQueryDropped: "Sin filtrar ni ordenar por {{fields}}: solo existe en el borrador hasta que publiques.", + withheldFieldsLeftOut: "Sin mostrar, filtrar, ordenar ni agrupar por {{fields}}: el paquete que lo añade está desactivado. Vuelve cuando se activa el paquete.", inlineEditShort: "Edición en línea", inlineEditLabel: "Editar registros en línea (haga clic en una celda para editar)", }, diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index fab972ac509..6fce02fa9c2 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -961,6 +961,7 @@ const fr = { groupingUnstoredNotice: "Cette liste ne peut pas être regroupée par {{fields}} : sa valeur est calculée à l’affichage et n’est pas stockée. La liste est affichée sans ce regroupement.", groupingUnstoredRemove: "Retirer du regroupement", draftOnlyQueryDropped: "Non filtré ni trié par {{fields}} : ce champ n’existe que dans le brouillon jusqu’à la publication.", + withheldFieldsLeftOut: "Non affiché, filtré, trié ni groupé par {{fields}} : le paquet qui ajoute ce champ est désactivé. Il revient lorsque le paquet est réactivé.", inlineEditShort: "Édition en ligne", inlineEditLabel: "Modifier les enregistrements en ligne (cliquez sur une cellule pour modifier)", }, diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 4734e5c2374..24298c44e76 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -936,6 +936,7 @@ const ja = { groupingUnstoredNotice: "{{fields}} ではこの一覧をグループ化できません。値は表示時に計算され、保存されていません。このグループ化を除いて一覧を表示しています。", groupingUnstoredRemove: "グループ化から削除", draftOnlyQueryDropped: "{{fields}} での絞り込みと並べ替えは行われていません。下書きにのみ存在し、公開後に有効になります。", + withheldFieldsLeftOut: "{{fields}} は表示、絞り込み、並べ替え、グループ化されていません。この項目を追加するパッケージが無効になっています。パッケージを有効にすると戻ります。", inlineEditShort: "インライン編集", inlineEditLabel: "レコードをインラインで編集(セルをクリックして編集)", }, diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 0cac6f179bc..7111c687233 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -936,6 +936,7 @@ const ko = { groupingUnstoredNotice: "{{fields}} 기준으로 이 목록을 그룹화할 수 없습니다. 값이 표시될 때 계산되며 저장되지 않습니다. 해당 그룹화 없이 목록을 표시합니다.", groupingUnstoredRemove: "그룹화에서 제거", draftOnlyQueryDropped: "{{fields}} 기준 필터와 정렬이 적용되지 않았습니다. 초안에만 있으며 게시 후 적용됩니다.", + withheldFieldsLeftOut: "{{fields}} 기준 표시, 필터, 정렬, 그룹화가 적용되지 않았습니다. 이 필드를 추가하는 패키지가 비활성화되어 있습니다. 패키지를 활성화하면 다시 나타납니다.", inlineEditShort: "인라인 편집", inlineEditLabel: "레코드를 인라인으로 편집(셀을 클릭하여 편집)", }, diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 190013429d6..e7407fd69a8 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -961,6 +961,7 @@ const pt = { groupingUnstoredNotice: "Esta lista não pode ser agrupada por {{fields}}: o valor é calculado ao ser exibido e não é armazenado. A lista é exibida sem esse agrupamento.", groupingUnstoredRemove: "Remover do agrupamento", draftOnlyQueryDropped: "Sem filtrar nem ordenar por {{fields}}: existe apenas no rascunho até você publicar.", + withheldFieldsLeftOut: "Sem exibir, filtrar, ordenar nem agrupar por {{fields}}: o pacote que o adiciona está desativado. Ele volta quando o pacote for ativado.", inlineEditShort: "Edição em linha", inlineEditLabel: "Editar registros em linha (clique em uma célula para editar)", }, diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 7a93373a9d8..affff7e2bac 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -992,6 +992,7 @@ const ru = { groupingUnstoredNotice: "Этот список нельзя сгруппировать по полю {{fields}}: его значение вычисляется при отображении и не хранится. Список показан без этой группировки.", groupingUnstoredRemove: "Убрать из группировки", draftOnlyQueryDropped: "Без фильтрации и сортировки по {{fields}}: поле есть только в черновике до публикации.", + withheldFieldsLeftOut: "Не показано, без фильтрации, сортировки и группировки по {{fields}}: пакет, который добавляет это поле, отключён. Поле вернётся, когда пакет будет включён.", inlineEditShort: "Встроенное редактирование", inlineEditLabel: "Редактировать записи в таблице (щёлкните ячейку для редактирования)", }, diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index de45750e418..0e5cb2d9217 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -963,6 +963,7 @@ const zh = { groupingUnstoredNotice: '无法按 {{fields}} 分组:它的值在显示时计算,并未存储。列表已暂不按它分组显示。', groupingUnstoredRemove: '从分组中移除', draftOnlyQueryDropped: '未按 {{fields}} 筛选或排序:它仅存在于草稿中,发布后才生效。', + withheldFieldsLeftOut: '未显示 {{fields}},也未按其筛选、排序或分组:添加该字段的软件包已停用,启用后即恢复。', inlineEditShort: '行内编辑', inlineEditLabel: '行内编辑记录(点击单元格进行编辑)', }, diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 359b24f8b48..5a54de8898d 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -963,6 +963,7 @@ const zhHant = { groupingUnstoredNotice: '無法按 {{fields}} 分組:它的值在顯示時計算,並未儲存。列表已暫不按它分組顯示。', groupingUnstoredRemove: '從分組中移除', draftOnlyQueryDropped: '未按 {{fields}} 篩選或排序:它僅存在於草稿中,釋出後才生效。', + withheldFieldsLeftOut: '未顯示 {{fields}},也未按其篩選、排序或分組:新增該欄位的套件已停用,啟用後即恢復。', inlineEditShort: '行內編輯', inlineEditLabel: '行內編輯記錄(點選單元格進行編輯)', }, diff --git a/ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx b/ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx index 2ff1b2f35b7..d3a21ca5ef2 100644 --- a/ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx +++ b/ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx @@ -14,7 +14,7 @@ import { resolveGridCellRendering, gridCellRendererForFixedKey, linkCellRenderer import { isWithheldGridColumn } from './maskedColumn'; import { humanizeLabel, MaskedCellRenderer } from '@object-ui/fields'; import { Button, EmptyValue } from '@object-ui/components'; -import { isDeadlineSettled, leadWithNameField, columnIdentity } from '@object-ui/core'; +import { isDeadlineSettled, leadWithNameField, columnIdentity, readWithheldFieldNames, refersToWithheldField } from '@object-ui/core'; import { usePermissions } from '@object-ui/permissions'; import { Type, Hash, Calendar, CheckSquare, User, Tag, Clock } from 'lucide-react'; import { applyRelationalMeta } from './relationalMetaKeys'; @@ -226,6 +226,13 @@ export function useObjectGridGenerateColumns({ if (!Object.prototype.hasOwnProperty.call(objectFields ?? {}, fieldName)) return true; return perms.checkField(schema.objectName, fieldName, 'read'); }; + // objectstack#34901 — an authored column on a field a disabled package + // withholds from the served object (`_withheldFields`) is not drawn: the + // row load never asks for it, so it could only draw empty. Derived from + // the definition on every call, so it is drawn again once the package is + // enabled; nothing is written. + const packageWithheld = readWithheldFieldNames(objectSchema); + const notWithheld = (entry: unknown): boolean => !refersToWithheldField(columnIdentity(entry), packageWithheld); // ObjectStack's DECLARED column spelling is the only one read // (objectui#5068). `ObjectGridSchema.columns` is `string[] | ListColumn[]`, // and `ListColumnSchema` in `@objectstack/spec/ui` is a STRICT object: @@ -259,6 +266,7 @@ export function useObjectGridGenerateColumns({ return (cols as ListColumn[]) .filter((col) => resolvesToDataColumn(col)) .filter((col) => passesFieldGate(col)) + .filter((col) => notWithheld(col)) .map((col, colIndex, shown) => { // The column's own `label` is the spec's "Display label override" // (`ListColumnSchema`), so when the author wrote one it IS the @@ -584,6 +592,7 @@ export function useObjectGridGenerateColumns({ return (cols as string[]) .filter((fieldName) => typeof fieldName === 'string' && fieldName.trim().length > 0) .filter((fieldName) => passesFieldGate(fieldName)) + .filter((fieldName) => notWithheld(fieldName)) .map((fieldName, colIndex) => { const fieldDef = objectFields?.[fieldName]; // objectui#10657 — a bare field name carries no type of its own, so diff --git a/ui/packages/plugin-grid/src/objectGridGroupingDecisions.ts b/ui/packages/plugin-grid/src/objectGridGroupingDecisions.ts index b161247731d..8bc6124f42b 100644 --- a/ui/packages/plugin-grid/src/objectGridGroupingDecisions.ts +++ b/ui/packages/plugin-grid/src/objectGridGroupingDecisions.ts @@ -10,6 +10,7 @@ import React, { useEffect, useState } from 'react'; import type { ObjectGridSchema, DataSource, ListColumn, ViewData } from '@object-ui/types'; import type { usePermissions } from '@object-ui/permissions'; +import { withheldFieldNamesOfFieldMap } from '@object-ui/core'; import { isMaskedGridColumn } from './maskedColumn'; import { usableGroupingFields } from './useGroupedData'; import { normalizeColumns } from './objectGridColumns'; @@ -106,17 +107,38 @@ export function useObjectGridGroupingDecisions({ () => JSON.parse(draftOnlyGroupingKey) as string[], [draftOnlyGroupingKey], ); + // objectstack#34901 — a field a disabled package withholds from the served + // object is REFUSED as a grouping key on the same terms: the door refuses + // every `groupBy` name the served object does not declare. The names are + // the ones the row load read beside this field map (`_withheldFields`, via + // `readWithheldFieldNames`), so the entry groups again on the first + // definition read after the package is enabled. Dropped without a note of + // the grid's own: a list view names it in its line above the rows. + const packageWithheld = withheldFieldNamesOfFieldMap(objectFields); + const packageWithheldGroupingKey = JSON.stringify( + packageWithheld.size === 0 + ? [] + : usableGroupingFields(groupingFieldsRaw) + .map((gf) => gf.field) + .filter((field) => packageWithheld.has(field)), + ); + const packageWithheldGroupingFields = React.useMemo( + () => JSON.parse(packageWithheldGroupingKey) as string[], + [packageWithheldGroupingKey], + ); // Keyed on the authored array and the signature STRING, never on a memo's // identity (AGENTS.md #10). Read only when something was refused: the // unmasked path below hands `useGroupedData` the authored config itself. const unmaskedGroupingFields = React.useMemo(() => { const { refused }: { refused: string[] } = JSON.parse(maskedGroupingSignature); const draftOnly: string[] = JSON.parse(draftOnlyGroupingKey); + const byPackage: string[] = JSON.parse(packageWithheldGroupingKey); return usableGroupingFields(groupingFieldsRaw) - .filter((gf) => !refused.includes(gf.field) && !draftOnly.includes(gf.field)); - }, [groupingFieldsRaw, maskedGroupingSignature, draftOnlyGroupingKey]); + .filter((gf) => !refused.includes(gf.field) && !draftOnly.includes(gf.field) && !byPackage.includes(gf.field)); + }, [groupingFieldsRaw, maskedGroupingSignature, draftOnlyGroupingKey, packageWithheldGroupingKey]); const groupingRefusesNothing = maskedGroupingSignature === NO_GROUPING_REFUSAL - && draftOnlyGroupingFields.length === 0; + && draftOnlyGroupingFields.length === 0 + && packageWithheldGroupingFields.length === 0; useEffect(() => { const { warned: masked }: { warned: string[] } = JSON.parse(maskedGroupingSignature); if (masked.length === 0) return; @@ -158,8 +180,9 @@ export function useObjectGridGroupingDecisions({ () => [ ...(JSON.parse(maskedGroupingSignature) as { warned: string[] }).warned, ...(JSON.parse(draftOnlyGroupingKey) as string[]), + ...(JSON.parse(packageWithheldGroupingKey) as string[]), ], - [maskedGroupingSignature, draftOnlyGroupingKey], + [maskedGroupingSignature, draftOnlyGroupingKey, packageWithheldGroupingKey], ); // A grouping field this principal may not READ is not a key the server may // group by: a header row carries every key's raw value, so grouping by it @@ -252,6 +275,7 @@ export function useObjectGridGroupingDecisions({ return { unmaskedGroupingFields, draftOnlyGroupingFields, + packageWithheldGroupingFields, groupingRefusesNothing, groupingKeyReadable, serverGroupedFetch, diff --git a/ui/packages/plugin-grid/src/objectGridRowLoad.ts b/ui/packages/plugin-grid/src/objectGridRowLoad.ts index 09a4be98b87..1b0a14ef6d5 100644 --- a/ui/packages/plugin-grid/src/objectGridRowLoad.ts +++ b/ui/packages/plugin-grid/src/objectGridRowLoad.ts @@ -12,7 +12,7 @@ import React, { useEffect } from 'react'; import type { ObjectGridSchema, DataSource, DependsOnInput, ViewData } from '@object-ui/types'; import { useDataInvalidation } from '@object-ui/react'; import { recordCurrencyReadField } from '@object-ui/i18n'; -import { resolveDependsOnFields, declaredNameField, buildExpandFields, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, isProjectableField, convertSortToQueryParams, normalizeSortEntries, type QuerySortEntry } from '@object-ui/core'; +import { resolveDependsOnFields, declaredNameField, buildExpandFields, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, isProjectableField, convertSortToQueryParams, normalizeSortEntries, readWithheldFieldNames, refersToWithheldField, type QuerySortEntry } from '@object-ui/core'; import type { usePermissions } from '@object-ui/permissions'; import { findParamsSignature } from './objectGridQuery'; import { normalizeColumns } from './objectGridColumns'; @@ -181,6 +181,10 @@ export function useObjectGridRowLoad({ throw new Error('DataSource required'); } + // objectstack#34901 — read before the definition is handed on, so the + // grouping decisions find the names beside its field map on the + // render it causes (`withheldFieldNamesOfFieldMap`). + const withheld = readWithheldFieldNames(resolvedSchema); if (!cancelled) { setObjectSchema(resolvedSchema); } @@ -206,9 +210,14 @@ export function useObjectGridRowLoad({ // objectstack#34898 — the names the definition marks draft-only (see // `draftOnlyFieldNames`); empty outside the draft preview. const draftOnly = draftOnlyFieldNames(resolvedSchema); - const withoutDraftOnly = (list: any[]): any[] => (draftOnly.size === 0 + // objectstack#34901 — `withheld` (read above) are the names a disabled + // package withholds from the served object: the door refuses each on + // every axis, so no `$select`, `$orderby` or `$searchFields` below + // names one. + const withoutDraftOnly = (list: any[]): any[] => (draftOnly.size === 0 && withheld.size === 0 ? list - : list.filter((f: any) => !refersToDraftOnly(columnIdentity(f), draftOnly))); + : list.filter((f: any) => !refersToDraftOnly(columnIdentity(f), draftOnly) + && !refersToWithheldField(columnIdentity(f), withheld))); const getSelectFields = () => { // Always include 'id' so row click / navigation handlers can resolve // the record key — without it `record.id` is undefined and the @@ -608,7 +617,12 @@ export function useObjectGridRowLoad({ // interpolated unconditionally, so `[{ field: 'name' }]` went out // as `'name undefined'` and `[]` as `''`. The join, and only the // join, stays this block's (see {@link toOrderByClause}). - const orderBy = toOrderByClause(schemaSort as unknown as QuerySortEntry[]); + // A header click can only name a drawn column, and a withheld + // one is not drawn (`useObjectGridGenerateColumns`); a declared + // entry on one is left out here. + const orderBy = toOrderByClause((withheld.size > 0 + ? schemaSort.filter((s) => !refersToWithheldField((s as { field?: unknown } | null)?.field, withheld)) + : schemaSort) as unknown as QuerySortEntry[]); if (orderBy !== undefined) { params.$orderby = orderBy; } @@ -631,8 +645,11 @@ export function useObjectGridRowLoad({ const trimmedSearch = querySearchTerm.trim(); if (trimmedSearch) { params.$search = trimmedSearch; - if (schema.searchableFields && schema.searchableFields.length > 0) { - params.$searchFields = schema.searchableFields; + const searchFields = withheld.size > 0 && schema.searchableFields + ? schema.searchableFields.filter((f) => !refersToWithheldField(f, withheld)) + : schema.searchableFields; + if (searchFields && searchFields.length > 0) { + params.$searchFields = searchFields; } } diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 81e51912ceb..73271f53f39 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -51,7 +51,7 @@ import { useDensityMode, resolveInlineAriaProps } from '@object-ui/react'; import type { DataTableSchema, DependsOnInput, ListViewSchema, ObjectMapConfig } from '@object-ui/types'; import { detectStatusField, isSystemManagedField } from '@object-ui/types'; import { usePullToRefresh } from '@object-ui/mobile'; -import { type ListViewVisualization, resolveConditionalFormatting, buildExpandFields, buildExportFileName, resolveAffordance, type SchemaLike, partitionRowsByPredicate, normalizeListViewSchema, isListViewVisualization, rowHeightToDensityMode, mergeFilterNodes, toFilterNodeSafely, FilterOperatorError, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, PLATFORM_RECORD_COLUMNS, EXPANDABLE_FIELD_TYPES, UNMATERIALIZED_FIELD_TYPES, readObjectSortability, isPlatformSortableField, leadWithNameField, filterPlatformSortableSort, applyNonGridRowCeiling, type NonGridCeilingResult, resolveNameField, declaredNameField, resolveDependsOnFields, GANTT_CONFIG_SPELLING, kanbanDeclaredLanes, csvBlob } from '@object-ui/core'; +import { type ListViewVisualization, resolveConditionalFormatting, buildExpandFields, buildExportFileName, resolveAffordance, type SchemaLike, partitionRowsByPredicate, normalizeListViewSchema, isListViewVisualization, rowHeightToDensityMode, mergeFilterNodes, toFilterNodeSafely, FilterOperatorError, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, PLATFORM_RECORD_COLUMNS, EXPANDABLE_FIELD_TYPES, UNMATERIALIZED_FIELD_TYPES, readObjectSortability, isPlatformSortableField, leadWithNameField, filterPlatformSortableSort, applyNonGridRowCeiling, type NonGridCeilingResult, resolveNameField, declaredNameField, resolveDependsOnFields, GANTT_CONFIG_SPELLING, kanbanDeclaredLanes, csvBlob, readWithheldFieldNames, refersToWithheldField } from '@object-ui/core'; import { useObjectLabel, useSafeFieldLabel, createSafeTranslation, useDisplayLocale, pickLocalized, recordCurrencyField, recordCurrencyReadField } from '@object-ui/i18n'; // Two resolvers, two vocabularies — the repo spells the distinction into the // NAMES (objectui#4167). `resolveInlineI18nLabel` is the spec's own @@ -1480,6 +1480,8 @@ export const LIST_DEFAULT_TRANSLATIONS: Record = { 'list.recordOpenDeclaredPage': 'This object is declared to open as a full page', // The draft preview's note on a sort or filter it left out (objectstack#34807). 'list.draftOnlyQueryDropped': 'Not filtered or sorted by {{fields}}: it exists only in the draft until you publish.', + // The note on view fields a disabled package withholds (objectstack#34901). + 'list.withheldFieldsLeftOut': 'Not shown, filtered, sorted or grouped by {{fields}}: the package that adds it is disabled. It comes back when the package is enabled.', // Heading of the record-detail overlay this view opens when a child view's // row is clicked (objectui#3426). Borrowed from the `detail.*` namespace // rather than minted as `list.recordDetail`: `NavigationOverlay` already @@ -2244,6 +2246,24 @@ export const ListView = React.forwardRef(({ */ const draftOnlyFields = React.useMemo(() => readDraftOnlyFieldNames(objectDef), [objectDef]); + /** + * objectstack#34901 — the names a disabled package withholds from this + * object (`_withheldFields` on the served read, see `readWithheldFieldNames` + * in `@object-ui/core`). The data door refuses each of them on every axis, + * exactly as it refuses a draft-only name, so `queryDropFields` is the one + * set every request leg below leaves out. Unlike a draft-only field the + * definition does not declare a withheld one, so its column is hidden by + * derivation (`effectiveFields`), never written to the view or to the + * user's list preferences: re-enabling the package brings it back with no + * write. The persist boundary keeps it (`emitSortChange`). + */ + const withheldFields = React.useMemo(() => readWithheldFieldNames(objectDef), [objectDef]); + const queryDropFields = React.useMemo>(() => { + if (withheldFields.size === 0) return draftOnlyFields; + if (draftOnlyFields.size === 0) return withheldFields; + return new Set([...draftOnlyFields, ...withheldFields]); + }, [draftOnlyFields, withheldFields]); + /** * objectstack#34807 — the view's `searchableFields` as every query this list * makes or hands down sends them: without a draft-only field, which the data @@ -2254,10 +2274,10 @@ export const ListView = React.forwardRef(({ */ const searchFieldsSent = React.useMemo(() => { const declared = schema.searchableFields; - if (!declared || draftOnlyFields.size === 0) return declared; - const kept = declared.filter((f) => !refersToDraftOnlyField(f, draftOnlyFields)); + if (!declared || queryDropFields.size === 0) return declared; + const kept = declared.filter((f) => !refersToDraftOnlyField(f, queryDropFields)); return kept.length === declared.length ? declared : kept; - }, [schema.searchableFields, draftOnlyFields]); + }, [schema.searchableFields, queryDropFields]); /** * objectui#12966 — the object's `search` resolves to no field, so the server @@ -2387,10 +2407,11 @@ export const ListView = React.forwardRef(({ // objectstack#34807 — a draft-only field is not sortable by the data door // whatever the projection served (the published one does not name it, and // an older deployment or a never-published object serves none at all). - return draftOnlyFields.size > 0 - ? sortable.filter((item) => !refersToDraftOnlyField(item.field, draftOnlyFields)) + // objectstack#34901 — nor is a field a disabled package withholds. + return queryDropFields.size > 0 + ? sortable.filter((item) => !refersToDraftOnlyField(item.field, queryDropFields)) : sortable; - }, [currentSort, platformSortability, draftOnlyFields]); + }, [currentSort, platformSortability, queryDropFields]); /** * The view's DECLARED sort, for the "reset to default" affordance @@ -2641,19 +2662,29 @@ export const ListView = React.forwardRef(({ .map((level) => level.field) .filter((field) => !declaredGroupingFieldNames.has(field) && isVirtualSearchField(objectDef?.fields?.[field] as SearchFieldMeta | undefined)); + // objectstack#34901 — a level on a field a disabled package withholds is + // left out of the query as well, whoever added it, and kept in the chosen + // grouping: no button writes it away, and it groups again once the package + // is enabled. Named by `list.withheldFieldsLeftOut`. + const withheldGroupingFields = (chosenGroupingConfig?.fields ?? []) + .map((level) => level.field) + .filter((field) => refersToWithheldField(field, withheldFields)); + const groupingLeftOut = withheldGroupingFields.length > 0 + ? [...unstoredGroupingFields, ...withheldGroupingFields] + : unstoredGroupingFields; const reducedGroupingRef = React.useRef<{ chosen: typeof chosenGroupingConfig; key: string; value: typeof chosenGroupingConfig; } | null>(null); let groupingConfig = chosenGroupingConfig; - if (chosenGroupingConfig && unstoredGroupingFields.length > 0) { - const key = JSON.stringify(unstoredGroupingFields); + if (chosenGroupingConfig && groupingLeftOut.length > 0) { + const key = JSON.stringify(groupingLeftOut); const cached = reducedGroupingRef.current; if (cached && cached.chosen === chosenGroupingConfig && cached.key === key) { groupingConfig = cached.value; } else { - const kept = chosenGroupingConfig.fields.filter((level) => !unstoredGroupingFields.includes(level.field)); + const kept = chosenGroupingConfig.fields.filter((level) => !groupingLeftOut.includes(level.field)); groupingConfig = kept.length > 0 ? { ...chosenGroupingConfig, fields: kept } : undefined; reducedGroupingRef.current = { chosen: chosenGroupingConfig, key, value: groupingConfig }; } @@ -2817,6 +2848,36 @@ export const ListView = React.forwardRef(({ return dropped.size > 0 ? Array.from(dropped) : NO_DRAFT_ONLY_QUERY_DROPS; }, [draftOnlyFields, currentSort, authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions]); + /** + * objectstack#34901 — the withheld fields (see `withheldFields`) this list + * names anywhere a request would carry them: a column, the sort, a grouping + * level, `searchableFields` or the filter. Each is left out of every request + * and its column is not drawn; this list is what the one line above the + * rows names (`list.withheldFieldsLeftOut`). Empty while nothing is withheld. + */ + const withheldViewRefs = React.useMemo(() => { + if (withheldFields.size === 0) return NO_DRAFT_ONLY_QUERY_DROPS; + const named = new Set(); + const note = (ref: unknown) => { + if (refersToWithheldField(ref, withheldFields)) named.add(ref.split('.')[0]); + }; + if (Array.isArray(schema.columns)) for (const column of schema.columns as unknown[]) note(columnIdentity(column as any)); + for (const item of currentSort) note(item.field); + for (const level of chosenGroupingConfig?.fields ?? []) note(level.field); + for (const field of schema.searchableFields ?? []) note(field); + try { + omitDraftOnlyFilterFields( + mergeEffectiveFilterSources(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions), + withheldFields, + named, + ); + } catch (error) { + // A malformed filter is the fetch's own load error to raise, not this line's. + if (!(error instanceof FilterOperatorError)) throw error; + } + return named.size > 0 ? Array.from(named) : NO_DRAFT_ONLY_QUERY_DROPS; + }, [withheldFields, schema.columns, currentSort, chosenGroupingConfig, schema.searchableFields, authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions]); + // User filters render ONLY when explicitly configured (ADR-0047 §data // mode): saved list views already act as the preset switcher, so an // unconfigured view keeps a clean toolbar instead of growing auto-derived @@ -3795,7 +3856,7 @@ export const ListView = React.forwardRef(({ try { // Construct filter — shared with the export path so the file a user // downloads is built from the same three sources as the rows on screen. - const finalFilter = buildEffectiveFilter(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, draftOnlyFields); + const finalFilter = buildEffectiveFilter(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, queryDropFields); // Convert sort to query format // Use array format to ensure order is preserved (Object keys are not guaranteed ordered) @@ -3838,8 +3899,9 @@ export const ListView = React.forwardRef(({ // objectstack#34807 — a column on a draft-only field is drawn (empty, // under its draft label) but never asked for: the data door knows // only the published object and refuses the whole query for it. - const servedCols = draftOnlyFields.size > 0 - ? rawCols.filter(c => !refersToDraftOnlyField(c, draftOnlyFields)) + // objectstack#34901 — nor is one a disabled package withholds. + const servedCols = queryDropFields.size > 0 + ? rawCols.filter(c => !refersToDraftOnlyField(c, queryDropFields)) : rawCols; const cols = (perms?.isLoaded && schema.objectName) ? servedCols.filter(c => perms.checkField(schema.objectName!, c, 'read')) @@ -4464,7 +4526,7 @@ export const ListView = React.forwardRef(({ // silently un-suppresses nothing, because the finding it was suppressing // simply moves elsewhere. Add prose ABOVE this point, never below it. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [schema.objectName, schema.data, dataSource, authoredFilter, effectivePageSize, serverSort, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, refreshKey, searchTerm, searchFieldsSent, schema.columns, schema.kanban, schema.calendar, schema.gallery, schema.timeline, schema.gantt, schema.map, objectDef?.fields, objectDefLoaded, schema.refreshTrigger, perms, fetchSkip, groupingConfig, predicateProjectionKey, invalidationNonce, groupingNeedsHeaderQuery, calendarWindowKey, rowsCarryConcurrencyToken, draftOnlyFields]); // Re-fetch on filter/sort/search/refreshTrigger/perms/window change; `rowsCarryConcurrencyToken` (objectui#12292) re-reads the rows with their token when inline edit turns on + }, [schema.objectName, schema.data, dataSource, authoredFilter, effectivePageSize, serverSort, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, refreshKey, searchTerm, searchFieldsSent, schema.columns, schema.kanban, schema.calendar, schema.gallery, schema.timeline, schema.gantt, schema.map, objectDef?.fields, objectDefLoaded, schema.refreshTrigger, perms, fetchSkip, groupingConfig, predicateProjectionKey, invalidationNonce, groupingNeedsHeaderQuery, calendarWindowKey, rowsCarryConcurrencyToken, queryDropFields]); // Re-fetch on filter/sort/search/refreshTrigger/perms/window change; `rowsCarryConcurrencyToken` (objectui#12292) re-reads the rows with their token when inline edit turns on // Any change to the result-defining inputs (object, filters, sort, search, // grouping, page size) invalidates the current page number — snap back to @@ -4757,6 +4819,13 @@ export const ListView = React.forwardRef(({ }); } + // objectstack#34901 — a column on a field a disabled package withholds is + // not drawn. Derived here on every render, never written to `hiddenFields` + // or the view, so it is drawn again once the package is enabled. + if (withheldFields.size > 0) { + fields = fields.filter((f: any) => !refersToWithheldField(columnIdentity(f), withheldFields)); + } + // Remove hidden fields if (hiddenFields.size > 0) { fields = fields.filter((f: any) => { @@ -4776,7 +4845,7 @@ export const ListView = React.forwardRef(({ } return fields; - }, [schema.columns, schema.objectName, hiddenFields, schema.fieldOrder, perms]); + }, [schema.columns, schema.objectName, hiddenFields, schema.fieldOrder, perms, withheldFields]); /** * Did the AUTHOR declare a column projection at all? (objectui#6598) @@ -4890,7 +4959,7 @@ export const ListView = React.forwardRef(({ let selfQueryFilter: unknown = authoredFilter; if (currentView === 'gantt' || currentView === 'tree' || currentView === 'chart' || gridOwnsGroupedFetch || kanbanLanesPaged) { try { - const value = buildEffectiveFilter(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, draftOnlyFields); + const value = buildEffectiveFilter(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, queryDropFields); const key = JSON.stringify(value ?? null); const cached = selfQueryFilterRef.current; if (cached && cached.key === key) { @@ -5886,8 +5955,8 @@ export const ListView = React.forwardRef(({ * emitted unchanged. * * Nor does any REQUEST carry it (objectstack#30024): the fetch, the export - * and the child views read `serverSort`, which drops it through the same - * `filterPlatformSortableSort` call. This boundary used to leave it in "the + * and the child views read `serverSort`, which drops it through the same platform verdict, + * `filterPlatformSortableSort`. This boundary used to leave it in "the * order this list asks the server for", and the server answers such a sort * `400 INVALID_SORT`, so a stored view naming one failed its first fetch. * @@ -5898,15 +5967,22 @@ export const ListView = React.forwardRef(({ * * Only under a served projection: with no signal there is no verdict to * filter by, and the pre-objectstack#10235 behaviour stands unchanged. + * + * objectstack#34901 — an entry on a field a disabled package withholds is + * KEPT. The projection has no entry for it only while the package is off, + * which is no verdict on the sort: dropping it here would lose it from the + * user's stored sort for good. No request carries it (`serverSort`), and it + * orders the rows again once the package is enabled. */ const emitSortChange = React.useCallback((next: SortItem[]) => { if (!onSortChange) return; onSortChange( platformSortability - ? filterPlatformSortableSort(next, platformSortability) + ? next.filter((item) => refersToWithheldField(item?.field, withheldFields) + || isPlatformSortableField(platformSortability, item?.field)) : next, ); - }, [onSortChange, platformSortability]); + }, [onSortChange, platformSortability, withheldFields]); /** * A column-header sort from the child grid (#3106). @@ -6038,7 +6114,7 @@ export const ListView = React.forwardRef(({ const fields = (effectiveFields .map((f: any) => columnIdentity(f)) .filter(Boolean) as string[]) - .filter((f) => !refersToDraftOnlyField(f, draftOnlyFields)); + .filter((f) => !refersToDraftOnlyField(f, queryDropFields)); // The rows on screen were asked for with `serverSort`, so the file is too: // a refused entry would fail the export the way it failed the list. @@ -6059,7 +6135,7 @@ export const ListView = React.forwardRef(({ // file, no message. Here it lands in the catch below, which names it // in the toolbar the way the data fetch's own `try` names it in the // load-error panel — and nothing is exported unfiltered. - const finalFilter = buildEffectiveFilter(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, draftOnlyFields); + const finalFilter = buildEffectiveFilter(authoredFilter, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, queryDropFields); const blob = await dataSource!.exportDownload!(schema.objectName!, { format: format as 'csv' | 'xlsx' | 'json', fields: fields.length ? fields : undefined, @@ -6153,7 +6229,7 @@ export const ListView = React.forwardRef(({ setShowExport(false); // `searchTerm` / `searchableFields` belong here: the export now narrows by // the active search, so a stale closure would export the wrong row set. - }, [data, effectiveFields, resolvedExportOptions, schema.objectName, authoredFilter, searchFieldsSent, exportPermitted, dataSource, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, serverSort, searchTerm, objectDef, resolveObjectLabel, t, draftOnlyFields]); + }, [data, effectiveFields, resolvedExportOptions, schema.objectName, authoredFilter, searchFieldsSent, exportPermitted, dataSource, appliedFilters, appliedUserFilterConditions, appliedQueueSittingConditions, serverSort, searchTerm, objectDef, resolveObjectLabel, t, queryDropFields]); // All available fields for hide/show (with i18n) // @@ -7608,6 +7684,22 @@ export const ListView = React.forwardRef(({ )} + {/* objectstack#34901 — the fields a disabled package withholds that this + view names (`withheldViewRefs`): each is left out of every request + and its column is not drawn; this line says why. */} + {withheldViewRefs.length > 0 && ( +
+
+ )} + {/* View Content */}
{/* Re-fetch indicator: thin top progress bar shown when refreshing From bf6cbc8d49799b1fe9fb18e742a37a1e97bae754 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 19:46:02 +0000 Subject: [PATCH 02/15] test(objectql,metadata-protocol,console): pin the withheld-field marker, the view save door and the console legs (#34901) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .../34901-disabled-package-view-column.md | 20 ++ .../utils/__tests__/withheld-fields.test.ts | 65 ++++++ .../__tests__/withheldFields-34901.test.tsx | 186 ++++++++++++++++ .../ListView.withheldFields-34901.test.tsx | 198 ++++++++++++++++++ 4 files changed, 469 insertions(+) create mode 100644 .changeset/34901-disabled-package-view-column.md create mode 100644 ui/packages/core/src/utils/__tests__/withheld-fields.test.ts create mode 100644 ui/packages/plugin-grid/src/__tests__/withheldFields-34901.test.tsx create mode 100644 ui/packages/plugin-list/src/__tests__/ListView.withheldFields-34901.test.tsx diff --git a/.changeset/34901-disabled-package-view-column.md b/.changeset/34901-disabled-package-view-column.md new file mode 100644 index 00000000000..3d8c897a72e --- /dev/null +++ b/.changeset/34901-disabled-package-view-column.md @@ -0,0 +1,20 @@ +--- +'@objectstack/objectql': patch +'@objectstack/metadata-protocol': patch +'@objectstack/spec': patch +'@object-ui/core': patch +'@object-ui/plugin-list': patch +'@object-ui/plugin-grid': patch +'@object-ui/i18n': patch +--- + +fix(objectql, metadata-protocol, console): a list view column on a field a disabled package adds no longer fails the whole list + +Clause-②: yes (widening: the view save door accepts withheld names; one spec read-decoration member; two locale keys) +Metadata-protocol: none + +A package can add fields to another package's object. While that package is disabled, the platform leaves those fields out of the served object, and the data door refuses every request that names one (`400 INVALID_FIELD`, or `400 INVALID_SORT` for a sort). The owner's views still named the field, so a view with such a column, sort, filter, grouping level or searchable field failed for everyone. Saving the view (a rename, a pin, a Studio edit) was refused too (`422`, `list-view-field-unknown` / `sort-field-unknown`). + +- **The served object read names what is withheld.** `GET /api/v1/meta/object/:name` and the object list read carry `_withheldFields: { [field]: { packageId } }` when a disabled package withholds a field from the object. It is a read decoration (`METADATA_READ_DECORATIONS`), so the save door strips it, and the execution face and the layered editor read do not carry it. The registry gains `getWithheldExtensionFields(name)`. +- **The view save door judges a view against the stored object.** A `view` write is judged against the object with every disabled package's extension folded in (the new fold option `includeDisabledExtensions`). A withheld field is a real stored field, so the view saves and keeps its column and sort. A misspelled field is still refused. Other writes are still judged against the served object, so a page or flow that names a withheld field is still refused while the package is off. +- **The console leaves withheld names out.** The list view and the grid leave a withheld field out of `$select`, `$filter`, `$orderby`, `$searchFields` and `groupBy`, and do not draw its column. A line above the rows names it (`list.withheldFieldsLeftOut`). Nothing is written to the view or to the user's list preferences, and a sort the user saves keeps the withheld entry. Once the package is enabled, the column, the sort and the grouping come back without any write. diff --git a/ui/packages/core/src/utils/__tests__/withheld-fields.test.ts b/ui/packages/core/src/utils/__tests__/withheld-fields.test.ts new file mode 100644 index 00000000000..7116eeab2f5 --- /dev/null +++ b/ui/packages/core/src/utils/__tests__/withheld-fields.test.ts @@ -0,0 +1,65 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#34901 — the reader of `_withheldFields`, the served object's + * note of the fields a disabled package withholds from it. + */ +import { describe, it, expect } from 'vitest'; +import { + NO_WITHHELD_FIELDS, + readWithheldFieldNames, + refersToWithheldField, + withheldFieldNamesOfFieldMap, +} from '../withheld-fields'; + +const marked = () => ({ + name: 'crm_expense', + fields: { name: { type: 'text' } }, + _withheldFields: { crm_project: { packageId: 'com.example.projects' } }, +}); + +describe('readWithheldFieldNames (objectstack#34901)', () => { + it('reads the marked names', () => { + expect([...readWithheldFieldNames(marked())]).toEqual(['crm_project']); + }); + + it('answers the one shared empty set for a definition without the marker, and for non-objects', () => { + expect(readWithheldFieldNames({ name: 'x', fields: {} })).toBe(NO_WITHHELD_FIELDS); + expect(readWithheldFieldNames(null)).toBe(NO_WITHHELD_FIELDS); + expect(readWithheldFieldNames({ name: 'x', _withheldFields: ['crm_project'] })).toBe(NO_WITHHELD_FIELDS); + }); + + it('never withholds a name the definition declares, in either field-map shape', () => { + const declaredMap = { ...marked(), fields: { crm_project: { type: 'text' } } }; + expect(readWithheldFieldNames(declaredMap)).toBe(NO_WITHHELD_FIELDS); + const declaredList = { ...marked(), fields: [{ name: 'crm_project', type: 'text' }] }; + expect(readWithheldFieldNames(declaredList)).toBe(NO_WITHHELD_FIELDS); + }); + + it('is answered again beside the field map it was read with', () => { + const def = marked(); + expect(withheldFieldNamesOfFieldMap(def.fields)).toBe(NO_WITHHELD_FIELDS); + readWithheldFieldNames(def); + expect([...withheldFieldNamesOfFieldMap(def.fields)]).toEqual(['crm_project']); + expect(withheldFieldNamesOfFieldMap({ name: { type: 'text' } }), 'another map knows nothing of it').toBe(NO_WITHHELD_FIELDS); + }); +}); + +describe('refersToWithheldField (objectstack#34901)', () => { + const withheld = new Set(['crm_project']); + it('matches the field and a dotted path that starts at it', () => { + expect(refersToWithheldField('crm_project', withheld)).toBe(true); + expect(refersToWithheldField('crm_project.name', withheld)).toBe(true); + }); + it('does not match another field, a non-string, or anything against the empty set', () => { + expect(refersToWithheldField('crm_projects', withheld)).toBe(false); + expect(refersToWithheldField(undefined, withheld)).toBe(false); + expect(refersToWithheldField('crm_project', NO_WITHHELD_FIELDS)).toBe(false); + }); +}); diff --git a/ui/packages/plugin-grid/src/__tests__/withheldFields-34901.test.tsx b/ui/packages/plugin-grid/src/__tests__/withheldFields-34901.test.tsx new file mode 100644 index 00000000000..689a8a33431 --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/withheldFields-34901.test.tsx @@ -0,0 +1,186 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#34901 — a grid never asks the data door for a field a DISABLED + * package contributes. + * + * While the extending package is off the served definition leaves the field + * out and names it under `_withheldFields`, and the door refuses it on every + * axis. The double answers as the door does: a `$select`, `$orderby` or + * `groupBy` name the served object does not declare is refused, naming it. + * Enabling the package serves the field again and drops the marker. + * + * CONTROL: each shape with the package ON asks for the field exactly as + * before, so the pins read the marker, not the field's name. + */ +import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest'; +import { render, cleanup, screen } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +import { ObjectGrid } from '../ObjectGrid'; +import { ActionProvider } from '@object-ui/react'; +import { registerAllFields } from '@object-ui/fields'; +import type { DataSource, ObjectGridSchema } from '@object-ui/types'; + +beforeAll(() => { + registerAllFields(); +}); + +afterEach(() => cleanup()); + +const OBJECT = 'crm_expense'; +const WITHHELD = 'crm_project'; + +const BASE_FIELDS: Record> = { + id: { type: 'text', label: 'Id' }, + name: { type: 'text', label: 'Name' }, + category: { type: 'text', label: 'Category' }, +}; +const PROJECT = { type: 'text', label: 'Project' }; + +const ROWS: Array> = [ + { id: 'e1', name: 'Taxi', category: 'travel', crm_project: 'apollo' }, + { id: 'e2', name: 'Hotel', category: 'travel', crm_project: 'gemini' }, + { id: 'e3', name: 'Laptop', category: 'hardware', crm_project: 'apollo' }, +]; + +/** The `FilterCondition` subset the compiled group queries use. */ +function matches(row: Record, cond: unknown): boolean { + if (cond === undefined || cond === null) return true; + return Object.entries(cond as Record).every(([key, value]) => { + if (key === '$and') return (value as unknown[]).every((c) => matches(row, c)); + if (value && typeof value === 'object' && !Array.isArray(value)) { + const op = value as Record; + if ('$eq' in op) return row[key] === op.$eq; + if ('$null' in op) return op.$null ? row[key] == null : row[key] != null; + throw new Error(`double: unsupported operator ${JSON.stringify(op)}`); + } + return row[key] === value; + }); +} + +/** The door and the served definition over one state: `packageOff` withholds `crm_project`. */ +function makeDataSource(state: { packageOff: boolean }) { + const servedFields = () => (state.packageOff ? BASE_FIELDS : { ...BASE_FIELDS, [WITHHELD]: PROJECT }); + const refuse = (name: unknown) => { + throw new Error(`INVALID_FIELD: Unknown field '${String(name)}' on object '${OBJECT}'`); + }; + const orderByNames = (orderBy: unknown): string[] => (typeof orderBy === 'string' + ? orderBy.split(',').map((part) => part.trim().split(/\s+/)[0]) + : Array.isArray(orderBy) ? orderBy.map((s: any) => s?.field) : []); + const ds = { + queryGroupHeaders: vi.fn(async (_object: string, query: { where?: unknown; groupBy?: string[] }) => { + const groupBy = query.groupBy ?? []; + const unknown = groupBy.find((f) => !(f in servedFields())); + if (unknown !== undefined) refuse(unknown); + const buckets = new Map(); + for (const row of ROWS.filter((r) => matches(r, query.where))) { + const key = JSON.stringify(groupBy.map((f) => row[f] ?? null)); + buckets.set(key, (buckets.get(key) ?? 0) + 1); + } + return [...buckets.entries()].map(([key, count]) => { + const values = JSON.parse(key) as unknown[]; + return { ...Object.fromEntries(groupBy.map((f, i) => [f, values[i]])), count }; + }); + }), + find: vi.fn(async (_object: string, params: Record) => { + const select = (params.$select as unknown[] | undefined) ?? []; + const unknownSelect = select.find((entry) => typeof entry !== 'string' || !(entry in servedFields())); + if (unknownSelect !== undefined) refuse(unknownSelect); + const unknownOrder = orderByNames(params.$orderby).find((f) => !(f in servedFields())); + if (unknownOrder !== undefined) refuse(unknownOrder); + const matching = ROWS.filter((r) => matches(r, params.$filter)); + const skip = (params.$skip as number | undefined) ?? 0; + const top = (params.$top as number | undefined) ?? matching.length; + const project = (row: Record) => (select.length === 0 + ? row + : Object.fromEntries(select.map((f) => [f as string, row[f as string]]))); + return { data: matching.slice(skip, skip + top).map(project), total: matching.length }; + }), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn(async () => (state.packageOff + ? { name: OBJECT, fields: BASE_FIELDS, _withheldFields: { [WITHHELD]: { packageId: 'com.example.projects' } } } + : { name: OBJECT, fields: { ...BASE_FIELDS, [WITHHELD]: PROJECT } })), + }; + return ds; +} +type Ds = ReturnType; + +const gridNode = (ds: Ds, schemaExtra: Record) => ( + + + +); + +const SORTED = { sort: [{ field: WITHHELD, order: 'asc' }, { field: 'name', order: 'desc' }] }; +const BY_PROJECT_THEN_CATEGORY = { grouping: { fields: [{ field: WITHHELD, order: 'asc' }, { field: 'category', order: 'asc' }] } }; + +const everyRequest = (ds: Ds) => JSON.stringify([...ds.find.mock.calls, ...ds.queryGroupHeaders.mock.calls]); +const groupBys = (ds: Ds) => ds.queryGroupHeaders.mock.calls.map(([, q]) => (q as { groupBy?: string[] }).groupBy); +const groupRowErrors = () => [...document.querySelectorAll('[data-testid^="group-rows-error-"]')]; + +describe('a grid over a field a disabled package withholds (objectstack#34901)', () => { + it('flat: no `$select` or `$orderby` names it, the column is not drawn, and the rows load', async () => { + const ds = makeDataSource({ packageOff: true }); + render(gridNode(ds, SORTED)); + + await vi.waitFor(() => expect(screen.getByText('Laptop')).toBeInTheDocument()); + expect(everyRequest(ds)).not.toContain(WITHHELD); + const params = ds.find.mock.calls[ds.find.mock.calls.length - 1][1]; + expect(params.$select).toEqual(['id', 'name']); + expect(params.$orderby).toBe('name desc'); + expect(screen.queryByText('Project')).not.toBeInTheDocument(); + expect(screen.queryByText('Error loading grid')).not.toBeInTheDocument(); + }); + + it('grouped: never sent as `groupBy`; groups by the key left, and no group row page selects it', async () => { + const ds = makeDataSource({ packageOff: true }); + render(gridNode(ds, { columns: ['name'], ...BY_PROJECT_THEN_CATEGORY })); + + await vi.waitFor(() => expect(screen.getByText('Laptop')).toBeInTheDocument()); + expect(groupBys(ds).length).toBeGreaterThan(0); + for (const groupBy of groupBys(ds)) expect(groupBy).toEqual(['category']); + expect(everyRequest(ds)).not.toContain(WITHHELD); + expect(groupRowErrors()).toHaveLength(0); + expect(screen.queryByText('Error loading grid')).not.toBeInTheDocument(); + }); + + it('CONTROL — with the package on, the column, the sort and the grouping key are all asked for', async () => { + const ds = makeDataSource({ packageOff: false }); + render(gridNode(ds, { ...SORTED, ...BY_PROJECT_THEN_CATEGORY })); + + await vi.waitFor(() => expect(screen.getByText('Laptop')).toBeInTheDocument()); + expect(groupBys(ds)).toContainEqual([WITHHELD, 'category']); + const lastRowPage = ds.find.mock.calls[ds.find.mock.calls.length - 1][1]; + expect(lastRowPage.$select).toContain(WITHHELD); + expect(lastRowPage.$orderby).toContain(WITHHELD); + expect(screen.getAllByText('Project').length).toBeGreaterThan(0); + }); + + it('enabling the package brings the column and the grouping back in place, with no reload', async () => { + const state = { packageOff: true }; + const ds = makeDataSource(state); + const { rerender } = render(gridNode(ds, { ...BY_PROJECT_THEN_CATEGORY })); + await vi.waitFor(() => expect(screen.getByText('Laptop')).toBeInTheDocument()); + expect(everyRequest(ds)).not.toContain(WITHHELD); + + state.packageOff = false; + rerender(gridNode({ ...ds } as Ds, { ...BY_PROJECT_THEN_CATEGORY })); + await vi.waitFor(() => expect(groupBys(ds)).toContainEqual([WITHHELD, 'category'])); + await vi.waitFor(() => expect(screen.getAllByText('Project').length).toBeGreaterThan(0)); + expect(groupRowErrors()).toHaveLength(0); + }); +}); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.withheldFields-34901.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.withheldFields-34901.test.tsx new file mode 100644 index 00000000000..bf9079afc1c --- /dev/null +++ b/ui/packages/plugin-list/src/__tests__/ListView.withheldFields-34901.test.tsx @@ -0,0 +1,198 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#34901 — a view naming a field a DISABLED package contributes. + * + * The served object read leaves the field out and names it under + * `_withheldFields`; the data door refuses it on every axis. The data source + * below answers as the door does: any request naming `crm_project` is refused + * `400 INVALID_FIELD`. The list must: + * + * - name it in no request (`$select`, `$filter`, `$orderby`, `$searchFields`) + * and hand the grid no column, sort, grouping level, filter or searchable + * field on it, while still naming it in one line above the rows; + * - keep it in every sort it persists (the objectstack#30024 boundary), since + * the projection lacks it only while the package is off; + * - draw it again, and ask for it again, once the definition no longer marks + * it, with no write in between. + * + * A stub grid stands in for the renderer, as in + * `ListView.groupedGridOwnsFetch-7189.test.tsx`: what is under test is what the + * list asks for and hands down. + */ +import { describe, it, expect, vi, beforeAll, afterAll, beforeEach, afterEach } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; +import { ComponentRegistry, attachObjectSortability } from '@object-ui/core'; +import { SchemaRendererProvider } from '@object-ui/react'; +import { ListView } from '../ListView'; +import type { ListViewSchema } from '@object-ui/types'; + +const OBJECT = 'crm_expense'; +const WITHHELD = 'crm_project'; +const PACKAGE = 'com.example.projects'; + +let lastGridProps: any = null; + +/** The served definition: the field left out, named under `_withheldFields` while the package is off. */ +function servedDefinition(packageOff: boolean) { + const fields: Record = { + name: { type: 'text', label: 'Name' }, + amount: { type: 'number', label: 'Amount' }, + }; + if (!packageOff) fields[WITHHELD] = { type: 'text', label: 'Project' }; + const def: Record = { name: OBJECT, label: 'Expense', fields }; + if (packageOff) def._withheldFields = { [WITHHELD]: { packageId: PACKAGE } }; + const sortability = { fields: Object.fromEntries(Object.keys(fields).map((f) => [f, { sortable: true }])) }; + return attachObjectSortability(def, sortability); +} + +function makeDataSource(state: { packageOff: boolean }) { + return { + find: vi.fn(async (_object: string, params: unknown) => { + if (state.packageOff && JSON.stringify(params ?? {}).includes(WITHHELD)) { + throw Object.assign(new Error(`Unknown field '${WITHHELD}' on object '${OBJECT}'`), { httpStatus: 400, code: 'INVALID_FIELD' }); + } + return { data: [{ id: 'e1', name: 'Taxi', amount: 12 }], total: 1 }; + }), + queryGroupHeaders: vi.fn(async () => []), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn(async () => servedDefinition(state.packageOff)), + } as any; +} + +const viewSchema = (over: Record = {}): ListViewSchema => ({ + type: 'list-view', + objectName: OBJECT, + viewType: 'grid', + columns: ['name', 'amount', WITHHELD], + sort: [{ field: WITHHELD, order: 'asc' }, { field: 'name', order: 'asc' }], + searchableFields: ['name', WITHHELD], + filter: [[WITHHELD, '=', 'p1'], ['amount', '>', 1]], + ...over, +} as unknown as ListViewSchema); + +let prevObjectGrid: any; +beforeAll(() => { + prevObjectGrid = ComponentRegistry.get('object-grid'); + ComponentRegistry.register('object-grid', (props: any) => { + lastGridProps = props; + return
; + }); +}); +afterAll(() => { + if (prevObjectGrid) ComponentRegistry.register('object-grid', prevObjectGrid); + else ComponentRegistry.unregister('object-grid'); +}); +beforeEach(() => { lastGridProps = null; }); +afterEach(() => { cleanup(); lastGridProps = null; }); + +function renderList(ds: any, schema: ListViewSchema, props: Record = {}) { + return render( + + + , + ); +} + +/** Every argument this list handed the data source, as one string. */ +const everyRequest = (ds: any) => JSON.stringify([...ds.find.mock.calls, ...ds.queryGroupHeaders.mock.calls]); +/** + * What the grid draws and orders by. The query inputs (`filter`, + * `searchableFields`) are handed only to a grid that runs its own grouped + * query (`gridOwnsGroupedFetch`); a flat grid is handed the rows this list + * fetched, so those two are read in the grouped case below. + */ +const gridNames = () => JSON.stringify({ columns: lastGridProps?.schema?.columns, fields: lastGridProps?.schema?.fields, sort: lastGridProps?.schema?.sort, grouping: lastGridProps?.schema?.grouping }); +const gridQueryInputs = () => JSON.stringify({ filter: lastGridProps?.schema?.filter, searchableFields: lastGridProps?.schema?.searchableFields }); + +describe('ListView over a field a disabled package withholds (objectstack#34901)', () => { + it('names it in no request on any axis, hands the grid nothing on it, and says so above the rows', async () => { + const state = { packageOff: true }; + const ds = makeDataSource(state); + renderList(ds, viewSchema(), { initialSearchTerm: 'taxi' }); + await waitFor(() => expect(ds.find).toHaveBeenCalled()); + await screen.findByTestId('list-withheld-fields-notice'); + + expect(everyRequest(ds)).not.toContain(WITHHELD); + const params = ds.find.mock.calls[ds.find.mock.calls.length - 1][1]; + // Positive controls in the same request: each axis still carries the rest. + expect(params.$select).toEqual(expect.arrayContaining(['name', 'amount'])); + expect(JSON.stringify(params.$filter)).toContain('amount'); + expect(JSON.stringify(params.$orderby ?? params.sort ?? params.$sort)).toContain('name'); + expect(params.$search ?? params.search).toBe('taxi'); + expect(JSON.stringify(params)).toContain('"name"'); + + expect(gridNames()).not.toContain(WITHHELD); + expect(screen.getByTestId('list-withheld-fields-notice')).toHaveTextContent(WITHHELD); + expect(screen.queryByText(/INVALID_FIELD|Unknown field/)).not.toBeInTheDocument(); + }); + + it('leaves a withheld grouping level out of the grouped query, and groups by the level left', async () => { + const ds = makeDataSource({ packageOff: true }); + renderList(ds, viewSchema({ + grouping: { fields: [{ field: WITHHELD, order: 'asc', collapsed: false }, { field: 'amount', order: 'asc', collapsed: false }] }, + }), { initialSearchTerm: 'taxi' }); + await waitFor(() => expect(lastGridProps?.schema?.grouping).toBeTruthy()); + await waitFor(() => expect(ds.find).toHaveBeenCalled()); + expect(lastGridProps.schema.grouping.fields.map((f: any) => f.field)).toEqual(['amount']); + expect(gridNames()).not.toContain(WITHHELD); + expect(gridQueryInputs(), 'the grid that runs its own grouped query is handed none of it').not.toContain(WITHHELD); + expect(gridQueryInputs(), 'positive control: the rest of the filter is handed down').toContain('amount'); + expect(everyRequest(ds)).not.toContain(WITHHELD); + expect(screen.getByTestId('list-withheld-fields-notice')).toHaveTextContent(WITHHELD); + }); + + it('keeps a withheld sort entry in the sort it persists, from the sort builder and from the grid', async () => { + const onSortChange = vi.fn(); + const ds = makeDataSource({ packageOff: true }); + renderList(ds, viewSchema({ filter: undefined, searchableFields: undefined }), { onSortChange }); + await waitFor(() => expect(ds.find).toHaveBeenCalled()); + + // The sort builder: remove the `name` row; the withheld row stays in the write. + fireEvent.click(screen.getByRole('button', { name: /^sort/i })); + const rows = await screen.findAllByTestId('sort-builder-row'); + expect(rows).toHaveLength(2); + fireEvent.click(within(rows[1]).getByRole('button')); + await waitFor(() => expect(onSortChange).toHaveBeenCalled()); + expect(onSortChange.mock.calls.at(-1)![0].map((s: any) => [s.field, s.order])).toEqual([[WITHHELD, 'asc']]); + + // The grid's header seam crosses the same boundary: a withheld entry it + // hands back is persisted, and an entry the projection refuses for any + // other reason is still dropped. + await waitFor(() => expect(typeof lastGridProps?.onSortChange).toBe('function')); + lastGridProps.onSortChange([{ field: 'amount', order: 'desc' }, { field: WITHHELD, order: 'asc' }, { field: 'not_a_field', order: 'asc' }]); + await waitFor(() => expect(onSortChange.mock.calls.at(-1)![0].map((s: any) => s.field)).toEqual(['amount', WITHHELD])); + expect(everyRequest(ds)).not.toContain(WITHHELD); + }); + + it('draws the column and asks for it again once the definition no longer marks it, with no write', async () => { + const state = { packageOff: true }; + const ds = makeDataSource(state); + const onSortChange = vi.fn(); + const { unmount } = renderList(ds, viewSchema({ filter: undefined, searchableFields: undefined }), { onSortChange }); + await waitFor(() => expect(ds.find).toHaveBeenCalled()); + expect(gridNames()).not.toContain(WITHHELD); + unmount(); + + // The package is enabled: the next definition read serves the field. + state.packageOff = false; + lastGridProps = null; + renderList(ds, viewSchema({ filter: undefined, searchableFields: undefined }), { onSortChange }); + await waitFor(() => expect(JSON.stringify(lastGridProps?.schema?.columns ?? [])).toContain(WITHHELD)); + await waitFor(() => expect(JSON.stringify(ds.find.mock.calls.at(-1)![1])).toContain(WITHHELD)); + expect(JSON.stringify(ds.find.mock.calls.at(-1)![1].$orderby ?? ds.find.mock.calls.at(-1)![1].sort)).toContain(WITHHELD); + expect(screen.queryByTestId('list-withheld-fields-notice')).not.toBeInTheDocument(); + expect(onSortChange, 'nothing was written to bring it back').not.toHaveBeenCalled(); + }); +}); From f4ea4f9b7ee1f692e594d4d0961d4d3c2806de06 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 19:50:47 +0000 Subject: [PATCH 03/15] fix(objectql): register getWithheldExtensionFields as a read in the registry revision ledger (#34901) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- packages/objectql/src/registry-revision.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/objectql/src/registry-revision.ts b/packages/objectql/src/registry-revision.ts index 9a5363a1ffb..cf97c60eff3 100644 --- a/packages/objectql/src/registry-revision.ts +++ b/packages/objectql/src/registry-revision.ts @@ -87,6 +87,7 @@ export const SCHEMA_REGISTRY_METHOD_KINDS: Readonly Date: Tue, 17 Nov 2026 20:22:08 +0000 Subject: [PATCH 04/15] chore(i18n): regenerate zh-Hant from zh-Hans for list.withheldFieldsLeftOut (#34901) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- ui/packages/i18n/src/locales/zh-Hant.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 5a54de8898d..9156b09fb9f 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -963,7 +963,7 @@ const zhHant = { groupingUnstoredNotice: '無法按 {{fields}} 分組:它的值在顯示時計算,並未儲存。列表已暫不按它分組顯示。', groupingUnstoredRemove: '從分組中移除', draftOnlyQueryDropped: '未按 {{fields}} 篩選或排序:它僅存在於草稿中,釋出後才生效。', - withheldFieldsLeftOut: '未顯示 {{fields}},也未按其篩選、排序或分組:新增該欄位的套件已停用,啟用後即恢復。', + withheldFieldsLeftOut: '未顯示 {{fields}},也未按其篩選、排序或分組:新增該欄位的軟體包已停用,啟用後即恢復。', inlineEditShort: '行內編輯', inlineEditLabel: '行內編輯記錄(點選單元格進行編輯)', }, From d639b903f34efc0f9f8fe4002ed5ece017a27d45 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 20:59:16 +0000 Subject: [PATCH 05/15] =?UTF-8?q?docs(changeset):=20the=20Clause-=E2=91=A1?= =?UTF-8?q?=20line=20counts=20one=20locale=20key=20(#34901)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .changeset/34901-disabled-package-view-column.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/34901-disabled-package-view-column.md b/.changeset/34901-disabled-package-view-column.md index 3d8c897a72e..b3b1bded60d 100644 --- a/.changeset/34901-disabled-package-view-column.md +++ b/.changeset/34901-disabled-package-view-column.md @@ -10,7 +10,7 @@ fix(objectql, metadata-protocol, console): a list view column on a field a disabled package adds no longer fails the whole list -Clause-②: yes (widening: the view save door accepts withheld names; one spec read-decoration member; two locale keys) +Clause-②: yes (widening: the view save door accepts withheld names; one spec read-decoration member; one locale key) Metadata-protocol: none A package can add fields to another package's object. While that package is disabled, the platform leaves those fields out of the served object, and the data door refuses every request that names one (`400 INVALID_FIELD`, or `400 INVALID_SORT` for a sort). The owner's views still named the field, so a view with such a column, sort, filter, grouping level or searchable field failed for everyone. Saving the view (a rename, a pin, a Studio edit) was refused too (`422`, `list-view-field-unknown` / `sort-field-unknown`). From c45d97c102c341f83188cf1e41225009baa2cf22 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:21:59 +0000 Subject: [PATCH 06/15] test(spec): the connector redactor's read-decoration pin carries _withheldFields The pin asserts its item carries every METADATA_READ_DECORATIONS member before checking the redactor leaves them alone; the new member made its fixture fall short (CI Test Core 2/10, connector-credential-redaction.test.ts:342). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .../spec/src/integration/connector-credential-redaction.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/spec/src/integration/connector-credential-redaction.test.ts b/packages/spec/src/integration/connector-credential-redaction.test.ts index ec284834169..6cefef9df26 100644 --- a/packages/spec/src/integration/connector-credential-redaction.test.ts +++ b/packages/spec/src/integration/connector-credential-redaction.test.ts @@ -338,7 +338,7 @@ describe('the connector redactor — top-level keys the entry does not declare', }); it('the read decorations are the response\'s and are left alone', () => { - const item = { ...base, _draft: true }; + const item = { ...base, _draft: true, _withheldFields: { crm_project: { packageId: 'com.vendor.projects' } } }; for (const key of METADATA_READ_DECORATIONS) expect(item).toHaveProperty(key); expect(redactConnectorItem(item)).toEqual({ item, redactedKeys: [] }); }); From 9733be7600e7a5b113e9578dda4e00d66a027720 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:19:27 +0000 Subject: [PATCH 07/15] fix(metadata-protocol): a served view's lint judges a withheld field as the save door does The served view's `_diagnostics` (item read and the layered editor read) judged each name against the served object, so a column, filter, grouping level or form section on a field a disabled package adds read back as `list-view-field-unknown` / `form-field-unknown` on a body the view save door accepts. Both lint passes now read the same disabled-package fold the gate uses (`viewLintObjectLookup` over `withDisabledExtensionsFolded`, moved beside the lint passes); a typo still warns. Also pins the save door for a filter, a grouping level, a searchable field and a form section on a withheld name (each with a typo control), makes the fold docblocks name every position, and corrects the runtime comment that spelled the read-decoration list with two members. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .../src/metadata-diagnostics.ts | 76 +++++++++++++++ .../src/protocol-authoring-gate.ts | 45 +-------- .../src/protocol-meta-item-reads.ts | 8 +- .../src/protocol-meta-layered-reads.ts | 7 +- ...protocol-withheld-extension-fields.test.ts | 94 ++++++++++++++++++- packages/objectql/src/registry-top-level.ts | 12 ++- packages/runtime/src/domains/packages.ts | 3 +- 7 files changed, 189 insertions(+), 56 deletions(-) diff --git a/packages/metadata-protocol/src/metadata-diagnostics.ts b/packages/metadata-protocol/src/metadata-diagnostics.ts index 30c81dde476..93aa78e22ee 100644 --- a/packages/metadata-protocol/src/metadata-diagnostics.ts +++ b/packages/metadata-protocol/src/metadata-diagnostics.ts @@ -710,6 +710,82 @@ export async function withListViewFieldWarnings( return { ...served, _diagnostics: diagnostics } as T; } +// --------------------------------------------------------------------------- +// [#34901] The universe a view's field names are judged against while a +// package that extends their object is disabled +// --------------------------------------------------------------------------- + +/** + * [#34901] The objects a `view` write is judged against: each object a + * disabled package extends, folded with that package's `extend` contribution + * IN (`includeDisabledExtensions`, the fold the storage layer keeps), and + * every other object exactly as served. + * + * A disable withholds the fields its extensions add from the served object, + * while the owner's views keep naming them on purpose: re-enabling the package + * serves the column again with no write. Judged against the served objects, + * every save of such a view (a rename, a pin, a Studio edit) was refused for + * as long as the package stayed off. Judged against this fold, a withheld + * name is the real, stored field it is, wherever the view names it: a + * column, a sort, a filter, a grouping level, a searchable field or a form + * section (every view rule that reads its object's fields). A name no + * contributor declares is still unknown. + * + * The runtime authoring gate applies it to the merged universe (registered + * and stored halves alike), so a stored overlay of an extended object is + * folded the same way. ⛔ View writes ONLY: a flow, a formula or a + * validation rule written while the package is off would read a field the + * served object does not carry. A served view's lint reads the same fold + * ({@link viewLintObjectLookup}), so the read and the save door judge one + * body alike. + */ +export function withDisabledExtensionsFolded(registry: unknown, objects: unknown[]): unknown[] { + const r = registry as { + getWithheldExtensionFields?: (name: string) => Record; + foldObjectExtendersOnto?: (name: string, base: unknown, options?: { includeDisabledExtensions?: true }) => unknown; + } | null | undefined; + if (typeof r?.getWithheldExtensionFields !== 'function' || typeof r.foldObjectExtendersOnto !== 'function') return objects; + let changed = false; + const folded = objects.map((object) => { + const name = (object as { name?: unknown } | null)?.name; + if (typeof name !== 'string' || Object.keys(r.getWithheldExtensionFields!(name)).length === 0) return object; + try { + const storage = r.foldObjectExtendersOnto!(name, object, { includeDisabledExtensions: true }); + if (storage === object || storage === null || typeof storage !== 'object') return object; + changed = true; + const packageId = (object as { _packageId?: unknown })._packageId; + return packageId === undefined ? storage : { ...(storage as Record), _packageId: packageId }; + } catch { + // The fold is a read over in-memory contributors; a failure leaves + // the served object, the judgement this write had before. + return object; + } + }); + return changed ? folded : objects; +} + +/** + * [#34901] The object lookup a served view's lint passes judge a name against + * ({@link withViewLintWarnings}): the object `registry` serves, folded with + * every disabled package's `extend` contribution exactly as the save door + * folds it ({@link withDisabledExtensionsFolded}). + * + * Judged against the served object, a view naming a field a disabled package + * adds read back `list-view-field-unknown` (and `form-field-unknown`) on a + * body the save door accepts, and a consumer that followed the warning would + * delete the column re-enabling the package is meant to bring back. A name no + * contributor declares still warns. An object the registry does not answer is + * not judged, as before. + */ +export function viewLintObjectLookup(registry: unknown): (name: string) => unknown { + const r = registry as { getObject?: (name: string) => unknown } | null | undefined; + return (name) => { + const served = r?.getObject?.(name); + if (served === null || typeof served !== 'object') return served; + return withDisabledExtensionsFolded(registry, [served])[0]; + }; +} + /** * The two lint passes a served view's read runs, in order: the form layout * ({@link withFormLayoutWarnings}) and the list-view field references diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 5d6ef7cd64e..87fc38a29dc 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -52,6 +52,7 @@ import { objectBodyExtensionFieldSuffixRefusal } from './protocol-extension-fiel import { datasourceCredentialsRefSaveRefusal } from './protocol-datasource-credentials-ref.js'; import { storedFlowVerdictBody } from './protocol-flow-save-replay.js'; import { evaluateRuntimeAuthoringGate } from './runtime-authoring-gate.js'; +import { withDisabledExtensionsFolded } from './metadata-diagnostics.js'; import type { PackagedRuleCopyRefusal, RuntimeAuthoringIssue, RuntimeAuthoringVerdict, RuntimePendingDeclarations } from './runtime-authoring-gate.js'; import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name'; import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared'; @@ -328,50 +329,6 @@ export async function assertRuntimeAuthoringRules( return verdict.advisories; } -/** - * [#34901] The objects a `view` write is judged against: each object a - * disabled package extends, folded with that package's `extend` contribution - * IN (`includeDisabledExtensions`, the fold the storage layer keeps), and - * every other object exactly as served. - * - * A disable withholds the fields its extensions add from the served object, - * while the owner's views keep naming them on purpose: re-enabling the package - * serves the column again with no write. Judged against the served objects, - * every save of such a view (a rename, a pin, a Studio edit) was refused as - * `list-view-field-unknown` / `sort-field-unknown` for as long as the package - * stayed off. Judged against this fold, a withheld name is the real, stored - * field it is, and a name no contributor declares is still unknown. - * - * Applied to the merged universe (registered and stored halves alike), so a - * stored overlay of an extended object is folded the same way. ⛔ View writes - * ONLY: a flow, a formula or a validation rule written while the package is - * off would read a field the served object does not carry. - */ -export function withDisabledExtensionsFolded(registry: unknown, objects: unknown[]): unknown[] { - const r = registry as { - getWithheldExtensionFields?: (name: string) => Record; - foldObjectExtendersOnto?: (name: string, base: unknown, options?: { includeDisabledExtensions?: true }) => unknown; - } | null | undefined; - if (typeof r?.getWithheldExtensionFields !== 'function' || typeof r.foldObjectExtendersOnto !== 'function') return objects; - let changed = false; - const folded = objects.map((object) => { - const name = (object as { name?: unknown } | null)?.name; - if (typeof name !== 'string' || Object.keys(r.getWithheldExtensionFields!(name)).length === 0) return object; - try { - const storage = r.foldObjectExtendersOnto!(name, object, { includeDisabledExtensions: true }); - if (storage === object || storage === null || typeof storage !== 'object') return object; - changed = true; - const packageId = (object as { _packageId?: unknown })._packageId; - return packageId === undefined ? storage : { ...(storage as Record), _packageId: packageId }; - } catch { - // The fold is a read over in-memory contributors; a failure leaves - // the served object, the judgement this write had before. - return object; - } - }); - return changed ? folded : objects; -} - /** * [#26707] The judgement {@link assertRuntimeAuthoringRules} enforces, handed * back instead of thrown: the gate's {@link RuntimeAuthoringVerdict}, its diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index 7fd4f2bedec..b9768ae625d 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -39,6 +39,7 @@ import { decorateMetadataItem, withPublishAdvisories, withPublishVerdict, + viewLintObjectLookup, withViewLintWarnings, } from './metadata-diagnostics.js'; import { noPendingDraftError } from './protocol-authoring-refusals.js'; @@ -837,10 +838,13 @@ export async function readMetaItem(host: Pick(served: T): Promise => (execution ? Promise.resolve(served) - : withViewLintWarnings(request.type, served, (name) => host.engine?.registry?.getObject?.(name))); + : withViewLintWarnings(request.type, served, viewLintObjectLookup(host.engine?.registry))); // [#26707] A served DRAFT is decorated as above and then told what its // publish would refuse: the runtime gate's verdict on the stored draft // body ({@link draftPublishVerdict}), folded into `_diagnostics` diff --git a/packages/metadata-protocol/src/protocol-meta-layered-reads.ts b/packages/metadata-protocol/src/protocol-meta-layered-reads.ts index f038dd88f90..e71d47ae821 100644 --- a/packages/metadata-protocol/src/protocol-meta-layered-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-layered-reads.ts @@ -43,7 +43,7 @@ import { storedRowDocument, withItemLockFamily, } from './item-lock.js'; -import { type MetadataDiagnostics, computeMetadataDiagnostics, withViewLintWarnings } from './metadata-diagnostics.js'; +import { type MetadataDiagnostics, computeMetadataDiagnostics, viewLintObjectLookup, withViewLintWarnings } from './metadata-diagnostics.js'; import { redactMetadataItem } from './metadata-redaction.js'; import { overlayMemberWhere } from './migrations/overlay-index.js'; import { @@ -895,12 +895,13 @@ export async function getMetaItemLayered(host: Pick), _diagnostics: schemaDiagnostics }, - (name) => host.engine?.registry?.getObject?.(name), + viewLintObjectLookup(host.engine?.registry), ))._diagnostics as MetadataDiagnostics | undefined : schemaDiagnostics; diff --git a/packages/objectql/src/protocol-withheld-extension-fields.test.ts b/packages/objectql/src/protocol-withheld-extension-fields.test.ts index 2e0a3a40e1f..ec0d28117ee 100644 --- a/packages/objectql/src/protocol-withheld-extension-fields.test.ts +++ b/packages/objectql/src/protocol-withheld-extension-fields.test.ts @@ -96,7 +96,17 @@ async function boot() { engine.registerApp({ id: Q, name: 'expenses', version: '1.0.0', namespace: 'crm', type: 'app', objects: [{ name: O, label: 'Expense', fields: { name: { name: 'name', label: 'Name', type: 'text' }, amount: { name: 'amount', label: 'Amount', type: 'number' } } }], - views: [{ object: O, listViews: { all: { label: 'All expenses', type: 'grid', data: { provider: 'object', object: O }, columns: [{ field: 'name' }, { field: 'amount' }, { field: 'crm_project' }], sort: [{ field: 'crm_project', order: 'asc' }] } } }], + views: [{ + object: O, + listViews: { + all: { label: 'All expenses', type: 'grid', data: { provider: 'object', object: O }, columns: [{ field: 'name' }, { field: 'amount' }, { field: 'crm_project' }], sort: [{ field: 'crm_project', order: 'asc' }] }, + // A code-registered view that never passed a write door, with a typo'd column: the read still warns on it. + typo: { label: 'Typo', type: 'grid', data: { provider: 'object', object: O }, columns: [{ field: 'name' }, { field: 'crm_projcet' }] }, + }, + formViews: { + main: { type: 'simple', data: { provider: 'object', object: O }, sections: [{ label: 'Main', columns: 2, fields: ['name', 'crm_project'] }] }, + }, + }], } as any); engine.registerApp({ id: P, name: 'projects', version: '1.0.0', namespace: 'crm', type: 'app', dependencies: { [Q]: '^1.0.0' }, @@ -199,4 +209,86 @@ describe('[#34901] a view over a field a disabled package contributes', () => { expect((refused as any).rules).toEqual(['page-field-unknown']); expect(await save('name'), 'control: a served field saves').toEqual({ ok: true }); }); + + // [#34901 L2 N5] Every view rule that reads the object's fields is judged + // against the same fold, not only the column and the sort. Each position is + // pinned with its control: the same position spelling a typo is refused, + // which proves the rule judges that position at all. + const POSITIONS: Array<[string, (field: string) => (config: any) => any, string]> = [ + ['a filter', (field) => (c) => ({ ...c, filter: [{ field, operator: 'equals', value: 'x' }] }), 'config.filter[0].field'], + ['a grouping level', (field) => (c) => ({ ...c, grouping: { fields: [{ field }] } }), 'config.grouping.fields[0].field'], + ['a searchable field', (field) => (c) => ({ ...c, searchableFields: ['name', field] }), 'config.searchableFields[1]'], + ]; + for (const [label, edit, path] of POSITIONS) { + it(`${label} naming the withheld field saves while P is off; a typo there is refused`, async () => { + const { registry, protocol } = await boot(); + registry.disablePackage(P); + const saved = await outcome(async () => protocol.saveMetaItem({ type: 'view', name: VIEW, item: await servedViewBody(protocol, edit('crm_project')), packageId: PAIR })); + expect(saved).toEqual({ ok: true }); + const typo = await outcome(async () => protocol.saveMetaItem({ type: 'view', name: VIEW, item: await servedViewBody(protocol, edit('crm_projcet')), packageId: PAIR })); + expect(typo).toMatchObject({ ok: false, status: 422 }); + expect((typo as any).message).toContain(path); + }); + } + + // A form section's unknown field is an ADVISORY at the door (`form-field-unknown` + // never refuses: the field just does not render), carried on the save's 2xx. + it('a form section naming the withheld field saves while P is off with no advisory on it; a typo is advised', async () => { + const { registry, protocol } = await boot(); + registry.disablePackage(P); + const form = async (field: string) => { + const { _packageId, _provenance, _diagnostics, ...body } = (await protocol.getMetaItem({ type: 'view', name: FORM })).item; + const config = { ...body.config, sections: [{ label: 'Main', columns: 2, fields: ['name', field] }] }; + return { ...body, config, overrides: { package: Q, basedOn: '1.0.0' } }; + }; + const advised = (result: any) => ((result?.advisories ?? []) as any[]).map((a) => `${a.rule}@${a.path}`); + const saved = await protocol.saveMetaItem({ type: 'view', name: FORM, item: await form('crm_project'), packageId: PAIR }); + expect(saved.success).toBe(true); + expect(advised(saved).filter((a) => a.startsWith('form-field-unknown'))).toEqual([]); + const typo = await protocol.saveMetaItem({ type: 'view', name: FORM, item: await form('crm_projcet'), packageId: PAIR }); + expect(advised(typo).filter((a) => a.startsWith('form-field-unknown')), 'control: the position is judged').toHaveLength(1); + }); +}); + +/** Every warning a served view's `_diagnostics` carries, as `path: message`. */ +function warningsOf(item: any): string[] { + return ((item?._diagnostics?.warnings ?? []) as any[]).map((w) => `${w.path}: ${w.message}`); +} + +const FORM = 'crm_expense.main'; + +describe('[#34901 L2 S1] a served view judges the withheld field as the save door does', () => { + it('a view the door accepts reads back with no field warning on the withheld name; a typo still warns', async () => { + const { registry, protocol } = await boot(); + registry.disablePackage(P); + const body = await servedViewBody(protocol, (c) => ({ + ...c, + filter: [{ field: 'crm_project', operator: 'equals', value: 'x' }], + grouping: { fields: [{ field: 'crm_project' }] }, + searchableFields: ['name', 'crm_project'], + })); + expect(await outcome(() => protocol.saveMetaItem({ type: 'view', name: VIEW, item: body, packageId: PAIR }))).toEqual({ ok: true }); + + const served = (await protocol.getMetaItem({ type: 'view', name: VIEW })).item; + expect(served.config.columns.map((c: any) => c.field), 'precondition: the saved view still names it').toContain('crm_project'); + expect(warningsOf(served).filter((w) => w.includes('crm_project'))).toEqual([]); + expect(warningsOf(served).filter((w) => w.includes('list-view-field-unknown') || w.includes('is not a field'))).toEqual([]); + + const layered = await protocol.getMetaItemLayered({ type: 'view', name: VIEW }); + expect(warningsOf({ _diagnostics: layered._diagnostics }).filter((w) => w.includes('crm_project')), 'the layered read too').toEqual([]); + + const typo = (await protocol.getMetaItem({ type: 'view', name: 'crm_expense.typo' })).item; + expect(warningsOf(typo).filter((w) => w.includes('crm_projcet')), 'control: a typo still warns').toHaveLength(1); + }); + + it('a form section naming the withheld field reads back with no form-field-unknown; with P on there was none either', async () => { + const { registry, protocol } = await boot(); + const on = (await protocol.getMetaItem({ type: 'view', name: FORM })).item; + expect(on.config.sections[0].fields, 'precondition: the form names it').toContain('crm_project'); + expect(warningsOf(on).filter((w) => w.includes('crm_project'))).toEqual([]); + + registry.disablePackage(P); + const off = (await protocol.getMetaItem({ type: 'view', name: FORM })).item; + expect(warningsOf(off).filter((w) => w.includes('crm_project'))).toEqual([]); + }); }); diff --git a/packages/objectql/src/registry-top-level.ts b/packages/objectql/src/registry-top-level.ts index 0091ee0e594..5cffdd711f6 100644 --- a/packages/objectql/src/registry-top-level.ts +++ b/packages/objectql/src/registry-top-level.ts @@ -723,11 +723,13 @@ type ServedObjectLayer = 'served' | 'code'; * [#34901] `includeDisabledExtensions` is `asEnabled` for EVERY disabled * package at once: no `extend` contribution is withheld, so the fold is the * one the storage layer keeps ({@link SchemaRegistry.getStorageObject}). The - * runtime authoring gate reads it on a `view` write ONLY, so a column or sort - * naming a field a disabled package adds is judged a real, stored field rather - * than an unknown one: the view the owner ships keeps naming it, and - * re-enabling the package serves it again with no write. A name no - * contributor declares is unknown either way. + * runtime authoring gate reads it on a `view` write ONLY (and a served view's + * lint reads the same fold), so a field a disabled package adds is judged a + * real, stored field rather than an unknown one wherever the view names it (a + * column, a sort, a filter, a grouping level, a searchable field or a form + * section): the view the owner ships keeps naming it, and re-enabling the + * package serves it again with no write. A name no contributor declares is + * unknown either way. */ export interface ObjectExtensionFoldOptions { withoutExtensionsOf?: string; diff --git a/packages/runtime/src/domains/packages.ts b/packages/runtime/src/domains/packages.ts index 95131f7df23..c3a32b87791 100644 --- a/packages/runtime/src/domains/packages.ts +++ b/packages/runtime/src/domains/packages.ts @@ -5054,7 +5054,8 @@ _context: HttpProtocolContext, // ⛔ NOT a blanket `startsWith('_')` strip, and deliberately not the // one `assemblePackageManifest` runs 300 lines up: the two paths // have opposite obligations, and the spec states both. - // `METADATA_READ_DECORATIONS` is `['_diagnostics', '_draft']` and + // `METADATA_READ_DECORATIONS` is the list of the read path's own + // annotations (`_diagnostics`, `_draft`, `_withheldFields`) and // its module says the ADR-0010 envelope (`_packageId`, // `_provenance`, …) is "deliberately NOT" a member — "the closed // metadata schemas allowlist them precisely so a served document From 2a4d8e5a852a8afb45e71b7d8a402bab8c6186f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 23:19:34 +0000 Subject: [PATCH 08/15] chore(changeset): name the served view diagnostics fold Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .changeset/34901-disabled-package-view-column.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/34901-disabled-package-view-column.md b/.changeset/34901-disabled-package-view-column.md index b3b1bded60d..8f1183aabd3 100644 --- a/.changeset/34901-disabled-package-view-column.md +++ b/.changeset/34901-disabled-package-view-column.md @@ -16,5 +16,5 @@ Metadata-protocol: none A package can add fields to another package's object. While that package is disabled, the platform leaves those fields out of the served object, and the data door refuses every request that names one (`400 INVALID_FIELD`, or `400 INVALID_SORT` for a sort). The owner's views still named the field, so a view with such a column, sort, filter, grouping level or searchable field failed for everyone. Saving the view (a rename, a pin, a Studio edit) was refused too (`422`, `list-view-field-unknown` / `sort-field-unknown`). - **The served object read names what is withheld.** `GET /api/v1/meta/object/:name` and the object list read carry `_withheldFields: { [field]: { packageId } }` when a disabled package withholds a field from the object. It is a read decoration (`METADATA_READ_DECORATIONS`), so the save door strips it, and the execution face and the layered editor read do not carry it. The registry gains `getWithheldExtensionFields(name)`. -- **The view save door judges a view against the stored object.** A `view` write is judged against the object with every disabled package's extension folded in (the new fold option `includeDisabledExtensions`). A withheld field is a real stored field, so the view saves and keeps its column and sort. A misspelled field is still refused. Other writes are still judged against the served object, so a page or flow that names a withheld field is still refused while the package is off. +- **The view save door judges a view against the stored object.** A `view` write is judged against the object with every disabled package's extension folded in (the new fold option `includeDisabledExtensions`). A withheld field is a real stored field, so the view saves and keeps its column and sort. A misspelled field is still refused. Other writes are still judged against the served object, so a page or flow that names a withheld field is still refused while the package is off. A served view's `_diagnostics` is judged against the same stored object, so it no longer warns `list-view-field-unknown` or `form-field-unknown` on a withheld name the save door accepts; a misspelled field still warns. - **The console leaves withheld names out.** The list view and the grid leave a withheld field out of `$select`, `$filter`, `$orderby`, `$searchFields` and `groupBy`, and do not draw its column. A line above the rows names it (`list.withheldFieldsLeftOut`). Nothing is written to the view or to the user's list preferences, and a sort the user saves keeps the withheld entry. Once the package is enabled, the column, the sort and the grouping come back without any write. From 323b0cc848fbe76ef63a7b2ce3b899e085b59598 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 00:56:49 +0000 Subject: [PATCH 09/15] feat(spec): an optional security-service member names the withheld fields a caller may be told about ISecurityService gains getMetadataReadableWithheldFields(object, context), add-only and OPTIONAL. It answers which of the fields a disabled package withholds from the served schema may be disclosed to the caller, judged against the stored definition (ADR-0106 D1/D7). A consumer reads absence, undefined and a throw as "disclose none". Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .../src/contracts/security-service.test.ts | 18 +++++++++++ .../spec/src/contracts/security-service.ts | 30 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/packages/spec/src/contracts/security-service.test.ts b/packages/spec/src/contracts/security-service.test.ts index d42ac2c41b4..da95c4befad 100644 --- a/packages/spec/src/contracts/security-service.test.ts +++ b/packages/spec/src/contracts/security-service.test.ts @@ -270,6 +270,24 @@ describe('Security Service Contract', () => { await expect(nothingDisclosable.getMetadataReadableFields?.('deal', { userId: 'u1' })).resolves.toEqual([]); }); + it('[ADR-0106 D1] getMetadataReadableWithheldFields is OPTIONAL, and a service without it still satisfies the contract', async () => { + // A security service that predates the member is still an ISecurityService; + // its consumers drop every withheld entry for it (fail closed), which the + // projection's own pins measure in metadata-core. + const withoutIt: ISecurityService = makeService({ getReadableFields: async () => ['id', 'name'] }); + expect(typeof withoutIt.getMetadataReadableWithheldFields).toBe('undefined'); + const mustNotCompileWithoutAGuard = () => + // @ts-expect-error possibly undefined — a consumer must feature-detect first + withoutIt.getMetadataReadableWithheldFields('deal', { userId: 'u1' }); + expect(typeof mustNotCompileWithoutAGuard).toBe('function'); + + const withIt = makeService({ + getMetadataReadableWithheldFields: async (_object, context) => (context?.isSystem ? ['crm_project'] : []), + }); + await expect(withIt.getMetadataReadableWithheldFields?.('deal', { isSystem: true })).resolves.toEqual(['crm_project']); + await expect(withIt.getMetadataReadableWithheldFields?.('deal', { userId: 'u1' })).resolves.toEqual([]); + }); + it('getWritableFields is OPTIONAL — absence degrades to getReadableFields, and the two answers differ', async () => { const withoutIt: ISecurityService = makeService({ getReadableFields: async () => ['id', 'name', 'locked'] }); expect(typeof withoutIt.getWritableFields).toBe('undefined'); diff --git a/packages/spec/src/contracts/security-service.ts b/packages/spec/src/contracts/security-service.ts index 3ba43c7522b..90728e8bd77 100644 --- a/packages/spec/src/contracts/security-service.ts +++ b/packages/spec/src/contracts/security-service.ts @@ -705,6 +705,36 @@ export interface ISecurityService { */ getMetadataReadableFields?(object: string, context?: SecurityContext): Promise; + /** + * [ADR-0106 D1/D7] The METADATA-PLANE answer for the fields of `object` that + * a disabled package withholds from the served schema: which of those names + * may be DISCLOSED to `context`. A served object read carries the names in + * its `_withheldFields` read decoration; a schema-serving outlet keeps an + * entry for a caller only when this answer names it. + * + * **Why {@link getMetadataReadableFields} cannot answer it.** That answer + * enumerates the live object's fields, and a withheld field is not one of + * them, so it names a withheld field for no caller, admitted or denied. This + * member judges each withheld name against the field's STORAGE definition + * (the definition with every `extend` contribution folded in, disabled or + * not): the caller's permission-set field entry, the stored field's own + * `requiredPermissions`, the same zero-set fallback resolution as + * {@link getMetadataReadableFields}, and the on-behalf-of delegator's + * intersection. A name it cannot judge is not admitted. + * + * **Answers:** the admitted names, a subset of the withheld ones; `[]` when + * nothing is withheld or nothing withheld may be disclosed; `undefined` when + * the withheld set or the caller's posture cannot be determined. A system + * context yields every withheld name. + * + * **OPTIONAL, and absence fails CLOSED.** Unlike the readable-field answers, + * a consumer reads absence, `undefined` and a throw alike as "no withheld + * name may be disclosed" and drops every entry: the decoration is a hint to + * a client, never a field the caller needs to read, so dropping it costs a + * convenience and serving it on a guess discloses a field's existence. + */ + getMetadataReadableWithheldFields?(object: string, context?: SecurityContext): Promise; + /** * [#20935] The field names `context` may QUERY ON in `object` — filter, sort, * group or aggregate by — as far as field-level security decides. The From 343c61d6ff89e2b1f3b742abea50fce7014b091c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 00:56:49 +0000 Subject: [PATCH 10/15] feat(plugin-security): judge a disabled package's withheld fields against the stored definition getMetadataReadableWithheldFields reads the withheld names and the storage fold from the registry and judges each one with the evaluator the readable projection uses: the permission-set field entry, the stored field's own requiredPermissions, the D7 fallback set, the delegator intersection and the computed-field fold. Registered on the security service; the registered-members pin declares it. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- ...-metadata-readable-withheld-fields.test.ts | 177 ++++++++++++++++++ ...tered-security-service-members.pin.test.ts | 1 + .../src/security-plugin-security-service.ts | 10 +- .../security-plugin-withheld-field-readers.ts | 175 +++++++++++++++++ .../plugin-security/src/security-plugin.ts | 33 +++- 5 files changed, 394 insertions(+), 2 deletions(-) create mode 100644 packages/plugins/plugin-security/src/get-metadata-readable-withheld-fields.test.ts create mode 100644 packages/plugins/plugin-security/src/security-plugin-withheld-field-readers.ts diff --git a/packages/plugins/plugin-security/src/get-metadata-readable-withheld-fields.test.ts b/packages/plugins/plugin-security/src/get-metadata-readable-withheld-fields.test.ts new file mode 100644 index 00000000000..0e1a553990b --- /dev/null +++ b/packages/plugins/plugin-security/src/get-metadata-readable-withheld-fields.test.ts @@ -0,0 +1,177 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0106 D1/D7, #34901] `getMetadataReadableWithheldFields` — which of the + * fields a disabled package withholds from an object's served schema may be + * disclosed to a caller, judged against the STORAGE definition. + * + * The object and the extension are registered on a REAL `SchemaRegistry`, so + * the withheld names and the stored definition are the registry's own answers + * (`getWithheldExtensionFields`, `getStorageObject`), not a double's. Package + * `PROJECTS` extends `m1_deal` with `m1_project` (guarded by the capability + * `view_projects`) and `m1_margin` (computed from the live field `amount`), and + * is disabled in every case that expects something withheld. + * + * The control beside each denial: `getMetadataReadableFields` answers the same + * live field set to every caller here, so it cannot tell them apart — which is + * why this member exists. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { SchemaRegistry } from '@objectstack/objectql'; +import type { PermissionSet } from '@objectstack/spec/security'; +import { SecurityPlugin } from './security-plugin.js'; + +const DEALS = 'com.qa.m1.deals'; +const PROJECTS = 'com.qa.m1.projects'; +const OBJECT = 'm1_deal'; + +const set = (name: string, extra: Record = {}): PermissionSet => + ({ name, label: name, objects: { [OBJECT]: { allowRead: true } }, ...extra }) as unknown as PermissionSet; + +const SETS: PermissionSet[] = [ + set('member_default'), + // Holds the capability, but its field entry denies the read. + set('deny_project', { systemPermissions: ['view_projects'], fields: { [`${OBJECT}.m1_project`]: { readable: false, editable: false } } }), + // Reads the object; holds no capability. + set('open'), + set('projects_viewer', { systemPermissions: ['view_projects'] }), + // Holds the capability; denies the live field `m1_margin` is computed from. + set('deny_amount', { systemPermissions: ['view_projects'], fields: { [`${OBJECT}.amount`]: { readable: false, editable: false } } }), +]; + +/** Denied by a permission set's `readable: false`; denied by the stored field's `requiredPermissions`; admitted. */ +const CALLERS = { + deniedBySet: { userId: 'u_deny', positions: [], permissions: ['deny_project'] }, + deniedByCapability: { userId: 'u_open', positions: [], permissions: ['open'] }, + admitted: { userId: 'u_viewer', positions: [], permissions: ['projects_viewer'] }, +} as const; + +function registryWithExtension(options: { disabled?: boolean; extensionFields?: Record } = {}) { + const registry = new SchemaRegistry({ multiTenant: false }); + (registry as any).logLevel = 'silent'; + registry.installPackage({ id: DEALS, name: DEALS, version: '1.0.0', type: 'app', namespace: 'm1' } as any, 'code'); + registry.installPackage({ id: PROJECTS, name: PROJECTS, version: '1.0.0', type: 'module', namespace: 'm1', dependencies: { [DEALS]: '^1.0.0' } } as any, 'code'); + registry.registerObject({ + name: OBJECT, label: 'Deal', + fields: { name: { name: 'name', type: 'text', label: 'Name' }, amount: { name: 'amount', type: 'number', label: 'Amount' } }, + } as any, DEALS, 'm1', 'own'); + registry.registerObject({ + name: OBJECT, + fields: options.extensionFields ?? { + m1_project: { name: 'm1_project', type: 'text', label: 'Project', requiredPermissions: ['view_projects'] }, + m1_margin: { name: 'm1_margin', type: 'formula', label: 'Margin', expression: 'record.amount * 2' }, + }, + } as any, PROJECTS, 'm1', 'extend'); + if (options.disabled !== false) registry.disablePackage(PROJECTS); + return registry; +} + +async function boot(options: { registry?: unknown; sets?: PermissionSet[] } = {}) { + const registry = options.registry === undefined ? registryWithExtension() : options.registry; + // The sets live where the plugin's catalog reads them: the plugin binds its + // catalog to the engine's registry at start, and from then on that catalog, + // not `metadata.list`, answers every by-name request. + for (const s of options.sets ?? SETS) (registry as any)?.registerItem?.('permission', s, 'name'); + const ql: any = { + registerMiddleware: () => {}, + getSchema: (name: string) => (registry as any)?.getObject?.(name) ?? null, + findOne: async () => null, + registry, + }; + const metadata: any = { + get: async (_type: string, name: string) => (registry as any)?.getObject?.(name) ?? null, + list: async () => options.sets ?? SETS, + }; + const services: Record = { manifest: { register: vi.fn() }, objectql: ql, metadata }; + const registerService = vi.fn(); + const ctx: any = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' } as any); + await plugin.init(ctx); + await plugin.start(ctx); + const security = registerService.mock.calls.find((c: unknown[]) => c[0] === 'security')?.[1]; + return { plugin, security }; +} + +describe('[ADR-0106 D1, #34901] SecurityPlugin.getMetadataReadableWithheldFields', () => { + it('judges each withheld name against its stored definition: a set\'s readable:false and the field\'s requiredPermissions deny, a holder is admitted', async () => { + const { security } = await boot(); + const answers: Record = {}; + const readable: Record = {}; + for (const [label, caller] of Object.entries(CALLERS)) { + answers[label] = (await security.getMetadataReadableWithheldFields(OBJECT, caller))?.slice().sort(); + readable[label] = (await security.getMetadataReadableFields(OBJECT, caller))?.filter((f: string) => f.startsWith('m1_')); + } + expect(answers).toEqual({ + deniedBySet: ['m1_margin'], + deniedByCapability: ['m1_margin'], + admitted: ['m1_margin', 'm1_project'], + }); + // Control: the live-field answer names no withheld field for anyone. + expect(readable).toEqual({ deniedBySet: [], deniedByCapability: [], admitted: [] }); + }); + + it('is served on the registered `security` service, and the plugin answers the same', async () => { + const { plugin, security } = await boot(); + expect(typeof security.getMetadataReadableWithheldFields).toBe('function'); + await expect(security.getMetadataReadableWithheldFields(OBJECT, CALLERS.admitted)) + .resolves.toEqual(await plugin.getMetadataReadableWithheldFields(OBJECT, CALLERS.admitted)); + }); + + it('a computed withheld field reading a field the caller may not read is not admitted', async () => { + const { security } = await boot(); + const answer = await security.getMetadataReadableWithheldFields(OBJECT, { userId: 'u_amount', positions: [], permissions: ['deny_amount'] }); + expect(answer).toEqual(['m1_project']); + }); + + it('a computed withheld field reading through a reference is not admitted (fail closed: the referenced object is not walked)', async () => { + const registry = registryWithExtension({ + extensionFields: { m1_owner_name: { name: 'm1_owner_name', type: 'formula', label: 'Owner', expression: 'record.owner.name' } }, + }); + const { security } = await boot({ registry }); + await expect(security.getMetadataReadableWithheldFields(OBJECT, CALLERS.admitted)).resolves.toEqual([]); + }); + + it('a zero-set caller is judged by the D7 fallback set', async () => { + const fallbackDenies = SETS.map((s) => (s.name === 'member_default' + ? set('member_default', { fields: { [`${OBJECT}.m1_margin`]: { readable: false, editable: false } } }) + : s)); + const { security } = await boot({ sets: fallbackDenies }); + // No `userId`: no baseline is applied, so the caller resolves no set and the fallback decides. + const guest = { positions: [], permissions: [] }; + await expect(security.getMetadataReadableWithheldFields(OBJECT, guest)).resolves.toEqual([]); + // Control: the same caller under a fallback that denies nothing reads m1_margin (m1_project needs a capability it lacks). + const { security: open } = await boot(); + await expect(open.getMetadataReadableWithheldFields(OBJECT, guest)).resolves.toEqual(['m1_margin']); + }); + + it('an on-behalf-of caller is narrowed by the delegator: denied there ⇒ not admitted; a dangling delegator answers nothing', async () => { + const { plugin, security } = await boot(); + const delegated = { ...CALLERS.admitted, onBehalfOf: { userId: 'u_delegator' } }; + const spy = vi.spyOn(plugin as any, 'resolveDelegatorForContext') + .mockResolvedValue({ kind: 'resolved', context: { userId: 'u_delegator', positions: [], permissions: ['deny_project'] } }); + await expect(security.getMetadataReadableWithheldFields(OBJECT, delegated)).resolves.toEqual(['m1_margin']); + spy.mockResolvedValue({ kind: 'missing', userId: 'u_delegator' }); + await expect(security.getMetadataReadableWithheldFields(OBJECT, delegated)).resolves.toEqual([]); + }); + + it('a system context is told every withheld name; nothing withheld answers []', async () => { + const { security } = await boot(); + await expect(security.getMetadataReadableWithheldFields(OBJECT, { isSystem: true }).then((a: string[]) => a.sort())) + .resolves.toEqual(['m1_margin', 'm1_project']); + const { security: enabled } = await boot({ registry: registryWithExtension({ disabled: false }) }); + await expect(enabled.getMetadataReadableWithheldFields(OBJECT, CALLERS.admitted)).resolves.toEqual([]); + }); + + it('answers undefined when the registry offers no storage read, so the consumer drops every entry', async () => { + const { security } = await boot({ registry: { getObject: () => ({ name: OBJECT, fields: { name: { name: 'name', type: 'text' } } }) } }); + await expect(security.getMetadataReadableWithheldFields(OBJECT, CALLERS.admitted)).resolves.toBeUndefined(); + }); +}); diff --git a/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts b/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts index 9893995172b..c26d553ee69 100644 --- a/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts +++ b/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts @@ -61,6 +61,7 @@ const DECLARED_MEMBERS = { getReadFilter: 'required', getReadableFields: 'required', getMetadataReadableFields: 'optional', + getMetadataReadableWithheldFields: 'optional', getQueryableFields: 'optional', getWritableFields: 'optional', getRecordFieldAccess: 'optional', diff --git a/packages/plugins/plugin-security/src/security-plugin-security-service.ts b/packages/plugins/plugin-security/src/security-plugin-security-service.ts index b2b1c5e4726..440aa81de1f 100644 --- a/packages/plugins/plugin-security/src/security-plugin-security-service.ts +++ b/packages/plugins/plugin-security/src/security-plugin-security-service.ts @@ -117,6 +117,7 @@ export interface SecurityServiceHost { explainAccessForCaller: SecurityPlugin['explainAccessForCaller']; getEffectiveObjectPermissions: SecurityPlugin['getEffectiveObjectPermissions']; getMetadataReadableFields: SecurityPlugin['getMetadataReadableFields']; + getMetadataReadableWithheldFields: SecurityPlugin['getMetadataReadableWithheldFields']; getObjectSecurityMeta: SecurityPlugin['getObjectSecurityMeta']; getQueryableFields: SecurityPlugin['getQueryableFields']; getReadFilter: SecurityPlugin['getReadFilter']; @@ -128,7 +129,7 @@ export interface SecurityServiceHost { /** The `security` service registration `SecurityPlugin#start` runs; the comment above its call there is its contract. */ export function registerSecurityService( - this: Pick, + this: Pick, ctx: PluginContext, ql: IObjectQLEngine, metadata: IMetadataService, @@ -164,6 +165,13 @@ export function registerSecurityService( // route uses it to project columns instead of inferring readability // from already-masked data rows. See getReadableFields. getReadableFields: (object: string, context?: any) => this.getReadableFields(object, context), + // [ADR-0106 D1, #34901] Which fields a disabled package withholds from + // the served schema may be disclosed to the caller, judged against the + // STORAGE definition. The object-schema projection drops every + // `_withheldFields` entry it does not name, and drops them all when this + // member is absent. See getMetadataReadableWithheldFields. + getMetadataReadableWithheldFields: (object: string, context?: any) => + this.getMetadataReadableWithheldFields(object, context), // [#18386] Its write-side twin: the fields step 2.5 would not refuse. // The import template narrows its columns by it. See getWritableFields. getWritableFields: (object: string, context?: any) => this.getWritableFields(object, context), diff --git a/packages/plugins/plugin-security/src/security-plugin-withheld-field-readers.ts b/packages/plugins/plugin-security/src/security-plugin-withheld-field-readers.ts new file mode 100644 index 00000000000..fbd483eb2e9 --- /dev/null +++ b/packages/plugins/plugin-security/src/security-plugin-withheld-field-readers.ts @@ -0,0 +1,175 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0106 D1/D7, #34901] The body of + * `SecurityPlugin#getMetadataReadableWithheldFields`: which of the fields a + * disabled package withholds from an object's served schema may be DISCLOSED + * to a caller. The contract is the member's docblock on `ISecurityService` + * (`@objectstack/spec/contracts`). + * + * ## Why the readable projection cannot answer it + * + * A served object read names the withheld fields in its `_withheldFields` read + * decoration, and the metadata plane's projection (`applyObjectSchemaMask`, + * `@objectstack/metadata-core`) must drop every entry the caller may not read, + * or a disable discloses a field's existence that ADR-0106 D1 removes whole. + * `getMetadataReadableFields` enumerates the LIVE object's fields, which leave + * a withheld field out, so it names a withheld field for no caller: it cannot + * tell a denied caller from an admitted one. + * + * ## The derivation + * + * The same evaluator, sets and folds the readable projection takes + * (`resolveProjectionFieldMask`, `computeReadableFields`), with the withheld + * fields' own declarations read from the STORAGE definition + * (`SchemaRegistry.getStorageObject`, every `extend` contribution folded in): + * + * 1. the withheld names (`SchemaRegistry.getWithheldExtensionFields`); none ⇒ + * `[]`, and a system context ⇒ all of them; + * 2. the caller's permission sets, or the configured fallback set when it + * resolves none (ADR-0106 D7, as the metadata-plane projection does); + * 3. the object's posture; unresolved ⇒ `[]` (fail closed, as #3545); + * 4. the evaluator's field map, with the per-field capability fold over the + * live fields' `requiredPermissions` AND the stored withheld fields'; + * 5. the on-behalf-of delegator's map intersected in (ADR-0090 D10), and the + * delegator's refusals answered `[]`, as the projection answers them; + * 6. a computed withheld field is folded over what it reads + * (`foldComputedFieldReads`): withheld when it reads a field the caller may + * not read, a field this object masks, or a live field withheld for what it + * reads through a reference. + * + * Two places it is deliberately NARROWER than the readable projection, each + * failing closed (an entry dropped costs the console a hint; one served + * wrongly discloses a field): a computed withheld field that reads through a + * reference is not admitted (its referenced object is not walked here), and + * a withheld field whose capability fold denies it is not admitted even when a + * `maskingRule` would serve it masked on the data plane. + * + * `undefined` when the registry offers neither storage read, or the object has + * no storage definition: the consumer drops every entry for it. + */ + +import type { SecurityPlugin } from './security-plugin.js'; +import type { PermissionSet } from '@objectstack/spec/security'; +import { delegatedOrganizationRefusal, intersectFieldMasks } from './explain-engine.js'; +import { foldComputedFieldReads, readComputedFieldExpression, type ComputedFieldInput } from './field-masker.js'; + +/** + * The `SecurityPlugin` members {@link computeMetadataReadableWithheldFields} + * reads, each typed AS the class member, the shape `FieldReadersHost` takes + * (`security-plugin-field-readers.ts`, whose header carries the reasoning). + * `permissionEvaluator`, `ql` and `tenancyPosture` go as getters. + */ +export interface WithheldFieldReadersHost { + readonly permissionEvaluator: SecurityPlugin['permissionEvaluator']; + readonly ql: SecurityPlugin['ql']; + readonly tenancyPosture: SecurityPlugin['tenancyPosture']; + foldFieldRequiredPermissions: SecurityPlugin['foldFieldRequiredPermissions']; + resolveCallerPosture: SecurityPlugin['resolveCallerPosture']; + resolveDelegatorForContext: SecurityPlugin['resolveDelegatorForContext']; + resolveFallbackPermissionSets: SecurityPlugin['resolveFallbackPermissionSets']; + resolveHopWithheldFields: SecurityPlugin['resolveHopWithheldFields']; + resolvePermissionSetsForContext: SecurityPlugin['resolvePermissionSetsForContext']; +} + +/** The two registry reads the derivation needs, both added to `SchemaRegistry` for this purpose or before it. */ +interface WithheldFieldRegistry { + getWithheldExtensionFields(name: string): Record | undefined; + getStorageObject(name: string): { fields?: unknown } | undefined; +} + +/** The stored field definitions of `storage`, by name (the record `packages/spec` declares, or a list of named entries). */ +function storedFieldDefinitions(storage: { fields?: unknown }): Record { + const fields = storage.fields; + if (Array.isArray(fields)) { + const out: Record = {}; + for (const f of fields) if (f && typeof f === 'object' && (f as { name?: unknown }).name) out[String((f as { name: unknown }).name)] = f; + return out; + } + return fields && typeof fields === 'object' ? fields as Record : {}; +} + +/** A stored field's own `requiredPermissions` (ADR-0066 D3), or `undefined` when it declares none. */ +function declaredRequiredPermissions(def: unknown): string[] | undefined { + const rp = (def as { requiredPermissions?: unknown } | undefined)?.requiredPermissions; + return Array.isArray(rp) && rp.length > 0 ? rp.map(String) : undefined; +} + +/** The body of `SecurityPlugin#getMetadataReadableWithheldFields`; the contract is the member's docblock on `ISecurityService`. */ +export async function computeMetadataReadableWithheldFields( + this: Pick, + object: string, + context: any, +): Promise { + const objectName = String(object ?? ''); + if (!objectName) return undefined; + const registry = this.ql?.registry as Partial | undefined; + if (typeof registry?.getWithheldExtensionFields !== 'function' || typeof registry.getStorageObject !== 'function') { + return undefined; + } + + // 1. The withheld names. Nothing withheld is the common case and costs no set resolution. + const withheld = Object.keys(registry.getWithheldExtensionFields(objectName) ?? {}); + if (withheld.length === 0) return []; + if (context?.isSystem) return withheld; + const storage = registry.getStorageObject(objectName); + if (!storage) return undefined; + const stored = storedFieldDefinitions(storage); + + // 2. The caller's sets, the D7 fallback set when it resolves none. + let permissionSets: PermissionSet[] = await this.resolvePermissionSetsForContext(context); + if (permissionSets.length === 0) permissionSets = await this.resolveFallbackPermissionSets(context); + + // 3. The posture; unresolvable answers nothing, as the projection does (#3545). + const secMeta = await this.resolveCallerPosture(objectName, permissionSets); + if (secMeta.unresolved) return []; + + // 4. The evaluator's map with the capability fold: the live fields' contract + // from the posture, the withheld fields' from their stored definition. + const fieldRequiredPermissions: Record = { ...secMeta.fieldRequiredPermissions }; + const computedFieldInputs: Record = { ...secMeta.computedFieldInputs }; + const readsThroughReference = new Set(); + for (const name of withheld) { + const required = declaredRequiredPermissions(stored[name]); + if (required) fieldRequiredPermissions[name] = required; + const input = readComputedFieldExpression(stored[name]); + if (input !== undefined) { + computedFieldInputs[name] = input; + if (input.hops.size > 0) readsThroughReference.add(name); + } + } + let fieldPerms = this.foldFieldRequiredPermissions( + this.permissionEvaluator.getFieldPermissions(objectName, permissionSets), + fieldRequiredPermissions, + permissionSets, + ); + + // 5. The delegator's intersection, asked where the projection asks it. + if (permissionSets.length > 0 && context?.onBehalfOf?.userId) { + const del = await this.resolveDelegatorForContext(context); + if (del.kind === 'missing') return []; + if (del.kind === 'resolved') { + if (delegatedOrganizationRefusal(context, del.context, this.tenancyPosture) !== undefined) return []; + const delegatorSets = await this.resolvePermissionSetsForContext(del.context); + const delegatorPerms = this.foldFieldRequiredPermissions( + this.permissionEvaluator.getFieldPermissions(objectName, delegatorSets), + fieldRequiredPermissions, + delegatorSets, + ); + fieldPerms = intersectFieldMasks(fieldPerms, delegatorPerms); + } + } + + // 6. What a computed withheld field reads: every masked field counts as not + // served whole, and the live fields withheld through a reference too. + const hopWithheld = await this.resolveHopWithheldFields(secMeta, context, { fallbackOnEmptySets: true }); + const { withheld: notServed } = foldComputedFieldReads( + fieldPerms, + computedFieldInputs, + Object.keys(secMeta.fieldMaskingRules ?? {}), + hopWithheld, + ); + + return withheld.filter((name) => + fieldPerms[name]?.readable !== false && !notServed.has(name) && !readsThroughReference.has(name)); +} diff --git a/packages/plugins/plugin-security/src/security-plugin.ts b/packages/plugins/plugin-security/src/security-plugin.ts index 936fc6b83f3..34f99f645f6 100644 --- a/packages/plugins/plugin-security/src/security-plugin.ts +++ b/packages/plugins/plugin-security/src/security-plugin.ts @@ -185,6 +185,9 @@ import { resolveProjectionFieldMask, type FieldReadersHost, } from './security-plugin-field-readers.js'; +// [#34901] The metadata-plane answer for a disabled package's withheld fields +// (`WithheldFieldReadersHost`). +import { computeMetadataReadableWithheldFields, type WithheldFieldReadersHost } from './security-plugin-withheld-field-readers.js'; // [#25223 cut 9] The object-level admissions: read, read over resolved sets, // write and export; the methods of the same names below hand each body the // members it reads (`ObjectAdmissionHost`). @@ -2328,7 +2331,7 @@ export class SecurityPlugin implements Plugin { const readQl = () => this.ql; const readTenancyPosture = () => this.tenancyPosture; const readEpoch = () => this.epoch; - const host: Pick = { + const host: Pick = { acceptedDefaultPermissionSets: this.acceptedDefaultPermissionSets, baselinePermissionSets: this.baselinePermissionSets, bootstrapPermissionSets: this.bootstrapPermissionSets, @@ -2345,6 +2348,7 @@ export class SecurityPlugin implements Plugin { explainAccessForCaller: (...a) => this.explainAccessForCaller(...a), getEffectiveObjectPermissions: (...a) => this.getEffectiveObjectPermissions(...a), getMetadataReadableFields: (...a) => this.getMetadataReadableFields(...a), + getMetadataReadableWithheldFields: (...a) => this.getMetadataReadableWithheldFields(...a), getObjectSecurityMeta: (...a) => this.getObjectSecurityMeta(...a), getQueryableFields: (...a) => this.getQueryableFields(...a), getReadFilter: (...a) => this.getReadFilter(...a), @@ -3231,6 +3235,33 @@ export class SecurityPlugin implements Plugin { return this.computeReadableFields(object, context, { fallbackOnEmptySets: true }); } + /** + * [ADR-0106 D1/D7, #34901] The metadata-plane answer {@link getMetadataReadableFields} + * cannot give: which of the fields a disabled package withholds from + * `object`'s served schema may be disclosed to `context`, judged against + * each field's STORAGE definition by the same evaluator, sets, fallback, + * capability fold and delegator intersection. The object-schema projection + * drops every `_withheldFields` entry not named here. The body and its + * derivation are in `security-plugin-withheld-field-readers.ts`. + */ + async getMetadataReadableWithheldFields(object: string, context?: any): Promise { + const readPermissionEvaluator = () => this.permissionEvaluator; + const readQl = () => this.ql; + const readTenancyPosture = () => this.tenancyPosture; + const host: Pick = { + foldFieldRequiredPermissions: (...a) => this.foldFieldRequiredPermissions(...a), + get permissionEvaluator() { return readPermissionEvaluator(); }, + get ql() { return readQl(); }, + resolveCallerPosture: (...a) => this.resolveCallerPosture(...a), + resolveDelegatorForContext: (...a) => this.resolveDelegatorForContext(...a), + resolveFallbackPermissionSets: (...a) => this.resolveFallbackPermissionSets(...a), + resolveHopWithheldFields: (...a) => this.resolveHopWithheldFields(...a), + resolvePermissionSetsForContext: (...a) => this.resolvePermissionSetsForContext(...a), + get tenancyPosture() { return readTenancyPosture(); }, + }; + return computeMetadataReadableWithheldFields.call(host, object, context); + } + private computeReadableFields( object: string, context: any, From 5ed144f457b72efcb70bfbc420d455a062c3b1f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 00:56:50 +0000 Subject: [PATCH 11/15] fix(metadata-core): the object-schema projection drops withheld entries the caller may not read For a project-posture caller applyObjectSchemaMask keeps a _withheldFields entry only when the security service's getMetadataReadableWithheldFields admits it, and folds each dropped entry into the D3 fingerprint as withheld:NAME. An absent member, an undefined answer or a throw drops every entry (ADR-0106 D1, fail closed). The changeset names the member and adds metadata-core and plugin-security at patch. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .../34901-disabled-package-view-column.md | 5 +- .../src/object-schema-fls.test.ts | 90 ++++++++++- .../metadata-core/src/object-schema-fls.ts | 153 ++++++++++++++++-- 3 files changed, 233 insertions(+), 15 deletions(-) diff --git a/.changeset/34901-disabled-package-view-column.md b/.changeset/34901-disabled-package-view-column.md index 8f1183aabd3..2e8186c6c17 100644 --- a/.changeset/34901-disabled-package-view-column.md +++ b/.changeset/34901-disabled-package-view-column.md @@ -2,6 +2,8 @@ '@objectstack/objectql': patch '@objectstack/metadata-protocol': patch '@objectstack/spec': patch +'@objectstack/metadata-core': patch +'@objectstack/plugin-security': patch '@object-ui/core': patch '@object-ui/plugin-list': patch '@object-ui/plugin-grid': patch @@ -10,11 +12,12 @@ fix(objectql, metadata-protocol, console): a list view column on a field a disabled package adds no longer fails the whole list -Clause-②: yes (widening: the view save door accepts withheld names; one spec read-decoration member; one locale key) +Clause-②: yes (widening: the view save door accepts withheld names; one spec read-decoration member; one locale key; one optional security-service member, add-only) Metadata-protocol: none A package can add fields to another package's object. While that package is disabled, the platform leaves those fields out of the served object, and the data door refuses every request that names one (`400 INVALID_FIELD`, or `400 INVALID_SORT` for a sort). The owner's views still named the field, so a view with such a column, sort, filter, grouping level or searchable field failed for everyone. Saving the view (a rename, a pin, a Studio edit) was refused too (`422`, `list-view-field-unknown` / `sort-field-unknown`). - **The served object read names what is withheld.** `GET /api/v1/meta/object/:name` and the object list read carry `_withheldFields: { [field]: { packageId } }` when a disabled package withholds a field from the object. It is a read decoration (`METADATA_READ_DECORATIONS`), so the save door strips it, and the execution face and the layered editor read do not carry it. The registry gains `getWithheldExtensionFields(name)`. +- **A caller who may not read a withheld field is not told it exists.** The object-schema projection (ADR-0106) keeps a `_withheldFields` entry only for a caller the security service admits. `ISecurityService` gains an optional member, `getMetadataReadableWithheldFields(object, context)`, which answers the withheld names the caller may read; `@objectstack/plugin-security` implements it from each field's stored definition: the permission set's field entry, the field's own `requiredPermissions`, the fallback set for a caller with no set, and the on-behalf-of delegator. A security service without the member, an `undefined` answer or a throw drops every entry. Each dropped entry moves the caller's ETag, so two callers who are told different things never share a `304`. A caller exempt from the projection (a platform admin, a system context) is served every entry, as before. - **The view save door judges a view against the stored object.** A `view` write is judged against the object with every disabled package's extension folded in (the new fold option `includeDisabledExtensions`). A withheld field is a real stored field, so the view saves and keeps its column and sort. A misspelled field is still refused. Other writes are still judged against the served object, so a page or flow that names a withheld field is still refused while the package is off. A served view's `_diagnostics` is judged against the same stored object, so it no longer warns `list-view-field-unknown` or `form-field-unknown` on a withheld name the save door accepts; a misspelled field still warns. - **The console leaves withheld names out.** The list view and the grid leave a withheld field out of `$select`, `$filter`, `$orderby`, `$searchFields` and `groupBy`, and do not draw its column. A line above the rows names it (`list.withheldFieldsLeftOut`). Nothing is written to the view or to the user's list preferences, and a sort the user saves keeps the withheld entry. Once the package is enabled, the column, the sort and the grouping come back without any write. diff --git a/packages/metadata-core/src/object-schema-fls.test.ts b/packages/metadata-core/src/object-schema-fls.test.ts index 00ba0a1d01e..b643bfb179b 100644 --- a/packages/metadata-core/src/object-schema-fls.test.ts +++ b/packages/metadata-core/src/object-schema-fls.test.ts @@ -5,7 +5,7 @@ * per-exit contract suites consume rather than re-derive. */ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, vi } from 'vitest'; import { ObjectSchemaMaskEvaluationError, actionObjectOverrideTargets, @@ -721,3 +721,91 @@ describe('[decision 6840464379] an object whose owner declares a schemaReadDeleg expect(await bare.declaredDelegate('sys_request')).toBeUndefined(); }); }); + +describe('[ADR-0106 D1/D3, #34901] a disabled package\'s withheld fields, judged per caller', () => { + /** A served object read whose package-disabled extension withholds two fields. */ + const SERVED = { + name: 'deal', + label: 'Deal', + fields: { id: { type: 'text' }, amount: { type: 'number' } }, + _withheldFields: { crm_project: { packageId: 'com.acme.projects' }, crm_margin: { packageId: 'com.acme.projects' } }, + }; + const caller = { userId: 'u1', systemPermissions: [] as string[] }; + /** A service that reads every live field and admits `admitted` of the withheld ones. */ + const service = (admitted: string[] | undefined | (() => never)) => ({ + getMetadataReadableFields: async () => ['id', 'amount'], + getMetadataReadableWithheldFields: async () => (typeof admitted === 'function' ? admitted() : admitted), + }); + const servedTo = async (security: Record | undefined, context: unknown = caller, telemetry?: Record) => { + const posture = await resolveObjectSchemaMaskPosture({ objectName: 'deal', context, security: security as any, enabled: true, telemetry: telemetry as any }); + return applyObjectSchemaMask(SERVED, posture); + }; + + it('drops every entry the member does not admit, and the decoration with the last one', async () => { + const some = await servedTo(service(['crm_margin'])); + expect((some.document as any)._withheldFields).toEqual({ crm_margin: { packageId: 'com.acme.projects' } }); + expect(some.document).not.toBe(SERVED); + expect(SERVED._withheldFields, 'the cached document is never mutated').toHaveProperty('crm_project'); + const none = await servedTo(service([])); + expect('_withheldFields' in (none.document as object)).toBe(false); + // Nothing else moves: every live field, no denied field, not emptied. + expect(Object.keys((none.document as any).fields)).toEqual(['id', 'amount']); + expect({ denied: none.denied, emptied: none.emptied, hidden: none.hidden }).toEqual({ denied: [], emptied: false, hidden: false }); + }); + + it('an admitted caller is served the decoration whole, by reference, with no fingerprint', async () => { + const all = await servedTo(service(['crm_project', 'crm_margin'])); + expect(all.document).toBe(SERVED); + expect(all.fingerprint).toBe(''); + }); + + it('fails closed: a service without the member, an undefined answer and a throw each drop every entry', async () => { + const warn = vi.fn(); + const cases = { + 'member absent': { getMetadataReadableFields: async () => ['id', 'amount'] }, + 'undefined answer': service(undefined), + throws: service(() => { throw new Error('security service unhealthy (test)'); }), + }; + for (const [label, security] of Object.entries(cases)) { + const masked = await servedTo(security, caller, { warn }); + expect('_withheldFields' in (masked.document as object), label).toBe(false); + expect(Object.keys((masked.document as any).fields), label).toEqual(['id', 'amount']); + } + // A throw is no D6 fault — nothing the caller needs depends on it — and is said once, at warn. + expect(warn.mock.calls.filter(([, meta]) => meta?.decision === 'drop-withheld-fields')).toHaveLength(1); + }); + + it('a passthrough posture keeps the decoration: a D4-exempt caller, no security service, the D8 switch', async () => { + const admin = { userId: 'u_admin', systemPermissions: [OBJECT_SCHEMA_MASK_EXEMPT_CAPABILITIES[0]] }; + expect((await servedTo(service([]), admin)).document).toBe(SERVED); + expect((await servedTo(undefined)).document).toBe(SERVED); + const disabled = await resolveObjectSchemaMaskPosture({ objectName: 'deal', context: caller, security: service([]) as any, enabled: false }); + expect(applyObjectSchemaMask(SERVED, disabled).document).toBe(SERVED); + }); + + it('a project posture built without the answer drops every entry', () => { + const masked = applyObjectSchemaMask(SERVED, { kind: 'project', readable: new Set(['id', 'amount']) }); + expect('_withheldFields' in (masked.document as object)).toBe(false); + }); + + it('[D3] the ETag fingerprint differs between callers who see different withheld sets, and is equal for the same set', async () => { + const a = await servedTo(service([])); + const b = await servedTo(service(['crm_margin'])); + const c = await servedTo(service([])); + expect(a.fingerprint).not.toBe(''); + expect(a.fingerprint).not.toBe(b.fingerprint); + expect(a.fingerprint).toBe(c.fingerprint); + // Qualified: a dropped withheld entry never hashes equal to a removed field of the same name. + expect(a.fingerprint).not.toBe(objectFieldVisibilityFingerprint(['crm_margin', 'crm_project'])); + expect(foldVisibilityFingerprintIntoEtag('shared', a.fingerprint)).not.toBe(foldVisibilityFingerprintIntoEtag('shared', b.fingerprint)); + }); + + it('the member is asked once per posture, with the caller\'s context', async () => { + const ask = vi.fn(async () => ['crm_margin']); + await resolveObjectSchemaMaskPosture({ + objectName: 'deal', context: caller, enabled: true, + security: { getMetadataReadableFields: async () => ['id', 'amount'], getMetadataReadableWithheldFields: ask } as any, + }); + expect(ask.mock.calls).toEqual([['deal', caller]]); + }); +}); diff --git a/packages/metadata-core/src/object-schema-fls.ts b/packages/metadata-core/src/object-schema-fls.ts index ee87cc59a04..1541a6b7af5 100644 --- a/packages/metadata-core/src/object-schema-fls.ts +++ b/packages/metadata-core/src/object-schema-fls.ts @@ -49,7 +49,7 @@ * | masking disabled (D8 escape hatch) / no `security` service / exempt caller (D4) | `passthrough` | serve unmasked, byte-identical to pre-ADR | * | `getReadableFields` → `undefined` (field universe unresolvable) | `undetermined` | serve unmasked + structured warn + metric + `Cache-Control: private, no-store`, **no shared ETag** | * | `getReadableFields` throws | throws {@link ObjectSchemaMaskEvaluationError} | the exit answers 5xx — never the unmasked body, never an empty-fields 200 | - * | otherwise | `project` | fields ∉ readable are deleted whole, references included | + * | otherwise | `project` | fields ∉ readable are deleted whole, references included; a `_withheldFields` entry the caller may not read is dropped | * | `canReadObject` → not `true` (ruling record 6787890900) | `hidden` | left out of every list; a read answers as for a name that names no object | * | `canReadObject` → not `true`, the field posture is determined, and the object's declared `schemaReadDelegate` answers `true` (decision 6840464379) | the field posture | served as to a reader of the object: listed, and projected by the caller's own field security | * | the declared `schemaReadDelegate` throws (or its lookup does) | throws {@link ObjectSchemaMaskEvaluationError} | the exit answers 5xx — never a false "no such object" | @@ -75,8 +75,26 @@ * is the empty string and the ETag is byte-identical to today's; callers in one * permission cohort share 304s; a permission change moves the fingerprint and * self-invalidates the stale 304. + * + * ## A disabled package's withheld fields (#34901) + * + * A served object read names, in its `_withheldFields` read decoration, the + * fields a disabled package's `extend` contribution adds and the served fold + * leaves out. Those names are not in `fields`, so the readable projection + * never sees them: D1's "a field the caller cannot read does not exist for + * that caller" is kept by asking the security service's + * `getMetadataReadableWithheldFields` once per `project` posture, which judges + * each name against the field's STORAGE definition, and dropping every entry + * it does not admit. An absent member, an `undefined` answer and a throw all + * drop every entry (fail closed: the decoration is a client hint, never a + * field anyone needs). Each dropped entry folds `withheld:NAME` into the + * fingerprint, which no field name (snake_case) or `objectOverride` read + * (`object.field`) can collide with. A `passthrough` posture (D4-exempt + * caller, D8, no security service) and an `undetermined` one (D6 tier 2, + * served unmasked under `private, no-store`) keep the decoration as served. */ +import type { MetadataReadDecoration } from '@objectstack/spec/kernel'; import { maskDeniedFieldReferences, objectOverrideReads } from './object-schema-fls-references.js'; /** @@ -231,6 +249,16 @@ export type ObjectSchemaFieldPosture = * nothing. */ relate?: (objectName: string) => Promise | undefined>; + /** + * [#34901] The names of the document's `_withheldFields` read + * decoration this caller may be told about — the security service's + * `getMetadataReadableWithheldFields` answer, asked by + * {@link resolveObjectSchemaMaskPosture}. An entry not in it is + * dropped by {@link applyObjectSchemaMask}; absent (a posture built + * anywhere else, or a service that could not answer) drops every + * entry, which fails closed. + */ + withheldReadable?: ReadonlySet; }; /** @@ -365,6 +393,14 @@ export interface ObjectSchemaMaskSecuritySurface { * set. Preferred when present; exits fall back to `getReadableFields`. */ getMetadataReadableFields?(object: string, context?: unknown): Promise | string[] | undefined; + /** + * [ADR-0106 D1, #34901] Which of the fields a disabled package withholds + * from `object` (its served read's `_withheldFields` decoration) may be + * disclosed to the caller, judged against the STORAGE definition. Asked + * once per `project` posture. Absent, `undefined` or a throw: no entry is + * disclosed (fail closed). + */ + getMetadataReadableWithheldFields?(object: string, context?: unknown): Promise | string[] | undefined; /** * [ADR-0106, amended by ruling record 6787890900] The object-level read * admission — the data plane's own answer to "may this caller read this @@ -507,7 +543,10 @@ export async function resolveObjectSchemaMaskPosture(input: { const canRead = typeof security?.canReadObject === 'function' ? security.canReadObject.bind(security) : undefined; - const fields = await resolveFieldPosture(objectName, context, ask, telemetry); + const askWithheld = typeof security?.getMetadataReadableWithheldFields === 'function' + ? security.getMetadataReadableWithheldFields.bind(security) + : undefined; + const fields = await resolveFieldPosture(objectName, context, ask, telemetry, askWithheld); // [ruling record 6787890900] An object the caller may not read does not // exist for them on any schema-serving outlet. Decided HERE, once, so no @@ -635,6 +674,7 @@ async function resolveFieldPosture( context: unknown, ask: ((object: string, context?: unknown) => Promise | string[] | undefined) | undefined, telemetry: ObjectSchemaMaskTelemetry | undefined, + askWithheld?: (object: string, context?: unknown) => Promise | string[] | undefined, ): Promise { // D6 tier 1 — no FLS posture in this deployment at all. The data plane does // not mask either, so tightening the metadata plane alone would be theater. @@ -688,7 +728,79 @@ async function resolveFieldPosture( return new Set(answer); }; - return { kind: 'project', readable: new Set(readable), relate }; + const withheldReadable = await resolveWithheldReadable(objectName, context, askWithheld, telemetry); + return { kind: 'project', readable: new Set(readable), relate, withheldReadable }; +} + +/** + * [#34901] The `_withheldFields` entries a `project` caller may be told about: + * the security service's `getMetadataReadableWithheldFields` answer for this + * object. A service without the member, an answer that is not a list, and a + * throw all answer the empty set, so {@link applyObjectSchemaMask} drops every + * entry — fail closed, because the decoration is a client hint and serving it + * on a guess discloses a field's existence (ADR-0106 D1). Unlike the field + * question's D6 tiers, a fault here neither opens the document nor fails the + * request: nothing the caller needs depends on it. A throw is said at warn. + */ +async function resolveWithheldReadable( + objectName: string, + context: unknown, + askWithheld: ((object: string, context?: unknown) => Promise | string[] | undefined) | undefined, + telemetry: ObjectSchemaMaskTelemetry | undefined, +): Promise> { + if (!askWithheld) return NO_WITHHELD_READABLE; + let answer: string[] | undefined; + try { + answer = await askWithheld(objectName, context); + } catch (error) { + telemetry?.warn?.( + '[ADR-0106] the fields a disabled package withholds could not be judged for this caller — ' + + 'every `_withheldFields` entry is dropped from the served object', + { object: objectName, decision: 'drop-withheld-fields', error: String(error) }, + ); + return NO_WITHHELD_READABLE; + } + return Array.isArray(answer) ? new Set(answer.filter((name): name is string => typeof name === 'string')) : NO_WITHHELD_READABLE; +} + +/** The empty `withheldReadable` answer: no `_withheldFields` entry is disclosed. */ +const NO_WITHHELD_READABLE: ReadonlySet = new Set(); + +/** [#34901] The read decoration naming a disabled package's withheld fields, as `packages/spec` declares it. */ +const WITHHELD_FIELDS_DECORATION = '_withheldFields' satisfies MetadataReadDecoration; + +/** + * Qualifies a dropped `_withheldFields` entry in the D3 fingerprint. `:` occurs + * in no field or object machine name, so the entry can never hash equal to a + * field the mask removed (a bare name), an `objectOverride` read + * (`object.field`) or a runtime-view entry (`@runtime:NAME`). + */ +const WITHHELD_FINGERPRINT_QUALIFIER = 'withheld:'; + +/** + * [#34901] The `_withheldFields` entries of `rec` the posture does not admit, + * sorted. Empty when the document carries no such decoration (the one shape + * `packages/spec` declares is a record keyed by field name). + */ +function droppedWithheldFields(rec: Record, withheldReadable: ReadonlySet | undefined): string[] { + const withheld = rec[WITHHELD_FIELDS_DECORATION]; + if (!withheld || typeof withheld !== 'object' || Array.isArray(withheld)) return []; + return Object.keys(withheld).filter((name) => !withheldReadable?.has(name)).sort(); +} + +/** + * [#34901] `projected` with the `_withheldFields` entries in `dropped` removed, + * and the decoration removed entirely when none is left (a served read carries + * it only when something is withheld). Mutates `projected`, which is always a + * fresh copy of the served document. + */ +function dropWithheldFields(projected: Record, dropped: readonly string[]): void { + if (dropped.length === 0) return; + const withheld = projected[WITHHELD_FIELDS_DECORATION] as Record; + const drop = new Set(dropped); + const kept = Object.fromEntries(Object.entries(withheld).filter(([name]) => !drop.has(name))); + if (Object.keys(kept).length === 0) delete projected[WITHHELD_FIELDS_DECORATION]; + else projected[WITHHELD_FIELDS_DECORATION] = kept; } /** @@ -858,8 +970,9 @@ export interface ObjectSchemaMaskResult { /** Field names removed, sorted. Empty for an unrestricted caller. */ denied: readonly string[]; /** - * {@link objectFieldVisibilityFingerprint} over {@link denied} and the - * `objectOverride` reads withheld (as `object.field`, #21884); `''` when + * {@link objectFieldVisibilityFingerprint} over {@link denied}, the + * `objectOverride` reads withheld (as `object.field`, #21884) and the + * `_withheldFields` entries dropped (as `withheld:NAME`, #34901); `''` when * nothing was removed. */ fingerprint: string; @@ -925,7 +1038,12 @@ export function applyObjectSchemaMask(document: T, posture: ObjectSchemaMaskP const relatedDenied = [...new Set(objectOverrideReads(rec) .filter((read) => !posture.related?.get(read.object)?.has(read.field)) .map((read) => `${read.object}.${read.field}`))]; - if (denied.length === 0 && relatedDenied.length === 0) return unchanged; + // [#34901] The disabled-package fields the served read names and this + // caller may not be told about: not in `fields`, so judged apart (see the + // module header), and each one changes the served body as surely as a + // denied field does. + const withheldDropped = droppedWithheldFields(rec, posture.withheldReadable); + if (denied.length === 0 && relatedDenied.length === 0 && withheldDropped.length === 0) return unchanged; denied.sort(); const kept: Record = {}; @@ -936,17 +1054,26 @@ export function applyObjectSchemaMask(document: T, posture: ObjectSchemaMaskP // D1's "whole" covers the field's references too: a validation rule over it, // a role pointer naming it, a readable field's formula reading it, … — see // `object-schema-fls-references.ts` for every position and its disposition. - const projected = maskDeniedFieldReferences( - { ...rec, fields: kept }, - new Set(denied), - posture.related ?? new Map(), - ); + const projected = denied.length === 0 && relatedDenied.length === 0 + ? { ...rec } + : maskDeniedFieldReferences( + { ...rec, fields: kept }, + new Set(denied), + posture.related ?? new Map(), + ); + dropWithheldFields(projected as Record, withheldDropped); return { document: projected as unknown as T, denied, - fingerprint: objectFieldVisibilityFingerprint([...denied, ...relatedDenied]), - emptied: Object.keys(kept).length === 0, + fingerprint: objectFieldVisibilityFingerprint([ + ...denied, + ...relatedDenied, + ...withheldDropped.map((name) => `${WITHHELD_FINGERPRINT_QUALIFIER}${name}`), + ]), + // A copy made only to drop `_withheldFields` entries removed no field, + // so it cannot have emptied the schema, whatever `fields` holds. + emptied: (denied.length > 0 || relatedDenied.length > 0) && Object.keys(kept).length === 0, hidden: false, }; } From 865ff1799144599400035f676bb4498581c42dbc Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 00:56:50 +0000 Subject: [PATCH 12/15] test(rest, runtime): a disabled package's withheld field is served per caller on both transports Real protocol, registry and SecurityPlugin: denied by a permission set, denied by requiredPermissions and admitted, on the REST item read (cached and uncached), the REST list, the runtime item and list reads; the cached ETag differs between callers who see different withheld sets; a service without the member fails closed. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .../src/meta-disabled-package-doors.test.ts | 143 ++++++++++++++++++ .../meta-disabled-package-doors.test.ts | 132 ++++++++++++++++ 2 files changed, 275 insertions(+) diff --git a/packages/rest/src/meta-disabled-package-doors.test.ts b/packages/rest/src/meta-disabled-package-doors.test.ts index 20641b656bf..45e529d48e4 100644 --- a/packages/rest/src/meta-disabled-package-doors.test.ts +++ b/packages/rest/src/meta-disabled-package-doors.test.ts @@ -30,6 +30,8 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { SchemaRegistry } from '@objectstack/objectql'; import { createRegistryEmailTemplateLoader } from '@objectstack/plugin-email'; +// [#34901] Paid at collection, not inside a case's clock: the withheld-field pins boot the real plugin. +import { SecurityPlugin } from '@objectstack/plugin-security'; import { RestServer } from './rest-server.js'; const META = '/api/v1/meta'; @@ -1108,3 +1110,144 @@ describe('[#32814] RestServer: a pair row of a name only a disabled package hold expect([read.status, read.body?.error?.code], JSON.stringify(read.body)).toEqual([404, 'RESOURCE_NOT_FOUND']); }, 60_000); }); + +/** + * [ADR-0106 D1/D3/D5, #34901] The served object read names a disabled + * package's withheld fields in its `_withheldFields` read decoration; this + * door's projection keeps an entry only for a caller the security service's + * `getMetadataReadableWithheldFields` admits, judged against the field's + * STORAGE definition. Real protocol, real registry and the real + * `SecurityPlugin`'s registered service: package `PROJECTS` extends `m1_deal` + * with `m1_project`, guarded by the capability `view_projects`, and is + * disabled. FROM (the head before this fix): every caller was served the entry, + * both denied ones included. TO: only the admitted caller is. + */ +describe('[ADR-0106 D1/D3, #34901] RestServer: a disabled package\'s withheld field, per caller', () => { + const DEALS = 'com.qa.m1.deals'; + const PROJECTS = 'com.qa.m1.projects'; + const OBJECT = 'm1_deal'; + const set = (name: string, extra: Record = {}) => + ({ name, label: name, objects: { [OBJECT]: { allowRead: true } }, ...extra }); + const SETS = [ + set('member_default'), + set('deny_project', { systemPermissions: ['view_projects'], fields: { [`${OBJECT}.m1_project`]: { readable: false, editable: false } } }), + set('open'), + set('projects_viewer', { systemPermissions: ['view_projects'] }), + set('projects_viewer_too', { systemPermissions: ['view_projects'] }), + ]; + /** Denied by a permission set's `readable: false`; denied by the stored field's `requiredPermissions`; admitted (twice, for the 304 cohort). */ + const CALLERS: Record> = { + 'denied by a permission set': { userId: 'u_deny', positions: [], permissions: ['deny_project'] }, + 'denied by requiredPermissions': { userId: 'u_open', positions: [], permissions: ['open'] }, + admitted: { userId: 'u_viewer', positions: [], permissions: ['projects_viewer'] }, + 'admitted, another set': { userId: 'u_viewer2', positions: [], permissions: ['projects_viewer_too'] }, + }; + const WITHHELD = { m1_project: { packageId: PROJECTS } }; + + async function realSecurityService(registry: SchemaRegistry) { + // Where the plugin's catalog reads the sets once it binds to this registry at start. + for (const s of SETS) registry.registerItem('permission', s as any, 'name' as any); + const ql = { registerMiddleware: () => {}, getSchema: (n: string) => registry.getObject(n) ?? null, findOne: async () => null, registry }; + const metadata = { get: async (_t: string, n: string) => registry.getObject(n) ?? null, list: async () => SETS }; + const services: Record = { manifest: { register: vi.fn() }, objectql: ql, metadata }; + const registerService = vi.fn(); + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService, + getService: (n: string) => { if (!(n in services)) throw new Error(`no ${n}`); return services[n]; }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' } as any); + await plugin.init(ctx as any); + await plugin.start(ctx as any); + return registerService.mock.calls.find((c: unknown[]) => c[0] === 'security')?.[1] as Record; + } + + async function withheldHost(caller: Record, options: { cached?: boolean; dropMember?: boolean } = {}) { + const host = setup(undefined, caller); + host.registry.installPackage({ id: DEALS, name: DEALS, version: '1.0.0', type: 'app', namespace: 'm1' } as any, 'code'); + host.registry.installPackage({ id: PROJECTS, name: PROJECTS, version: '1.0.0', type: 'module', namespace: 'm1', dependencies: { [DEALS]: '^1.0.0' } } as any, 'code'); + host.registry.registerObject({ + name: OBJECT, label: 'Deal', + fields: { name: { name: 'name', type: 'text', label: 'Name' }, amount: { name: 'amount', type: 'number', label: 'Amount' } }, + } as any, DEALS, 'm1', 'own'); + host.registry.registerObject({ + name: OBJECT, + fields: { m1_project: { name: 'm1_project', type: 'text', label: 'Project', requiredPermissions: ['view_projects'] } }, + } as any, PROJECTS, 'm1', 'extend'); + host.registry.disablePackage(PROJECTS); + const security = await realSecurityService(host.registry); + const served = options.dropMember ? { ...security, getMetadataReadableWithheldFields: undefined } : security; + (host.rest as any).securityServiceProvider = async () => served; + if (options.cached === false) (host.protocol as any).getMetaItemCached = undefined; + const read = async (pattern: string, path: string, params: Record) => { + const route = host.rest.getRoutes().find((r: any) => r.method === 'GET' && r.path === `${META}${pattern}`); + if (!route) throw new Error(`GET ${pattern} is not registered`); + const res = makeRes(); + await route.handler({ method: 'GET', path: `${META}${path}`, params, query: {}, body: {}, headers: {} }, res); + return { status: res.statusCode, body: res.body, headers: res.headers as Record }; + }; + return { + item: () => read('/:type/:name', `/object/${OBJECT}`, { type: 'object', name: OBJECT }), + list: () => read('/:type', '/object', { type: 'object' }), + }; + } + const itemOf = (body: any) => body?.item ?? body?.data?.item ?? body; + const listed = (body: any) => { + const items: any[] = Array.isArray(body) ? body : body?.items ?? body?.data?.items ?? body?.data ?? []; + return items.find((i) => i?.name === OBJECT); + }; + + for (const cached of [true, false]) { + it(`the item read (${cached ? 'cached' : 'uncached'}): only the admitted caller is told the field is withheld`, async () => { + const seen: Record = {}; + for (const [label, caller] of Object.entries(CALLERS)) { + const answer = await (await withheldHost(caller, { cached })).item(); + expect(answer.status, label).toBe(200); + expect(Object.keys(itemOf(answer.body)?.fields ?? {}), label).toContain('amount'); + seen[label] = itemOf(answer.body)?._withheldFields ?? null; + } + expect(seen).toEqual({ + 'denied by a permission set': null, + 'denied by requiredPermissions': null, + admitted: WITHHELD, + 'admitted, another set': WITHHELD, + }); + }, 60_000); + } + + it('the object list read: only the admitted caller is told the field is withheld', async () => { + const seen: Record = {}; + for (const [label, caller] of Object.entries(CALLERS)) { + const answer = await (await withheldHost(caller)).list(); + expect(answer.status, label).toBe(200); + seen[label] = listed(answer.body)?._withheldFields ?? null; + } + expect(seen).toEqual({ + 'denied by a permission set': null, + 'denied by requiredPermissions': null, + admitted: WITHHELD, + 'admitted, another set': WITHHELD, + }); + }, 60_000); + + it('[D3] the cached read\'s ETag differs between callers who see different withheld sets, and is equal for the same set', async () => { + const etag: Record = {}; + for (const [label, caller] of Object.entries(CALLERS)) { + etag[label] = (await (await withheldHost(caller)).item()).headers.ETag; + } + expect(etag.admitted).toBeTruthy(); + expect(etag['denied by a permission set']).not.toBe(etag.admitted); + expect(etag['denied by a permission set']).toBe(etag['denied by requiredPermissions']); + expect(etag.admitted).toBe(etag['admitted, another set']); + }, 60_000); + + it('fails closed: a security service without the member drops the entry for every caller, the admitted one included', async () => { + for (const [label, caller] of Object.entries(CALLERS)) { + const host = await withheldHost(caller, { dropMember: true }); + const item = await host.item(); + expect(item.status, label).toBe(200); + expect(itemOf(item.body)?._withheldFields, label).toBeUndefined(); + expect(listed((await host.list()).body)?._withheldFields, label).toBeUndefined(); + } + }, 60_000); +}); diff --git a/packages/runtime/src/domains/meta-disabled-package-doors.test.ts b/packages/runtime/src/domains/meta-disabled-package-doors.test.ts index a9eabcfc56c..67a531d2953 100644 --- a/packages/runtime/src/domains/meta-disabled-package-doors.test.ts +++ b/packages/runtime/src/domains/meta-disabled-package-doors.test.ts @@ -29,6 +29,10 @@ import { describe, it, expect, vi } from 'vitest'; import { HttpDispatcher } from '../http-dispatcher.js'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SchemaRegistry } from '@objectstack/objectql'; +// [#34901] Paid at collection, not inside a case's clock: the withheld-field pins boot the real plugin. +import { SecurityPlugin } from '@objectstack/plugin-security'; // Paid at collection, not inside a case's clock: the dispatcher's reach loads it lazily. import '@objectstack/metadata'; @@ -408,3 +412,131 @@ describe('[ruling record 6787890900] the dispatcher: an object the caller may no }); } }); + +/** + * [ADR-0106 D1/D5, #34901] The dispatcher's `/metadata` object read and list + * read, over the real protocol, the real registry and the real + * `SecurityPlugin`'s registered service: the served object names a disabled + * package's withheld field in `_withheldFields`, and the projection keeps the + * entry only for a caller `getMetadataReadableWithheldFields` admits, judged + * against the field's STORAGE definition. Package `PROJECTS` extends `m1_deal` + * with `m1_project`, guarded by the capability `view_projects`, and is + * disabled. FROM (the head before this fix): every caller was served the + * entry. TO: only the admitted caller is. + */ +describe('[ADR-0106 D1, #34901] the dispatcher: a disabled package\'s withheld field, per caller', () => { + const DEALS = 'com.qa.m1.deals'; + const PROJECTS = 'com.qa.m1.projects'; + const OBJECT = 'm1_deal'; + const set = (name: string, extra: Record = {}) => + ({ name, label: name, objects: { [OBJECT]: { allowRead: true } }, ...extra }); + const SETS = [ + set('member_default'), + set('deny_project', { systemPermissions: ['view_projects'], fields: { [`${OBJECT}.m1_project`]: { readable: false, editable: false } } }), + set('open'), + set('projects_viewer', { systemPermissions: ['view_projects'] }), + ]; + const CALLERS: Record> = { + 'denied by a permission set': { userId: 'u_deny', positions: [], permissions: ['deny_project'] }, + 'denied by requiredPermissions': { userId: 'u_open', positions: [], permissions: ['open'] }, + admitted: { userId: 'u_viewer', positions: [], permissions: ['projects_viewer'] }, + }; + const WITHHELD = { m1_project: { packageId: PROJECTS } }; + + async function withheldStack(options: { dropMember?: boolean } = {}) { + const registry = new SchemaRegistry({ multiTenant: false }); + (registry as any).logLevel = 'silent'; + registry.installPackage({ id: DEALS, name: DEALS, version: '1.0.0', type: 'app', namespace: 'm1' } as any, 'code'); + registry.installPackage({ id: PROJECTS, name: PROJECTS, version: '1.0.0', type: 'module', namespace: 'm1', dependencies: { [DEALS]: '^1.0.0' } } as any, 'code'); + registry.registerObject({ + name: OBJECT, label: 'Deal', + fields: { name: { name: 'name', type: 'text', label: 'Name' }, amount: { name: 'amount', type: 'number', label: 'Amount' } }, + } as any, DEALS, 'm1', 'own'); + registry.registerObject({ + name: OBJECT, + fields: { m1_project: { name: 'm1_project', type: 'text', label: 'Project', requiredPermissions: ['view_projects'] } }, + } as any, PROJECTS, 'm1', 'extend'); + registry.disablePackage(PROJECTS); + // Where the plugin's catalog reads the sets once it binds to this registry at start. + for (const s of SETS) registry.registerItem('permission', s as any, 'name' as any); + // No stored row in this stack: every read is served from the registry. + const engine: any = { + registry, + findOne: async () => null, + find: async () => [], + insert: async () => ({ id: null }), + update: async () => ({ id: null }), + delete: async () => ({ deleted: 0 }), + syncObjectSchema: async () => {}, + }; + const protocol = new ObjectStackProtocolImplementation(engine, undefined, 'env_test'); + + const ql = { registerMiddleware: () => {}, getSchema: (n: string) => registry.getObject(n) ?? null, findOne: async () => null, registry }; + const metadataForPlugin = { get: async (_t: string, n: string) => registry.getObject(n) ?? null, list: async () => SETS }; + const pluginServices: Record = { manifest: { register: vi.fn() }, objectql: ql, metadata: metadataForPlugin }; + const registerService = vi.fn(); + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' } as any); + const pluginCtx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService, + getService: (n: string) => { if (!(n in pluginServices)) throw new Error(`no ${n}`); return pluginServices[n]; }, + }; + await plugin.init(pluginCtx as any); + await plugin.start(pluginCtx as any); + const security = registerService.mock.calls.find((c: unknown[]) => c[0] === 'security')?.[1] as Record; + + const services: Record = { + protocol, + objectql: { registry }, + security: options.dropMember ? { ...security, getMetadataReadableWithheldFields: undefined } : security, + }; + const get = (n: string) => services[n] ?? null; + const kernel = { context: { getService: get }, getService: get, getServiceAsync: async (n: string) => get(n) } as any; + const dispatcher = new HttpDispatcher(kernel, undefined, { enforceProjectMembership: false }); + const read = async (path: string, caller: Record) => { + const res = await dispatcher.handleMetadata( + path, { request: { headers: {} }, environmentId: 'platform', executionContext: { ...caller } } as any, 'GET', + ); + return { status: res.response?.status, body: res.response?.body as any }; + }; + return { + item: async (caller: Record) => { + const { status, body } = await read(`/object/${OBJECT}`, caller); + return { status, document: body?.data?.item ?? body?.data }; + }, + list: async (caller: Record) => { + const { status, body } = await read('/object', caller); + const items: any[] = body?.data?.items ?? body?.data ?? []; + return { status, document: (Array.isArray(items) ? items : []).find((i: any) => i?.name === OBJECT) }; + }, + }; + } + + it('the object read and the list read: only the admitted caller is told the field is withheld', async () => { + const stack = await withheldStack(); + const seen: Record = {}; + for (const [label, caller] of Object.entries(CALLERS)) { + const item = await stack.item(caller); + const listed = await stack.list(caller); + expect([item.status, listed.status], label).toEqual([200, 200]); + expect(Object.keys(item.document?.fields ?? {}), label).toContain('amount'); + expect(listed.document, `${label}: the object is listed`).toBeDefined(); + seen[label] = { item: item.document?._withheldFields ?? null, list: listed.document?._withheldFields ?? null }; + } + expect(seen).toEqual({ + 'denied by a permission set': { item: null, list: null }, + 'denied by requiredPermissions': { item: null, list: null }, + admitted: { item: WITHHELD, list: WITHHELD }, + }); + }, 60_000); + + it('fails closed: a security service without the member drops the entry for every caller, the admitted one included', async () => { + const stack = await withheldStack({ dropMember: true }); + for (const [label, caller] of Object.entries(CALLERS)) { + const item = await stack.item(caller); + expect(item.status, label).toBe(200); + expect(item.document?._withheldFields, label).toBeUndefined(); + expect((await stack.list(caller)).document?._withheldFields, label).toBeUndefined(); + } + }, 60_000); +}); From 74073018f054f5fb10a06ff366fe8c7c8f03575a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:13:54 +0000 Subject: [PATCH 13/15] test: the withheld-field doubles route through the engine contract helpers The runtime engine double's findOne, update and delete, and the ql doubles of the plugin-security, REST and runtime harnesses, open with the shared assertEngine* predicates; the pinned ledger records the new coverage. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- ...-metadata-readable-withheld-fields.test.ts | 4 ++-- .../src/meta-disabled-package-doors.test.ts | 7 +++++- .../meta-disabled-package-doors.test.ts | 15 ++++++++----- scripts/engine-double-contract.pinned.json | 22 ++++++++++++++++++- 4 files changed, 39 insertions(+), 9 deletions(-) diff --git a/packages/plugins/plugin-security/src/get-metadata-readable-withheld-fields.test.ts b/packages/plugins/plugin-security/src/get-metadata-readable-withheld-fields.test.ts index 0e1a553990b..78640609a8d 100644 --- a/packages/plugins/plugin-security/src/get-metadata-readable-withheld-fields.test.ts +++ b/packages/plugins/plugin-security/src/get-metadata-readable-withheld-fields.test.ts @@ -18,7 +18,7 @@ */ import { describe, it, expect, vi } from 'vitest'; -import { SchemaRegistry } from '@objectstack/objectql'; +import { SchemaRegistry, assertEngineFindOnePredicate } from '@objectstack/objectql'; import type { PermissionSet } from '@objectstack/spec/security'; import { SecurityPlugin } from './security-plugin.js'; @@ -76,7 +76,7 @@ async function boot(options: { registry?: unknown; sets?: PermissionSet[] } = {} const ql: any = { registerMiddleware: () => {}, getSchema: (name: string) => (registry as any)?.getObject?.(name) ?? null, - findOne: async () => null, + findOne: async (object: string, query?: any) => { assertEngineFindOnePredicate(object, query); return null; }, registry, }; const metadata: any = { diff --git a/packages/rest/src/meta-disabled-package-doors.test.ts b/packages/rest/src/meta-disabled-package-doors.test.ts index 45e529d48e4..3daa5a0107c 100644 --- a/packages/rest/src/meta-disabled-package-doors.test.ts +++ b/packages/rest/src/meta-disabled-package-doors.test.ts @@ -1147,7 +1147,12 @@ describe('[ADR-0106 D1/D3, #34901] RestServer: a disabled package\'s withheld fi async function realSecurityService(registry: SchemaRegistry) { // Where the plugin's catalog reads the sets once it binds to this registry at start. for (const s of SETS) registry.registerItem('permission', s as any, 'name' as any); - const ql = { registerMiddleware: () => {}, getSchema: (n: string) => registry.getObject(n) ?? null, findOne: async () => null, registry }; + const ql = { + registerMiddleware: () => {}, + getSchema: (n: string) => registry.getObject(n) ?? null, + findOne: async (object: string, query?: any) => { assertEngineFindOnePredicate(object, query); return null; }, + registry, + }; const metadata = { get: async (_t: string, n: string) => registry.getObject(n) ?? null, list: async () => SETS }; const services: Record = { manifest: { register: vi.fn() }, objectql: ql, metadata }; const registerService = vi.fn(); diff --git a/packages/runtime/src/domains/meta-disabled-package-doors.test.ts b/packages/runtime/src/domains/meta-disabled-package-doors.test.ts index 67a531d2953..d3f77ad755d 100644 --- a/packages/runtime/src/domains/meta-disabled-package-doors.test.ts +++ b/packages/runtime/src/domains/meta-disabled-package-doors.test.ts @@ -30,7 +30,7 @@ import { describe, it, expect, vi } from 'vitest'; import { HttpDispatcher } from '../http-dispatcher.js'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; -import { SchemaRegistry } from '@objectstack/objectql'; +import { SchemaRegistry, assertEngineDeleteDispatch, assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/objectql'; // [#34901] Paid at collection, not inside a case's clock: the withheld-field pins boot the real plugin. import { SecurityPlugin } from '@objectstack/plugin-security'; // Paid at collection, not inside a case's clock: the dispatcher's reach loads it lazily. @@ -462,16 +462,21 @@ describe('[ADR-0106 D1, #34901] the dispatcher: a disabled package\'s withheld f // No stored row in this stack: every read is served from the registry. const engine: any = { registry, - findOne: async () => null, + findOne: async (object: string, query?: any) => { assertEngineFindOnePredicate(object, query); return null; }, find: async () => [], insert: async () => ({ id: null }), - update: async () => ({ id: null }), - delete: async () => ({ deleted: 0 }), + update: async (_object: string, data: any, options?: any) => { assertEngineUpdateDispatch(data, options); return { id: null }; }, + delete: async (_object: string, options?: any) => { assertEngineDeleteDispatch(options); return { deleted: 0 }; }, syncObjectSchema: async () => {}, }; const protocol = new ObjectStackProtocolImplementation(engine, undefined, 'env_test'); - const ql = { registerMiddleware: () => {}, getSchema: (n: string) => registry.getObject(n) ?? null, findOne: async () => null, registry }; + const ql = { + registerMiddleware: () => {}, + getSchema: (n: string) => registry.getObject(n) ?? null, + findOne: async (object: string, query?: any) => { assertEngineFindOnePredicate(object, query); return null; }, + registry, + }; const metadataForPlugin = { get: async (_t: string, n: string) => registry.getObject(n) ?? null, list: async () => SETS }; const pluginServices: Record = { manifest: { register: vi.fn() }, objectql: ql, metadata: metadataForPlugin }; const registerService = vi.fn(); diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index c78b258b2a5..fefab8f2dac 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -4446,6 +4446,11 @@ "verb": "findOne", "pinned": 2 }, + { + "file": "packages/plugins/plugin-security/src/get-metadata-readable-withheld-fields.test.ts", + "verb": "findOne", + "pinned": 1 + }, { "file": "packages/plugins/plugin-security/src/get-queryable-fields.test.ts", "verb": "findOne", @@ -4984,7 +4989,7 @@ { "file": "packages/rest/src/meta-disabled-package-doors.test.ts", "verb": "findOne", - "pinned": 1 + "pinned": 2 }, { "file": "packages/rest/src/meta-disabled-package-doors.test.ts", @@ -5286,6 +5291,21 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/runtime/src/domains/meta-disabled-package-doors.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/runtime/src/domains/meta-disabled-package-doors.test.ts", + "verb": "findOne", + "pinned": 2 + }, + { + "file": "packages/runtime/src/domains/meta-disabled-package-doors.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/runtime/src/domains/meta-published-runtime-publish.test.ts", "verb": "delete", From 24d71a88271cdab0dbfc5d82934550b6c832eec9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:13:54 +0000 Subject: [PATCH 14/15] docs(permissions): the system-context census names the withheld-field reader's bypass Row 4 (field-level security returns all fields) gains computeMetadataReadableWithheldFields: a system context is told every withheld name. The site register is regenerated. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- content/docs/permissions/system-context.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index c434d7b58e9..d221ce0be0b 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -103,7 +103,7 @@ bugs — it is the protection or the side effect that silently does not happen. | 1b | **App-authored automation's system context is REFUSED governed writes to the identity-assignment objects** — a flow run's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and an action body's; checked ahead of the middleware's short-circuit, beside the append-only refusal (`assertAppAutomationAppendOnlyWriteAllowed`) | plugin-security | Get: nothing — an insert, update, delete, transfer, restore or purge of `sys_user_position`, `sys_user_permission_set`, `sys_invitation` or `sys_member` from a context carrying `isSystem` and either a `flowRunId` (a `runAs: 'system'` flow's data nodes) or the app-automation elevation mark (`@objectstack/core`; set only by a hook's `runAs: 'system'` derivation, by the action body's execution-context builder and `ObjectRepository.execute`, and on the api of a hook bound through the hook binder, whose inherited system context and `sudo()` it marks), at any depth of their writes, is refused `PERMISSION_DENIED` before the short-circuit skips the ADR-0090 D12 gate and the identity write guard. Lose: nothing a platform writer held — a system context with neither (the seeders, better-auth and its reconciliation, invitation placement, platform code's `sudo()`, which never sets the mark, and a hook registered in code) passes on to the short-circuit unchanged, reads are not judged, and a `runAs: 'user'` flow or hook carries no `isSystem`, so the D12 gate judges it as the user it acts for | `elevationSource`, `appAuthoredHookApi` | | 2 | **`owner_id` is not auto-stamped on INSERT** (the step 3.5 anchor guard is inside the block row 1 skips) — except an action body's insert | plugin-security | Lose: the row lands `owner_id = NULL`, so the default `owner_only_writes` policy hides it **from its own creator**. Get: nothing — this is a gap, not a capability. Except an action body's: an insert from a context carrying `isSystem` and the `'action'` app-automation elevation mark, with no `flowRunId`, has every EMPTY `owner_id` stamped with the envelope's own `userId` ahead of the short-circuit, by the same stamp step 3.5 applies (nothing for the guest; an owner the body sets is kept; an `owner_id` supplied empty beside a supplied queue parks the row). Like a direct create, such an insert is the invoker's own record, so assignment rules (ADR-0142 D5), which route only a row whose owner and queue are both still empty, route neither; a body has no spelling today that asks a rule to route its row. The mark is set on every handler an action door dispatches (a host code action handler included) and by `ObjectRepository.execute`. A flow run, a hook's `runAs: 'system'`, the seeders and every other system context still land the owner they write, or none, and an unowned, queue-less one is still routed | the step 3.5 guard block and the short-circuit that skips it are both inside `registerAuthzMiddleware`; the action-body exception is `isActionBodyElevation` | | 3 | Row-level read filter resolves to "no filter" | plugin-security | Get: unscoped reads. Lose: row-level scoping entirely | `getReadFilter` | -| 4 | Field-level security returns **all** fields | plugin-security | Get: every column readable (`getReadableFields`) and writable (`getWritableFields`). Lose: field masking | `resolveProjectionFieldMask` | +| 4 | Field-level security returns **all** fields | plugin-security | Get: every column readable (`getReadableFields`) and writable (`getWritableFields`), and every field a disabled package withholds named to it (`getMetadataReadableWithheldFields`, so the served object's `_withheldFields` keeps every entry). Lose: field masking | `resolveProjectionFieldMask`, `computeMetadataReadableWithheldFields` | | 5 | Export permission granted unconditionally | plugin-security | Get: `canExport` is `true` | `canExport` | | 6 | Object-level read admission granted unconditionally | plugin-security | Get: `canReadObject` is `true`. This is the OBJECT-level half of a read — "may this caller read this object at all" — which the doors that bypass this middleware ask before they compile a statement of their own; `getReadFilter` is its row-level half, and the two are not interchangeable | `canReadObject` | | 6b | WRITE admission granted unconditionally | plugin-security | Get: `canWriteObject` is `true`. The WRITE twin of the object-level read admission above, asked by the write PREVIEW (`ObjectQL.validate()`), which runs no middleware for its target object and so has no gate of its own. It exists because a validation rule that reads one hop through a reference field is evaluated against a related row fetched under system authority, and that elevation is bounded to the arms the question RUNS — named, ⛔ never a category of the write decision, and ⛔ not a promise the write would succeed. The arms: the ADR-0103 engine-owned affordance gate and the ADR-0090 D12 delegated-admin gate (both ahead of every resolution), the fail-closed postures (#3545's unresolvable posture, the D10 dangling delegator and, on a walled posture, the D10 delegator who is not a member of the organization the request runs in), the ADR-0066 D3 capability arm, the CRUD grant, the ADR-0090 D10 delegator arm that a bare CRUD-grant check misses, the field-level-security write gate over the caller's payload when one is supplied, and the ADR-0123 D2 no-active-organization wall | `canWriteObject` | @@ -617,6 +617,7 @@ and CI refuses one that differs from what the tree produces. | `packages/plugins/plugin-security/src/security-plugin-object-admission.ts#canWriteObject` | 1 | 6b | | `packages/plugins/plugin-security/src/security-plugin-read-filter.ts#getReadFilter` | 1 | 3 | | `packages/plugins/plugin-security/src/security-plugin-security-service.ts#registerSecurityService` | 3 | 7 | +| `packages/plugins/plugin-security/src/security-plugin-withheld-field-readers.ts#computeMetadataReadableWithheldFields` | 1 | 4 | | `packages/plugins/plugin-security/src/security-plugin-write-tenant-wall.ts#writeWallVerdict` | 1 | 6c | | `packages/plugins/plugin-security/src/stored-permission-set-package-stamp.ts#holderLeftToEngine` | 1 | 23h | | `packages/plugins/plugin-security/src/stored-permission-set-package-stamp.ts#onUpdate` | 1 | 23h | From 610ee495e41136cb48ef3ef8489ddc9b7d61f9e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:20:38 +0000 Subject: [PATCH 15/15] test(plugin-security): the delegator census counts the withheld-field reader security-plugin-withheld-field-readers.ts resolves one delegator and asks the organization refusal once, so the enumeration pin lists eight files. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzg2evNa1V3zxrQq3KX --- .../src/delegated-organization-membership.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-security/src/delegated-organization-membership.test.ts b/packages/plugins/plugin-security/src/delegated-organization-membership.test.ts index d5d987a5bd1..41d2f84de75 100644 --- a/packages/plugins/plugin-security/src/delegated-organization-membership.test.ts +++ b/packages/plugins/plugin-security/src/delegated-organization-membership.test.ts @@ -855,7 +855,7 @@ describe('[#25107] every reader in this package that resolves a delegator asks t const MEMO_FILE = 'security-plugin.ts'; const memoAsks = (text: string) => (text.match(/\bthis\.resolveDelegatorForContext\(context\b/g) ?? []).length; - it('per source file, the asks equal the resolutions — and the seven files that resolve one are all counted', () => { + it('per source file, the asks equal the resolutions — and the eight files that resolve one are all counted', () => { const counted: Record = {}; for (const file of readdirSync(SRC, { recursive: true }) as string[]) { if (!file.endsWith('.ts') || file.endsWith('.test.ts') || file.includes('.testkit.')) continue; @@ -876,6 +876,7 @@ describe('[#25107] every reader in this package that resolves a delegator asks t 'security-plugin-operation-principals.ts', 'security-plugin-read-filter.ts', 'security-plugin-security-service.ts', + 'security-plugin-withheld-field-readers.ts', ]); for (const [file, [resolutions, asks]] of Object.entries(counted)) expect(asks, file).toBe(resolutions); });