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..d2de21addd2 --- /dev/null +++ b/.changeset/32780-stored-permission-set-package-slot.md @@ -0,0 +1,20 @@ +--- +'@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 + +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 + +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 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: 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. diff --git a/packages/metadata-protocol/src/protocol-registry-hydration.ts b/packages/metadata-protocol/src/protocol-registry-hydration.ts index e31d31d79f2..d7d391da52d 100644 --- a/packages/metadata-protocol/src/protocol-registry-hydration.ts +++ b/packages/metadata-protocol/src/protocol-registry-hydration.ts @@ -212,7 +212,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); @@ -267,12 +271,39 @@ 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 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, + 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. */ @@ -889,9 +920,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 @@ -1958,7 +1992,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..c4e276f2410 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 * @@ -376,8 +377,8 @@ function registryPackageHoldersOf(registry: unknown, name: string): readonly str * * - **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 + * 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; 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..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 @@ -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'; @@ -120,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'; @@ -295,20 +312,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([ @@ -408,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); @@ -426,3 +434,267 @@ 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 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 + * 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 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[] = []) => + ({ + 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 (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, declares[id]), 'authored'); + before?.(engine); + 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 }); + return grantConfers(engine, catalog, N, column); + } + + /** 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 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, 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([]); + // 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, [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' } }]); + } + }); + + 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 }, + ]); + } + }); + + 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]); + 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])).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 () => { + 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/protocol-registry-heal-packageless-refusal.test.ts b/packages/objectql/src/protocol-registry-heal-packageless-refusal.test.ts index 7ab64629f6d..36b38dc4ef6 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]); diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 3b59a0175a2..24349f24661 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -5094,7 +5094,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. * @@ -5129,6 +5131,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 }); @@ -5240,6 +5247,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 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 @@ -5264,11 +5278,26 @@ 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; + 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 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' } }); } } 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..ff25a719d43 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,14 @@ 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 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; - 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..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,6 +30,8 @@ import { PackagedPermissionSetProvenanceUnknownError, } from './packaged-permission-set-lock.js'; import { registerPackagedPermissionSetLockGate } from './packaged-permission-set-lock-gate.js'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SchemaRegistry } from '@objectstack/objectql'; // ───────────────────────────────────────────────────────────────────────────── // Doubles @@ -367,3 +369,63 @@ 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. + */ +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; + }, + 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', 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] }); + }); +});