From c2d7c39fce9bbe82556b7acdfb30ae4bddaa168d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:56:30 +0000 Subject: [PATCH 01/11] fix(metadata-protocol): keep each package's stored permission set in its own registry slot A stored permission row bound to a package now takes that package's overlay slot and wears only its own package's envelope, so two namespaces' stored sets of one name are two sets. The save door judges a stored holder by the one namespace predicate, and the remedy names steps the writer can take. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- .../src/protocol-registry-hydration.ts | 53 ++++++++++++++++--- .../src/protocol-save-door-refusals.ts | 43 ++++++++------- 2 files changed, 70 insertions(+), 26 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-registry-hydration.ts b/packages/metadata-protocol/src/protocol-registry-hydration.ts index 4f9d7c44397..b53e652e8f8 100644 --- a/packages/metadata-protocol/src/protocol-registry-hydration.ts +++ b/packages/metadata-protocol/src/protocol-registry-hydration.ts @@ -194,7 +194,11 @@ function soleHolderOf(registry: { packageScopedHoldersOf?(type: string, name: st * - a `permission`: a stored fork of a shipped permission set keeps the * disposition of its own maintainer ruling (detection, never a silent * change of the grants the deployment enforces; see - * `isUnservedSealedOverlay`). + * `isUnservedSealedOverlay`). A row of a package that holds no set of the + * name is that package's own set (ADR-0150 D2): it wears no other + * package's envelope ({@link ownPermissionEnvelope}) and takes its own + * package's slot ({@link takesPackageOverlaySlot}), so it is never a + * holder's item to decline. */ function judgesRowHolder(canonicalType: string): boolean { return canonicalType !== 'flow' && canonicalType !== 'permission' && !BORROWED_ENVELOPE_DECLINED_TYPES.has(canonicalType); @@ -249,12 +253,42 @@ function namesNoHolderAmongMany( * * ⛔ Not a `flow`: the name's one bare slot keeps the shipping package's * declared override over any other row ({@link incomingTakesStoredFlowSlot}, - * #28717), which the boot pull reads. ⛔ Not a `permission`: a stored fork of - * a shipped permission set keeps the disposition of its own maintainer ruling - * (see {@link judgesRowHolder}). A package-less row keeps the bare slot. + * #28717), which the boot pull reads. A package-less row keeps the bare slot. + * + * A `permission` takes its package's slot too (ADR-0150 D2/D3 "security + * catalog: permission sets by (package, name)"): a set is `(package, name)`, so + * two namespaces' stored sets of one name are two sets, each served at its own + * package and each retired by its own delete, in every boot read order. With + * the one bare slot the set stored last took the other package's place, so the + * save door had to refuse a second namespace's stored set. Its envelope is its + * own package's ({@link ownPermissionEnvelope}). */ function takesPackageOverlaySlot(canonicalType: string): boolean { - return PACKAGE_SLOTTED_STORE_TYPES.has(canonicalType) && canonicalType !== 'flow' && canonicalType !== 'permission'; + return PACKAGE_SLOTTED_STORE_TYPES.has(canonicalType) && canonicalType !== 'flow'; +} + +/** + * [ADR-0150 D2/D4] The artifact whose envelope a stored `permission` row bound + * to `bound` wears: `artifact` only when it is the row's own package's set, or + * the set of the base whose customization pair `bound` is (ADR-0146). The + * artifact lookup scoped to a package that ships no set of the name falls back + * to the first package that does, so a set stored by a package of another + * namespace wore that package's envelope (`_packageId`, `_provenance: + * 'package'`): the registry bound it to that package, whose grants then + * conferred the stored body, and the lock read the stored set as shipped. + * Without an envelope it registers as the tenant-authored set it is, bound to + * its own package. Any other type, or a package-less row, keeps `artifact`. + */ +function ownPermissionEnvelope( + registry: InstalledPackageSource, + canonicalType: string, + bound: string | undefined, + artifact: unknown, +): unknown { + if (canonicalType !== 'permission' || bound === undefined || artifact === undefined || artifact === null) return artifact; + const shipper = (artifact as { _packageId?: unknown })._packageId; + if (shipper === bound) return artifact; + return typeof shipper === 'string' && isPairOf(bound, shipper, installedManifestsOf(registry)) ? artifact : undefined; } /** {@link pairRowEnvelopeHolder}'s answer for a row that is not a customization pair's row of a two-holder name. */ @@ -871,9 +905,12 @@ export class ProtocolRegistryHydrationFacet { const envelopePackage = pairHolder !== NOT_A_PAIR_ROW ? pairHolder : options.packageId ?? (scoped ? soleHolderOf(registry, canonicalType, rowName) : undefined); - const artifact = envelopePackage === null ? undefined : host.lookupArtifactItem( + // [ADR-0150 D2] A stored permission row wears its own package's + // envelope only ({@link ownPermissionEnvelope}), never the envelope of + // another namespace's set the lookup falls back to. + const artifact = envelopePackage === null ? undefined : ownPermissionEnvelope(registry, canonicalType, boundPackageOf(options.packageId), host.lookupArtifactItem( type, (data as any).name, envelopePackage ?? undefined, bundleMemberOf(type, data), - ); + )); // [#29600] See the header: a dashboard, report or email-template row // bound to a package that ships no artifact of its name, under a name // another package ships, is not registered under the bare name, where @@ -1926,7 +1963,7 @@ export class ProtocolRegistryHydrationFacet { // where the pair relation names zero or several bases: the only // refusal {@link readHealBaseline} lets through for a bound row. // Its entry sits in the bare slot for a type with no package - // overlay slot (`flow`, `permission`), where it kept serving the + // overlay slot (`flow`; a `permission` until it took its own), where it kept serving the // deleted body to the non-holder's read and stood as a refused // holder read's candidate. Retiring it picks nobody and restores // each holder's exact address (entry kept → retired). diff --git a/packages/metadata-protocol/src/protocol-save-door-refusals.ts b/packages/metadata-protocol/src/protocol-save-door-refusals.ts index 5613f547913..48173add5f9 100644 --- a/packages/metadata-protocol/src/protocol-save-door-refusals.ts +++ b/packages/metadata-protocol/src/protocol-save-door-refusals.ts @@ -357,9 +357,10 @@ function registryPackageHoldersOf(registry: unknown, name: string): readonly str * set of a name ACTIVE under an owner other than a holder it meets is refused * here, with nothing written — a package never writes into a record another * owns (ADR-0086 D4). The environment meets every holder, as before. A set - * another package STORES meets every writer too: the registry keeps one entry - * per stored set of a name, so two stored sets of one name are not yet kept - * apart there (#31698), and a second one stays refused. + * another package STORES is judged by the same predicate as a shipped one: the + * registry keeps each package's stored set of a name in that package's own + * slot (the hydrator's package overlay slot, ADR-0150 D2/D4), so a second + * namespace's stored set lands beside the first, each served at its package. * * ## The owner * @@ -375,9 +376,9 @@ function registryPackageHoldersOf(registry: unknown, name: string): readonly str * ## The holders: two readings, met * * - **The stored active rows** of the environment (ADR-0131 D6), by - * `package_id`. A set published through the metadata door is stored, and - * the registry holds it in the bare slot with no package (hydration and the - * write-through register a stored row without one), so only the row says + * ``package_id`. A set published through the metadata door is stored, and + * the registry holds it in its package's overlay slot, which the + * registry's package-held reading does not count, so only the row says * which package it belongs to — the half the registry's reading cannot see, * and why this door's reading is wider than the cold boot's. * - **The registry's package half** ({@link registryPackageHoldersOf}): a set @@ -444,18 +445,17 @@ export async function permissionSetNameCollisionRefusal( // holder the writing package does not meet under the ONE predicate the // install gate asks ({@link permissionSetHoldersMeet}) holds its own set of // the name, not this one. The environment, on either side, still meets - // every holder. ⛔ A STORED row of another package still holds the name - // whatever its namespace: the registry keeps one entry per stored set of a - // name, so a second stored set would take the first one's place there. Two - // namespaces' sets of one name are admitted where the first is shipped (an - // installed package's own), never beside another package's stored set. + // every holder. A STORED set of another package is judged the same way: + // the registry keeps each package's stored set in that package's own slot, + // so a second namespace's set lands beside it and neither takes the + // other's place. const namespaceOf = (packageId: string): string | undefined => { const namespace = (this.engine?.registry as { getPackage?: (id: string) => { manifest?: { namespace?: unknown } } | undefined } | undefined) ?.getPackage?.(packageId)?.manifest?.namespace; return typeof namespace === 'string' && namespace !== '' ? namespace : undefined; }; const meets = (holder: string | null): boolean => - holder === null || written === null || storedPackages.has(holder) + holder === null || written === null || permissionSetHoldersMeet(namespaceOf(written), namespaceOf(holder), name); const foreign = [...holders] .filter((holder) => holder !== written && meets(holder)) @@ -465,19 +465,26 @@ export async function permissionSetNameCollisionRefusal( const holderPhrase = (holder: string | null) => (holder === null ? 'the environment catalog' : `package "${holder}"`); const writer = written === null ? 'this environment' : `package "${written}"`; - const releases = foreign - .map((holder) => (holder === null ? 'rename or delete the environment catalog\'s set' : `rename it in package "${holder}"`)) + // The steps the WRITER can take: a name of its own, or deleting a set the + // environment or another package STORES (a stored set is deleted through + // the metadata door); never an edit inside another package. A set a + // package ships leaves the writer only the rename. + const deletable = foreign.filter((holder) => holder === null || storedPackages.has(holder)); + const releases = deletable + .map((holder) => (holder === null ? 'delete the environment catalog\'s set' : `delete the set package "${holder}" stores`)) .join(', or '); const remedy = verb === 'restore' - ? `Restore it once the name is free (${releases} first), or save this version's body as a set of a name no other ` - + 'holder holds.' - : `Rename this set to a name no other holder holds (prefix it with your own module prefix), or ${releases} first.`; + ? (releases === '' + ? 'Save this version\'s body as a set of a name no other holder holds.' + : `Restore it once the name is free (${releases} first), or save this version's body as a set of a name no other ` + + 'holder holds.') + : `Rename this set to a name no other holder holds (prefix it with your own module prefix)${releases === '' ? '' : `, or ${releases} first`}.`; const err = new Error( `Security catalog name conflict: ${writer} cannot ${verb} the permission set "${name}" — it is already held by ` + `${foreign.map(holderPhrase).join(' and ')}. Nothing was ${verb === 'publish' ? 'published' : 'written'}. ${remedy} ` + 'A permission set holds one name per namespace: two packages of one namespace, a platform package ' + '(`base`, `system`, `sys`), a package with no namespace, the environment, or a name the platform requests ' - + 'by spelling share one set of it, and a set another package stores holds its name. See ADR-0150 D2.', + + 'by spelling share one set of it. See ADR-0150 D2.', ) as Error & { code: 'NAMESPACE_CONFLICT'; status: 422 }; err.code = 'NAMESPACE_CONFLICT'; err.status = 422; From a06a8d538f1f96645ccf4e05f75b80fd8b095b5a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:59:36 +0000 Subject: [PATCH 02/11] test: pin two namespaces' stored permission sets each served at its own package Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- ...2780-stored-permission-set-package-slot.md | 19 ++ ...rmission-set-name-registry-reading.test.ts | 214 +++++++++++++++++- .../webhook-stored-row-boot-hydration.test.ts | 10 +- .../src/packaged-permission-set-lock.test.ts | 68 ++++++ 4 files changed, 298 insertions(+), 13 deletions(-) create mode 100644 .changeset/32780-stored-permission-set-package-slot.md diff --git a/.changeset/32780-stored-permission-set-package-slot.md b/.changeset/32780-stored-permission-set-package-slot.md new file mode 100644 index 00000000000..16801cc3370 --- /dev/null +++ b/.changeset/32780-stored-permission-set-package-slot.md @@ -0,0 +1,19 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): two namespaces' stored permission sets of one name are each kept and served at their own package + +Clause-②: yes (widening) +Metadata-protocol: none + +A permission set is `(package, name)` (ADR-0150 D2). The host kernel now keeps a stored permission set bound to a package in that package's own registry slot, at the save's write-through and at the boot hydration alike. It used to put every stored set of a name into the name's one bare registry entry, so a second package's set of the name took the first one's place. The save door therefore refused it, even when the two packages had two namespaces. + +What moves, for packages `crm` and `hr` of two namespaces: + +- FROM `422 NAMESPACE_CONFLICT` naming `crm` TO saved, for `hr`'s save, publish or restore of a set whose name `crm` stores. `crm`'s own save of a set of the name beside the one `hr` stores, and a third namespace's, are admitted too. A grant bound to each package confers that package's set, in every order the boot reads the stored rows. A grant naming no package of a name two packages hold confers nothing, as for two shipped sets (ADR-0150 D3). +- FROM the shipper's set replaced TO each set served at its own package, for a set `hr` stores beside a set `crm` ships. The stored set used to take the shipper's envelope, so `crm`'s grants conferred `hr`'s stored body and `hr`'s grants conferred nothing. Each package's stored set is now tenant-authored and bound to its own package. The packaged-permission-set lock reads only the shipped set as packaged. +- A delete of one package's stored set retires that package's slot alone, and the other package's set stays served, before and after a restart. +- The refusal that stays (two packages of one namespace, a platform namespace, a package with no namespace, the environment, a name the platform requests by spelling) now names steps the writer can take: rename its own set, or delete a set the environment or another package stores. It no longer tells the writer to rename the set inside another package. Envelope unchanged: `422 NAMESPACE_CONFLICT`. + +Nothing to migrate. A package-less stored permission row keeps the name's bare registry entry, as before. diff --git a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts index 9dc10932a51..9b348ec2f10 100644 --- a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts +++ b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts @@ -36,6 +36,7 @@ import { resolveUserAuthzGrants, } from '@objectstack/core'; import { namespacedHoldersMeet } from '@objectstack/spec/kernel'; +import { isTenantAuthored } from '@objectstack/metadata-core'; import { assertEngineFindOnePredicate } from './engine-findone-predicate.js'; import { ObjectQL } from './engine.js'; import { ObjectQLPlugin } from './plugin.js'; @@ -295,20 +296,20 @@ describe('[#31698] a permission set is one name per namespace: one predicate, th expect(await doors('crm', 'hr', 'qa_reader')).toEqual({ installGate: 'admitted', itemSeam: 'admitted', saveDoor: 'admitted' }); }); - it('⛔ crm + hr where crm STORES its set (no shipped one): the save door still refuses hr\'s, and crm\'s set stays served at its package', async () => { + it('crm + hr where crm STORES its set (no shipped one): the save door admits hr\'s, and each set is served at its own package (FROM refused, #32780)', async () => { + // FROM (main at the change): `422 NAMESPACE_CONFLICT` naming crm, "a + // set another package stores holds its name": the registry kept one + // bare entry per stored set of a name, so hr's would take crm's place. const { engine, protocol } = await bootBare(); engine.registry.installPackage(manifest(HOLDING, 'crm'), 'authored'); engine.registry.installPackage(manifest(INCOMING, 'hr'), 'authored'); - await protocol.saveMetaItem({ type: 'permission', name: 'qa_reader', item: permissionSet('qa_reader'), packageId: HOLDING }); + await protocol.saveMetaItem({ type: 'permission', name: 'qa_reader', item: { ...permissionSet('qa_reader'), label: 'crm' }, packageId: HOLDING }); expect(engine.registry.packageScopedHoldersOf('permission', 'qa_reader', null)).toEqual([HOLDING]); - const error = await protocol.saveMetaItem({ type: 'permission', name: 'qa_reader', item: permissionSet('qa_reader'), packageId: INCOMING }) - .then(() => undefined, (e: any) => e); - expect([error?.code, error?.status]).toEqual(['NAMESPACE_CONFLICT', 422]); - expect(String(error?.message)).toContain(`package "${HOLDING}"`); - expect(String(error?.message)).toContain('a set another package stores holds its name'); - // Nothing moved: crm's stored set is the one the registry serves at crm. - expect(engine.registry.packageScopedHoldersOf('permission', 'qa_reader', null)).toEqual([HOLDING]); - expect(engine.registry.getPackageScopedItem('permission', 'qa_reader', HOLDING)).toBeDefined(); + const saved = await protocol.saveMetaItem({ type: 'permission', name: 'qa_reader', item: { ...permissionSet('qa_reader'), label: 'hr' }, packageId: INCOMING }); + expect(saved.success).toBe(true); + expect([...engine.registry.packageScopedHoldersOf('permission', 'qa_reader', null)].sort()).toEqual([HOLDING, INCOMING]); + const label = (id: string) => (engine.registry.getPackageScopedItem('permission', 'qa_reader', id) as { label?: string } | undefined)?.label; + expect([label(HOLDING), label(INCOMING)]).toEqual(['crm', 'hr']); }); it.each([ @@ -426,3 +427,196 @@ describe('[#31698] a permission set is one name per namespace: one predicate, th expect(await read()).toEqual({ columnLess: [], crm: ['cap_crm'], hr: [] }); }); }); + +/** + * [ADR-0150 D2/D3 "security catalog: permission sets by (package, name)", + * #32780] Two packages of two namespaces each STORE a permission set of one + * name (a runtime package duplicated into another namespace). The host kernel + * keeps each stored set in its package's own registry slot — the hydrator's + * package overlay slot, at the write-through and at the boot hydration alike — + * so each package's grants confer its own set, across a restart, in either + * order the store reads the rows; a delete of either set leaves the other + * served; and each set stays tenant-authored (the lock's provenance input, + * `_provenance: 'org'`, bound to its own package), never a shipped one. + * + * FROM (main at the change): the save door refused the second namespace's + * stored set (`422 NAMESPACE_CONFLICT`, "a set another package stores holds its + * name"), and a set stored beside a set another namespace SHIPS took the + * shipper's envelope into the name's one bare slot: the shipper's grants + * conferred the stored body, the stored package's conferred nothing, and the + * restart's environment-catalog check refused the boot. + * + * The restart is a second kernel over the same driver stores, the packages + * installed before its boot hydration (`ObjectQLPlugin.start`), as a cold boot + * registers them in its first phase. + */ +describe('[#32780] two namespaces\' stored permission sets of one name: each served at its own package', () => { + const live: ObjectKernel[] = []; + afterEach(async () => { + while (live.length) { + const kernel = live.pop()!; + if (kernel.getState() === 'running') await kernel.shutdown(); + } + }); + + const CRM = 'com.qa.crm'; + const HR = 'com.qa.hr'; + const FIN = 'com.qa.fin'; + /** A second package of the `crm` namespace: its co-owner (CONTROL). */ + const CRM_TWO = 'com.qa.crm_two'; + const NS: Record = { [CRM]: 'crm', [HR]: 'hr', [FIN]: 'fin', [CRM_TWO]: 'crm' }; + const N = 'qa_shared_reader'; + const setOf = (cap: string) => ({ ...permissionSet(N), label: cap, systemPermissions: [cap] }); + const manifestOf = (id: string, sets: string[] = []) => + ({ id, name: id, version: '1.0.0', namespace: NS[id], ...(sets.length ? { permissions: sets.map(permissionSet) } : {}) }) as any; + + /** Boot over `stores`, with `installs` installed before the boot hydration reads the stored rows. */ + async function boot(stores: Stores, installs: readonly string[]): Promise<{ engine: ObjectQL; protocol: any }> { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + live.push(kernel); + const engine = new ObjectQL(); + engine.registry.logLevel = 'silent'; + engine.registerDriver(makeMemoryDriver(stores), true); + for (const id of installs) engine.registry.installPackage(manifestOf(id), 'authored'); + await kernel.use(new ObjectQLPlugin({ ql: engine })); + await kernel.bootstrap(); + engine.registry.logLevel = 'silent'; + return { engine, protocol: (kernel as any).getService('protocol') }; + } + + /** `stores` with its stored rows in reverse order, so the next boot hydration reads them the other way round. */ + function reversedRows(stores: Stores): Stores { + const out: Stores = new Map(stores); + out.set('sys_metadata', new Map([...(stores.get('sys_metadata') ?? new Map())].reverse())); + return out; + } + + /** What one grant of {@link N} with this package column confers, read by the authorization resolver. */ + async function confers(engine: ObjectQL, column: string | null): Promise { + const catalog = createSecurityCatalogReader({ registry: engine.registry as any, metadata: { get: () => undefined, list: () => [] } as any }); + const rows: Record = { + sys_user: [{ id: 'u1', email: 'u1@example.com' }], + sys_member: [{ user_id: 'u1', organization_id: 'org_a', role: 'member' }], + sys_user_permission_set: [{ user_id: 'u1', permission_set: N, permission_set_package: column, organization_id: 'org_a' }], + }; + const ql = { registry: engine.registry, find: async (object: string) => rows[object] ?? [], findOne: async (object: string, query?: any) => { assertEngineFindOnePredicate(object, query); return rows[object]?.[0]; }, count: async () => 0 }; + bindSecurityCatalogReader(ql, catalog); + return (await resolveUserAuthzGrants(ql, 'u1', { tenantId: 'org_a' })).systemPermissions; + } + + /** Each package's grant, by its package column. */ + const grants = async (engine: ObjectQL, ids: readonly string[]) => + Object.fromEntries(await Promise.all(ids.map(async (id) => [id, await confers(engine, id)] as const))); + + /** + * The lock's provenance input for every registry item of {@link N}: the + * classifier reads a set as shipped only from an item that is not + * tenant-authored and carries a package (`packaged-permission-set-lock.ts`). + */ + const provenance = (engine: ObjectQL) => (engine.registry.listItems('permission') as any[]) + .filter((item) => item?.name === N) + .map((item) => ({ packageId: item._packageId, tenantAuthored: isTenantAuthored(item) })) + .sort((a, b) => String(a.packageId).localeCompare(String(b.packageId))); + + const save = (protocol: any, id: string, cap: string) => + protocol.saveMetaItem({ type: 'permission', name: N, item: setOf(cap), packageId: id }); + + async function refusal(run: () => Promise): Promise { + try { await run(); } catch (error) { return error; } + return undefined; + } + + for (const order of [[CRM, HR], [HR, CRM]] as const) { + const tag = `${NS[order[0]]} saves first`; + + it(`${tag}: both stored sets land, each package's grant confers its own set, neither is locked, and so after a restart in either read order`, async () => { + const stores: Stores = new Map(); + const first = await boot(stores, [CRM, HR]); + for (const id of order) expect((await save(first.protocol, id, `cap_${NS[id]}`)).success, `${id}'s save`).toBe(true); + const served = { [CRM]: ['cap_crm'], [HR]: ['cap_hr'] }; + expect(await grants(first.engine, [CRM, HR]), 'the running kernel').toEqual(served); + // A grant naming no package of a name two packages hold confers nothing (ADR-0150 D3). + expect(await confers(first.engine, null)).toEqual([]); + const tenantSets = [{ packageId: CRM, tenantAuthored: true }, { packageId: HR, tenantAuthored: true }]; + expect(provenance(first.engine), 'neither set reads as shipped').toEqual(tenantSets); + + for (const [reading, rows] of [['store order', stores], ['reversed', reversedRows(stores)]] as const) { + for (const installs of [[CRM, HR], [HR, CRM]] as const) { + const restarted = await boot(rows, installs); + const at = `restart (${reading}, ${NS[installs[0]]} installed first)`; + expect(await grants(restarted.engine, [CRM, HR]), at).toEqual(served); + expect(provenance(restarted.engine), at).toEqual(tenantSets); + } + } + }); + + for (const deleted of [CRM, HR] as const) { + const kept = deleted === CRM ? HR : CRM; + it(`${tag}: a delete of ${NS[deleted]}'s set retires its slot alone, and ${NS[kept]}'s stays served, also after a restart`, async () => { + const stores: Stores = new Map(); + const { engine, protocol } = await boot(stores, [CRM, HR]); + for (const id of order) await save(protocol, id, `cap_${NS[id]}`); + await protocol.deleteMetaItem({ type: 'permission', name: N, packageId: deleted }); + const after = { [deleted]: [], [kept]: [`cap_${NS[kept]}`] }; + expect(await grants(engine, [CRM, HR]), 'the running kernel').toEqual(after); + expect(engine.registry.packageScopedHoldersOf('permission', N, null)).toEqual([kept]); + // One holder left: a grant naming no package confers its set. + expect(await confers(engine, null)).toEqual([`cap_${NS[kept]}`]); + const restarted = await boot(stores, [CRM, HR]); + expect(await grants(restarted.engine, [CRM, HR]), 'after a restart').toEqual(after); + }); + } + } + + it('crm ships a set, hr saves one of the name, then crm saves its own and a third namespace saves one: each lands and each is served at its own package, also after a restart (FROM: crm\'s and fin\'s saves refused naming hr)', async () => { + const stores: Stores = new Map(); + const { engine, protocol } = await boot(stores, [CRM, HR, FIN]); + const ship = (target: ObjectQL) => target.registry.registerItem('permission', setOf('cap_crm_shipped') as any, 'name', CRM); + ship(engine); + expect(await grants(engine, [CRM]), 'the shipped set').toEqual({ [CRM]: ['cap_crm_shipped'] }); + expect((await save(protocol, HR, 'cap_hr')).success).toBe(true); + // hr's stored set never takes crm's place: crm's grant still confers the shipped set. + expect(await grants(engine, [CRM, HR]), 'hr beside the shipped set').toEqual({ [CRM]: ['cap_crm_shipped'], [HR]: ['cap_hr'] }); + expect((await save(protocol, CRM, 'cap_crm_stored')).success, 'crm\'s own save').toBe(true); + expect((await save(protocol, FIN, 'cap_fin')).success, 'a third namespace\'s save').toBe(true); + const served = { [CRM]: ['cap_crm_stored'], [HR]: ['cap_hr'], [FIN]: ['cap_fin'] }; + expect(await grants(engine, [CRM, HR, FIN]), 'the running kernel').toEqual(served); + // Only crm's own set wears crm's envelope; hr's and fin's are their own packages' tenant sets. + expect(provenance(engine).filter((p) => p.packageId !== CRM)).toEqual([ + { packageId: FIN, tenantAuthored: true }, { packageId: HR, tenantAuthored: true }, + ]); + for (const rows of [stores, reversedRows(stores)]) { + const restarted = await boot(rows, [CRM, HR, FIN]); + ship(restarted.engine); + expect(await grants(restarted.engine, [CRM, HR, FIN]), 'after a restart').toEqual(served); + } + }); + + it('CONTROL — a second package of the SAME namespace is still refused beside a stored set; the remedy names steps the writer can take, never an edit inside the other package', async () => { + const stores: Stores = new Map(); + const { engine, protocol } = await boot(stores, [CRM, CRM_TWO]); + await save(protocol, CRM, 'cap_crm'); + const error = await refusal(() => save(protocol, CRM_TWO, 'cap_crm_two')); + expect([error?.code, error?.status]).toEqual(['NAMESPACE_CONFLICT', 422]); + const message = String(error?.message); + expect(message).toContain(`package "${CRM}"`); + expect(message).toContain(`delete the set package "${CRM}" stores`); + expect(message).not.toContain('rename it in package'); + // Nothing of crm_two's was written; crm's set is still the one served. + expect(Array.from(stores.get('sys_metadata')?.values() ?? []).filter((r) => r.type === 'permission').map((r) => r.package_id)).toEqual([CRM]); + expect(await grants(engine, [CRM, CRM_TWO])).toEqual({ [CRM]: ['cap_crm'], [CRM_TWO]: [] }); + }); + + it('CONTROL — an install-declared name of the same namespace is still refused, and the remedy offers only the writer\'s own rename', async () => { + const kernel = await boot(new Map(), []); + kernel.engine.registry.installPackage(manifestOf(CRM, [N]), 'authored'); + kernel.engine.registry.installPackage(manifestOf(CRM_TWO), 'authored'); + const error = await refusal(() => save(kernel.protocol, CRM_TWO, 'cap_crm_two')); + expect([error?.code, error?.status]).toEqual(['NAMESPACE_CONFLICT', 422]); + const message = String(error?.message); + expect(message).toContain(`package "${CRM}"`); + expect(message).toContain('Rename this set to a name no other holder holds'); + expect(message).not.toContain('rename it in package'); + expect(message).not.toContain('delete the set'); + }); +}); diff --git a/packages/objectql/src/webhook-stored-row-boot-hydration.test.ts b/packages/objectql/src/webhook-stored-row-boot-hydration.test.ts index 6fce68555bc..9443097d2e5 100644 --- a/packages/objectql/src/webhook-stored-row-boot-hydration.test.ts +++ b/packages/objectql/src/webhook-stored-row-boot-hydration.test.ts @@ -267,12 +267,16 @@ describe('a stored row of a two-holder name at boot, beyond the webhook (#32692) expect(registry.listItems('dashboard').map((item) => (item as { label?: string }).label)).not.toContain('row:beta-custom'); }); - it(`CONTROL — permission (${first} first): a stray row keeps its reading (the first-registered holder's slot, an order-dependent pick), pending the maintainer's ruling on a stored permission fork under two holders`, async () => { + it(`permission (${first} first): a stray package's row is its own package's set, in its own slot, and each holder keeps its shipped set (ADR-0150 D2, #32780)`, async () => { + // FROM (main at #32780): the row wore the first-registered + // holder's envelope in the name's one bare slot, so that holder's + // slot (and its grants) answered the stray package's body, by + // registration order. A permission set is `(package, name)`: the + // stray package's stored set is its own. const body = (label: string) => ({ name: N, label, description: label }); const { registry } = await boot('permission', order, (id) => body(`shipped:${id}`), [{ packageId: S, body: body('row:stray') }]); const label = (id: string) => (registry.getPackageScopedItem('permission', N, id) as { label?: string } | undefined)?.label; - expect(label(order[0])).toBe('row:stray'); - expect(label(order[1])).toBe(`shipped:${order[1]}`); + expect([label(A), label(B), label(S)]).toEqual([`shipped:${A}`, `shipped:${B}`, 'row:stray']); }); it(`CONTROL — email_template (${first} first): a shared pair's undeclared row of a locale no holder ships keeps its bare-slot registration, as before`, async () => { diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts index b9ed6192ea4..8f7ef9819b1 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts @@ -30,6 +30,9 @@ import { PackagedPermissionSetProvenanceUnknownError, } from './packaged-permission-set-lock.js'; import { registerPackagedPermissionSetLockGate } from './packaged-permission-set-lock-gate.js'; +import { assertEngineFindOnePredicate } from '@objectstack/metadata-core'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SchemaRegistry } from '@objectstack/objectql'; // ───────────────────────────────────────────────────────────────────────────── // Doubles @@ -367,3 +370,68 @@ describe('[#31698] a name two packages declare: the lock names every holder', () expect(unknown).toBeInstanceOf(PackagedPermissionSetProvenanceUnknownError); }); }); + +// ───────────────────────────────────────────────────────────────────────────── +// [ADR-0150 D2, #32780] A stored set in its package's registry slot is tenant-authored +// ───────────────────────────────────────────────────────────────────────────── + +/** + * The host kernel's boot hydration (`loadMetaFromDb`, the real + * `ObjectStackProtocolImplementation` over a real `SchemaRegistry`) keeps each + * package's stored set of a name in that package's own registry slot. The + * classifier reads those slots as the tenant-authored sets they are, in either + * order the store reads the rows: two namespaces' stored sets of one name lock + * nothing, and a set stored beside a set another namespace ships never lends + * the lock its own package. BASE: a set stored beside a shipped one wore the + * shipper's envelope, so the shipper's grants conferred the stored body. + */ +describe('[#32780] a stored permission set in its package\'s registry slot is never read as shipped', () => { + const CRM = 'com.qa.crm'; + const HR = 'com.qa.hr'; + const N = 'qa_shared_reader'; + const set = (label: string) => ({ name: N, label, objects: {} }); + + async function hydrate(rows: Array<{ packageId: string; label: string }>, ships?: string) { + const registry = new SchemaRegistry(); + registry.logLevel = 'silent'; + for (const id of [CRM, HR]) { + registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop() } as never, 'authored'); + } + if (ships) registry.registerItem('permission', set(`shipped:${ships}`) as never, 'name' as never, ships); + const stored = rows.map((r, i) => ({ + id: `row_${i}`, type: 'permission', name: N, organization_id: null, package_id: r.packageId, state: 'active', + metadata: JSON.stringify(set(r.label)), + })); + const engine: any = { + async find(table: string, opts?: { where?: Record; limit?: number }) { + if (table !== 'sys_metadata') return []; + const where = opts?.where ?? {}; + const found = stored.filter((r) => Object.entries(where).every(([k, v]) => v === undefined || typeof v === 'object' || (r as any)[k] === v)); + return typeof opts?.limit === 'number' ? found.slice(0, opts.limit) : found; + }, + async findOne(object: string, query?: any) { + assertEngineFindOnePredicate(object, query); + return null; + }, + registry, + }; + const load = await new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_prod').loadMetaFromDb(); + const label = (id: string) => (registry.getPackageScopedItem('permission', N, id) as { label?: string } | undefined)?.label; + return { load, ql: { registry }, label }; + } + + for (const order of [[CRM, HR], [HR, CRM]] as const) { + it(`two packages' stored sets (${order[0].split('.').pop()}'s row read first): each is its package's own, and the name is not locked`, async () => { + const { load, ql, label } = await hydrate(order.map((id) => ({ packageId: id, label: `row:${id}` }))); + expect(load).toMatchObject({ loaded: 2, errors: 0 }); + expect([label(CRM), label(HR)]).toEqual([`row:${CRM}`, `row:${HR}`]); + expect(classifyPackagedPermissionSet(N, ql)).toEqual({ status: 'org' }); + }); + } + + it('a set stored beside the set another namespace ships: the lock names the shipper alone, and each package serves its own set (BASE: the shipper served the stored body)', async () => { + const { ql, label } = await hydrate([{ packageId: HR, label: `row:${HR}` }], CRM); + expect([label(CRM), label(HR)]).toEqual([`shipped:${CRM}`, `row:${HR}`]); + expect(classifyPackagedPermissionSet(N, ql)).toEqual({ status: 'packaged', packageId: CRM, packageIds: [CRM] }); + }); +}); From 51eb426d072f66439ed04118fcd4931bcf9db8b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 16:03:00 +0000 Subject: [PATCH 03/11] docs: state the permission envelope rule at rule level Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- .changeset/32780-stored-permission-set-package-slot.md | 2 +- .../metadata-protocol/src/protocol-registry-hydration.ts | 9 +++------ ...protocol-permission-set-name-registry-reading.test.ts | 8 +++----- .../src/webhook-stored-row-boot-hydration.test.ts | 8 +++----- .../src/packaged-permission-set-lock.test.ts | 5 ++--- 5 files changed, 12 insertions(+), 20 deletions(-) diff --git a/.changeset/32780-stored-permission-set-package-slot.md b/.changeset/32780-stored-permission-set-package-slot.md index 16801cc3370..d1565b468b0 100644 --- a/.changeset/32780-stored-permission-set-package-slot.md +++ b/.changeset/32780-stored-permission-set-package-slot.md @@ -12,7 +12,7 @@ A permission set is `(package, name)` (ADR-0150 D2). The host kernel now keeps a What moves, for packages `crm` and `hr` of two namespaces: - FROM `422 NAMESPACE_CONFLICT` naming `crm` TO saved, for `hr`'s save, publish or restore of a set whose name `crm` stores. `crm`'s own save of a set of the name beside the one `hr` stores, and a third namespace's, are admitted too. A grant bound to each package confers that package's set, in every order the boot reads the stored rows. A grant naming no package of a name two packages hold confers nothing, as for two shipped sets (ADR-0150 D3). -- FROM the shipper's set replaced TO each set served at its own package, for a set `hr` stores beside a set `crm` ships. The stored set used to take the shipper's envelope, so `crm`'s grants conferred `hr`'s stored body and `hr`'s grants conferred nothing. Each package's stored set is now tenant-authored and bound to its own package. The packaged-permission-set lock reads only the shipped set as packaged. +- A set `hr` stores beside a set `crm` ships is `hr`'s own set: it is served at `hr`, `crm` keeps serving the set it ships, and the stored set is tenant-authored and bound to `hr`. The packaged-permission-set lock reads only the shipped set as packaged. - A delete of one package's stored set retires that package's slot alone, and the other package's set stays served, before and after a restart. - The refusal that stays (two packages of one namespace, a platform namespace, a package with no namespace, the environment, a name the platform requests by spelling) now names steps the writer can take: rename its own set, or delete a set the environment or another package stores. It no longer tells the writer to rename the set inside another package. Envelope unchanged: `422 NAMESPACE_CONFLICT`. diff --git a/packages/metadata-protocol/src/protocol-registry-hydration.ts b/packages/metadata-protocol/src/protocol-registry-hydration.ts index b53e652e8f8..2888da99a42 100644 --- a/packages/metadata-protocol/src/protocol-registry-hydration.ts +++ b/packages/metadata-protocol/src/protocol-registry-hydration.ts @@ -272,12 +272,9 @@ function takesPackageOverlaySlot(canonicalType: string): boolean { * to `bound` wears: `artifact` only when it is the row's own package's set, or * the set of the base whose customization pair `bound` is (ADR-0146). The * artifact lookup scoped to a package that ships no set of the name falls back - * to the first package that does, so a set stored by a package of another - * namespace wore that package's envelope (`_packageId`, `_provenance: - * 'package'`): the registry bound it to that package, whose grants then - * conferred the stored body, and the lock read the stored set as shipped. - * Without an envelope it registers as the tenant-authored set it is, bound to - * its own package. Any other type, or a package-less row, keeps `artifact`. + * to a package that does; that package's envelope is never this row's. With + * none of its own, the row registers as the tenant-authored set it is, bound + * to its own package. Any other type, or a package-less row, keeps `artifact`. */ function ownPermissionEnvelope( registry: InstalledPackageSource, diff --git a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts index 9b348ec2f10..0a327dc066b 100644 --- a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts +++ b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts @@ -441,10 +441,8 @@ describe('[#31698] a permission set is one name per namespace: one predicate, th * * FROM (main at the change): the save door refused the second namespace's * stored set (`422 NAMESPACE_CONFLICT`, "a set another package stores holds its - * name"), and a set stored beside a set another namespace SHIPS took the - * shipper's envelope into the name's one bare slot: the shipper's grants - * conferred the stored body, the stored package's conferred nothing, and the - * restart's environment-catalog check refused the boot. + * name"), and a set stored beside a set another namespace SHIPS was not served + * at its own package. * * The restart is a second kernel over the same driver stores, the packages * installed before its boot hydration (`ObjectQLPlugin.start`), as a cold boot @@ -575,7 +573,7 @@ describe('[#32780] two namespaces\' stored permission sets of one name: each ser ship(engine); expect(await grants(engine, [CRM]), 'the shipped set').toEqual({ [CRM]: ['cap_crm_shipped'] }); expect((await save(protocol, HR, 'cap_hr')).success).toBe(true); - // hr's stored set never takes crm's place: crm's grant still confers the shipped set. + // Each package's grant confers its own package's set. expect(await grants(engine, [CRM, HR]), 'hr beside the shipped set').toEqual({ [CRM]: ['cap_crm_shipped'], [HR]: ['cap_hr'] }); expect((await save(protocol, CRM, 'cap_crm_stored')).success, 'crm\'s own save').toBe(true); expect((await save(protocol, FIN, 'cap_fin')).success, 'a third namespace\'s save').toBe(true); diff --git a/packages/objectql/src/webhook-stored-row-boot-hydration.test.ts b/packages/objectql/src/webhook-stored-row-boot-hydration.test.ts index 9443097d2e5..ff25a719d43 100644 --- a/packages/objectql/src/webhook-stored-row-boot-hydration.test.ts +++ b/packages/objectql/src/webhook-stored-row-boot-hydration.test.ts @@ -268,11 +268,9 @@ describe('a stored row of a two-holder name at boot, beyond the webhook (#32692) }); it(`permission (${first} first): a stray package's row is its own package's set, in its own slot, and each holder keeps its shipped set (ADR-0150 D2, #32780)`, async () => { - // FROM (main at #32780): the row wore the first-registered - // holder's envelope in the name's one bare slot, so that holder's - // slot (and its grants) answered the stray package's body, by - // registration order. A permission set is `(package, name)`: the - // stray package's stored set is its own. + // FROM (main at #32780): the first-registered holder's slot + // answered the row (the CONTROL this replaces). A permission set + // is `(package, name)`: the stray package's stored set is its own. const body = (label: string) => ({ name: N, label, description: label }); const { registry } = await boot('permission', order, (id) => body(`shipped:${id}`), [{ packageId: S, body: body('row:stray') }]); const label = (id: string) => (registry.getPackageScopedItem('permission', N, id) as { label?: string } | undefined)?.label; diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts index 8f7ef9819b1..c16af145f4b 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts @@ -382,8 +382,7 @@ describe('[#31698] a name two packages declare: the lock names every holder', () * classifier reads those slots as the tenant-authored sets they are, in either * order the store reads the rows: two namespaces' stored sets of one name lock * nothing, and a set stored beside a set another namespace ships never lends - * the lock its own package. BASE: a set stored beside a shipped one wore the - * shipper's envelope, so the shipper's grants conferred the stored body. + * the lock its own package. */ describe('[#32780] a stored permission set in its package\'s registry slot is never read as shipped', () => { const CRM = 'com.qa.crm'; @@ -429,7 +428,7 @@ describe('[#32780] a stored permission set in its package\'s registry slot is ne }); } - it('a set stored beside the set another namespace ships: the lock names the shipper alone, and each package serves its own set (BASE: the shipper served the stored body)', async () => { + it('a set stored beside the set another namespace ships: the lock names the shipper alone, and each package serves its own set', async () => { const { ql, label } = await hydrate([{ packageId: HR, label: `row:${HR}` }], CRM); expect([label(CRM), label(HR)]).toEqual([`shipped:${CRM}`, `row:${HR}`]); expect(classifyPackagedPermissionSet(N, ql)).toEqual({ status: 'packaged', packageId: CRM, packageIds: [CRM] }); From 3bd43b5fd80697a4f8433572c20f457d4f90f46b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 16:04:18 +0000 Subject: [PATCH 04/11] test: register the shipped set before the boot hydration in the restart pin Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- ...otocol-permission-set-name-registry-reading.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts index 0a327dc066b..6bd5c6f132f 100644 --- a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts +++ b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts @@ -469,13 +469,14 @@ describe('[#32780] two namespaces\' stored permission sets of one name: each ser ({ id, name: id, version: '1.0.0', namespace: NS[id], ...(sets.length ? { permissions: sets.map(permissionSet) } : {}) }) as any; /** Boot over `stores`, with `installs` installed before the boot hydration reads the stored rows. */ - async function boot(stores: Stores, installs: readonly string[]): Promise<{ engine: ObjectQL; protocol: any }> { + async function boot(stores: Stores, installs: readonly string[], before?: (engine: ObjectQL) => void): Promise<{ engine: ObjectQL; protocol: any }> { const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); live.push(kernel); const engine = new ObjectQL(); engine.registry.logLevel = 'silent'; engine.registerDriver(makeMemoryDriver(stores), true); for (const id of installs) engine.registry.installPackage(manifestOf(id), 'authored'); + before?.(engine); await kernel.use(new ObjectQLPlugin({ ql: engine })); await kernel.bootstrap(); engine.registry.logLevel = 'silent'; @@ -568,9 +569,9 @@ describe('[#32780] two namespaces\' stored permission sets of one name: each ser it('crm ships a set, hr saves one of the name, then crm saves its own and a third namespace saves one: each lands and each is served at its own package, also after a restart (FROM: crm\'s and fin\'s saves refused naming hr)', async () => { const stores: Stores = new Map(); - const { engine, protocol } = await boot(stores, [CRM, HR, FIN]); + // crm's set is registered before the boot hydration, as a cold boot registers a package's items. const ship = (target: ObjectQL) => target.registry.registerItem('permission', setOf('cap_crm_shipped') as any, 'name', CRM); - ship(engine); + const { engine, protocol } = await boot(stores, [CRM, HR, FIN], ship); expect(await grants(engine, [CRM]), 'the shipped set').toEqual({ [CRM]: ['cap_crm_shipped'] }); expect((await save(protocol, HR, 'cap_hr')).success).toBe(true); // Each package's grant confers its own package's set. @@ -584,8 +585,7 @@ describe('[#32780] two namespaces\' stored permission sets of one name: each ser { packageId: FIN, tenantAuthored: true }, { packageId: HR, tenantAuthored: true }, ]); for (const rows of [stores, reversedRows(stores)]) { - const restarted = await boot(rows, [CRM, HR, FIN]); - ship(restarted.engine); + const restarted = await boot(rows, [CRM, HR, FIN], ship); expect(await grants(restarted.engine, [CRM, HR, FIN]), 'after a restart').toEqual(served); } }); From ea9807b0ef10200a5155bd5ef091bcee5cf026ad Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 16:40:14 +0000 Subject: [PATCH 05/11] test: share one grant double in the permission-set harness Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- ...rmission-set-name-registry-reading.test.ts | 36 +++++++++---------- .../src/packaged-permission-set-lock.test.ts | 5 --- 2 files changed, 18 insertions(+), 23 deletions(-) diff --git a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts index 6bd5c6f132f..e167afe9ee8 100644 --- a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts +++ b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts @@ -121,6 +121,22 @@ function makeMemoryDriver(stores: Stores) { return driver; } +/** + * What one grant of the permission set `name`, bound to the package `column` + * (`null`: no package column), confers to a member of `org_a`, read by the + * authorization resolver through `catalog`. + */ +async function grantConfers(engine: ObjectQL, catalog: unknown, name: string, column: string | null): Promise { + const rows: Record = { + sys_user: [{ id: 'u1', email: 'u1@example.com' }], + sys_member: [{ user_id: 'u1', organization_id: 'org_a', role: 'member' }], + sys_user_permission_set: [{ user_id: 'u1', permission_set: name, permission_set_package: column, organization_id: 'org_a' }], + }; + const ql = { registry: engine.registry, find: async (object: string) => rows[object] ?? [], findOne: async (object: string, query?: any) => { assertEngineFindOnePredicate(object, query); return rows[object]?.[0]; }, count: async () => 0 }; + bindSecurityCatalogReader(ql, catalog as any); + return (await resolveUserAuthzGrants(ql, 'u1', { tenantId: 'org_a' })).systemPermissions; +} + /** The package whose install declares the set's name, and a second installed package. */ const HOLDER = 'com.qa.holder'; const OTHER = 'com.qa.other'; @@ -409,16 +425,7 @@ describe('[#31698] a permission set is one name per namespace: one predicate, th engine.registry.registerItem('permission', set('cap_hr') as any, 'name', INCOMING); const catalog = createSecurityCatalogReader({ registry: engine.registry as any, metadata: { get: () => undefined, list: () => [] } as any }); /** What one grant of `qa_reader` with this column confers, read by the authorization resolver. */ - const confers = async (column: string | null) => { - const rows: Record = { - sys_user: [{ id: 'u1', email: 'u1@example.com' }], - sys_member: [{ user_id: 'u1', organization_id: 'org_a', role: 'member' }], - sys_user_permission_set: [{ user_id: 'u1', permission_set: 'qa_reader', permission_set_package: column, organization_id: 'org_a' }], - }; - const ql = { registry: engine.registry, find: async (object: string) => rows[object] ?? [], findOne: async (object: string, query?: any) => { assertEngineFindOnePredicate(object, query); return rows[object]?.[0]; }, count: async () => 0 }; - bindSecurityCatalogReader(ql, catalog); - return (await resolveUserAuthzGrants(ql, 'u1', { tenantId: 'org_a' })).systemPermissions; - }; + const confers = (column: string | null) => grantConfers(engine, catalog, 'qa_reader', column); const read = async () => ({ columnLess: await confers(null), crm: await confers(HOLDING), hr: await confers(INCOMING) }); expect(await read()).toEqual({ columnLess: [], crm: ['cap_crm'], hr: ['cap_hr'] }); engine.registry.disablePackage(INCOMING); @@ -493,14 +500,7 @@ describe('[#32780] two namespaces\' stored permission sets of one name: each ser /** What one grant of {@link N} with this package column confers, read by the authorization resolver. */ async function confers(engine: ObjectQL, column: string | null): Promise { const catalog = createSecurityCatalogReader({ registry: engine.registry as any, metadata: { get: () => undefined, list: () => [] } as any }); - const rows: Record = { - sys_user: [{ id: 'u1', email: 'u1@example.com' }], - sys_member: [{ user_id: 'u1', organization_id: 'org_a', role: 'member' }], - sys_user_permission_set: [{ user_id: 'u1', permission_set: N, permission_set_package: column, organization_id: 'org_a' }], - }; - const ql = { registry: engine.registry, find: async (object: string) => rows[object] ?? [], findOne: async (object: string, query?: any) => { assertEngineFindOnePredicate(object, query); return rows[object]?.[0]; }, count: async () => 0 }; - bindSecurityCatalogReader(ql, catalog); - return (await resolveUserAuthzGrants(ql, 'u1', { tenantId: 'org_a' })).systemPermissions; + return grantConfers(engine, catalog, N, column); } /** Each package's grant, by its package column. */ diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts index c16af145f4b..7d7636294cb 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock.test.ts @@ -30,7 +30,6 @@ import { PackagedPermissionSetProvenanceUnknownError, } from './packaged-permission-set-lock.js'; import { registerPackagedPermissionSetLockGate } from './packaged-permission-set-lock-gate.js'; -import { assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { SchemaRegistry } from '@objectstack/objectql'; @@ -408,10 +407,6 @@ describe('[#32780] a stored permission set in its package\'s registry slot is ne const found = stored.filter((r) => Object.entries(where).every(([k, v]) => v === undefined || typeof v === 'object' || (r as any)[k] === v)); return typeof opts?.limit === 'number' ? found.slice(0, opts.limit) : found; }, - async findOne(object: string, query?: any) { - assertEngineFindOnePredicate(object, query); - return null; - }, registry, }; const load = await new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_prod').loadMetaFromDb(); From 04bd217aa4133879683a0c2d98915589855cb602 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 17:39:45 +0000 Subject: [PATCH 06/11] test: co-own the namespace by dependency and ship the set after the first boot in the permission pins Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- ...ocol-permission-set-name-registry-reading.test.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts index e167afe9ee8..adbffad4651 100644 --- a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts +++ b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts @@ -473,7 +473,12 @@ describe('[#32780] two namespaces\' stored permission sets of one name: each ser const N = 'qa_shared_reader'; const setOf = (cap: string) => ({ ...permissionSet(N), label: cap, systemPermissions: [cap] }); const manifestOf = (id: string, sets: string[] = []) => - ({ id, name: id, version: '1.0.0', namespace: NS[id], ...(sets.length ? { permissions: sets.map(permissionSet) } : {}) }) as any; + ({ + id, name: id, version: '1.0.0', namespace: NS[id], + // crm_two co-owns the `crm` namespace by a declared dependency (ADR-0141 D5). + ...(id === CRM_TWO ? { dependencies: { [CRM]: '^1.0.0' } } : {}), + ...(sets.length ? { permissions: sets.map(permissionSet) } : {}), + }) as any; /** Boot over `stores`, with `installs` installed before the boot hydration reads the stored rows. */ async function boot(stores: Stores, installs: readonly string[], before?: (engine: ObjectQL) => void): Promise<{ engine: ObjectQL; protocol: any }> { @@ -569,9 +574,9 @@ describe('[#32780] two namespaces\' stored permission sets of one name: each ser it('crm ships a set, hr saves one of the name, then crm saves its own and a third namespace saves one: each lands and each is served at its own package, also after a restart (FROM: crm\'s and fin\'s saves refused naming hr)', async () => { const stores: Stores = new Map(); - // crm's set is registered before the boot hydration, as a cold boot registers a package's items. const ship = (target: ObjectQL) => target.registry.registerItem('permission', setOf('cap_crm_shipped') as any, 'name', CRM); - const { engine, protocol } = await boot(stores, [CRM, HR, FIN], ship); + const { engine, protocol } = await boot(stores, [CRM, HR, FIN]); + ship(engine); expect(await grants(engine, [CRM]), 'the shipped set').toEqual({ [CRM]: ['cap_crm_shipped'] }); expect((await save(protocol, HR, 'cap_hr')).success).toBe(true); // Each package's grant confers its own package's set. @@ -584,6 +589,7 @@ describe('[#32780] two namespaces\' stored permission sets of one name: each ser expect(provenance(engine).filter((p) => p.packageId !== CRM)).toEqual([ { packageId: FIN, tenantAuthored: true }, { packageId: HR, tenantAuthored: true }, ]); + // The restart registers crm's set before its boot hydration, as a cold boot registers a package's items. for (const rows of [stores, reversedRows(stores)]) { const restarted = await boot(rows, [CRM, HR, FIN], ship); expect(await grants(restarted.engine, [CRM, HR, FIN]), 'after a restart').toEqual(served); From 88a5bcf110d6368e889a8f539512425ea78e6d71 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 18:03:27 +0000 Subject: [PATCH 07/11] test: model the declared set and the shipped-after-stored restart as two permission pins Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- ...rmission-set-name-registry-reading.test.ts | 46 +++++++++++-------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts index adbffad4651..6da8a4454a3 100644 --- a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts +++ b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts @@ -480,14 +480,14 @@ describe('[#32780] two namespaces\' stored permission sets of one name: each ser ...(sets.length ? { permissions: sets.map(permissionSet) } : {}), }) as any; - /** Boot over `stores`, with `installs` installed before the boot hydration reads the stored rows. */ - async function boot(stores: Stores, installs: readonly string[], before?: (engine: ObjectQL) => void): Promise<{ engine: ObjectQL; protocol: any }> { + /** Boot over `stores`, with `installs` installed (declaring `declares`' sets) before the boot hydration reads the stored rows. */ + async function boot(stores: Stores, installs: readonly string[], before?: (engine: ObjectQL) => void, declares: Record = {}): Promise<{ engine: ObjectQL; protocol: any }> { const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); live.push(kernel); const engine = new ObjectQL(); engine.registry.logLevel = 'silent'; engine.registerDriver(makeMemoryDriver(stores), true); - for (const id of installs) engine.registry.installPackage(manifestOf(id), 'authored'); + for (const id of installs) engine.registry.installPackage(manifestOf(id, declares[id]), 'authored'); before?.(engine); await kernel.use(new ObjectQLPlugin({ ql: engine })); await kernel.bootstrap(); @@ -572,30 +572,36 @@ describe('[#32780] two namespaces\' stored permission sets of one name: each ser } } - it('crm ships a set, hr saves one of the name, then crm saves its own and a third namespace saves one: each lands and each is served at its own package, also after a restart (FROM: crm\'s and fin\'s saves refused naming hr)', async () => { + it('crm declares a set, hr saves one of the name, then crm saves its own and a third namespace saves one: each lands and each is served at its own package, also after a restart (FROM: crm\'s and fin\'s saves refused naming hr)', async () => { const stores: Stores = new Map(); - const ship = (target: ObjectQL) => target.registry.registerItem('permission', setOf('cap_crm_shipped') as any, 'name', CRM); - const { engine, protocol } = await boot(stores, [CRM, HR, FIN]); - ship(engine); - expect(await grants(engine, [CRM]), 'the shipped set').toEqual({ [CRM]: ['cap_crm_shipped'] }); - expect((await save(protocol, HR, 'cap_hr')).success).toBe(true); - // Each package's grant confers its own package's set. - expect(await grants(engine, [CRM, HR]), 'hr beside the shipped set').toEqual({ [CRM]: ['cap_crm_shipped'], [HR]: ['cap_hr'] }); - expect((await save(protocol, CRM, 'cap_crm_stored')).success, 'crm\'s own save').toBe(true); + const { engine, protocol } = await boot(stores, [CRM, HR, FIN], undefined, { [CRM]: [N] }); + expect((await save(protocol, HR, 'cap_hr')).success, 'hr\'s save beside crm\'s declared set').toBe(true); + expect((await save(protocol, CRM, 'cap_crm')).success, 'crm\'s own save').toBe(true); expect((await save(protocol, FIN, 'cap_fin')).success, 'a third namespace\'s save').toBe(true); - const served = { [CRM]: ['cap_crm_stored'], [HR]: ['cap_hr'], [FIN]: ['cap_fin'] }; + const served = { [CRM]: ['cap_crm'], [HR]: ['cap_hr'], [FIN]: ['cap_fin'] }; expect(await grants(engine, [CRM, HR, FIN]), 'the running kernel').toEqual(served); - // Only crm's own set wears crm's envelope; hr's and fin's are their own packages' tenant sets. - expect(provenance(engine).filter((p) => p.packageId !== CRM)).toEqual([ - { packageId: FIN, tenantAuthored: true }, { packageId: HR, tenantAuthored: true }, - ]); - // The restart registers crm's set before its boot hydration, as a cold boot registers a package's items. + expect(await confers(engine, null)).toEqual([]); for (const rows of [stores, reversedRows(stores)]) { - const restarted = await boot(rows, [CRM, HR, FIN], ship); + const restarted = await boot(rows, [CRM, HR, FIN], undefined, { [CRM]: [N] }); expect(await grants(restarted.engine, [CRM, HR, FIN]), 'after a restart').toEqual(served); } }); + it('a set hr stores, then crm ships a set of the name: after a restart in either read order crm\'s grant confers the set crm ships and hr\'s the set hr stores, and only crm\'s reads as shipped', async () => { + const stores: Stores = new Map(); + const first = await boot(stores, [CRM, HR]); + expect((await save(first.protocol, HR, 'cap_hr')).success).toBe(true); + // crm's set is registered before the boot hydration, as a cold boot registers a package's items. + const ship = (target: ObjectQL) => target.registry.registerItem('permission', setOf('cap_crm_shipped') as any, 'name', CRM); + for (const rows of [stores, reversedRows(stores)]) { + const restarted = await boot(rows, [CRM, HR], ship); + expect(await grants(restarted.engine, [CRM, HR]), 'after a restart').toEqual({ [CRM]: ['cap_crm_shipped'], [HR]: ['cap_hr'] }); + expect(provenance(restarted.engine)).toEqual([ + { packageId: CRM, tenantAuthored: false }, { packageId: HR, tenantAuthored: true }, + ]); + } + }); + it('CONTROL — a second package of the SAME namespace is still refused beside a stored set; the remedy names steps the writer can take, never an edit inside the other package', async () => { const stores: Stores = new Map(); const { engine, protocol } = await boot(stores, [CRM, CRM_TWO]); @@ -608,7 +614,7 @@ describe('[#32780] two namespaces\' stored permission sets of one name: each ser expect(message).not.toContain('rename it in package'); // Nothing of crm_two's was written; crm's set is still the one served. expect(Array.from(stores.get('sys_metadata')?.values() ?? []).filter((r) => r.type === 'permission').map((r) => r.package_id)).toEqual([CRM]); - expect(await grants(engine, [CRM, CRM_TWO])).toEqual({ [CRM]: ['cap_crm'], [CRM_TWO]: [] }); + expect(await grants(engine, [CRM])).toEqual({ [CRM]: ['cap_crm'] }); }); it('CONTROL — an install-declared name of the same namespace is still refused, and the remedy offers only the writer\'s own rename', async () => { From d83ef3b461017362e4d4bd2faacbf065180b4dc4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 19:03:44 +0000 Subject: [PATCH 08/11] test: read a permission row bound to a non-holder as taking its package's own slot in the heal pin Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- ...rotocol-registry-heal-packageless-refusal.test.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/objectql/src/protocol-registry-heal-packageless-refusal.test.ts b/packages/objectql/src/protocol-registry-heal-packageless-refusal.test.ts index 1b5fd23c0e0..8cc4d054e72 100644 --- a/packages/objectql/src/protocol-registry-heal-packageless-refusal.test.ts +++ b/packages/objectql/src/protocol-registry-heal-packageless-refusal.test.ts @@ -161,7 +161,9 @@ describe('[#32366, ruling 6812637203 Q2] a refused package-less heal retires the * slot, so the non-holder's read served the deleted body and each holder's * read was refused with the non-holder as its candidate. Every other * package-slotted type already retires the row's own package slot (#33127); - * for those only the line moves (`action` below, the CONTROL). + * for those only the line moves (`action` below, the CONTROL). Since #32780 a + * `permission` row bound to a package takes that package's own slot too, so + * `permission` reads as the CONTROL and `flow` alone keeps the bare-slot shape. * * The holders here are served by the metadata service only (no composite slot * in the registry), the shape Q2's first pin measures. @@ -202,7 +204,7 @@ describe('[#32620, ruling 6818436831] a refused heal of a non-holder\'s row reti const holders = (order: readonly string[]) => [...order].map((id) => ({ kind: 'package', packageId: id })); - for (const type of ['flow', 'permission']) { + for (const type of ['flow']) { for (const order of [[A, B], [B, A]] as const) { it(`${type} (${order[0] === A ? 'alpha' : 'beta'} first): the non-holder's removed row leaves the bare slot; each holder's read answers its own item, the bare read is the 409 naming both holders, and the list shows the two holders only`, async () => { const h = await boot(type, order); @@ -229,11 +231,11 @@ describe('[#32620, ruling 6818436831] a refused heal of a non-holder\'s row reti } } - it('CONTROL — action, whose bound row takes its package\'s own slot (#33127): the holders serve as before the move, and the line says that slot was retired', async () => { - const h = await boot('action', [A, B]); + it.each(['action', 'permission'])('CONTROL — %s, whose bound row takes its package\'s own slot (#33127, #32780): the holders serve as before the move, and the line says that slot was retired', async (type) => { + const h = await boot(type, [A, B]); expect(h.bareEntry()).toBeUndefined(); - await h.protocol.deleteMetaItem({ type: 'action', name: NAME, packageId: O }); + await h.protocol.deleteMetaItem({ type, name: NAME, packageId: O }); expect(h.bareEntry()).toBeUndefined(); expect([await h.read(A), await h.read(B), await h.read(O)]).toEqual([`shipped:${A}`, `shipped:${B}`, undefined]); From f64e61a57968524deaf10e394db6237654d5b98a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 23:20:31 +0000 Subject: [PATCH 09/11] fix(objectql): the cold boot reads a stored set bound to the declaring package in its own slot as the environment's Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- ...2780-stored-permission-set-package-slot.md | 14 +++++++---- ...rmission-set-name-registry-reading.test.ts | 23 +++++++++++++++---- packages/objectql/src/registry.ts | 11 ++++++++- 3 files changed, 39 insertions(+), 9 deletions(-) diff --git a/.changeset/32780-stored-permission-set-package-slot.md b/.changeset/32780-stored-permission-set-package-slot.md index d1565b468b0..721c7394412 100644 --- a/.changeset/32780-stored-permission-set-package-slot.md +++ b/.changeset/32780-stored-permission-set-package-slot.md @@ -1,19 +1,25 @@ --- '@objectstack/metadata-protocol': patch +'@objectstack/objectql': patch --- -fix(metadata-protocol): two namespaces' stored permission sets of one name are each kept and served at their own package +fix(metadata-protocol)!: two namespaces' stored permission sets of one name are each kept and served at their own package -Clause-②: yes (widening) +Clause-②: yes (narrowing) — widened: a save, publish or restore of a permission set whose name a package of another namespace stores moves from `422 NAMESPACE_CONFLICT` to saved, and each package serves its own stored set; narrowed: after a restart, a grant naming no package of a name two packages hold (one ships it, one of another namespace stores it) moves from conferring a set to conferring nothing, as the running kernel already answered before the restart (ADR-0150 D3). Metadata-protocol: none + + +**BREAKING** for a grant that names no package while two packages hold the set's name: a grant naming no package confers nothing when two packages hold the name, after a restart as before it. Name the package on the grant (`permission_set_package`) to confer that package's set. A name one package holds confers as before. + A permission set is `(package, name)` (ADR-0150 D2). The host kernel now keeps a stored permission set bound to a package in that package's own registry slot, at the save's write-through and at the boot hydration alike. It used to put every stored set of a name into the name's one bare registry entry, so a second package's set of the name took the first one's place. The save door therefore refused it, even when the two packages had two namespaces. What moves, for packages `crm` and `hr` of two namespaces: -- FROM `422 NAMESPACE_CONFLICT` naming `crm` TO saved, for `hr`'s save, publish or restore of a set whose name `crm` stores. `crm`'s own save of a set of the name beside the one `hr` stores, and a third namespace's, are admitted too. A grant bound to each package confers that package's set, in every order the boot reads the stored rows. A grant naming no package of a name two packages hold confers nothing, as for two shipped sets (ADR-0150 D3). +- FROM `422 NAMESPACE_CONFLICT` naming `crm` TO saved, for `hr`'s save, publish or restore of a set whose name `crm` stores. `crm`'s own save of a set of the name beside the one `hr` stores, and a third namespace's, are admitted too. A grant bound to each package confers that package's set, in every order the boot reads the stored rows. +- FROM a set TO nothing, for a grant naming no package of a name `crm` ships and `hr` stores, after a restart (ADR-0150 D3), as for two shipped sets. - A set `hr` stores beside a set `crm` ships is `hr`'s own set: it is served at `hr`, `crm` keeps serving the set it ships, and the stored set is tenant-authored and bound to `hr`. The packaged-permission-set lock reads only the shipped set as packaged. - A delete of one package's stored set retires that package's slot alone, and the other package's set stays served, before and after a restart. - The refusal that stays (two packages of one namespace, a platform namespace, a package with no namespace, the environment, a name the platform requests by spelling) now names steps the writer can take: rename its own set, or delete a set the environment or another package stores. It no longer tells the writer to rename the set inside another package. Envelope unchanged: `422 NAMESPACE_CONFLICT`. -Nothing to migrate. A package-less stored permission row keeps the name's bare registry entry, as before. +Unchanged (ADR-0048 N.3): a stored set bound to the package that declares the name is the environment's at the cold boot, so the boot still refuses with `422 NAMESPACE_CONFLICT` naming that package. A package-less stored permission row keeps the name's bare registry entry, as before. diff --git a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts index 6da8a4454a3..406497b464b 100644 --- a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts +++ b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts @@ -572,18 +572,33 @@ describe('[#32780] two namespaces\' stored permission sets of one name: each ser } } - it('crm declares a set, hr saves one of the name, then crm saves its own and a third namespace saves one: each lands and each is served at its own package, also after a restart (FROM: crm\'s and fin\'s saves refused naming hr)', async () => { + it('crm declares a set, hr saves one of the name, then crm saves its own and a third namespace saves one: each lands and each is served at its own package (FROM: crm\'s and fin\'s saves refused naming hr)', async () => { const stores: Stores = new Map(); const { engine, protocol } = await boot(stores, [CRM, HR, FIN], undefined, { [CRM]: [N] }); expect((await save(protocol, HR, 'cap_hr')).success, 'hr\'s save beside crm\'s declared set').toBe(true); - expect((await save(protocol, CRM, 'cap_crm')).success, 'crm\'s own save').toBe(true); expect((await save(protocol, FIN, 'cap_fin')).success, 'a third namespace\'s save').toBe(true); + const othersOnly: Stores = new Map([...stores].map(([table, rows]) => [table, new Map(rows)])); + expect((await save(protocol, CRM, 'cap_crm')).success, 'crm\'s own save').toBe(true); const served = { [CRM]: ['cap_crm'], [HR]: ['cap_hr'], [FIN]: ['cap_fin'] }; expect(await grants(engine, [CRM, HR, FIN]), 'the running kernel').toEqual(served); expect(await confers(engine, null)).toEqual([]); - for (const rows of [stores, reversedRows(stores)]) { + // The other namespaces' stored sets are their own packages': a restart beside crm's declared set boots and serves each. + for (const rows of [othersOnly, reversedRows(othersOnly)]) { const restarted = await boot(rows, [CRM, HR, FIN], undefined, { [CRM]: [N] }); - expect(await grants(restarted.engine, [CRM, HR, FIN]), 'after a restart').toEqual(served); + expect(await grants(restarted.engine, [HR, FIN]), 'after a restart').toEqual({ [HR]: ['cap_hr'], [FIN]: ['cap_fin'] }); + } + }); + + it('CONTROL (ADR-0048 N.3) — a stored set bound to the package that declares the name is the environment\'s at the cold boot, as before: the restart is refused naming that package alone', async () => { + const stores: Stores = new Map(); + const first = await boot(stores, [CRM, HR], undefined, { [CRM]: [N] }); + expect((await save(first.protocol, HR, 'cap_hr')).success).toBe(true); + expect((await save(first.protocol, CRM, 'cap_crm')).success).toBe(true); + for (const rows of [stores, reversedRows(stores)]) { + const error: any = await refusal(() => boot(rows, [CRM, HR], undefined, { [CRM]: [N] })); + const envelope = error?.cause ?? error; + expect([envelope?.code, envelope?.status]).toEqual(['NAMESPACE_CONFLICT', 422]); + expect(envelope?.conflicts).toEqual([{ catalogType: 'permission', name: N, incomingPackageId: CRM, existingHolder: { kind: 'environment' } }]); } }); diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 32b01657cd4..bb80a650f8f 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -5201,6 +5201,10 @@ export class SchemaRegistry { * boot hydration grafts the package's envelope onto the stored row (the * protocol's artifact-protection merge), so the stamp names the very * package the row collides with. + * A stored row bound to the declaring package itself is the environment's + * too where it sits in that package's own overlay slot ({@link overlaySlotKey}; + * a stored permission set bound to a package takes it, #32780): it counts + * against that package alone, and a row in another package's slot does not. * - **A package holds a name** through an item registered under it (its * composite slot) or its install claim — never through the bare slot. * - **Built-in names are skipped**, as the item seam skips the environment @@ -5225,11 +5229,16 @@ export class SchemaRegistry { private environmentHeldSecurityCatalogConflicts(): SecurityCatalogNameConflict[] { const conflicts: SecurityCatalogNameConflict[] = []; for (const { catalogType, name, packageIds } of this.packageHeldSecurityCatalogNames()) { + const collection = this.metadata.get(catalogType); // The environment's item: the bare slot, whatever `_packageId` it wears. // A held name never contains `:` and is never a built-in, so this is the // bare-slot reading the method header states. - if (!this.metadata.get(catalogType)?.has(name)) continue; + const bare = collection?.has(name) === true; for (const packageId of packageIds) { + // [ADR-0048 N.3, #32780] A stored row bound to the declaring package + // itself is the environment's too, also where it took that package's + // own overlay slot (a stored permission set does since #32780). + if (!bare && collection?.has(overlaySlotKey(packageId, name)) !== true) continue; conflicts.push({ catalogType, name, incomingPackageId: packageId, existingHolder: { kind: 'environment' } }); } } From 3a6b040c51534ae545e405f444ed2cdcb25f1583 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 02:24:18 +0000 Subject: [PATCH 10/11] fix(objectql): a package's overlay slot counts as a holder of its name at every security-catalog name check Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- .../src/protocol-save-door-refusals.ts | 2 +- ...rmission-set-name-registry-reading.test.ts | 55 ++++++++++++++++++- packages/objectql/src/registry.ts | 38 ++++++++++--- 3 files changed, 84 insertions(+), 11 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-save-door-refusals.ts b/packages/metadata-protocol/src/protocol-save-door-refusals.ts index 48173add5f9..c4e276f2410 100644 --- a/packages/metadata-protocol/src/protocol-save-door-refusals.ts +++ b/packages/metadata-protocol/src/protocol-save-door-refusals.ts @@ -376,7 +376,7 @@ function registryPackageHoldersOf(registry: unknown, name: string): readonly str * ## The holders: two readings, met * * - **The stored active rows** of the environment (ADR-0131 D6), by - * ``package_id`. A set published through the metadata door is stored, and + * `package_id`. A set published through the metadata door is stored, and * the registry holds it in its package's overlay slot, which the * registry's package-held reading does not count, so only the row says * which package it belongs to — the half the registry's reading cannot see, diff --git a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts index 406497b464b..a7f923ec0c9 100644 --- a/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts +++ b/packages/objectql/src/protocol-permission-set-name-registry-reading.test.ts @@ -469,7 +469,8 @@ describe('[#32780] two namespaces\' stored permission sets of one name: each ser const FIN = 'com.qa.fin'; /** A second package of the `crm` namespace: its co-owner (CONTROL). */ const CRM_TWO = 'com.qa.crm_two'; - const NS: Record = { [CRM]: 'crm', [HR]: 'hr', [FIN]: 'fin', [CRM_TWO]: 'crm' }; + const CRM_CUSTOM = `${CRM}.custom`; + const NS: Record = { [CRM]: 'crm', [HR]: 'hr', [FIN]: 'fin', [CRM_TWO]: 'crm', [CRM_CUSTOM]: 'crmx' }; const N = 'qa_shared_reader'; const setOf = (cap: string) => ({ ...permissionSet(N), label: cap, systemPermissions: [cap] }); const manifestOf = (id: string, sets: string[] = []) => @@ -617,6 +618,58 @@ describe('[#32780] two namespaces\' stored permission sets of one name: each ser } }); + const packageConflict = (incoming: string, holder: string) => + ({ catalogType: 'permission', name: N, incomingPackageId: incoming, existingHolder: { kind: 'package', packageId: holder } }); + const environmentConflict = (incoming: string) => + ({ catalogType: 'permission', name: N, incomingPackageId: incoming, existingHolder: { kind: 'environment' } }); + const envelopeOf = (error: any) => { + const envelope = error?.cause ?? error; + return { code: envelope?.code, status: envelope?.status, conflicts: envelope?.conflicts }; + }; + + it('a package\'s stored set counts as its holding of the name: a package of the same namespace declaring or registering the name after it is refused, and before it the save is refused', async () => { + // The stored set first, then the second holder: the package door and the item seam. + const stores: Stores = new Map(); + const { engine, protocol } = await boot(stores, [CRM]); + expect((await save(protocol, CRM, 'cap_crm')).success).toBe(true); + const installed = await refusal(async () => engine.registry.installPackage(manifestOf(CRM_TWO, [N]), 'authored')); + expect(envelopeOf(installed)).toEqual({ code: 'NAMESPACE_CONFLICT', status: 422, conflicts: [packageConflict(CRM_TWO, CRM)] }); + engine.registry.installPackage(manifestOf(CRM_TWO), 'authored'); + const registered = await refusal(async () => engine.registry.registerItem('permission', setOf('cap_crm_two') as any, 'name', CRM_TWO)); + expect(envelopeOf(registered)).toEqual({ code: 'NAMESPACE_CONFLICT', status: 422, conflicts: [packageConflict(CRM_TWO, CRM)] }); + expect(await grants(engine, [CRM])).toEqual({ [CRM]: ['cap_crm'] }); + // The second holder first, then the stored set: the save door. + const other = await boot(new Map(), [CRM]); + other.engine.registry.installPackage(manifestOf(CRM_TWO, [N]), 'authored'); + const saved = await refusal(() => save(other.protocol, CRM, 'cap_crm')); + expect([saved?.code, saved?.status]).toEqual(['NAMESPACE_CONFLICT', 422]); + // A package of another namespace still declares the name beside the stored set. + engine.registry.installPackage(manifestOf(HR, [N]), 'authored'); + }); + + it('a cold boot over a package\'s stored set is refused when a package of the same namespace declares the name, as before (ADR-0048 N.3)', async () => { + const stores: Stores = new Map(); + const first = await boot(stores, [CRM]); + expect((await save(first.protocol, CRM, 'cap_crm')).success).toBe(true); + const error = await refusal(() => boot(stores, [CRM, CRM_TWO], undefined, { [CRM_TWO]: [N] })); + expect(envelopeOf(error)).toEqual({ code: 'NAMESPACE_CONFLICT', status: 422, conflicts: [environmentConflict(CRM_TWO)] }); + // CONTROL: a package of another namespace declaring the name boots beside the stored set. + const booted = await boot(stores, [CRM, HR], undefined, { [HR]: [N] }); + expect(await grants(booted.engine, [CRM])).toEqual({ [CRM]: ['cap_crm'] }); + }); + + it('a cold boot over a stored set held against a package that ships the name is refused, as before (ADR-0048 N.3)', async () => { + const stores: Stores = new Map(); + const first = await boot(stores, [CRM, HR, CRM_CUSTOM]); + expect((await save(first.protocol, HR, 'cap_other')).success).toBe(true); + const rows = stores.get('sys_metadata')!; + const [key, row] = [...rows].find(([, r]) => r.type === 'permission')!; + rows.set(key, { ...row, package_id: CRM_CUSTOM }); + const ship = (target: ObjectQL) => target.registry.registerItem('permission', setOf('cap_crm_shipped') as any, 'name', CRM); + const error = await refusal(() => boot(stores, [CRM, HR, CRM_CUSTOM], ship)); + expect(envelopeOf(error)).toEqual({ code: 'NAMESPACE_CONFLICT', status: 422, conflicts: [environmentConflict(CRM)] }); + }); + it('CONTROL — a second package of the SAME namespace is still refused beside a stored set; the remedy names steps the writer can take, never an edit inside the other package', async () => { const stores: Stores = new Map(); const { engine, protocol } = await boot(stores, [CRM, CRM_TWO]); diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index bb80a650f8f..d0d11a40cfd 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -5055,7 +5055,9 @@ export class SchemaRegistry { * {@link BUILT_IN_SECURITY_CATALOG_NAMES} for why the item seam does not ask); * the bare slot (an override a package bound to itself, else an * environment-authored item — the latter only when `environment`); every - * composite `:` slot; the package claims. A package that + * composite `:` slot; every package overlay slot (a stored + * item bound to a package is that package's holding, #32780); the package + * claims. A package that * holds the name more than one way is one holder. A disabled package is still * installed, and still holds its names. * @@ -5090,6 +5092,11 @@ export class SchemaRegistry { kind: 'package', packageId: typeof stamped === 'string' && stamped !== '' ? stamped : key.slice(0, -suffix.length), }); + } else { + // [#32780] A package's overlay slot counts as a holder of its name: + // the stored set bound to that package is its holding. + const slot = parseOverlaySlotKey(key); + if (slot !== undefined && slot.bareKey === name) add({ kind: 'package', packageId: slot.packageId }); } } for (const claimant of this.securityCatalogClaims.get(type)?.get(name) ?? []) add({ kind: 'package', packageId: claimant }); @@ -5201,10 +5208,13 @@ export class SchemaRegistry { * boot hydration grafts the package's envelope onto the stored row (the * protocol's artifact-protection merge), so the stamp names the very * package the row collides with. - * A stored row bound to the declaring package itself is the environment's - * too where it sits in that package's own overlay slot ({@link overlaySlotKey}; - * a stored permission set bound to a package takes it, #32780): it counts - * against that package alone, and a row in another package's slot does not. + * A stored row in a package overlay slot ({@link overlaySlotKey}; a stored + * permission set bound to a package takes one, #32780) is the environment's + * too where it is held against the declaring package: the declarer's own + * slot, a slot whose item is served as the declarer's, or, for a permission + * set, the slot of a package that meets the declarer under the one + * predicate ({@link permissionSetHoldersMeet}). A slot of a package of + * another namespace is that package's own set and holds nothing against it. * - **A package holds a name** through an item registered under it (its * composite slot) or its install claim — never through the bare slot. * - **Built-in names are skipped**, as the item seam skips the environment @@ -5234,11 +5244,21 @@ export class SchemaRegistry { // A held name never contains `:` and is never a built-in, so this is the // bare-slot reading the method header states. const bare = collection?.has(name) === true; + const stored = collection === undefined ? [] : overlaySlotEntriesOf(collection, name).map((entry) => ({ + packageId: storedRowPackageOf(entry)!, + stamped: (entry.item as { _packageId?: unknown } | null | undefined)?._packageId, + })); for (const packageId of packageIds) { - // [ADR-0048 N.3, #32780] A stored row bound to the declaring package - // itself is the environment's too, also where it took that package's - // own overlay slot (a stored permission set does since #32780). - if (!bare && collection?.has(overlaySlotKey(packageId, name)) !== true) continue; + // [ADR-0048 N.3, #32780] A stored row in a package overlay slot is the + // environment's too when it is held against the declaring package: the + // declarer's own slot, a slot whose item is served as the declarer's, + // or (a permission set) the slot of a package that meets the declarer + // under the one predicate; any slot for a type of one holder per name. + const heldAgainst = (slot: { packageId: string; stamped: unknown }) => slot.packageId === packageId + || slot.stamped === packageId + || catalogType !== 'permission' + || permissionSetHoldersMeet(this.bareNameHolderNamespace(packageId), this.bareNameHolderNamespace(slot.packageId), name); + if (!bare && !stored.some(heldAgainst)) continue; conflicts.push({ catalogType, name, incomingPackageId: packageId, existingHolder: { kind: 'environment' } }); } } From 0e5a620352d6c9dd85b0a51b17af4a1530722c9b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 02:25:25 +0000 Subject: [PATCH 11/11] docs(changeset): restate the permission-set move from the measured restart answers Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- .../32780-stored-permission-set-package-slot.md | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/.changeset/32780-stored-permission-set-package-slot.md b/.changeset/32780-stored-permission-set-package-slot.md index 721c7394412..d2de21addd2 100644 --- a/.changeset/32780-stored-permission-set-package-slot.md +++ b/.changeset/32780-stored-permission-set-package-slot.md @@ -3,23 +3,18 @@ '@objectstack/objectql': patch --- -fix(metadata-protocol)!: two namespaces' stored permission sets of one name are each kept and served at their own package +fix(metadata-protocol): two namespaces' stored permission sets of one name are each kept and served at their own package -Clause-②: yes (narrowing) — widened: a save, publish or restore of a permission set whose name a package of another namespace stores moves from `422 NAMESPACE_CONFLICT` to saved, and each package serves its own stored set; narrowed: after a restart, a grant naming no package of a name two packages hold (one ships it, one of another namespace stores it) moves from conferring a set to conferring nothing, as the running kernel already answered before the restart (ADR-0150 D3). +Clause-②: yes (widening) — widened: a save, publish or restore of a permission set whose name a package of another namespace stores moves from `422 NAMESPACE_CONFLICT` to saved; and a restart over a stored set of one package beside a set of the name another namespace's package ships or declares moves from a boot refused with `422 NAMESPACE_CONFLICT` to a boot that serves each package's set at its package. Metadata-protocol: none - - -**BREAKING** for a grant that names no package while two packages hold the set's name: a grant naming no package confers nothing when two packages hold the name, after a restart as before it. Name the package on the grant (`permission_set_package`) to confer that package's set. A name one package holds confers as before. - -A permission set is `(package, name)` (ADR-0150 D2). The host kernel now keeps a stored permission set bound to a package in that package's own registry slot, at the save's write-through and at the boot hydration alike. It used to put every stored set of a name into the name's one bare registry entry, so a second package's set of the name took the first one's place. The save door therefore refused it, even when the two packages had two namespaces. +A permission set is `(package, name)` (ADR-0150 D2). The host kernel now keeps a stored permission set bound to a package in that package's own registry slot, at the save's write-through and at the boot hydration alike. It used to put every stored set of a name into the name's one bare registry entry, so a second package's set of the name took the first one's place. The save door therefore refused it, even when the two packages had two namespaces, and a restart over a stored set beside another namespace's shipped or declared set of the name was refused. What moves, for packages `crm` and `hr` of two namespaces: - FROM `422 NAMESPACE_CONFLICT` naming `crm` TO saved, for `hr`'s save, publish or restore of a set whose name `crm` stores. `crm`'s own save of a set of the name beside the one `hr` stores, and a third namespace's, are admitted too. A grant bound to each package confers that package's set, in every order the boot reads the stored rows. -- FROM a set TO nothing, for a grant naming no package of a name `crm` ships and `hr` stores, after a restart (ADR-0150 D3), as for two shipped sets. -- A set `hr` stores beside a set `crm` ships is `hr`'s own set: it is served at `hr`, `crm` keeps serving the set it ships, and the stored set is tenant-authored and bound to `hr`. The packaged-permission-set lock reads only the shipped set as packaged. +- FROM a boot refused with `422 NAMESPACE_CONFLICT` TO a boot that serves each set at its package, for a restart over a set `hr` stores beside a set of the name `crm` ships or declares. `crm` keeps serving the set it ships, `hr` serves the set it stores, and the stored set is tenant-authored and bound to `hr`. The packaged-permission-set lock reads only the shipped set as packaged. - A delete of one package's stored set retires that package's slot alone, and the other package's set stays served, before and after a restart. - The refusal that stays (two packages of one namespace, a platform namespace, a package with no namespace, the environment, a name the platform requests by spelling) now names steps the writer can take: rename its own set, or delete a set the environment or another package stores. It no longer tells the writer to rename the set inside another package. Envelope unchanged: `422 NAMESPACE_CONFLICT`. -Unchanged (ADR-0048 N.3): a stored set bound to the package that declares the name is the environment's at the cold boot, so the boot still refuses with `422 NAMESPACE_CONFLICT` naming that package. A package-less stored permission row keeps the name's bare registry entry, as before. +Unchanged: a package's stored set counts as its holding of the name at every name check. A package of the same namespace declaring or registering the name beside it is refused with `422 NAMESPACE_CONFLICT`, and so is a cold boot where it is held against a package that declares or ships the name (ADR-0048 N.3), including a stored set bound to the declaring package itself. A grant naming no package of a name two packages hold confers nothing (ADR-0150 D3). A package-less stored permission row keeps the name's bare registry entry, as before.