diff --git a/.changeset/34401-own-permission-set-restore.md b/.changeset/34401-own-permission-set-restore.md new file mode 100644 index 00000000000..3e7a3727b97 --- /dev/null +++ b/.changeset/34401-own-permission-set-restore.md @@ -0,0 +1,16 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): a package's rollback, commit revert or package rollback of its own permission set is no longer refused because a package of another namespace ships a set of that name + +Clause-②: yes (widening) — a rollback, a commit revert or a package rollback of a package's own permission set N, refused 403 `NOT_OVERRIDABLE` ("provided by a managed package and is sealed") while a package of another namespace ships N, now restores; a delete of that set answers "Deleted permission 'N' (package=P) — it no longer exists." in place of "Customization overlay deleted (package=P) — permission/N reset to artifact default.", with `reset: true` as before; nothing the doors accepted is refused +Metadata-protocol: none + +A permission set is `(package, name)` (ADR-0150 D2/D9). The save door, the draft publish and the publish undo already judge a write of a package's own set `N` by the package it is addressed to. The per-item rollback (`POST /api/v1/meta/:type/:name/rollback`), the commit revert (`POST /packages/:id/commits/:commitId/revert`) and the package rollback (`POST /packages/:id/rollback`, which reverts commit by commit) still judged the name alone: when package `crm` shipped `N`, package `hr` of another namespace could not restore an earlier version of its own `N`. The rollback answered 403 `NOT_OVERRIDABLE`, and a revert listed `N` in `failed[]`. + +Those restores now read the same verdict as the save. A restore into `hr`'s own `N` is a runtime write to `hr`, so the earlier version is restored and `hr`'s grants confer it. Every package that ships the name is judged, so the answer is the same in every registration order. A restore into a row bound to no package, to the shipper, to the shipper's customization pair or to a package that shares the shipper's set of the name is refused exactly as before. + +A delete of `hr`'s own `N` already succeeded, but its receipt said an overlay was deleted and `N` was reset to its artifact default. `hr` ships no `N`, so the receipt now says the set was deleted and no longer exists. A delete naming `hr` when `hr` holds no `N` answers "nothing to delete" in place of "already at artifact default". The receipts for a customization of a shipped set are unchanged. + +Nothing to migrate. diff --git a/packages/metadata-protocol/src/protocol-class-head.ts b/packages/metadata-protocol/src/protocol-class-head.ts index ba260c9f2c5..40831746248 100644 --- a/packages/metadata-protocol/src/protocol-class-head.ts +++ b/packages/metadata-protocol/src/protocol-class-head.ts @@ -42,7 +42,7 @@ import type { IObjectQLEngine, IPubSub } from '@objectstack/spec/contracts'; import { isPairOf } from '@objectstack/metadata-core'; import { installedManifestsOfEngine } from './installed-manifests.js'; import { someShipperOf } from './protocol-environment-rows.js'; -import { overrideWriteRefusalError } from './protocol-packaged-base-refusal.js'; +import { isOwnPermissionSetWrite, overrideWriteRefusalError } from './protocol-packaged-base-refusal.js'; import { OBJECT_EXTENSION_TYPE, registrableObjectExtension } from './protocol-object-extension-item.js'; import type { ObjectExtensionRegistry } from './protocol-object-extension-item.js'; import { canonicalMetaType } from './protocol-meta-type-schema.js'; @@ -201,19 +201,27 @@ export class ProtocolClassHeadFacet { * `deriveRestoredBody`, so nothing is written. Any other binding: the * caller's `artifactBacked` decides the intent, and the body writer is * {@link restoredBodyWriter}'s alone. + * + * [ADR-0150 D2, #34401] A restore into a package's OWN permission set, + * beside sets other namespaces' packages ship, overrides no shipped set, + * so the name-wide `artifactBacked` is narrowed by the verdict the save, + * publish and undo doors read ({@link isOwnPermissionSetWrite}): the + * store is told a runtime-only write, as that package's save is. Every + * restore that does override a shipped set keeps the intent it had. */ static restoreWriteFor(host: Pick, singularType: string, name: string, binding: string | null, artifactBacked: boolean, source: string,): { intent: 'override-artifact' | 'runtime-only'; deriveRestoredBody: (historyBody: unknown) => Promise } { + const overridesShipped = artifactBacked && !isOwnPermissionSetWrite(host.engine, singularType, name, binding); // [ADR-0150 D4, #32552] The binding is judged against every package // that ships the name ({@link someShipperOf}): each namespace's holder // has its own pair, never only the shipper registered first. const installed = installedManifestsOfEngine(host.engine); - const pairRow = artifactBacked && someShipperOf(host, singularType, name, + const pairRow = overridesShipped && someShipperOf(host, singularType, name, (owner) => owner !== undefined && isPairOf(binding, owner, installed)); - const intent: 'override-artifact' | 'runtime-only' = artifactBacked && !pairRow ? 'override-artifact' : 'runtime-only'; + const intent: 'override-artifact' | 'runtime-only' = overridesShipped && !pairRow ? 'override-artifact' : 'runtime-only'; const writeRestored = host.restoredBodyWriter(singularType, name, binding, source); const deriveRestoredBody = pairRow ? async (historyBody: unknown): Promise => { diff --git a/packages/metadata-protocol/src/protocol-diff-delete-load.ts b/packages/metadata-protocol/src/protocol-diff-delete-load.ts index 9893064fbf6..6ff0a8b003b 100644 --- a/packages/metadata-protocol/src/protocol-diff-delete-load.ts +++ b/packages/metadata-protocol/src/protocol-diff-delete-load.ts @@ -47,7 +47,7 @@ import type { ServedOverrideRow } from './served-override.js'; import { REFERENCE_SITES } from './reference-sites.js'; import { computeMetadataDiagnostics } from './metadata-diagnostics.js'; import { hasMetadataRedactor, redactMetadataItem } from './metadata-redaction.js'; -import { isPairRowRemoval } from './protocol-packaged-base-refusal.js'; +import { isOwnPermissionSetWrite, isPairRowRemoval } from './protocol-packaged-base-refusal.js'; import { canonicalMetaType, canonicalizeMetaRequestType } from './protocol-meta-type-schema.js'; import { boundPackageOf, servesSealedOverrideRow } from './protocol-package-bindings.js'; import { remainingRowsPhrase } from './protocol-authoring-refusals.js'; @@ -750,6 +750,13 @@ export class ProtocolDiffDeleteLoadFacet { } const packageId: string | null = request.packageId ?? (draftAddress !== undefined ? draftAddress.key : rowsAtAddress.packageId); + // [ADR-0150 D2, #34401] Whether a code-shipped item sits under + // THIS address, which the two receipts below claim: a package's + // own permission set beside sets other namespaces' packages ship + // has none ({@link isOwnPermissionSetWrite}, the verdict its save + // reads), so removing it removes the set, never resets one. + const shippedUnderAddress = artifactBacked + && !isOwnPermissionSetWrite(host.engine, singularTypeForRepo, request.name, packageId); // Probe first — "no overlay exists" is a success/no-op, not // a conflict. The repo would otherwise throw ConflictError. const current = await repo.get(ref, { state: targetState, packageId, ...memberOption(member) }); @@ -817,7 +824,7 @@ export class ProtocolDiffDeleteLoadFacet { // unchanged, verbatim. message: targetState === 'draft' ? `No pending draft for ${request.type}/${request.name}.` - : artifactBacked + : shippedUnderAddress ? `No customization overlay found for ${request.type}/${request.name} — already at artifact default.` : `No ${singularTypeForRepo} '${request.name}' found — nothing to delete.`, }; @@ -1005,7 +1012,7 @@ export class ProtocolDiffDeleteLoadFacet { // discard reads byte for byte as before. message: (request.state === 'draft') ? `Draft discarded${deletedPackage} — ${request.type}/${request.name}. [seq=${result.seq}]` - : artifactBacked + : shippedUnderAddress ? (remains ? `Customization overlay deleted${deletedPackage} — ${request.type}/${request.name} still carries another overlay: ${remainingRowsPhrase(remainingPackages, unboundRemains, 'row')}. [seq=${result.seq}]` : `Customization overlay deleted${deletedPackage} — ${request.type}/${request.name} reset to artifact default. [seq=${result.seq}]`) diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.test.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.test.ts index e2acb13951a..cb7d1b68251 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.test.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.test.ts @@ -106,6 +106,7 @@ function makeFakeEngine(opts?: { listItemsThrows?: boolean }) { ]; return { rows, + historyRows, manifests: new Map([[PKG, { id: PKG }]]), registry: { getPackage: () => undefined, @@ -143,7 +144,9 @@ function makeFakeEngine(opts?: { listItemsThrows?: boolean }) { historyRows.push(h); return { id: h.id as string }; } - const k = keyOf(data, table); + // A metadata row is keyed by its address; a row of any other table (a + // package commit) by its own id, so a second one never replaces the first. + const k = table === 'sys_metadata' ? keyOf(data, table) : `${table}|${String(data.id ?? rows.size + 1)}`; const row: Row = { id: `r_${rows.size + 1}`, __table: table, ...data }; rows.set(k, row); return { id: row.id as string }; @@ -314,6 +317,68 @@ describe('#11843 — the lock answers at the metadata door', () => { // [ADR-0150 D2, #34226] The seal and the lock judge a save by (package, name) // ───────────────────────────────────────────────────────────────────────────── +// The composition both permission-set describes below share: the packages, the set N, +// the real protocol and registry over this file's fake engine, and the grant reader. +const CRM = 'com.qa.crm'; +const HR = 'com.qa.hr'; +const FIN = 'com.qa.fin'; +/** A second package of the `crm` namespace: it shares crm's set of a name. */ +const CRM_TWO = 'com.qa.crm_two'; +/** crm's customization pair, with a namespace of its own. */ +const CRM_PAIR = `${CRM}.custom`; +const NS: Record = { [CRM]: 'crm', [HR]: 'hr', [FIN]: 'fin', [CRM_TWO]: 'crm', [CRM_PAIR]: 'crmx' }; +const N = 'qa_shared_reader'; +const setOf = (cap: string) => ({ name: N, label: cap, objects: {}, systemPermissions: [cap] }); + +type Order = 'shipped first' | 'shipped last'; +const ORDERS: readonly Order[] = ['shipped first', 'shipped last']; + +/** The composition: `shippers` ship N, every package of {@link NS} installed, in `order`. */ +async function composition(order: Order, shippers: readonly string[] = [CRM]) { + const registry = new SchemaRegistry(); + registry.logLevel = 'silent'; + const install = (id: string) => registry.installPackage( + { id, name: id, version: '1.0.0', type: 'app', namespace: NS[id], ...(id === CRM_TWO ? { dependencies: { [CRM]: '^1.0.0' } } : {}) } as never, + 'authored', + ); + const ship = () => { for (const id of shippers) registry.registerItem('permission', setOf(`cap_${NS[id]}_shipped`) as never, 'name' as never, id); }; + if (order === 'shipped first') { + for (const id of shippers) install(id); + ship(); + for (const id of Object.keys(NS)) if (!shippers.includes(id)) install(id); + } else { + for (const id of Object.keys(NS)) install(id); + ship(); + } + const engine = makeFakeEngine(); + (engine as { registry: unknown }).registry = registry; + const protocol = new ObjectStackProtocolImplementation(engine as never, () => new Map(), undefined) as unknown as { + saveMetaItem(req: Record): Promise; + }; + expect(registerPackagedPermissionSetLockGate(protocol, engine)).toBe(true); + // The lock gate alone, on the same registry, for the arms the seal answers first. + let gate: ((ctx: Record) => Promise) | undefined; + registerPackagedPermissionSetLockGate({ registerAuthoringGate: (_t: string, g: typeof gate) => { gate = g; } }, engine); + return { engine, protocol, registry, gate: (packageId?: string) => gate!({ type: 'permission', name: N, body: setOf('cap'), ...(packageId ? { packageId } : {}) }).then(() => null, (e: unknown) => e) }; +} + +/** What one grant of N with this package column confers, read by the authorization resolver. */ +async function confers(registry: unknown, 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: N, permission_set_package: column, organization_id: 'org_a' }], + }; + const ql = { + registry, + find: async (object: string) => rows[object] ?? [], + findOne: async (object: string, query?: unknown) => { assertEngineFindOnePredicate(object, query as never); return rows[object]?.[0]; }, + count: async () => 0, + }; + bindSecurityCatalogReader(ql, createSecurityCatalogReader({ registry: registry as never, metadata: { get: () => undefined, list: () => [] } as never })); + return (await resolveUserAuthzGrants(ql, 'u1', { tenantId: 'org_a' })).systemPermissions; +} + /** * A permission set is `(package, name)` (ADR-0150 D2), one set per namespace * (D9). Package `crm` ships the set N. Package `hr`, of another namespace, then @@ -336,66 +401,6 @@ describe('#11843 — the lock answers at the metadata door', () => { * packages install, and after. */ describe('[#34226] a permission set is (package, name): the seal and the lock judge a save by the package it addresses', () => { - const CRM = 'com.qa.crm'; - const HR = 'com.qa.hr'; - const FIN = 'com.qa.fin'; - /** A second package of the `crm` namespace: it shares crm's set of a name. */ - const CRM_TWO = 'com.qa.crm_two'; - /** crm's customization pair, with a namespace of its own. */ - const CRM_PAIR = `${CRM}.custom`; - const NS: Record = { [CRM]: 'crm', [HR]: 'hr', [FIN]: 'fin', [CRM_TWO]: 'crm', [CRM_PAIR]: 'crmx' }; - const N = 'qa_shared_reader'; - const setOf = (cap: string) => ({ name: N, label: cap, objects: {}, systemPermissions: [cap] }); - - type Order = 'shipped first' | 'shipped last'; - const ORDERS: readonly Order[] = ['shipped first', 'shipped last']; - - /** The composition: `shippers` ship N, every package of {@link NS} installed, in `order`. */ - async function composition(order: Order, shippers: readonly string[] = [CRM]) { - const registry = new SchemaRegistry(); - registry.logLevel = 'silent'; - const install = (id: string) => registry.installPackage( - { id, name: id, version: '1.0.0', type: 'app', namespace: NS[id], ...(id === CRM_TWO ? { dependencies: { [CRM]: '^1.0.0' } } : {}) } as never, - 'authored', - ); - const ship = () => { for (const id of shippers) registry.registerItem('permission', setOf(`cap_${NS[id]}_shipped`) as never, 'name' as never, id); }; - if (order === 'shipped first') { - for (const id of shippers) install(id); - ship(); - for (const id of Object.keys(NS)) if (!shippers.includes(id)) install(id); - } else { - for (const id of Object.keys(NS)) install(id); - ship(); - } - const engine = makeFakeEngine(); - (engine as { registry: unknown }).registry = registry; - const protocol = new ObjectStackProtocolImplementation(engine as never, () => new Map(), undefined) as unknown as { - saveMetaItem(req: Record): Promise; - }; - expect(registerPackagedPermissionSetLockGate(protocol, engine)).toBe(true); - // The lock gate alone, on the same registry, for the arms the seal answers first. - let gate: ((ctx: Record) => Promise) | undefined; - registerPackagedPermissionSetLockGate({ registerAuthoringGate: (_t: string, g: typeof gate) => { gate = g; } }, engine); - return { engine, protocol, registry, gate: (packageId?: string) => gate!({ type: 'permission', name: N, body: setOf('cap'), ...(packageId ? { packageId } : {}) }).then(() => null, (e: unknown) => e) }; - } - - /** What one grant of N with this package column confers, read by the authorization resolver. */ - async function confers(registry: unknown, 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: N, permission_set_package: column, organization_id: 'org_a' }], - }; - const ql = { - registry, - find: async (object: string) => rows[object] ?? [], - findOne: async (object: string, query?: unknown) => { assertEngineFindOnePredicate(object, query as never); return rows[object]?.[0]; }, - count: async () => 0, - }; - bindSecurityCatalogReader(ql, createSecurityCatalogReader({ registry: registry as never, metadata: { get: () => undefined, list: () => [] } as never })); - return (await resolveUserAuthzGrants(ql, 'u1', { tenantId: 'org_a' })).systemPermissions; - } - const sealed = (err: unknown) => { expect(err, 'refused by the seal, not by the lock').not.toBeInstanceOf(PackagedPermissionSetLockedError); expect(err).toMatchObject({ code: 'NOT_OVERRIDABLE', status: 403 }); @@ -522,3 +527,150 @@ describe('[#34226] a permission set is (package, name): the seal and the lock ju }, 30_000); } }); + +// [#34401] A rollback, a commit revert and a package rollback of hr's own set N +// write the row bound to hr, so they judge it as hr's save does: a runtime item +// to hr, never an override of crm's shipped N. A delete of it says what it did. +describe('[#34401] restoring or deleting a package\'s own set N beside another namespace\'s shipped N', () => { + type Proto = { + saveMetaItem(req: Record): Promise; + rollbackMetaItem(req: Record): Promise; + publishPackageDrafts(req: Record): Promise<{ commitId?: string; failed?: unknown[] }>; + revertCommit(req: Record): Promise<{ success: boolean; failed: Array<{ name: string; code?: string }> }>; + rollbackToPackageCommit(req: Record): Promise<{ success: boolean; failed: unknown[] }>; + deleteMetaItem(req: Record): Promise<{ success: boolean; reset?: boolean; message?: string }>; + }; + type Engine = Awaited>['engine']; + const settle = (p: Promise) => p.then((v) => ({ ok: v, err: null as unknown }), (e: unknown) => ({ ok: undefined as T | undefined, err: e })); + const envelope = (err: unknown) => [(err as { code?: unknown } | null)?.code, (err as { status?: unknown } | null)?.status]; + const activeCaps = (engine: Engine) => metaRowsOf(engine) + .filter((r) => r.state === 'active') + .map((r) => ({ package_id: r.package_id, caps: (JSON.parse(String(r.metadata)) as { systemPermissions?: string[] }).systemPermissions })); + /** Every stored row and history entry of N moved to `binding`, as a row stored before the seal would be bound. */ + const rebind = (engine: Engine, binding: string | null) => { + for (const [key, row] of engine.rows) if (row.__table === 'sys_metadata') engine.rows.set(key, { ...row, package_id: binding }); + for (const h of engine.historyRows) h.package_id = binding; + }; + + /** hr's own N saved at v1, then edited to v2, each a save addressed to hr. */ + async function savedTwice(order: Order, shippers?: readonly string[]) { + const c = await composition(order, shippers); + const p = c.protocol as unknown as Proto; + expect(await save(p, { type: 'permission', name: N, item: setOf('cap_hr_v1'), packageId: HR })).toBeNull(); + expect(await save(p, { type: 'permission', name: N, item: setOf('cap_hr_v2'), packageId: HR })).toBeNull(); + expect(activeCaps(c.engine)).toEqual([{ package_id: HR, caps: ['cap_hr_v2'] }]); + return { ...c, p }; + } + + /** hr's own N published at v1 (commit one), then edited and published at v2 (commit two). */ + async function publishedTwice(order: Order, shippers?: readonly string[]) { + const c = await composition(order, shippers); + const p = c.protocol as unknown as Proto; + const commits: string[] = []; + for (const cap of ['cap_hr_v1', 'cap_hr_v2']) { + expect(await save(p, { type: 'permission', name: N, item: setOf(cap), packageId: HR, mode: 'draft' })).toBeNull(); + const res = await p.publishPackageDrafts({ packageId: HR }); + expect(res.commitId, JSON.stringify(res)).toEqual(expect.any(String)); + commits.push(res.commitId!); + } + expect(activeCaps(c.engine)).toEqual([{ package_id: HR, caps: ['cap_hr_v2'] }]); + return { ...c, p, commits }; + } + + for (const order of ORDERS) { + it(`${order}: rolling back hr's own N to v1 restores v1, and hr's grant confers it (FROM 403 NOT_OVERRIDABLE)`, async () => { + const { engine, registry, p } = await savedTwice(order); + const { err } = await settle(p.rollbackMetaItem({ type: 'permission', name: N, toVersion: 1, packageId: HR })); + expect(err).toBeNull(); + expect(activeCaps(engine)).toEqual([{ package_id: HR, caps: ['cap_hr_v1'] }]); + expect({ crm: await confers(registry, CRM), hr: await confers(registry, HR) }).toEqual({ crm: ['cap_crm_shipped'], hr: ['cap_hr_v1'] }); + }, 30_000); + + it(`${order}: reverting hr's commit that edited N restores v1 (FROM N in failed[] with NOT_OVERRIDABLE)`, async () => { + const { engine, registry, p, commits } = await publishedTwice(order); + const res = await p.revertCommit({ commitId: commits[1], packageId: HR }); + expect(res.failed).toEqual([]); + expect(res.success).toBe(true); + expect(activeCaps(engine)).toEqual([{ package_id: HR, caps: ['cap_hr_v1'] }]); + expect(await confers(registry, HR)).toEqual(['cap_hr_v1']); + }, 30_000); + + it(`${order}: rolling hr back to its earlier commit restores v1 (FROM the revert failed)`, async () => { + const { engine, p, commits } = await publishedTwice(order); + const res = await p.rollbackToPackageCommit({ commitId: commits[0], packageId: HR }); + expect(res.failed).toEqual([]); + expect(res.success).toBe(true); + expect(activeCaps(engine)).toEqual([{ package_id: HR, caps: ['cap_hr_v1'] }]); + }, 30_000); + + it(`${order}: with crm AND fin shipping N, the rollback and the commit revert still restore: every shipper is judged`, async () => { + const saved = await savedTwice(order, [CRM, FIN]); + expect((await settle(saved.p.rollbackMetaItem({ type: 'permission', name: N, toVersion: 1, packageId: HR }))).err).toBeNull(); + expect(activeCaps(saved.engine)).toEqual([{ package_id: HR, caps: ['cap_hr_v1'] }]); + const published = await publishedTwice(order, [FIN, CRM]); + expect((await published.p.revertCommit({ commitId: published.commits[1], packageId: HR })).failed).toEqual([]); + expect(activeCaps(published.engine)).toEqual([{ package_id: HR, caps: ['cap_hr_v1'] }]); + }, 30_000); + + // Rows of N bound to an address that overrides crm's shipped set cannot be saved + // there; each case stores hr's rows, then rebinds them, as a row stored before + // the seal would be. The restore into each is refused as it was, nothing written. + // Each envelope is the one main answered, measured before this change: the + // restore's seal for crm and its pair, and a refusal judged ahead of it for + // the rest (the one-name-per-namespace rule, and a package-less address). + it.each([ + ['bound to no package', null, [CRM], ['RESOURCE_CONFLICT', 409]], + ['bound to crm', CRM, [CRM], ['NOT_OVERRIDABLE', 403]], + ['bound to crm\'s customization pair (another namespace)', CRM_PAIR, [CRM], ['NOT_OVERRIDABLE', 403]], + ['bound to a co-owner of crm\'s namespace', CRM_TWO, [CRM], ['NAMESPACE_CONFLICT', 422]], + ['bound to a co-owner of fin\'s namespace, fin also shipping', CRM_TWO, [FIN, CRM], ['NAMESPACE_CONFLICT', 422]], + ] as const)(`${order}: CONTROL — a rollback of N %s is refused as before`, async (_how, binding, shippers, expected) => { + const { engine, p } = await savedTwice(order, shippers); + rebind(engine, binding); + const { err } = await settle(p.rollbackMetaItem({ type: 'permission', name: N, toVersion: 1, ...(binding ? { packageId: binding } : {}) })); + expect(envelope(err)).toEqual(expected); + expect(activeCaps(engine)).toEqual([{ package_id: binding, caps: ['cap_hr_v2'] }]); + }, 30_000); + + it.each([ + ['bound to no package', null, [CRM], 'NAMESPACE_CONFLICT'], + ['bound to crm', CRM, [CRM], 'NOT_OVERRIDABLE'], + ['bound to crm\'s customization pair (another namespace)', CRM_PAIR, [CRM], 'NOT_OVERRIDABLE'], + ['bound to a co-owner of crm\'s namespace', CRM_TWO, [CRM], 'NAMESPACE_CONFLICT'], + ['bound to a co-owner of fin\'s namespace, fin also shipping', CRM_TWO, [FIN, CRM], 'NAMESPACE_CONFLICT'], + ] as const)(`${order}: CONTROL — a revert of a commit of N %s fails N as before`, async (_how, binding, shippers, code) => { + const { engine, p, commits } = await publishedTwice(order, shippers); + rebind(engine, binding); + for (const row of engine.rows.values()) if (row.__table === 'sys_metadata_commit') row.package_id = binding; + const res = await p.revertCommit({ commitId: commits[1] }); + expect(res.failed.map((f) => [f.name, f.code])).toEqual([[N, code]]); + expect(activeCaps(engine)).toEqual([{ package_id: binding, caps: ['cap_hr_v2'] }]); + }, 30_000); + + it(`${order}: deleting hr's own N removes hr's set and says so, never "reset to artifact default" (FROM the reset receipt)`, async () => { + const { engine, registry, p } = await savedTwice(order); + const res = await p.deleteMetaItem({ type: 'permission', name: N, packageId: HR }); + expect(res.success).toBe(true); + // `reset` is "a row was deleted" (DeleteMetaItemResponseSchema): one was. + expect(res.reset).toBe(true); + expect(res.message).toMatch(new RegExp(`^Deleted permission '${N}' \\(package=${HR.replace(/\./g, '\\.')}\\) — it no longer exists\\.`)); + expect(metaRowsOf(engine)).toEqual([]); + expect(await confers(registry, CRM)).toEqual(['cap_crm_shipped']); + }, 30_000); + + it(`${order}: a delete naming hr when hr holds no N answers that nothing was found, never "already at artifact default" (FROM the reset receipt)`, async () => { + const { protocol } = await composition(order); + const res = await (protocol as unknown as Proto).deleteMetaItem({ type: 'permission', name: N, packageId: HR }); + expect([res.success, res.reset, res.message]).toEqual([true, false, `No permission '${N}' found — nothing to delete.`]); + }, 30_000); + + it(`${order}: CONTROL — deleting the customization of crm's N stored for crm's pair still reads as a reset to the artifact default`, async () => { + const { engine, p } = await savedTwice(order); + rebind(engine, CRM_PAIR); + const res = await p.deleteMetaItem({ type: 'permission', name: N, packageId: CRM_PAIR }); + expect(res.success).toBe(true); + expect(res.reset).toBe(true); + expect(res.message).toContain('reset to artifact default'); + }, 30_000); + } +});